Compare commits
24
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
427095212b | ||
|
|
12895e9868 | ||
|
|
9c03cd5900 | ||
|
|
b939101565 | ||
|
|
ae4e0909a6 | ||
|
|
530e768a5b | ||
|
|
3367bb6454 | ||
|
|
2a90201bfa | ||
|
|
b776ce58eb | ||
|
|
ffc0548e1f | ||
|
|
264fee5127 | ||
|
|
3b8a93e12c | ||
|
|
cf879c9265 | ||
|
|
01d1b54caa | ||
|
|
f3d7423d02 | ||
|
|
62f143fe9f | ||
|
|
9837ca581b | ||
|
|
c787ef325b | ||
|
|
3c4e6e7e37 | ||
|
|
ba5b13667b | ||
|
|
1baf908ba4 | ||
|
|
6d0b92c515 | ||
|
|
7d5ea814ec | ||
|
|
b21960cda1 |
No files matched your search
@@ -0,0 +1,11 @@
|
||||
# 项目维护约定
|
||||
|
||||
## 持续版本记录
|
||||
|
||||
- 项目的统一问题与修改记录是根目录 `版本问题与修改记录.md`。
|
||||
- 后续每次修改功能、修复问题、分析新的诊断包或发布版本,均同步更新该文件;不得只在聊天中说明。
|
||||
- 工作尚未完成时写入“未发布与文档维护”;发布时补全真实版本、日期、问题、证据、修改、验证、限制和交付信息。
|
||||
- 若改变了历史方案,保留旧记录并明确标注替代关系,同时更新“当前有效行为”。
|
||||
- 未验证的根因、版本归属和现场结果写“待核实”;不能把模拟测试、便携版自检写成全部真实 CAD 工程验收通过。
|
||||
- 纯文档维护不自动增加程序版本,不覆盖既有发布 ZIP;需要更新交付包时遵循该次任务范围。
|
||||
- `tools/package_portable.py` 会把主记录复制为包内的 `版本问题与修改记录.md`;以后打包前确保记录已同步。
|
||||
@@ -4,9 +4,15 @@
|
||||
|
||||
面向 **Windows + DxDesigner / Expedition Enterprise 7.9.5** 的器件批量替换工具。一个工程对应一个任务,可以只替换同料号下的部分位号;支持直接编辑和 Excel BOM 导入,同批工程按顺序执行。
|
||||
|
||||
**最新版本:V1.1.4 Beta 2(预发布)** · [下载便携包](https://git.simgreek.com/simgreek/dxdesigner-part-replacement/releases/download/v1.1.4-beta.2/DxPartReplace-1.1.4-beta.2.zip) · [版本说明与附件](https://git.simgreek.com/simgreek/dxdesigner-part-replacement/releases/tag/v1.1.4-beta.2) · [完整使用说明](docs/user/v1.1.0-project-tasks.md)
|
||||
**当前本地交付版本:1.2.0-beta.31。** 从早期版本到当前的问题、修改、诊断依据、验证范围及后续更新,统一见 [版本问题与修改记录](版本问题与修改记录.md)。下面的 1.1.x 发布链接和教程属于历史资料,当前行为以该记录为准。
|
||||
|
||||
所有发布均标记为 **Beta 预发布**。V1.1.4 Beta 1 因 BOM 导入缺少 `win32timezone` 已撤回,请使用 Beta 2;旧 Git 标签保留供回溯。升级前备份 `data`,完整更新 EXE 与 `_internal`,不要只替换 EXE。
|
||||
本分支附有 [Windows x64 离线依赖和安装说明](dependencies/windows-x64/README.md)。
|
||||
|
||||
**历史公开发布:V1.1.4 Beta 4(预发布)** · [下载便携包](https://git.simgreek.com/simgreek/dxdesigner-part-replacement/releases/download/v1.1.4-beta.4/DxPartReplace-1.1.4-beta.4.zip) · [版本说明与附件](https://git.simgreek.com/simgreek/dxdesigner-part-replacement/releases/tag/v1.1.4-beta.4) · [完整使用说明](docs/user/v1.1.0-project-tasks.md)
|
||||
|
||||
所有发布均标记为 **Beta 预发布**。V1.1.4 Beta 1 因 BOM 导入缺少 `win32timezone` 已撤回,请使用 Beta 4;旧 Git 标签保留供回溯。升级前备份 `data`,完整更新 EXE 与 `_internal`,不要只替换 EXE。
|
||||
|
||||
Beta 4 面向停止与资源收尾复测:普通暂停等待当前项保存核验,写入中无进度不再自动杀进程;新增明确确认的强制结束,保留中断证据与恢复入口。[本版变更和复测说明](docs/releases/v1.1.4-beta.4.md)。
|
||||
|
||||
本版提供[目标封装选择](docs/user/target-cell-selection.md):目标封装可留空,此时工具不主动覆写封装,可后续与中心库同步;需要指定时,在料号规则中读取并选择合法封装。BOM 保持原 11 列。
|
||||
|
||||
@@ -18,7 +24,7 @@
|
||||
|
||||
### 第 1 步:解压并打开应用
|
||||
|
||||
[下载 V1.1.4 Beta 2 便携包](https://git.simgreek.com/simgreek/dxdesigner-part-replacement/releases/download/v1.1.4-beta.2/DxPartReplace-1.1.4-beta.2.zip),**完整解压**,双击 `DxPartReplace.exe`。保留它与 `_internal` 的相对位置,无需安装 Python;本机需要可用的 DxDesigner、许可证和中央库。
|
||||
[下载 V1.1.4 Beta 4 便携包](https://git.simgreek.com/simgreek/dxdesigner-part-replacement/releases/download/v1.1.4-beta.4/DxPartReplace-1.1.4-beta.4.zip),**完整解压**,双击 `DxPartReplace.exe`。保留它与 `_internal` 的相对位置,无需安装 Python;本机需要可用的 DxDesigner、许可证和中央库。
|
||||
|
||||
打开后看到下图主窗口。首次使用请准备完整的工程副本,执行前保存并关闭待处理工程。
|
||||
|
||||
@@ -131,6 +137,8 @@
|
||||
|
||||
运行期间可以在主桌面查看其他文件,请勿打开或修改本次正在处理的同一工程。需要暂停时,点击 **完成当前项后暂停**,等待当前步骤安全收尾。
|
||||
|
||||
Beta 4 在保存或核验尚未确认时保留应用等待,可先 **导出诊断包**。只有明确接受中断后需要核验时,才选择 **强制结束…**;之后先核验恢复,不能直接重复替换。详见[停止、强制结束与恢复](docs/user/safe-stop-and-recovery.md)。
|
||||
|
||||
**完成标志:** 任务显示已完成,底部提示本批执行结束。还要打开结果核对,不能只看进度条。
|
||||
|
||||
### 第 12 步:查看实际修改结果与日志
|
||||
@@ -194,7 +202,7 @@ DxPartReplace/
|
||||
|
||||
## 验证范围与已知限制
|
||||
|
||||
V1.1.4 Beta 2 新增批次后台资源管理:一次 BOM 导入或顺序执行共用一个私有桌面,CAD 按需启动并在同批工程间复用,批次结束统一退出。若提示 **资源释放待处理**,已保存核验的结果保留,请点击 **重新清理资源**;该操作只清理后台资源,不会再次替换。旧的工程保护锁仍按“核验并恢复”处理。设计、异常边界与实机结果见[批次运行时验收记录](docs/testing/2026-10-21-batch-private-runtime.md)。
|
||||
V1.1.4 Beta 4 沿用批次后台资源管理:一次 BOM 导入或顺序执行共用一个私有桌面,CAD 按需启动并在同批工程间复用,批次结束统一退出。若提示 **资源释放待处理**,已保存核验的结果保留,请点击 **重新清理资源**;该操作只清理后台资源,不会再次替换。旧的工程保护锁仍按“核验并恢复”处理。设计、异常边界与实机结果见[批次运行时验收记录](docs/testing/2026-10-21-batch-private-runtime.md)。
|
||||
|
||||
资源释放会追加日志:在 **替换结果 / 日志 → 完整日志** 查看本批开始释放、释放成功/失败及重新清理的结果。独立文件位于 `data/batch-resources/<批次ID>/resource-release.log`,记录批次、桌面、CAD PID、退出码、释放耗时、句柄关闭和桌面消失的分别确认,以及失败原因;同时保留 `session.json` 的原始释放证明。重启后重新检查也会追加记录,不覆盖原失败日志。
|
||||
|
||||
|
||||
Vendored
+16
@@ -0,0 +1,16 @@
|
||||
# beta.31 Windows x64 离线依赖
|
||||
|
||||
`wheels/` 收录 Python 3.12 x64 使用的运行、测试和打包依赖。`requirements.lock` 固定每个包的版本和 SHA256。运行库版本与 beta.31 便携包的第三方版本清单一致。
|
||||
|
||||
安装 Python 3.12 x64 后,从仓库根目录执行以下 PowerShell 命令。
|
||||
|
||||
```powershell
|
||||
py -3.12 -m venv .venv
|
||||
.\.venv\Scripts\python.exe -m pip install --no-index --find-links dependencies/windows-x64/wheels --require-hashes -r dependencies/windows-x64/requirements.lock
|
||||
.\.venv\Scripts\python.exe -m pip install --no-index --no-build-isolation --no-deps -e .
|
||||
.\.venv\Scripts\python.exe -m pip check
|
||||
```
|
||||
|
||||
打包入口为 `packaging/Build-DxPartReplace.ps1`。真实 CAD 操作需要本机安装 DxDesigner、有效许可证及工程使用的器件库。
|
||||
|
||||
核对基准为 `DxPartReplace-1.2.0-beta.31-Windows-x64.zip`,SHA256 为 `7f0fc33a9c3e83e647eeb8f29641ae04dc9aa2895b923f91884f499d157b33f6`。已逐一核对包内 103 个应用模块、程序入口及两份 VBS 脚本与本分支导入的源码。
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
# Windows x64, CPython 3.12. Runtime, test and build dependencies.
|
||||
altgraph==0.17.5 --hash=sha256:f3a22400bce1b0c701683820ac4f3b159cd301acab067c51c653e06961600597
|
||||
build==1.6.1 --hash=sha256:ecd351a4be9d35a9eaaba244a7687143c9c7d4aea6ac964e7e7ddab20cbcf4e7
|
||||
colorama==0.4.6 --hash=sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6
|
||||
comtypes==1.4.17 --hash=sha256:4e0a221dde2c589b82977bed802efd71cd5eb67a380347b732e02735e597f586
|
||||
coverage==7.17.0 --hash=sha256:88a1a9fb0075b83389dd9b403bb3fce976031b3c2aa0e05e3e57143cf639de69
|
||||
et_xmlfile==2.0.0 --hash=sha256:7a91720bc756843502c3b7504c77b8fe44217c85c537d85037f0f536151b2caa
|
||||
iniconfig==2.3.1 --hash=sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7
|
||||
openpyxl==3.1.5 --hash=sha256:5282c12b107bffeef825f4617dc029afaf41d0ea60823bbb665ef3079dc79de2
|
||||
packaging==26.3 --hash=sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c
|
||||
pefile==2024.8.26 --hash=sha256:76f8b485dcd3b1bb8166f1128d395fa3d87af26360c2358fb75b80019b957c6f
|
||||
pillow==12.3.0 --hash=sha256:a2b55dd6b2a4c4b7d87ffa56bdb33fdc5fdb9a462173861a7bc097f17d91cb09
|
||||
pluggy==1.7.0 --hash=sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec
|
||||
Pygments==2.21.0 --hash=sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9
|
||||
pyinstaller==6.22.3 --hash=sha256:500bd58c7bf7e584a8435adccbd763a0b918d5c12b08d74ff50fd79b2915458b
|
||||
pyinstaller-hooks-contrib==2026.9 --hash=sha256:fb3e67dd64122561724c48ad0366ac9e8c16e638b63bf7d85de03bf3fdbf06c3
|
||||
pyproject_hooks==1.3.3 --hash=sha256:5fc53fdac9f7bd63fbcdc868fb5f90b4784d78a53a3d3388cd738b807441a20b
|
||||
PySide6_Essentials==6.8.3 --hash=sha256:3c0fae5550aff69f2166f46476c36e0ef56ce73d84829eac4559770b0c034b07
|
||||
pytest==8.4.2 --hash=sha256:872f880de3fc3a5bdc88a11b39c9710c3497a547cfa9320bc3c5e62fbf272e79
|
||||
pytest-cov==6.3.0 --hash=sha256:440db28156d2468cafc0415b4f8e50856a0d11faefa38f30906048fe490f1749
|
||||
pytest-qt==4.5.0 --hash=sha256:ed21ea9b861247f7d18090a26bfbda8fb51d7a8a7b6f776157426ff2ccf26eff
|
||||
pywin32==312 --hash=sha256:b457f6d628a47e8a7346ce22acb7e1a46a4a78b52e1d17e1af56871bd19a93bc
|
||||
pywin32-ctypes==0.2.3 --hash=sha256:8a1513379d709975552d202d942d9837758905c8d01eb82b8bcc30918929e7b8
|
||||
pywinauto==0.6.9 --hash=sha256:5924b3072864a1d730c5546bbeb17cf4063ba518b618dbc5e43c18276c7c9356
|
||||
setuptools==84.2.1 --hash=sha256:ca140b45d5325a9478f880e351484f62fef15f336462e449ca0c03c873d589c2
|
||||
shiboken6==6.8.3 --hash=sha256:bca3a94513ce9242f7d4bbdca902072a1631888e0aa3a8711a52cc5dbe93588f
|
||||
six==1.17.0 --hash=sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274
|
||||
typing_extensions==4.16.0 --hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8
|
||||
wheel==0.48.0 --hash=sha256:3217dcc807155e45db462d7ef2431f5ddda0d7273b700d05a67b271ceb1287ab
|
||||
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,37 @@
|
||||
# DxPartReplace V1.1.4 Beta 3
|
||||
|
||||
2026-10-23,**Beta 预发布/工单现场复测版**,对应工单 [#1](https://git.simgreek.com/simgreek/dxdesigner-part-replacement/issues/1)、[#3](https://git.simgreek.com/simgreek/dxdesigner-part-replacement/issues/3)。
|
||||
|
||||
## 下载与升级
|
||||
|
||||
完整解压 `DxPartReplace-1.1.4-beta.3.zip`,运行 `DxPartReplace.exe`,无需安装 Python。保留 EXE 与 `_internal` 的相对位置;本机需要可用的 DxDesigner、许可证和中央库。
|
||||
|
||||
建议在新目录解压,用工程副本复测。需要沿用任务时,先关闭旧程序、备份旧 `data`,再完整复制数据目录;不同版本不能同时打开同一数据目录。旧保护锁保留,不能通过删除保护记录来重试。
|
||||
|
||||
包内包含中文图文教程、窗口 GIF、空白 11 列 BOM 模板、发布清单。教程沿用旧版已录制的基本操作,新增加的恢复与归档选项以本版界面为准。
|
||||
|
||||
## 本版修改
|
||||
|
||||
- 修复内部长路径访问:缩短批次 attempt 目录,补齐扩展路径、兼容工作目录、深目录工程扫描、日志和保护记录访问;不要求修改系统注册表。
|
||||
- 后台资源由独立批次监督进程持有,批内复用桌面与按需启动的 CAD,批末退出后由主界面独立复核。主界面不持有私有桌面或 COM 对象。
|
||||
- 只有持久化证据证明尚未修改、工程身份一致、旧资源已释放,才允许每工程自动重试一次;修改后、保存核验失败或结果不确定时不重放。
|
||||
- 自有 CAD 启动期间退出时及时检测,避免探针继续空等 120 秒。真实连续启动故障的检测与收尾阶段约 0.25–0.33 秒,完整任务仍受 CAD 启动、替换及保存回读耗时影响。
|
||||
- 分别保留首发错误、清理错误与 BOM 逐行报告。清理资源不重新执行已完成替换;恢复请求和消息检查批次、代次及尝试身份。
|
||||
- 补充自有进程/句柄归属诊断,提供“导出诊断包”,包含独立的批次释放日志并脱敏。
|
||||
- 增加“正常关闭时归档并清空当前任务列表”,默认关闭。启用后安全任务移至回收站;存在保护、中断或未释放资源的任务保留,不物理删除工程、日志及执行证据。
|
||||
- 持久化只读采集缓存,绑定工程指纹及完整载荷摘要;损坏缓存隔离后重新读取。
|
||||
|
||||
## 工单复测步骤
|
||||
|
||||
1. 使用原问题目录长度及工程副本,创建任务并导入原 BOM;确认通过、失败、未检查行数和逐行原因都能显示,失败后再次导入会刷新状态。
|
||||
2. 先选择两个工程的少量位号,保存计划并顺序执行;核对目标料号、未选位号、保存重开结果及释放日志,再扩大批次。
|
||||
3. 遇到资源待处理时,使用“重新清理资源”,确认不会重复替换。仍失败请点击“导出诊断包”,将 ZIP、版本及触发步骤附到原工单。
|
||||
4. 需要关闭后清空列表时,启用正常关闭归档选项;重开后可从回收站恢复。保护或待核验任务应继续保留。
|
||||
|
||||
## 验证范围与已知边界
|
||||
|
||||
实现阶段完成两份新工程副本的完整 EXE BOM 流程、真实替换、保存重开与独立属性/连接对照:每工程 57 器件、103 引脚,56 个非目标器件不变;顺序执行共一个桌面、一次 CAD 启动。另完成深中文路径的冻结 EXE 检查、真实外部桌面持有者、标记写入失败、连续启动失败及写后监督进程崩溃的测试。
|
||||
|
||||
故障实机入口部分为源码非 GUI parent+真实冻结 supervisor/helper/VBS,不等同于完整 GUI 硬退出或机器掉电测试。不同候选的具体哈希、命令和范围见[实施与验收记录](../testing/2026-10-23-issue-3-safe-recovery.md)。本发布包重新构建并检查冻结源码一致性、解压启动及资源释放,结果写入发布清单。
|
||||
|
||||
**仍需现场验证:** 关闭系统长路径支持且没有 8.3 的组合环境尚未完整验收;原工单 102 个工程没有完成原工程实机替换,其中 96 个连报告回放也未覆盖,见[逐工程清单](../testing/2026-10-23-issue-3-uncovered-projects.md)。工单 #1 现场残留桌面的具体持有者仍未确定,不能宣称根因已根治。两个工单保持打开,等待现场反馈。
|
||||
@@ -0,0 +1,37 @@
|
||||
# V1.1.4 Beta 4 构建与发布验证
|
||||
|
||||
2026-10-26,用户授权发布下一版 Beta。版本 `1.1.4-beta.4`,Python 元数据 `1.1.4b4`,Windows 文件版本 `1.1.4.4`,预发布标志开启。业务修改基于 `9c03cd5`;本轮产品代码只调整版本标识。
|
||||
|
||||
## 构建门禁
|
||||
|
||||
- `packaging/Build-DxPartReplace.ps1`:退出码 0,源码门禁 **923 passed,232.69 秒**,一条既有 pywinauto STA 警告。
|
||||
- 打包配置及外部验收脚本检查:**17 passed,11.08 秒**。
|
||||
- 构建产物在完整冻结 EXE 主进程中启动独立监督进程、读取真实进程创建时间并确认自有进程/Job/桌面释放,再完成 GUI 启动与正常关闭检查。
|
||||
- 冻结的 92 个 `dx_productivity` 模块及应用入口逐项对照源码,递归标准化 code filename 后 code object 一致。包含新的 `stop_control` 模块;两份 VBS 在包装阶段另做哈希比对。
|
||||
- EXE SHA256:`ee64d983f6f0457bac2bb16225ee8a8044753b5bf7779e498549c61d8ed4d13b`。
|
||||
|
||||
构建日志:`build/release-1.1.4-beta.4-build.log`。源码比对:`build/release-1.1.4-beta.4/frozen-source-check.json`。实现阶段扩大测试 1147 项通过的范围见[安全停止验收](../testing/2026-10-26-safe-stop-acceptance.md),不与本轮构建门禁数量混算。
|
||||
|
||||
## 冻结监督进程实机验证
|
||||
|
||||
本轮用源码控制器驱动上述正式 EXE 的 `--batch-worker`,执行 BOM 导入与真实 CAD 队列;批内 helper 和 VBS 使用冻结产物。复制两个全新工程,不重放之前完成的替换。
|
||||
|
||||
在第一个工程的生产 `save_requested` 日志出现时只请求普通停止,结果为第一任务 completed、第二任务 pending、队列 paused。新 CAD 实例独立读回确认:第一工程 57 器件、103 引脚连接正确,56 个非目标器件保持;第二工程 57 器件完整属性/连接图与执行前一致。
|
||||
|
||||
执行批次 `orderly_shutdown=true`、`clean=true`、`forced_termination=false`,CAD 与 Quit helper 退出码均为 0,资源状态 released。源工程目录哈希和中央库 `.lmc` 哈希不变。
|
||||
|
||||
证据:`build/release-1.1.4-beta.4/frozen-save-stop.json` 与 `build/safe-stop-live-9894f95db1/`。后者由通用 source 探针生成,保留了其原始 scope 文本;本轮实际冻结进程路由、调用请求和 EXE 哈希以 companion `frozen-save-stop.json` 为准。前后独立读取使用源码读取器,不将其说成全部入口均冻结,也不将该测试说成完整 GUI 交互停止。
|
||||
|
||||
## 包装与公开附件
|
||||
|
||||
便携包只从 EXE、完整 `_internal`、仓库教程及文档生成,附空白 11 列 BOM 模板和历史窗口 GIF;不带 `data`、任务数据库、用户工程、工单附件或现场日志。
|
||||
|
||||
包装脚本要求本轮冻结停止验证的 EXE 哈希与被打包文件一致,检查 ZIP CRC、解压路径、所有程序文件 SHA256,并在清除源码 Python 环境变量后执行解压出来的完整 EXE smoke。ZIP 大小、SHA256、程序文件清单与解压验证结果由公开 `release-manifest-1.1.4-beta.4.json` 记录。
|
||||
|
||||
附件:`DxPartReplace-1.1.4-beta.4.zip`、`SHA256SUMS-1.1.4-beta.4.txt`、`release-manifest-1.1.4-beta.4.json`、`BOM-template.xlsx`、`window-tutorial-1.1.4-beta.4.gif`。GIF 沿用 1.1.2 基础教程,新停止功能以包内说明和界面为准。
|
||||
|
||||
发布流程为先创建草稿,上传后逐项回下载核对大小和 SHA256,全部一致才公开为 Beta 预发布。远端响应与附件校验证据保存在 `build/release-1.1.4-beta.4/`;认证信息不写入文件或日志。本轮没有授权给工单发消息,因此不发布工单评论、不关闭工单,也不修改旧版本附件。
|
||||
|
||||
## 现场边界
|
||||
|
||||
仍未完成原工单 102 个工程的全量现场复测,也没有完整冻结 GUI 的真实保存中强杀或掉电无损验收。工单现场桌面残留持有者尚未查明。本版本提供已验证的停止与收尾改进,不能据此宣布现场事故根因已经根治。
|
||||
@@ -0,0 +1,41 @@
|
||||
# DxPartReplace V1.1.4 Beta 4
|
||||
|
||||
2026-10-26,**Beta 预发布/安全停止与应用收尾复测版**。关联工单 [#1](https://git.simgreek.com/simgreek/dxdesigner-part-replacement/issues/1)、[#3](https://git.simgreek.com/simgreek/dxdesigner-part-replacement/issues/3)。
|
||||
|
||||
## 下载与升级
|
||||
|
||||
完整解压 `DxPartReplace-1.1.4-beta.4.zip`,运行 `DxPartReplace.exe`。无需安装 Python;保留 EXE 和 `_internal` 的相对位置,本机需要可用的 DxDesigner、许可证及中央库。
|
||||
|
||||
请在新目录解压,使用工程副本复测。沿用旧任务前,先安全退出旧程序并备份完整 `data`;不要同时用两个版本打开同一数据目录。不要删除原有保护记录来绕过核验。
|
||||
|
||||
便携包包含中文教程、空白 11 列 BOM 模板、历史窗口操作 GIF、停止与恢复说明及文件校验清单。GIF 沿用 1.1.2 基础操作,新版停止与强制结束功能以实际界面及[停止说明](https://git.simgreek.com/simgreek/dxdesigner-part-replacement/src/tag/v1.1.4-beta.4/docs/user/safe-stop-and-recovery.md)为准。
|
||||
|
||||
## 本版修改
|
||||
|
||||
- 普通“完成当前项后暂停”只停止后续调度,当前替换项完成必要校验、保存、回读和关闭后再停止;关闭窗口也等待收尾。
|
||||
- 有写入可能的阶段长时间没有进度时保留应用等待,不再仅凭超时自动杀进程;纯只读采集仍采用有界取消。
|
||||
- 新增独立的“强制结束…”确认。先可靠保存中断保护和批次证据,再终止本程序拥有的进程;保护写入失败时拒绝本次强制结束并显示原因。
|
||||
- 当前修改或保存结果不确定、应用拒绝退出时保留现场,禁止盲目保存、丢弃和重放。等待期间可导出诊断包。
|
||||
- 保存请求、保存调用返回、保存回读和工程关闭分别记录,避免保存后关闭失败被误记为未保存。
|
||||
- 修复收尾记录写入失败跳过正常 Quit 的路径;CAD 主进程正常退出后,给自有辅助进程短暂自然退出机会,再决定是否需要强制清理。
|
||||
- 正常退出、强制终止和物理资源释放分别报告。资源消失不再掩盖应用退出异常,已经核验的业务结果继续保留。
|
||||
- 控制通信异常不会直接授权终止正在运行的交互批次;强制结束及进程退出诊断记录保持一致。
|
||||
|
||||
## 复测建议
|
||||
|
||||
1. 新建两个工程副本的少量位号任务,导入 BOM 并保存计划。
|
||||
2. 在第一项执行或保存时点击普通暂停,核对当前项完成保存回读,下一项保持未执行;重新打开工程核对料号和连接。
|
||||
3. 对长时间等待先导出诊断。仅在接受当前结果需要核验时确认“强制结束…”;重开后先“核验并恢复”,不要直接重复替换。
|
||||
4. 如仍有异常,保留版本、触发步骤、诊断 ZIP 和失败工程名称。资源待处理时的清理不会重新执行替换。
|
||||
|
||||
为避免强制请求与任务切换同时发生而漏记目标,本版强制结束会保守保护本批可能涉及的任务。先前已完成任务也可能需要复核,但其保存结果和执行证据不被覆盖或重放。
|
||||
|
||||
## 验证范围与已知边界
|
||||
|
||||
实现阶段扩展回归 **1147 项通过**。源码监督入口在两份新工程副本上验证了保存期间请求普通停止:第一工程 completed,第二工程 pending;新 CAD 独立读回确认第一工程 57 器件、103 引脚连接正确、56 个非目标器件不变,第二工程完整图未变化。源工程及中央库 `.lmc` 哈希不变,执行批次正常退出且没有强制清理。
|
||||
|
||||
本轮发布门禁 923 项通过,打包与验收脚本检查 17 项通过。正式 EXE 的冻结监督进程再次完成真实 CAD 保存期间普通停止及新实例独立读回;当前项完成、下一项未执行,正常退出且无强制终止。该实机入口由源码控制器驱动,不等同于完整 GUI 交互验收。
|
||||
|
||||
发布构建、解压后完整 EXE 启动、冻结监督进程及资源释放检查另见[Beta 4 构建记录](https://git.simgreek.com/simgreek/dxdesigner-part-replacement/src/tag/v1.1.4-beta.4/docs/releases/v1.1.4-beta.4-build.md)和附件 manifest。源码/受控辅助进程故障测试不等同于完整冻结 GUI 下的真实 CAD 强制中断或掉电无损验证。
|
||||
|
||||
**现场资源残留根因仍未全部闭环。** 原工单全量 102 个工程及特定系统组合仍需现场复测,本版不宣称所有环境已根治,不自动关闭关联工单。完整范围见[实施验收](https://git.simgreek.com/simgreek/dxdesigner-part-replacement/src/tag/v1.1.4-beta.4/docs/testing/2026-10-26-safe-stop-acceptance.md)。
|
||||
@@ -0,0 +1,11 @@
|
||||
# DxPartReplace 1.2.0-beta.10
|
||||
|
||||
- 替换结果及 Excel 导出增加原 Value / 实际回读 Value。原值来自替换前快照,实际值在原有属性核验后读取;保存重开核验后重新记录实际值。按 job_id / 返回状态关联并立即保存在事件日志,避免下一个规则覆盖证据。旧历史缺失数据明确标注,不推算实际值。
|
||||
- 左侧工程列表分为正在替换、未完成、已完成,三组独立折叠并记忆偏好;使用蓝色、浅橙色、绿色背景,损坏/校验失败工程额外标红。只将真实活动工程归入正在替换;旧轮次保留在历史。
|
||||
- 按用户要求:损坏/无法读取的工程关闭读取会话后跳过,不修复、不重复尝试打开。只读采集取消、CAD 启动和无进展等待均有界;在确认资源退出后继续后面的工程。
|
||||
- 旧版强制关闭留下的只读监督进程可在新导入前回收,必须同时核验旧主窗口已退出、监督进程 PID 和创建时间吻合、操作属于只读白名单。写入过程保护和其他 CAD 进程不受此规则影响。
|
||||
- 新增“停止当前工程”,外层结束本次自有进程而不等待 COM,标红“已停止 / 结果待核验”。界面批量调度按工程隔离监督进程,保护当前工程后停止本轮;尚未执行的工程可另行继续。原有 Replace Part、属性恢复、保存和核验逻辑不变。安全暂停继续等待当前项收尾。
|
||||
|
||||
升级时保留完整 data,与新 EXE 和 _internal 配套使用。修复的是采集、取消和调度流程,不修复工程 iCDB 数据库。
|
||||
|
||||
验证及边界详见 docs/superpowers/plans/2026-10-29-values-and-project-groups.md。
|
||||
@@ -0,0 +1,13 @@
|
||||
# DxPartReplace 1.2.0-beta.11
|
||||
|
||||
本版增加读取和解析的诊断记录,用于定位 UID 报告格式、CAD 启动、工程打开及器件采集中的具体问题。保持所有解析接受条件、UID 校验、原生替换、Value/NC、取消和资源释放策略不变。
|
||||
|
||||
- `application.log` 增加受监督只读操作的进度、校验返回的通过/失败/未核对行数,以及最多 100 条失败行的工程、Excel 行号和原因。明确区分“调用返回”和“校验通过”。
|
||||
- 每次原生清单/后台 CAD 读取的证据目录增加 `read-trace.jsonl` 和 `read-state.json`,记录 UTC 时间、进程、工程/任务标识、解析阶段和退出结果。后台工作进程每 5 秒记录等待状态、无进展秒数、计数和是否请求取消;不模拟进度。
|
||||
- 原生 UID 错误增加报告文件名、行号、UID 原文和字符编码、附近报告片段;同时保留有界的正常器件标识样例。可区分大写 I、小写 l、数字 1 及隐藏字符;不会自动改写 UID。
|
||||
- 诊断包新增上述记录及现有原生采集元数据、工作进程状态/输出、读取会话释放记录;优先导出近期读取记录。继续执行容量限制和用户路径/凭证脱敏,不导出完整原生报告、BOM、数据库或工程。
|
||||
- 所有新增追踪写入均为尽力记录。诊断存储不可写时,不改变业务结果或跳过资源清理。
|
||||
|
||||
使用:升级后重新导入有问题的清单,出现等待或失败时点击“诊断包”,发送生成的完整 ZIP。仅发送 application.log 无法包含详细报告片段。新版本不能补录旧版已经发生的解析过程。
|
||||
|
||||
便携版已包含运行依赖;仍需本机安装可用的 DxDesigner。升级保留完整 data,并配套使用新 EXE 和 _internal。
|
||||
@@ -0,0 +1,7 @@
|
||||
# DxPartReplace 1.2.0-beta.12
|
||||
|
||||
- 诊断包 `DxPartReplace-诊断-20261030-112928` 显示:工程实际已打开;原生展开报告中的 `POWER_IN`,符号 `in.1` 且没有位号,被误判为缺少 UID 的物料。随后 CAD 采集又因为某对象 UID 或位号为空而停止。该诊断没有记录第二个对象的字段,因此不能断定它就是 POWER_IN,也不能由此认定工程损坏。
|
||||
- 原生解析只排除明确的 POWER_IN/in.1、POWER_OUT/out.1 无位号命名端口,要求符号类型单一、两份报告端口数量一致;其他不明对象继续执行原有安全检查和 CAD 回退。
|
||||
- CAD 采集按 BOM 位号匹配:无位号对象无法作为替换目标,跳过并记录;可定位的器件仍必须具有 UID。保留全部有位号器件,继续检测不同料号下重复位号。跳过对象的 UID、料号及图页写入日志,最多记录 20 条并显示总数。诊断包现在包含相关运行日志。
|
||||
- 真正的“有位号但缺 UID”单独报告器件身份不完整,不再直接断言工程损坏。替换、核验及 Value/NC 规则不变。
|
||||
- 本版按诊断证据构造报告、使用实际 Windows Script Host 运行模拟 CAD 的真实采集脚本,并执行回归及便携版启动检查。未对真实用户工程进行替换验收。
|
||||
@@ -0,0 +1,10 @@
|
||||
# DxPartReplace 1.2.0-beta.13
|
||||
|
||||
- 排查诊断包 `20261030-132517`:`LDO_S2032_SOT23_1V5` 两次通过后台 CAD 采集,随后工程文件指纹不可用;第二次快照读取 `database/icdb.dat` 时返回拒绝访问。当时同一自有只读 CAD 会话仍存活,但记录不足以证明具体占用者。
|
||||
- 当采集后完整指纹无法读取,仅在当前自有只读 CAD 的工程及工作进程已经通过同一工程和会话检查点确认关闭时,释放本次会话后重新读取完整指纹。设计文件变化仍不能通过;仅数据库会话数据变化仍需两次相同的器件清单。资源释放失败立即停止。若确认释放后仍无法核验,报告并跳过该工程,其他工程可以继续。
|
||||
- 原生清单按 `in.1` / `out.1` 类型识别无位号命名端口,如 `POWER_EN`,并保留两份报告的计数核对;不明、重复或不一致的符号仍回退到 CAD 验证。
|
||||
- 端口名称不限制为某个 CBB 或某个器件,可包含中文及常见标点;CAD 回退对无位号对象也采用通用规则。`20261030-134255` 诊断包中,BOB_XPON、CA_CARD_HIGH 等也出现了工程指纹校验失败;由于日志遗漏,不能断定各工程的具体占用原因相同。
|
||||
- Value 识别增加 `_NC`、`_nc`。旧 Value 含标识时,以新 Part Label 加 `/NC`;新值已有任一有效标识不重复,Part Label 不存在时保留旧 Value。`NC_OPTION`、`_NCM` 等较长文本不会误判。
|
||||
- 诊断包优先收集最近任务、后台记录及主日志的有界尾部;文件数与总大小仍有限制,继续脱敏并排除原始工程及数据库。
|
||||
|
||||
升级保留整个 `data`,配套使用 EXE 与 `_internal`。自动测试使用模拟工程和 Windows Script Host;本次未修改真实 CAD 工程,请在目标电脑先重新导入并核对实际结果。
|
||||
@@ -0,0 +1,14 @@
|
||||
# DxPartReplace 1.2.0-beta.9
|
||||
|
||||
修复强制退出后 CBB 导入被旧后台会话记录长期阻塞的问题。
|
||||
|
||||
- 导入/采集/执行前,在独占批次锁内自动复核已退出进程和资源记录,归并中断的监督记录;不重放旧请求。
|
||||
- 主窗口退出时,后台的人工核验等待可在持久保存中断保护后退出收尾,避免等待已不存在的主窗口。
|
||||
- 已退出监督进程、已退出 CAD/工作进程和空私有桌面的联合证据允许回收残留桌面对象;未知或仍存活的资源保持阻断。
|
||||
- 手动“检查后台会话”不再启动另一个清理监督进程;仍有待处理资源时明确提示,不再一律报告成功。
|
||||
- 保留全部中断写入保护、已保存执行结果和历史数据;原生替换和 Value/NC 规则未修改。
|
||||
- 白色界面优化工程名称/次要信息、导航选中态、状态标记、卡片间距和简短错误提示;器件明细保持主要空间,进度仍可折叠。
|
||||
|
||||
升级:关闭旧版,保存并保留完整 data,将新包 EXE 和 _internal 配套更新。若旧版后台已卡住,先保存其他 CAD 工程并重启一次电脑再使用新版。不要删除保护记录绕过核验。此更新处理软件恢复,不修复已损坏的工程 iCDB 数据库。
|
||||
|
||||
验证记录见 2026-10-29 interrupted-import 实施计划。进程级验证仅使用临时目录、真实 Windows 监督进程和模拟业务,没有打开或修改用户 CAD 工程。
|
||||
@@ -0,0 +1,62 @@
|
||||
# Safe User Stop Implementation Plan
|
||||
|
||||
> **For agentic workers:** use superpowers:subagent-driven-development or executing-plans; continue within the user-approved scope without another approval round.
|
||||
|
||||
**Goal:** 用户停止只在安全边界收尾;写入中的无进度不自动杀进程;明确强制中断有保护证据和恢复入口。
|
||||
|
||||
**Architecture:** 保留现有 Event/队列边界和独立监督进程,加入独立的强制停止意图、等待状态反馈;退出正常性与物理资源复核分开。使用既有任务保护与批次记录,不新增数据库版本。
|
||||
|
||||
**Tech Stack:** Python 3.12、Windows pywin32、PySide6、VBScript、pytest。
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-10-26-safe-user-stop.md`
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- 不修改原工程、中心库或未跟踪 feedback;真实测试只复制 fixture。
|
||||
- 不放宽身份、写前保护、禁止不确定重放的门禁。
|
||||
- 普通停止与强制结束独立,确认前不得产生强制意图。
|
||||
- 不通过无限创建桌面或删除旧保护绕过异常。
|
||||
- 不发布、不推送;本地分支 `codex/day0-safe-stop`。
|
||||
|
||||
## Task 1: 退出协议与后代进程
|
||||
|
||||
Files: `isolated_cad.py`, `isolated_desktop.py`, `tests/v1_1/test_isolated_cad.py`, `test_isolated_desktop.py`.
|
||||
|
||||
- [x] 先复现 closing 记录失败跳过 Quit、父进程自然退出后仍立即终止子进程的测试。
|
||||
- [x] 诊断写入失败不跳过满足身份/空工程条件的 Quit;将记录失败独立保留并报告,禁止伪报 clean。
|
||||
- [x] 根进程正常退出时,给 Job 后代 2 秒有界自然退出窗口;到期再强制并记录 `forced_termination`, `termination_reason`, `forced_descendant_pids`。根进程仍活着的异常清理仍有界。
|
||||
- [x] 保留所有权和退出确认,测试自然退出与强制升级两条路径。
|
||||
|
||||
## Task 2: 停止、等待与强制中断
|
||||
|
||||
Files: new `stop_control.py`; `worker_monitor.py`, `project_session.py`, `batch_runtime.py`, `batch_supervisor.py`, `execution_feedback.py`; associated tests.
|
||||
|
||||
Interface:
|
||||
```python
|
||||
class StopControl(Event):
|
||||
force_event: Event
|
||||
def request_force(self):
|
||||
self.set()
|
||||
self.force_event.set()
|
||||
```
|
||||
- [x] 首先测试 unsafe 保存阶段超时仍保留 worker,安全阶段仍有 watchdog,显式 force 才结束并产生 uncertain。
|
||||
- [x] `ProgressWatch` 提供 `waiting_for_safe_completion`;新进度可清除提示,不把心跳当作写入推进。
|
||||
- [x] 监督父进程持久化停止意图;force 先写保护与中断记录,再只终止已拥有的监督进程 Job,不使用名字或不可信 PID 清理。
|
||||
- [x] 业务完成但退出异常仍通过独立错误返回,附带已核验业务结果;纯桌面延迟且退出正常可继续使用现有复核恢复。
|
||||
- [x] 普通停止在当前项收尾后暂停;会话 close 不得因普通等待超时反向强杀仍在写入的 worker。
|
||||
|
||||
## Task 3: 保存边界与界面
|
||||
|
||||
Files: `QuickPartReplace.vbs`, `ui/run_panel.py`, `ui/main_window.py`, `ui/execution_feedback.py`, protocol serializer if required; VBS/UI tests.
|
||||
|
||||
- [x] VBS 用真实函数的失败先行测试覆盖保存已发出但工程关闭失败;保存请求前设置“可能保存”状态,独立记录保存返回/回读/关闭,不再声称未保存。
|
||||
- [x] 正常停止显示等待当前项收尾;unsafe 超时显示保存/核验尚未确认。
|
||||
- [x] 提供与普通暂停分离的强制结束按钮,确认文案明确结果待核验;取消确认没有副作用。
|
||||
- [x] 关闭窗口在运行/等待期间保持打开;任务失败后取消自动关闭,让用户看见恢复信息。
|
||||
|
||||
## Task 4: 集成验证与审查
|
||||
|
||||
- [x] 运行相关 VBS、monitor、supervisor、queue、UI、资源测试及完整发布门禁范围。
|
||||
- [x] 实机空 CAD 自然退出、两工程副本正常保存及独立回读;停止/强制结束采用受控替身或独立进程,明确验证边界。
|
||||
- [x] 独立审查关注:不确定写入重放、等待时 GUI 退出杀进程、force 身份校验与持久化失败、结果错误被吞、已完成项保留。
|
||||
- [x] 更新操作文档和验收记录,交付本地可审查修改及测试证据。
|
||||
@@ -0,0 +1,38 @@
|
||||
# Workspace Redesign Implementation Plan
|
||||
|
||||
> **For agentic workers:** Use superpowers:executing-plans inline. Track the checked tasks and evidence here.
|
||||
|
||||
**Goal:** 实现讨论确认的白色工作区、可重复导入和 Value/NC 规则,同时保持原生器件替换机制。
|
||||
|
||||
**Architecture:** 原生 VBS 继续负责替换与属性核验;Python 导入层负责每次实时库存、路径映射与按工程校验;新的 Qt 工作区复用已验证服务、后台 worker 和持久化接口。
|
||||
|
||||
**Tech Stack:** Python 3.12, PySide6, pywin32, openpyxl, VBScript, pytest, PyInstaller.
|
||||
|
||||
**Spec:** docs/superpowers/specs/2026-10-27-workspace-redesign.md
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- 固定白色,工程列表/器件明细独立卡片,紧凑进度。
|
||||
- 原生替换和连接/身份核验不移除;开发不修改真实 CAD 工程。
|
||||
- 源码无 Git;在当前目录工作,ZIP 是原始回退点。
|
||||
|
||||
## Review Focus
|
||||
|
||||
- 新旧料号并存、同位号跨图页、其他料号不能被误认已完成。
|
||||
- 已完成或删除任务不能让新导入使用陈旧库存。
|
||||
- 多文件重复器件和工程重名必须报告而不重复替换。
|
||||
- 缺少/空白 Part Label 的赋值、保存回读和恢复路径须一致。
|
||||
- 后台资源释放失败不能抹掉已核验结果,未核验不能当成功。
|
||||
|
||||
## Tasks
|
||||
|
||||
- [ ] 1. 环境/基线:保存源码备份,建立 Python 3.12 环境,运行现有 pytest;建立本文件作为进度账本。
|
||||
- [ ] 2. Value/NC:添加并运行真实 cscript 替身回归(先失败),实现缺失 Part Label 使用快照旧 Value,独立 NC 不分大小写,正常/恢复/验证一致。
|
||||
- [ ] 3. 导入:添加新旧料号混合回归(先失败);增加实时新旧料号库存和逐器件已达目标跳过、工程路径映射、多表合并、独立工程错误隔离。
|
||||
- [ ] 4. Qt 工作区:添加界面行为回归(先失败);新建白色桌面 shell,单工程/批量入口、独立工程与器件框、内嵌结果/历史、紧凑进度与日志导出,接入实际后台服务。
|
||||
- [ ] 5. 集成/交付:运行完整默认测试及受影响 VBS/应用/打包回归,截图检查桌面,构建 EXE 和说明;复核核心接口和未决实机风险。
|
||||
|
||||
## Ledger
|
||||
|
||||
Ruling: 用户已明确批准界面及功能并要求开始实现,因此不再要求重复批准实施计划。
|
||||
Ruling: 没有 Git 元数据,原位修改并保留同级源码 ZIP,不能创建 Git worktree 或提交。
|
||||
@@ -0,0 +1,45 @@
|
||||
# Interrupted import recovery implementation plan
|
||||
|
||||
> **For agentic workers:** Use superpowers:executing-plans to implement this plan task-by-task.
|
||||
|
||||
**Goal:** Permit CBB import after a crashed read session once resource exit is proven, retaining write uncertainty and improving the approved white workspace.
|
||||
|
||||
**Architecture:** Reconcile abandoned ownership under the existing supervisor lease before native admission; use the same path for manual cleanup. Keep business protection independent from physical resource release.
|
||||
|
||||
**Tech Stack:** Python 3.12, PySide6, Win32, PyInstaller.
|
||||
|
||||
**Spec:** ../specs/2026-10-29-interrupted-import-design.md
|
||||
|
||||
## Global constraints
|
||||
|
||||
- Do not change replacement/property rules or delete engineering data.
|
||||
- Retain uncertain-write markers and previously saved results.
|
||||
- Keep fixed white theme, left project list, compact progress and portable runtime.
|
||||
- The workspace has no Git metadata; edit in place and preserve user data.
|
||||
|
||||
## Review focus
|
||||
|
||||
- Dead read supervisors must not permanently block unrelated imports.
|
||||
- Interrupted writes must stay protected after physical cleanup.
|
||||
- Live or unknown process/desktop ownership must remain blocked.
|
||||
- A cleanup request must not create another stale cleanup supervisor.
|
||||
- Pending cleanup must not be presented as successful release.
|
||||
|
||||
## Tasks
|
||||
|
||||
- [x] Add failing crash-record/admission, empty-desktop and UI cleanup-feedback regression tests.
|
||||
- [x] Implement preflight reconciliation in batch_supervisor.py and proven orphan checks in batch_resources.py; run the targeted tests and existing safety coverage.
|
||||
- [x] Refine workspace_window.py/workspace_styles.py with compact status/notice, project list delegate, empty state and accurate cleanup feedback; render the actual Qt window.
|
||||
- [x] Review changes, run relevant checks, update version/release notes, build and inspect the portable beta.9 ZIP.
|
||||
|
||||
## Execution ledger
|
||||
|
||||
- Investigation: uploaded application.log contains only recent overview reads and export_diagnostics, without the shown earlier exception. Screenshot identifies batch_resources_pending; source confirms unconditional pending-supervisor admission and manual-only reconciliation.
|
||||
- Ruling: apply established UI choices and authorized repair directly; no new UX workflow or approval round needed.
|
||||
- Investigation: wait_for_resolution retained an interactive wait even after the actual GUI parent exited. Added durable owner-exit notification; pipe loss with a live parent only requests ordinary stop.
|
||||
- RED/GREEN: old admission reproduced batch_resources_pending; old manual cleanup unnecessarily launched another supervisor; old orphan empty-desktop recovery remained blocked. Regression tests now pass. A real temporary GUI was killed while its worker awaited reconciliation; worker exit and next batch admission passed without CAD.
|
||||
- Review: fixed exact CAD identity preference for PID reuse and gated orphan marker publication on confirmed parent exit. Fresh read-only reviewer found no remaining medium/high issues.
|
||||
- Ruling: corrected existing test fixtures for atomic PID observation, explicit extended-path directory creation and intended empty-residue semantics; no safety assertions for live windows were removed.
|
||||
- Ruling: native junction creation uses an existing 8.3 DOS target when available; direct extended-prefix targets are not valid for CPython's helper. Canonical target verification remains mandatory. Existing regression failed before correction and passes afterward.
|
||||
- Verification: 162 tests passed in 45.83s across interrupted-import recovery, supervisor/runtime, safe stop, isolated desktop/CAD, workspace import/operations/feedback/window and packaging. Real Qt screenshots inspected at 1400x940 and 1280x800.
|
||||
- Packaging: PyInstaller build and frozen EXE runtime smoke passed (real child process identity and private-desktop release, environment Python variables removed). ZIP CRC, required runtime files, beta.9 version and SHA256 sidecar verified; 254 files, including 229 dependency files, no user data. Archive SHA256: 79741a786ca8cf8cac3e7d5b28e0044d852b95432da96d40215874e8eb30691d.
|
||||
@@ -0,0 +1,32 @@
|
||||
# Value readback and collapsible project groups
|
||||
|
||||
User-authorized scope: display original and actual readback Value in results/export; three independently collapsible, clearly colored project groups. Existing white layout and replacement/attribute rules remain binding.
|
||||
|
||||
Design: collect Value using a read-only report after existing restore/save verification. Bind reports to the exact job/state and persist structured values in task events before the next queue item starts. Missing historical evidence displays “未记录”; do not derive actual Value from Part Label or a planned new value. Preserve existing five-column result parser callers through an optional detailed mode. The workspace/export use eight columns.
|
||||
|
||||
Sidebar groups: 正在替换 (blue), 未完成 (amber), 已完成 (green), including counts. Running and unfinished default expanded; completed defaults collapsed. Remember each group's preference. Only the active queue project is running; completed and validated already-target-only projects belong to completed. Failures/paused/unconfigured remain unfinished. Group headings do not select an engineering project or change execution order. Feedback moves projects between groups and refreshes terminal statuses.
|
||||
|
||||
- [x] Add failing structured Value parsing/report correlation tests and real WSH read-only report tests.
|
||||
- [x] Record and ingest Value readback, extend workspace result and Excel columns; preserve historical/failed-result honesty.
|
||||
- [x] Add collapsible groups, backgrounds, persistence and active-project updates with UI regression tests.
|
||||
- [x] Render actual results/group states, review, run relevant checks, build and verify portable beta.10.
|
||||
|
||||
Constraints: no actual user CAD project writes during verification; preserve old data and interrupted-write protections. No Git metadata is present.
|
||||
|
||||
## Steering and execution ledger
|
||||
|
||||
- User added corrupt-project cancellation/restart failure, then explicitly requested skip/no recovery for read failures, then immediate current-project Stop without waiting for COM. These are part of this delivery.
|
||||
- Read cancellation/runtime work was delegated under subagent-driven-development; Value/UI and final integration stayed in the parent. Read task limits: startup45s, no-progress45s +5s grace; cancel5s, bounded owned Quit/Job cleanup. Failed read sessions release before skip; no automatic failed-project retry.
|
||||
- Task reviews caught and resolved native CLI nonzero skip semantics, exact request/claim provenance for orphan termination, recovered Value reporting, first-project Running rendering and same-window old-round duplication. Reviewer usage limit prevented a final independent reread; parent finishes with regression and integration checks.
|
||||
- Immediate Stop uses one existing supervised engine per project. It durably protects only that project, exits owned processes, marks persistent manual_stop and leaves later projects unlaunched. Existing mixed/write interruption handling remains.
|
||||
|
||||
## Final verification — 2026-10-29
|
||||
|
||||
- Combined regression: **365 passed in 91.44s**, covering read/restart resource admission, real owned-process cancellation and forced Stop, isolated CAD lifecycle, native inventory handling, grouped UI, results/export, recovery evidence, real WSH Value reports, unchanged Value policy and packaging tests. Uses base Python with project/venv packages and offscreen Qt; does not open user CAD projects.
|
||||
- Initial concurrent build/regression run had one failure in the 1-second native-sidecar liveness timing test (364 passed). No monitor logic was changed to suppress it: the full monitor module passed 33/33, then the complete combined selection passed serially as above. Heavy concurrent build load is suspected, not proven, as the initial timing cause.
|
||||
- Actual Qt previews inspected at 1280 and 1400 widths: `build/beta10-workspace-1280.png`, `build/beta10-workspace.png`, `build/beta10-workspace-results.png`. Red current-project Stop remains visible in the compact bottom toolbar.
|
||||
- PyInstaller completed successfully; EXE FileVersion `1.2.0.10`, ProductVersion `1.2.0-beta.10`.
|
||||
- `tools/verify_packaged_runtime.py dist/DxPartReplace/DxPartReplace.exe build/beta10-frozen-check` passed with Python environment overrides removed. Actual frozen supervisor launched, process creation time read, owned desktop and process resources positively released, clean application exit recorded.
|
||||
- ZIP verified: 254 files, bundled Python DLL and native VBS present; VBS byte-identical to source; no `data/` user records; CRC test and SHA-256 sidecar match.
|
||||
- Deliverable: `dist/DxPartReplace-1.2.0-beta.10-Windows-x64.zip` (51,642,840 bytes), SHA-256 `ab4585e1580cbf638ccfab5e45cb8c44144619fafe55559095467553a8cc0151`.
|
||||
- Boundary: no real user DxDesigner project was replaced during verification. Existing developer-machine long-path fixture failures remain outside this change and are disclosed in the bundled instructions.
|
||||
@@ -0,0 +1,17 @@
|
||||
# Discovery fingerprint and signal ports
|
||||
|
||||
Evidence from `DxPartReplace-诊断-20261030-132517.zip`: the LDO_S2032_SOT23_1V5 native reader rejected the named `POWER_EN` symbol of type `in.1`. The fallback CAD reader opened the project and completed twice, each time returning ten component identities. The second native snapshot got `PermissionError` on `database/icdb.dat`; the same read-only CAD session remained alive. The task then failed in DiscoveryCache after its post-read fingerprint could not be verified. This indicates a locked/unreadable database; the bundle cannot prove which process held the lock. No CAD replacement occurred in this import.
|
||||
|
||||
Fix: recognize named in.1/out.1 ports independent of their names, retaining empty-reference, unique symbol-type, empty path, and paired-report count checks. For a post-discovery fingerprint that is unavailable, request release only from the active owned read-only CAD session after validating its matching project, session and closed-project/worker checkpoint. Recompute the entire fingerprint after confirmed release, then keep existing design-change, database-churn, equal-inventory, and cache-admission guards. A failed release or still-unreadable/changed project is not treated as valid; write sessions are never terminated by this path.
|
||||
|
||||
Diagnostic export: the supplied bundle reached the 512-file cap and omitted current task evidence, and application.log exceeded the per-file limit. Export a bounded redacted tail of the current application log, prioritize recently active tasks and recent batch sessions, and raise the still-bounded count to 4096 while retaining the existing 32 MiB and symlink/allowlist limits.
|
||||
|
||||
Tests: reproduce an owned CAD database lock, ensure real project modifications remain rejected, verify per-read database churn requires two equal inventories, verify failed cleanup is not cached, test the actual runtime checkpoint/ownership guard and write-session exclusion, cover POWER_EN and other named ports plus ambiguous symbol cases, and test bundle prioritization/tail redaction. No user CAD write during testing.
|
||||
|
||||
Steering: additionally recognize old Value's `_NC` and `_nc` as NC markers, using the existing `/NC` output convention, preventing duplicates, preserving original Value without a new Part Label, and rejecting longer tokens such as NC_OPTION. If a positively released read session still leaves the project unverifiable, report a released-project error so the BOM batch can continue with other projects.
|
||||
|
||||
The later `20261030-134255` bundle also shows the same final fingerprint error for BOB_XPON and CA_CARD_HIGH; several preceding projects passed and remaining rows were left unchecked. Its 512-file export cap omitted 485 records, so the exact underlying fingerprint issue for each project is not available. Do not assert they all have the same lock or are damaged. Port recognition is not tied to a project or fixed UID/name: named in.1/out.1 symbols with no Ref Designator are checked in both reports, including names with punctuation and non-ASCII text; unsupported or ambiguous cases still fall back to CAD. The existing CAD inventory handles no-reference objects generically across projects while retaining all addressable components.
|
||||
|
||||
Verification: 529 regression tests passed before the `_NC` and released-project reporting steering. Afterwards, 375 focused tests passed covering the modified NC flow, full actual VBS restoration on WSH fakes, cache safety, batch continuation, resource ownership, diagnostic export and UI. After further generalizing port-name characters, 73 impacted tests passed, including Chinese/punctuation names, ambiguous identities, actual WSH `_NC`, and verified-release skip behavior. The beta.12 VBS and final source differ only in the requested NC recognition regex. No real CAD engineering project was opened or written.
|
||||
|
||||
PyInstaller beta.13 build succeeded. Frozen supervisor, process identity and resource-release smoke passed with a fresh data root; ZIP CRC and SHA-256 sidecar passed, Python runtime included, source VBS matches bundled VBS, updated parser/cache modules archived, version 1.2.0.13, and no user data included. Deliverable: `dist/DxPartReplace-1.2.0-beta.13-Windows-x64.zip`, SHA-256 `855cffb0bfe3a3e98a2363ed22a4f612442905ea4b578c41a153b1f2a28a5fc2`.
|
||||
@@ -0,0 +1,11 @@
|
||||
# Power port identity during BOM inventory
|
||||
|
||||
Evidence: the supplied 11:29 diagnostic bundle for `LDO_1117_1V5` records a successful CAD open, followed by `inventory_read_component ... component identity is incomplete`. The native flat report rejects `POWER_IN`, whose symbol name is `in.1` and whose reference designator is blank. The native report also shows actual components including CP04 with `$1I44`. The exact CAD object with the incomplete identity is not recorded, so the CAD-side cause is not proven to be the same port.
|
||||
|
||||
Fix both causes without changing replacement or attribute rules: the native parser excludes only unambiguously identified POWER_IN/in.1 or POWER_OUT/out.1 named ports, and verifies that their counts match between both reports. Other malformed or ambiguous symbols continue to require CAD fallback. During CAD inventory, objects without a reference designator cannot be addressed by a BOM row and are excluded with logged details and a visible progress message. A nonempty reference with missing UID continues to fail. The wildcard inventory still collects all addressable components to detect duplicate references. A true missing UID is reported as an identity issue, not conclusively as a corrupt project.
|
||||
|
||||
Verification: use report fixtures based on the observed evidence, negative cases for conflicting symbol types and mismatched reports, real WSH tests using fake COM-shaped objects for the actual discovery routine, read-only recovery/cleanup tests, the existing Value/NC and native replace contract tests, and a frozen portable build. No actual user CAD project is opened or modified during automated tests.
|
||||
|
||||
Completed: 486 selected regression tests passed in 84.51s, including actual WSH execution of the discovery routine with named POWER_IN, a valid component, and a duplicate reference using another part. Tests verify missing UID for a real reference still fails, ambiguous named ports do not bypass checks, and released resources permit subsequent work. The extracted recovery-label test needed a stub for the existing Value-readback reporter; the real readback is separately covered by integration tests.
|
||||
|
||||
Compared the previous beta.11 bundled VBS with the current source: every routine outside the discovery subroutine and its new helper is identical after newline normalization. Frozen beta.12 passed the packaged supervisor/resource-release smoke check. ZIP CRC, version metadata, bundled Python, new VBS/source match, parser presence and SHA-256 sidecar all verified; user data is excluded. Deliverable: `dist/DxPartReplace-1.2.0-beta.12-Windows-x64.zip`, SHA-256 `083cf51bd37c6c9a34081d325bd5c8a8220b9c5d66de6eb389f5e92ccc10bf8c`. Actual user project and the precise CAD object missing UID/refdes remain to be checked on the target computer.
|
||||
@@ -0,0 +1,17 @@
|
||||
# Read and parser diagnostics
|
||||
|
||||
User request: record the parsing process so a later diagnostic export identifies the stalled stage. This is observability only; preserve parser acceptance, UID checks, replacement/property rules, cancellation and resource ownership behavior.
|
||||
|
||||
Implementation: bounded, best-effort JSONL traces plus an atomic last-stage snapshot beside existing native/discovery evidence. Record timestamp/PID/project, parser stages, tool exits, exact failing UID and report line context, CAD startup/worker stages, progress and stop/timeout/exit outcomes. Keep the main application log useful by recording supervised read progress and row/project report outcomes. Extend the diagnostic allowlist for these artifacts, worker status/output and existing native metadata; export sampled report context rather than full source reports or databases.
|
||||
|
||||
- [x] Add failing tests for invalid UID context, trace bounds/non-interference, real worker stage traces and diagnostic export.
|
||||
- [x] Implement parser and read-stage evidence, application summaries, bundle coverage.
|
||||
- [x] Run focused regressions and packaged runtime verification; build portable beta.11 and document how to reproduce/export.
|
||||
|
||||
No user CAD writes during verification. Trace I/O failure must never alter a business result or bypass resource cleanup.
|
||||
|
||||
Verification so far: 6 new targeted checks initially failed for missing tracing/progress/export, then passed. Read/runtime/diagnostic regression: 169 passed. Combined selection including UI, native ASCII parsing, stop/restart, service, unchanged Value/NC policy, real WSH reports and packaging: 413 passed in 82.62s. After adding report-header samples, reran all affected native-parser/reader/trace/export tests: 60 passed in 1.95s. No acceptance criteria or native VBS replacement code changed.
|
||||
|
||||
Final package verification: PyInstaller build succeeded. Frozen EXE runtime smoke passed using a fresh `build/beta11-frozen-check` with Python environment overrides removed; real owned supervisor/desktop resources released and clean exit recorded. Confirmed the new read_trace module is archived in PYZ, EXE FileVersion 1.2.0.11 / ProductVersion 1.2.0-beta.11. ZIP CRC test passed, Python runtime present, no user data included, native VBS byte-identical to source and SHA-256 sidecar matched.
|
||||
|
||||
Deliverable: `dist/DxPartReplace-1.2.0-beta.11-Windows-x64.zip`, 51,655,699 bytes; SHA-256 `bd4b50eaf2263ca28b86ea13548df6d3876e643ad52ee913d41d5f12f7c88087`. No real user CAD project opened or modified. Reproduce after upgrade and send the full diagnostic ZIP; old incidents cannot be retroactively traced.
|
||||
@@ -0,0 +1,9 @@
|
||||
# 用户停止与安全收尾(已批准)
|
||||
|
||||
用户已在本会话批准:普通停止冻结后续调度;未修改可取消;当前已修改项完成校验、保存、回读后停止;保存或修改结果不明保持保护,不自动重放或盲目保存/丢弃;关闭窗口等待收尾;强制结束必须由用户明确选择,记录中断并在重启后核验。
|
||||
|
||||
业务结果、应用正常退出、强制清理和物理资源状态分别记录。资源消失不抹去应用异常。保存中无进度超时进入等待/提示,不自动终止。提供明确确认的强制结束出口;其范围仅为本程序当前监督进程及自有 Job。
|
||||
|
||||
普通停止以当前替换项及其必要收尾为边界,不启动同工程下一项。保护记录、批次身份和进程创建时间核验继续有效。先保存中断证据再执行工具内强制终止;持久化失败时拒绝工具内强制操作并反馈错误。系统外强杀/掉电依赖已有写前保护与重启核验,不承诺可在终止时写入日志。
|
||||
|
||||
保持源码版本,不发布包、不关闭远端事故工单。真实工程验证只用全新副本。
|
||||
@@ -0,0 +1,20 @@
|
||||
# 物料替换工作区重构
|
||||
|
||||
## 已确认的产品行为
|
||||
|
||||
- 单工程和批量替换分别提供入口,共用原生替换、属性恢复和保存回读执行链。默认使用自有独立后台 CAD。
|
||||
- 固定白色界面、蓝色主按钮、柔和玻璃卡片。工程列表与当前工程器件明细分别成框。紧凑进度栏保留阶段、时间、进度、日志和诊断导出;详细阶段按需展开。
|
||||
- 支持总表、多份 CBB 分表及分表目录。先精确匹配路径,再按相对目录和唯一 CBB 名称匹配。冲突必须人工指定,不能猜测同名工程。
|
||||
- 每次重新读取当前库存。相同器件当前料号为旧料号则待替换,为目标新料号则禁用并标记已是目标,其他料号或身份不唯一则报错。一个 Excel 行多个位号分别判定。
|
||||
- 部分工程校验失败时,通过的工程可先保存执行;不确定 CAD 资源或保存结果继续阻断执行。
|
||||
- 删除只移出当前列表,历史证据保留;再次导入新建处理轮次,不能重放有未核验结果的旧操作。
|
||||
- 默认替换后 Value 来源为新器件有效 Part Label。属性不存在或空白时使用替换前快照中的旧 Value。旧 Value 的独立 NC/nc 或 /NC、/nc 标记同步到新 Value,避免重复追加;不把 NCM、NC_OPTION 判为 NC。旧 Value 样式按现有机制恢复。
|
||||
- 实际保存回读结果在独立结果页可见,不能把计划当实际成功。日志记录运行版本、工程、阶段、目标、异常编号、堆栈、阶段耗时和后台退出证据,支持导出诊断 ZIP。
|
||||
|
||||
## 工程约束
|
||||
|
||||
继续使用 Python 3.12 / PySide6,原生对话框与 Library Wins、器件身份和连接完整性检查保持。保留旧服务和旧数据兼容入口。不得在用户真实 CAD 工程上自动做开发测试;使用 VBS 替身、临时工程和 Qt offscreen 验证。
|
||||
|
||||
## 交付
|
||||
|
||||
当前源码目录无 Git 元数据,在同级保存修改前 ZIP。交付更新源码、可运行桌面程序与使用说明,标注实机 CAD 验证范围。
|
||||
@@ -0,0 +1,13 @@
|
||||
# Interrupted import recovery and workspace polish
|
||||
|
||||
The user authorized fixing CBB import after a forced exit and improving the existing white workspace. Existing decisions remain binding: project list in the sidebar, large component table, compact progress, persistent history, original replacement and Value/NC rules.
|
||||
|
||||
Recovery runs under the existing exclusive supervisor lease before launching another native batch. Recheck exact process identities, reconcile abandoned supervisor journals, retain all interrupted-write markers, and release only resources proven inactive. A dead supervisor plus exited recorded workers/CAD and an empty private desktop can be reconciled without requiring the obsolete owner to publish a final handle-close certificate. Live or unreadable ownership stays blocked with an actionable message. Never delete project databases or replay replacement work.
|
||||
|
||||
Explicit resource recheck uses the same local reconciliation path rather than creating another cleanup supervisor. The UI reports pending versus released resources accurately. Diagnostics retain the underlying error; the banner presents a short actionable description.
|
||||
|
||||
Visual changes refine the existing layout: neutral white cards, clearer navigation and project selection, compact header/controls, muted project metadata, accessible table text and a compact status badge. No dark mode or larger progress area.
|
||||
|
||||
Approaches: deleting protection files would lose uncertainty evidence; always requiring manual cleanup reproduces the reported dead end. Automatic evidence-based reconciliation is selected within the user's existing authorized recovery scope.
|
||||
|
||||
Validation uses synthetic persistent crash records, real Windows supervisor child processes without CAD, mocked Win32 observations for empty/live desktop cases, existing safety tests, UI rendering, and portable packaging. Real project writes are not part of validation.
|
||||
@@ -0,0 +1,25 @@
|
||||
# V1.1.4 Beta 3 现场复测包构建记录
|
||||
|
||||
用户在实现验收后授权“压缩发布一版本发给工单回去测试”。本轮交付为工单 #1/#3 的 Beta 复测包,不将此前未满足的严格现场条件写为已解决,不自动关闭工单。
|
||||
|
||||
## 发布构建
|
||||
|
||||
版本字符串 `1.1.4-beta.3`,Python 项目版本 `1.1.4b3`,Windows 文件版本 `1.1.4.3`,Windows 预发布标志启用。
|
||||
|
||||
- `packaging/Build-DxPartReplace.ps1` 退出码 0,源码发布门禁 **889 passed**,195.14 秒;一条既有 pywinauto STA 警告。原始构建输出:`build/release-1.1.4-beta.3-build.log`。
|
||||
- 打包配置与验收脚本检查 **17 passed**,6.11 秒。
|
||||
- 构建门禁在完整冻结 EXE 中启动独立批次监督进程,读取真实进程创建时间,确认 Job/进程/桌面释放,再完成 GUI 启动和正常退出检查。
|
||||
- EXE SHA256:`df08cd328f6f4c9019f232c845e09627551e7b2d24790a466d53efcd291622d1`。
|
||||
- 与上一实现验收候选 `f38411a2…` 比较 91 个冻结 `dx_productivity` 模块,只有 `version` 模块变化;应用入口一致。比较递归标准化 code filename 后的 Python code object,不以时间戳或文件名推断源码一致。
|
||||
|
||||
完整实现、两工程替换和故障注入的候选哈希及范围见[实施验收](2026-10-23-issue-3-safe-recovery.md)。本轮没有对已完成工程重放替换。
|
||||
|
||||
## 压缩与分发校验
|
||||
|
||||
便携包只从发布 EXE、完整 `_internal` 和仓库教程组装,附空白 11 列 BOM 模板、窗口 GIF、清单;不从运行目录打包 `data`、工程、数据库或现场日志。
|
||||
|
||||
发布准备脚本校验冻结模块与当前源码、应用入口、两份 VBS 的一致性,生成程序文件 SHA256 清单。ZIP 校验 CRC、解压路径和所有程序文件哈希,再在清除源码 Python 环境变量后运行解压出来的完整 EXE。具体 ZIP 大小、SHA256、文件数与解压启动结果记录在发布附件 `release-manifest-1.1.4-beta.3.json`,公开校验文件为 `SHA256SUMS-1.1.4-beta.3.txt`。
|
||||
|
||||
先上传为草稿,下载回验全部附件的大小和 SHA256,再标记为 Beta 预发布。工单回复包含版本、下载地址、复测步骤和诊断包反馈入口;工单保持打开。运行时 API 返回与下载校验留存于 `build/release-1.1.4-beta.3`,不将认证凭据写入文件或输出。
|
||||
|
||||
发布说明:[V1.1.4 Beta 3](../releases/v1.1.4-beta.3.md)。尚未覆盖的系统组合、原工程和现场持有者问题继续以该说明为准。
|
||||
@@ -0,0 +1,27 @@
|
||||
# Issue 3:外部 OpenDesktop 句柄实机验收
|
||||
|
||||
2026-10-23,在 Windows 本机运行 `python tools/probe_external_desktop_holder.py`,退出码为 0。探针使用真实 `BatchCadRuntime` / `PrivateDesktop`,只创建独立 Python 持有者,不启动 CAD,不打开工程,不执行替换。
|
||||
|
||||
真实证据保存在 `build/issue-3-external-holder/run-d0a0af0e6a154c65910fb5f29a645e61/evidence.json`,同时保留该目录下真实 `data/batch-resources/*/session.json`、`business-result.json` 和资源释放日志。每次运行创建全新的 `run-*` 目录,避免覆盖既有证据。
|
||||
|
||||
本次探针 PID 为 37744;桌面为 `dx-d346d3ab310f470c86ffd9d32ccbef4a`;独立持有者 PID 为 18136,使用 `OpenDesktop(..., DESKTOP_READOBJECTS)` 获得句柄 412。桌面所有者记录句柄 552 的创建与成功关闭,包含 PID 37744、原生线程 ID 22468。持有者仍在默认桌面,无测试窗口。
|
||||
|
||||
| 检查 | 实机结果 |
|
||||
| --- | --- |
|
||||
| 首次批次清理 | 自有桌面句柄关闭,但枚举仍发现桌面;等待 5 秒后 `blocked` |
|
||||
| 残留窗口 | `remaining_windows=[]`,仍然阻断,没有据此推断资源已释放 |
|
||||
| 持有者存活 | 首次失败与持有期间资源重试后,持有者均仍在运行 |
|
||||
| 新批次门禁 | `BatchCadRuntime.__enter__` 抛出 `batch_resources_pending`;候选批次 generation=0,未创建桌面 |
|
||||
| 持有中仅重试资源 | `cleanup_pending_resources` 再次确认阻断,没有启动 CAD 或业务操作 |
|
||||
| 持有者自行释放 | 通过探针持有的 stdin 发送 `release`;持有者调用 `CloseDesktop`,正常退出码 0 |
|
||||
| 释放后仅重试资源 | `cleanup_pending_resources` 返回空元组,session 状态为 `released`,桌面枚举确认消失 |
|
||||
| 业务结果 | 合成的已核验 `business-result.json` 逐字节保持一致;内存业务结果亦保持一致 |
|
||||
| CAD 与重放 | CAD 工厂调用次数 0;`cad_start_requested=false`、`cad_pid=null`、`processes=[]`;没有业务重放入口调用 |
|
||||
| 输入桌面 | 前后一致,未切换输入桌面 |
|
||||
| 释放后的准入 | 后续批次可通过准入检查,但探针不启动其桌面/CAD或业务 |
|
||||
|
||||
业务结果前后 SHA256 均为 `80507674ce6b5c1d11419bd6e7b2fdfea3c5a6697cb01d628abf232615e9dc7e`。本轮总耗时 10.609 秒,主要为两次有界的 5 秒释放确认。
|
||||
|
||||
诊断中的外部持有者仍为 `unknown`,未识别具体外部句柄持有 PID。上述 PID 18136 仅由探针自身创建进程返回值与辅助进程握手确认,不能视为产品诊断识别能力。空窗口列表也不能证明没有外部句柄持有者。
|
||||
|
||||
这轮覆盖的是资源门禁与资源清理 API 的真实 Windows 句柄路径。业务结果是独立合成验收夹具,不等同于真实 CAD 工程结果,也不替代打包 EXE 的交互验收。未修改 `src`。
|
||||
@@ -0,0 +1,33 @@
|
||||
# Issue 3:新版冻结 EXE 两次启动故障,最多恢复一次
|
||||
|
||||
2026-10-23,在 CAD 独占窗口运行 `tools/probe_frozen_startup_recovery.py --failures 2`,实机退出码 0。使用另一份全新 `Audio_D2128` 副本,不复用已完成替换或 postwrite 崩溃工程。未修改生产源码/VBS、未降低生产超时。
|
||||
|
||||
冻结 EXE SHA256 为 `3b6a8608bac9d88f93ac71487d5c32647af0894c639d624f380f60345d27d34a`,源码基线为 264fee5。本例入口仍为**源码非 GUI supervised parent + 冻结 worker/helper/VBS**;独立完整图读取为源码只读 inspector,在独立私有 CAD 中运行。
|
||||
|
||||
真实证据目录为 `build/issue-3-frozen-startup-recovery/run-275ef3111c8d423caa4242b9045e9c59`。
|
||||
|
||||
两次终止均使用同一安全约束:仅本轮 request/session/generation 的 CAD PID;核对 Windows 创建时间与拥有者记录相同、私有桌面相同、starting 状态、无 GUID/bootstrap/cad-ready、attempt=prepared;然后只终止该自有 CAD。未终止任何未知或外部进程。
|
||||
|
||||
| 检查 | 实机结果 |
|
||||
| --- | --- |
|
||||
| 第一代故障 | 自有 CAD PID 16192,创建时间 `2026-10-23 08:53:02.663000+00:00`,退出码 71 |
|
||||
| 第二代故障 | 自有 CAD PID 31544,创建时间 `2026-10-23 08:53:04.657000+00:00`,退出码 71 |
|
||||
| 提前退出检测 | reason=`owned private CAD exited during startup: exit code 71`,未等待 bootstrap 总超时 |
|
||||
| 故障阶段耗时 | 生产 `project_worker` 记录分别为 0.328 秒、0.250 秒;包含该阶段的启动/检测/本地清理,不是孤立检测函数的精确计时 |
|
||||
| 唯一预算 | execution generation=2;retries 只有一条且 `count=1`;第二次失败后任务 blocked/paused,无第三代 |
|
||||
| 两代 proof | 都保持 prepared;前后字节与 SHA256 不变;没有 mutation_possible |
|
||||
| 换代安全顺序 | 第一桌面确认消失、released_at 先于第二桌面创建 time_ns |
|
||||
| 业务执行 | 没有 `saved_ok`,未进入正式替换 |
|
||||
| 完整图对照 | before 与 after 结构完全一致:1 图页、57 器件、103 引脚,包括全部已读取属性、位置、方向、缩放、引脚编号/位置及 net UID/name |
|
||||
| RV05 | 仍为 `4100-CA0000-T7`、Value `0R`,没有修改 |
|
||||
| 清理 | 两代资源均确认释放,最终 session `released`,无 pending resources/supervisors |
|
||||
| 用户桌面 | 输入桌面未变化,自有 CAD 未成为前台或出现在输入桌面 |
|
||||
| 原始输入 | 原工程目录与中央库 LMC 哈希不变 |
|
||||
|
||||
第一代 prepared SHA256 为 `89ae4b40d87359a429f38afc9c653c39dab6722a8a2d2526d881aea8cec54f0e`;第二代为 `8d9fe3a23c1dfaf629db066dd6858f91c45103c4d08691f265f27fffa7e282da`。两者分别与自身执行前字节比较一致。
|
||||
|
||||
整个探针耗时 233.891 秒,包含两次独立私有 CAD 的完整图读取。此前旧 EXE SHA `4e251627…` 的同类第一代故障阶段耗时 120.187 秒;新版此处为 0.328 秒。不能把两轮探针总耗时直接视为性能对照:旧轮还完成了一次真实替换,本轮连续失败后没有替换。
|
||||
|
||||
主要证据为 `report.json`(`verified=true`)、`fault-observations.json`(两次准确身份与 prepared 快照)、`before.json`、`after.json`、`desktop-observation.json`、`data/batch-resources/*/session.json`(generation/retry/timings/release)及两代 attempt JSON。
|
||||
|
||||
本轮验证新版提前检测与一次恢复预算用尽后停止。旧 EXE 的首次故障后恢复成功并保存替换已在独立文档记录;没有再次对已完成工程运行替换,也没有将旧 EXE 成功结果改称为新版同一用例通过。完整 GUI 故障注入与机器掉电仍未覆盖。
|
||||
@@ -0,0 +1,38 @@
|
||||
# Issue 3:真实 native 写入后冻结监督进程硬退出
|
||||
|
||||
2026-10-23,`tools/probe_frozen_postwrite_crash.py` 在两份全新工程副本上运行,最终实机退出码 0。冻结 EXE SHA256 为 `3b6a8608bac9d88f93ac71487d5c32647af0894c639d624f380f60345d27d34a`,源码基线为 264fee5。本例是**源码非 GUI parent + 冻结 supervisor/helper/VBS**,不是完整 GUI 故障注入。
|
||||
|
||||
真实通过证据目录为 `build/issue-3-frozen-postwrite-crash/run-c26f51c28caf47e1bf3f612801af9f33`。工程 `Audio_D2128`、`Audio_T605A` 从原 checkout 样例分别复制;不触碰正常 UI、marker 写保护或启动恢复验收副本。生产意图均为 RV05 的 `4100-CA0000-T7 → 4100-CA0000-T0`。
|
||||
|
||||
测试 parent 使用 `TaskCenterService(supervised=True)`,仅在测试进程中覆盖 `_command`,使生产请求调用真实冻结 EXE `--batch-worker`。没有修改生产源码、VBS 或添加生产故障开关。
|
||||
|
||||
监视器仅接受第一任务 helper 原子发布的 `native_replace_applied` / `native_replace_verified` 报告,并同时要求非空 replaced UID、对应 attempt `mutation_possible`、execution session generation=1 / retries 为空、下一任务仍 pending、没有可信最终 business-result。随后打开 supervisor journal 中的进程,核对其 PID 与创建时间,在仍存活时仅硬退出该明确自有冻结监督进程。
|
||||
|
||||
本轮触发瞬间为:
|
||||
|
||||
- `stage=native_replace_verified`,`replaced_uids=["$2I2014"]`;没有使用 `native_replace_started` 冒充写后证据。
|
||||
- mutation marker 为 `mutation_possible`,SHA256 `7f7cfa6dd6cc991289e3e883a74d17e507a88424a44aee1ab818528047137502`。
|
||||
- supervisor PID 38916,创建时间 `2026-10-23 08:48:49.752000+00:00`,与 journal 身份一致。
|
||||
- batch ID `07a50287d6b840b3b160b35c035eb3f1`。
|
||||
|
||||
| 检查 | 实机结果 |
|
||||
| --- | --- |
|
||||
| 正写后硬退出 | 已触发;保存完整 native report、marker、队列及进程身份后 `TerminateProcess` 该自有 supervisor |
|
||||
| parent 业务反馈 | `supervisor_interrupted`;没有可信 business-result,不伪报成功 |
|
||||
| 自动重复 | session generation=1、retries 为空、唯一 attempt;没有重新执行业务 |
|
||||
| 下一任务 | 第一任务 running、第二任务 pending;第二工程没有执行 status 文件,执行前后目录完整文件哈希一致 |
|
||||
| 保护发布 | 两参与任务均保留 `reason=supervisor_interrupted` 的 uncertain.flag |
|
||||
| 重启边界 | 关闭原 parent 的 store 后,启动全新 Python parent 进程打开原数据目录 |
|
||||
| 新 parent 操作 | 只启动冻结 `cleanup_batch_resources` 请求;没有 BOM 或队列执行请求 |
|
||||
| 资源复核 | execution session `released`;supervisor journal `finished / outcome=interrupted` |
|
||||
| 业务保护 | 新 parent 启动与资源清理后,uncertain.flag 内容、mutation marker 字节及其 SHA256 均未变化 |
|
||||
| 外部输入 | 原始两工程目录与库 LMC 哈希不变 |
|
||||
| 桌面 | 所有自有 CAD 确认退出、私有桌面确认消失;输入桌面前后一致,自有 CAD 不成为前台 |
|
||||
|
||||
“第二工程未启动”指执行队列未进入第二任务;BOM 导入仍按生产流程读取两工程。通过轮首工程导入时 native CLI 曾遇到路径 `WinError 5`,生产流程转入只读私有 CAD 读取并完成库存核验。这发生在故障监视启用之前,未额外注入或修改生产处理。总耗时 187.343 秒包含这一导入路径。
|
||||
|
||||
首轮 `run-39fa3d839de54a748992f3c06e86f61c` 的测试监视器断言失败,仅发合作取消;第一任务正常保存后停止,第二任务 pending,没有硬退出。该轮保留为失败证据,不计为 postwrite 故障通过,也未重放或复用其已完成工程。旧监视器未记录具体断言栈,不能据此证明确切失败行。工具随后改进可正常变化阶段的等待处理,并保存详细异常栈;上述通过轮来自另一份全新副本。
|
||||
|
||||
主要证据:`postwrite-crash.json`(真实触发快照)、`report.json`(`verified=true`)、`restart-resource-recheck.json`(全新 parent 的 resource-only 验证)、`inputs.json`(第二工程执行前哈希)、`desktop-observation.json`、生产队列与资源 journal、原 uncertain.flag。
|
||||
|
||||
本例没有声称崩溃后的第一工程是完整成功结果,也未自动打开第一工程做修复或再次替换。真实 native 写入已经发生,最终保存/恢复结果缺少可信业务收尾证据,因此保留保护并等待人工核验符合预期。完整 GUI 硬退出、系统/机器掉电,以及任意时点崩溃仍不在本例覆盖范围。
|
||||
@@ -0,0 +1,32 @@
|
||||
# Issue 3:冻结监督进程中的首次 CAD 启动失败恢复
|
||||
|
||||
2026-10-23,运行 `tools/probe_frozen_startup_recovery.py --failures 1`,实机退出码 0。使用独立全新 `Audio_D2128` 副本,与正常 UI 验收及 marker 写保护验收目录隔离。
|
||||
|
||||
本轮冻结 EXE SHA256 为 `4e251627d1ed6f22786de6febec971f889b6b1f2f69c86f19ccdeebd0d41ed95`。该版本首次启动故障等待约 120 秒的行为如实保留;后续检测 CAD 提前退出的源码/EXE 优化不得套用本轮耗时。
|
||||
|
||||
本轮是**源码非 GUI parent + 真实冻结 worker/helper/VBS**。parent 创建 `TaskCenterService(supervised=True)`,测试中仅替换 `batch_supervisor._command`,使 BOM 与队列请求均启动该冻结 EXE 的 `--batch-worker` 模式。不修改生产源码、生产 VBS 或增加注入开关。完整图读取为独立源码只读 inspector,在独立私有 CAD 中运行。该混合入口不等同于完整 GUI 故障注入。
|
||||
|
||||
真实证据目录为 `build/issue-3-frozen-startup-recovery/run-b266b219d8374db3b926d8a24a7dcc2f`。
|
||||
|
||||
故障线程仅监视本轮 `execute_task_queue` 的 session/私有 CAD 记录。终止前交叉核对 batch/session/generation、桌面名、记录中的 CAD PID、进程创建时间、`state=starting`、无 GUID、无 bootstrap 绑定、无 cad-ready checkpoint,以及对应 `prepared` attempt。所有条件满足后,只终止该明确自有 CAD;不附着外部 COM,不终止未知或外部进程。
|
||||
|
||||
| 检查 | 真实结果 |
|
||||
| --- | --- |
|
||||
| 第一次自有 CAD | PID 40836,创建时间 `2026-10-23 08:32:26.507000+00:00`;确认尚未授权工程 worker 后终止 |
|
||||
| 第一次 attempt | `prepared` 保持不变;SHA256 `79c88c6b81d3488952aa154e50ef878cca1d68462cadb91e8ceb0bad5ea08737` 未变化 |
|
||||
| 第一次桌面 | `dx-3e9ef3b9fd75476d9e7b8825bc6172be` 释放确认成功 |
|
||||
| 安全换代顺序 | 第一代 `released_at` 早于第二代桌面 handle-create `time_ns`;观察第二代时桌面枚举中旧桌面已经消失 |
|
||||
| 第二代 CAD | PID 33116,创建时间 `2026-10-23 08:34:27.099000+00:00`,新桌面 `dx-89dbf9636ccd461db04a95ef1df03dfa` |
|
||||
| 重试预算 | execution session generation=2,项目 retries 只有一条且 `count=1` |
|
||||
| 正式业务结果 | 一次 `saved_ok`,任务 completed;没有重复完成或再次替换 |
|
||||
| 独立图对照 | 57 器件、103 引脚;56 个非目标器件完全一致;RV05 原 UID `$2I2014`、位置/方向/缩放与连接保持不变 |
|
||||
| 目标结果 | 料号 `4100-CA0000-T0`,Part Label `0R`,保留 native target 的 Value 属性不存在状态 |
|
||||
| 清理 | session `released`;所有自有 CAD 退出、桌面消失;无 pending resource/supervisor |
|
||||
| 用户桌面 | 输入桌面未变化;自有 CAD 未成为前台或出现在输入桌面 |
|
||||
| 原始输入 | 原始工程目录与中央库 LMC 哈希保持不变 |
|
||||
|
||||
本轮总耗时 349.859 秒,包含独立前后图读取。第一代 `project_worker` 耗时 120.187 秒,记录的重试原因为 `private CAD bootstrap timed out`;第二代 CAD 启动 18.188 秒,第二代 `project_worker` 89.750 秒。未降低生产超时,也未把等待失败降为成功。
|
||||
|
||||
主要证据:`report.json`(`verified=true`)、`fault-observations.json`、`before.json`、`after.json`、`desktop-observation.json`、两代私有 CAD 记录,以及 `data/batch-resources/*/{request.json,supervisor.json,session.json,result.json,business-result.json}`。
|
||||
|
||||
本轮只验证首次 prewrite 启动失败后安全恢复一次。连续两次启动失败、优化后提前退出检测的完整冻结重测,以及完整 GUI 故障注入不在本轮覆盖范围;postwrite 监督进程崩溃使用另外的新副本单独验收。
|
||||
@@ -0,0 +1,44 @@
|
||||
# Issue 3:真实写保护使 mutation marker 发布失败
|
||||
|
||||
2026-10-23,在 Windows 本机独占 CAD 验收窗口,使用全新复制的 `Audio_D2128` 工程运行源码生产 `TaskCenterService → execute_task_queue → QuickPartReplace.vbs → native_helper`。替换意图为 RV05 的 `4100-CA0000-T7 → 4100-CA0000-T0`,不勾选复制料号到 Value。中央库为 `mentor_lib.lmc`。未修改 `src`、生产 VBS 或根代理的 `build/issue-3-ui-acceptance`。
|
||||
|
||||
实际工作目录为 `build/issue-3-marker-failure/run-e361ef90cd1d4145b1c68cdfb067f4a6`。工程从原 checkout 的 `build/cbb-bom-import-live-20261015/projects/Audio_D2128` 单独复制。执行前检查没有其他 CAD 实机测试进程,并与冻结 UI 验收协调串行进行。
|
||||
|
||||
测试进程仅包装 `BatchCadRuntime._prepare_attempts`:生产方法返回并发布 `prepared` 记录后,对该 JSON 调用真实 `win32file.CreateFile`,以 `GENERIC_READ`、`FILE_SHARE_READ | FILE_SHARE_WRITE` 打开,明确不允许 `FILE_SHARE_DELETE`。该句柄不妨碍读取 prepared 记录,但阻止 helper 的 `os.replace` 原子发布。句柄保持到该次生产队列退出,并在 `finally` 关闭;没有添加生产故障开关。
|
||||
|
||||
实际证据:
|
||||
|
||||
| 检查 | 结果 |
|
||||
| --- | --- |
|
||||
| prepared 发布与读取 | 成功;真实测试句柄 1524,可读取原 JSON |
|
||||
| helper 首次发布 mutation marker | `PermissionError: [WinError 5]`,拒绝原子替换 |
|
||||
| 真实调用栈 | `run_native → mark_snapshot_mutation → mark_mutation_possible → _publish → os.replace` |
|
||||
| 原生提交边界 | 失败发生于 `mark_snapshot_mutation`,在原生 Replace 按钮 `click(...)` 之前 |
|
||||
| VBS 状态 | `awaiting_native_replace → batch_failed`,失败工程关闭且未保存 |
|
||||
| 队列结果 | `blocked`、`paused=true`,没有 `saved_ok` |
|
||||
| 重复执行 | `_prepare_attempts` 只调用 1 次;本批 `retries={}`;没有再次执行替换 |
|
||||
| 标记内容 | 保持 `state=prepared`,执行前后 SHA256 完全一致 |
|
||||
| 资源 | 批次 session 为 `released`;CAD 退出与桌面消失均已确认 |
|
||||
| 独立回读 | 私有 CAD 枚举工程全部图页,并读取所有器件属性、位置、方向、缩放及引脚位置、编号、net UID/name;前后结构化数据完全相同 |
|
||||
| 对照范围 | 1 图页 `Audio-D2128:S905L CVBS-LR`,57 器件,103 引脚 |
|
||||
| RV05 | UID `$2I2014`、料号 `4100-CA0000-T7`、Value `0R`,属性及两条引脚连接保持原样 |
|
||||
| 原始输入 | 源工程目录完整文件哈希与中央库 LMC 哈希保持不变 |
|
||||
| 可见性 | 输入桌面前后均为 Default;自有 CAD 未出现在输入桌面或成为前台 |
|
||||
|
||||
prepared 文件前后 SHA256 为 `a2ee4d65d953613c50fa14fb49a22159a7d4cc3b9c3685281ffb672962c41d17`。
|
||||
|
||||
native report 的 `stage=native_replace_started` 在源码中位于 marker 写入之前,不能仅凭该 stage 判断已提交原生修改。本轮以真实异常调用栈、prepared 标记未变化、未保存状态,以及完整原理图前后独立对照共同判定。
|
||||
|
||||
首轮工具错误地要求出现后置 VBS guard 文案 `durable mutation proof failed`。实际上 native helper 更早的 marker guard 已经失败,因此该工具文案断言退出码为 1;原始 `report.json` 保留此失败,未删除或改写。修正测试识别真实 helper `_publish/os.replace` 异常后,只对同一次已执行工程运行 `--verify-existing` 只读回读,退出码为 0;该分支没有导入或队列执行调用,没有重放业务。
|
||||
|
||||
主要证据文件:
|
||||
|
||||
- `report.json`:生产队列结果、唯一 attempt、真实拒绝删除共享句柄、prepared 前后哈希、原输入不变及首轮工具断言失败记录。
|
||||
- `data/tasks/*/quick-run/status.tsv` 与 `snapshot-*.tsv.native.json`:真实生产状态、WinError 5 与调用栈。
|
||||
- `data/batch-resources/*/session.json`:释放确认与空重试记录。
|
||||
- `before.json`、`readback-only/after.json`:完整结构化读取结果;JSON 对象内容比较一致,属性枚举顺序可能不同,不以文本字节哈希代替结构比较。
|
||||
- `readback-only/verification.json`:`verified=true`、`graph_identical=true`、`marker_unchanged=true`、`resources_released=true`、`business_replayed=false`。
|
||||
- 两阶段的 `desktop-observation.json`:真实 CAD 退出、桌面消失及前台/输入桌面观察。
|
||||
- `source-under-test.json`:本轮源代码与 VBS 哈希清单。
|
||||
|
||||
本例覆盖源码服务/队列/真实 VBS/helper/真实私有 CAD 的实际 Windows 写保护失败。通过测试进程包装方法实施故障注入,没有覆盖冻结 EXE 的同类注入;冻结 UI 正常流程由另一轮验收单独覆盖,不混记为本例通过。
|
||||
@@ -0,0 +1,102 @@
|
||||
# 工单 1/3:长路径与安全自恢复实施、验收记录
|
||||
|
||||
后续用户已授权提供 Beta 3 工单复测包,见[发布构建记录](2026-10-23-beta3-release.md)。下文保留实现阶段各候选的验证边界,不将现场未覆盖项改记为完成。
|
||||
|
||||
本轮在 `codex/issue-3-safe-recovery` 实施,不发布版本、不清除旧保护锁。工程与中心库原件只用于复制和哈希核对。
|
||||
|
||||
## 已实施
|
||||
|
||||
- 写入前记录改存 `data/batch-resources/<批次>/attempts/g<代次>/<尝试>/`。目录、原子写入和兼容入口预检在桌面创建前完成。Python 使用扩展路径,CAD/VBS 保留短路径或受控目录联接入口;身份仍用规范路径。
|
||||
- GUI 通过同一 EXE 的隐藏工作模式启动独立监督进程。桌面、CAD、CLI 和工作 Job 属于监督进程;GUI 只持有监督进程自己的 Job。SQLite 连接不跨进程传递。
|
||||
- 请求有版本、批次与尝试 ID、请求摘要、父子 PID/创建时间和一次性 claim。消息检查序号、代次;结果持久化后通知。缺失或不可信的写结果保留实际任务证据目录的保护标记,不从头执行。
|
||||
- GUI 修改与监督进程准入使用同一跨进程互斥。启动恢复持锁到 runner 初始化结束;已占用则只查询。监督进程构造 runner 时不再次执行启动恢复。
|
||||
- 业务结果在收尾前另存;资源失败保留结果。BOM 的两个预览引用均撤销,防止资源未安全释放时保存部分计划。界面分别显示首发错误与释放错误。
|
||||
- 持久化缓存绑定工程完整指纹与载荷摘要;损坏缓存隔离后重新读取。跨监督进程可复用命中的只读采集结果。
|
||||
- 日志分为 GUI、监督进程和逐批释放日志;资源记录包含自有进程创建时间、句柄归属与关闭结果。诊断包有大小边界并脱敏。
|
||||
- 正常关闭归档默认关闭。启用后使用现有回收站事务;未释放、保护或待核验任务保留。崩溃不归档。
|
||||
|
||||
## 安全裁定与审查
|
||||
|
||||
Ruling: 不为桌面残留创建更多桌面 — 释放未证实时保持阻断 — 外部持有者必须释放后才准入。
|
||||
|
||||
Ruling: 心跳丢失只记通信异常 — 不提供“未修改”证明 — 不能授权重放。
|
||||
|
||||
Ruling: 保持现有 Beta 2 版本标识,仅生成未发布验收产物 — 本轮没有发布授权 — 候选哈希和分支用于区分,不能与公开下载混用。
|
||||
|
||||
独立审查发现并修正:冻结 windowed EXE 没有 `sys.stdout`;保留请求可被重复调用;BOM 清理失败仍带预览;旧式任务保护根目录不一致;启动恢复只瞬时检查锁导致多窗口竞争。最后对 `f3d7423` 和 `c787ef3` 的独立复审未发现新增实质安全问题。
|
||||
|
||||
## 验收边界
|
||||
|
||||
本机 `LongPathsEnabled=1`,尚无关闭系统长路径支持且禁用 8.3 的独立 Windows 环境。扩展路径、真实深目录及强制兼容入口测试只能证明其覆盖的分支,不能替代该环境的完整冻结 EXE 验收。
|
||||
|
||||
工单原始多工程文件不齐备。报告回放只验证已有原生报告对应的行,不算原批量工程替换实机验收。故障注入中的替身测试与真实进程/CAD 测试分别记录,不相互替代。
|
||||
|
||||
外部持有者真实测试见 [独立记录](2026-10-23-issue-3-external-holder.md):保持阻断、持有者退出后仅资源清理恢复、业务结果未变化;产品仍不能识别任意外部持有者。不得据此宣称工单 1 根因已根治。
|
||||
|
||||
## 最终验证
|
||||
|
||||
最终源码整合回归:**896 passed,1 条既有 pywinauto STA 警告,205.29 秒**。命令为 `python -m pytest -q tests/v1_1 tests/trial_task_center/test_application.py tests/trial_task_center/test_service.py tests/trial_task_center/test_execution_safety.py tests/part_replace/test_verification.py`;原始输出在 `build/issue-3-final-source-regression.log`。工作树差异检查通过。
|
||||
|
||||
源码构建门禁 885 项通过。实际冻结深目录检查额外发现 `CreateProcess` 不能使用过长工作目录:首次 274 字符数据目录启动失败,保留在 `build/issue-3-frozen-deep`。修正为经过身份核验的兼容工作目录,并保留首发 transport error;22 项深目录/监督/结果相关回归通过。重建候选后,280 字符数据目录的完整 EXE smoke 成功启动监督进程,创建并释放桌面、Job 和自有进程;证据为 `build/issue-3-frozen-deep-report.json`。
|
||||
|
||||
未发布候选 EXE SHA256:`4e251627d1ed6f22786de6febec971f889b6b1f2f69c86f19ccdeebd0d41ed95`。完整交互证据保留在 `build/issue-3-ui-acceptance`,不是源码服务替代 UI。两份全新副本为 Audio_D2128 和 Audio_T605A,其中前者工程路径含中文、长度 287 字符。
|
||||
|
||||
| 完整 EXE 交互检查 | 结果 |
|
||||
| --- | --- |
|
||||
| 创建两任务、导出默认 11 列模板并填入替换项 | 通过 |
|
||||
| 含错误位号 BOM | 通过 2/失败 1/未检查 0;8.172 秒;未部分保存 |
|
||||
| 修正后 BOM | 通过 2/失败 0/未检查 0;4.891 秒 |
|
||||
| 资源与缓存 | 首次导入原生 CLI,两工程一个桌面、CAD 未启动;第二次命中持久化缓存,不创建桌面 |
|
||||
| 计划与搜索 | 四条目标记录,每工程仅 RV05 启用;RV11 未启用;搜索不改变批次范围 |
|
||||
| 顺序替换、保存、关闭重开回读 | 两任务 completed,每工程一条 saved_ok 事件;175.984 秒 |
|
||||
| 执行资源 | 一个桌面、一代会话、一次 CAD 启动,无重建;最终进程退出、句柄关闭和桌面消失均确认 |
|
||||
| 内部写前证据路径 | 两个 attempt JSON,规范路径最长 254 字符;迁移后不再随工程历史目录嵌套增长 |
|
||||
| 主桌面 | 独立观察未发现自有 CAD 成为前台或进入输入桌面,持续文件读取成功 |
|
||||
| 独立工程读回 | 每工程 57 器件、103 引脚;56 个非目标器件全部字段一致,目标的身份、位置和连接保持,RV05 新料号与 Value/Part Label 为预期值 |
|
||||
| 原件 | 两源工程整目录哈希不变,中心库 `.lmc` 哈希不变;未声称完成整个库目录前后哈希对照 |
|
||||
| 正常关闭与重开 | 归档开关默认关闭;两次正常关闭后两 completed 任务保留;重开仍能查看实际结果 |
|
||||
| 界面诊断导出 | 成功导出 30 个文件,包含释放日志,不包含 DB、工程、BOM、EXE 或中心库文件 |
|
||||
|
||||
与已记录的 Beta 2 同组 Audio_D2128/Audio_T605A、每工程 RV05、开启 Part Label→Value 的一次交互观测对比:
|
||||
|
||||
| 候选 | 执行总耗时 | CAD 启动 | 执行桌面创建 |
|
||||
| --- | --- | --- | --- |
|
||||
| 公开 Beta 2 的既有验收 | 209.406 秒 | 1 | 1 |
|
||||
| 本轮隔离监督候选完整 GUI 验收 | 175.984 秒 | 1 | 1 |
|
||||
|
||||
本轮另包含一个 287 字符工程路径。两次观测的缓存、机器负载及目录不同,没有统计重复,因此不能据此承诺稳定加速比例;主要收益是 GUI 与资源所有权分离,以及释放后独立复核。基线出处为 `2026-10-23-issue-2-frozen-runtime.md`。
|
||||
|
||||
独立读回证据为 `graph-before-report.json`、`graph-after-report.json` 和逐工程 `graph-read`;主桌面观察为 `desktop-observation-execute.json`。默认关闭证据为 `normal-close-report.json`。诊断探针曾在异步 ZIP 生成完毕前读取文件而失败,随后只读验证已完成的同一 ZIP 通过,未重新导出。
|
||||
|
||||
工单 BOM 报告回放为 `build/issue-3-bom-report-replay/report.json`:428 个原任务的副本中,仅现有 6 工程原生采集报告覆盖 31 行,20 通过、11 失败,与原行/工程/状态一致;0 资源创建、0 计划写入、原证据哈希不变。另有 406 行/96 工程缺少采集证据,未覆盖。
|
||||
|
||||
真实标记持久化失败检查见 [标记失败实机记录](2026-10-23-issue-3-marker-write-failure.md):生产 helper 因 deny-delete 持有句柄在原子发布时返回 WinError 5,唯一尝试终止,无 saved_ok;只读回读确认 57 元件、103 引脚完全一致。该故障注入以源码 parent/helper 运行,不替代冻结 GUI 的全部故障案例。
|
||||
|
||||
跨路径共享重试预算、不同工程独立预算以及真实子进程硬退出前后结果保护的证据边界见 [监督安全回归](2026-10-23-supervisor-safety-regressions.md)。
|
||||
|
||||
首次真实冻结启动故障恢复见 [冻结启动记录](2026-10-23-issue-3-frozen-startup-recovery.md):一代故障只重建一次,旧桌面消失后才创建二代,最终 saved_ok 恰一次且完整图对照通过。该实验发现 CAD 已退出后仍等待探针约 120 秒;后续 `264fee5` 在等待期间检查明确自有 CAD 的退出码,及时进入同一清理路径,未增加或绕过重试预算。新增用例先失败再通过,相关 65 项回归通过,独立审查确认没有跳过清理或复用死进程。
|
||||
|
||||
最后三行启动检测优化后的候选 SHA256 为 `3b6a8608bac9d88f93ac71487d5c32647af0894c639d624f380f60345d27d34a`,280 字符数据目录的冻结监督、Job/进程身份及桌面释放再次通过,证据在 `build/issue-3-final-frozen-runtime.json`。上表完整 GUI 交互属于前一候选 `4e251627…`,不能混淆两个产物的实测范围;之后的源码更改仅限 CAD 启动等待检测。
|
||||
|
||||
该候选的真实写后硬退出检查已通过,详见 [写后崩溃与仅资源恢复](2026-10-23-issue-3-frozen-postwrite-crash.md):在 `native_replace_verified`、明确 mutation marker 和自有监督 PID/创建时间均核对后终止监督进程;未知业务结果未伪报成功,无重试,第二工程仍 pending 且文件哈希不变。全新 parent 只请求资源清理,保护与 marker 字节保留。该例仍是源码非 GUI parent+真实冻结 supervisor/helper/VBS,不将其描述为 GUI 硬退出或掉电验收。
|
||||
|
||||
同候选 [连续两次启动失败实机记录](2026-10-23-issue-3-frozen-double-startup-failure.md) 通过:两次故障分别在 0.328/0.250 秒被检测,generation=2、重试 count=1,第二次失败后停止,没有第三代或 saved_ok。两个 prepared 记录字节不变,57 元件/103 引脚完整图前后一致。总 233.891 秒包含前后独立 CAD 图读取,不能把故障检测耗时当成全流程耗时。
|
||||
|
||||
## 最终路径补漏与冻结产物
|
||||
|
||||
`3367bb6` 只补扫描和归档的文件访问边界。受限长路径分支的 failing-first 测试证实:原扫描不能访问深工程,原孤立保护检测可能把没有 handoff 的受保护任务归档。修正后深工程可扫描,孤立保护任务 retained,保护文件未变化。30 项相关回归通过;独立审查确认公开路径身份、祖先/reparse/containment 检查未放宽。
|
||||
|
||||
该补丁后的最终未发布 EXE SHA256 为 `f38411a2d91f30461e1441249120b461a7f56ad3f2a0c4a0a95a817037fd9798`。最终冻结验证:
|
||||
|
||||
- 285 字符数据目录 smoke 通过真实监督、进程身份、Job 与私有桌面释放;`build/issue-3-final-path-frozen-runtime.json`。
|
||||
- 完整 GUI 在 296 字符数据目录扫描 302/152 字符工程路径,创建两任务并导出含两工程的 11 列默认模板;公开路径无扩展前缀泄漏,归档默认关闭,正常退出后任务保留,全程没有 CAD/私有桌面资源;`build/issue-3-final-scan-ui/report.json`。
|
||||
- 完整替换与故障注入对应上文注明的前两候选。最后三个模块只改扫描/孤立保护的 I/O,未再次重放已完成替换;不同候选的证据分别保留,不混写为同一个产物的整套验收。
|
||||
|
||||
## 未满足的严格验收条件
|
||||
|
||||
- 未取得 LongPathsEnabled=0 且 8.3 不可用的独立系统,不能宣称该组合环境完整冻结 EXE 验收完成。
|
||||
- 工单原工程的真实批量替换未覆盖,逐工程/原 Excel 行号见 [102 个原工程清单](2026-10-23-issue-3-uncovered-projects.md);其中 96 个连报告回放也未覆盖。
|
||||
- 工单 1 现场桌面残留的具体持有者仍未确定。新隔离设计与自有/人工外部持有者的释放测试通过,但不能宣称现场根因已根治。
|
||||
- 故障实机入口为源码非 GUI parent+冻结 worker/helper/VBS;没有完整 GUI 硬退出或掉电验收。原库只核对 `.lmc` 哈希,未完成整个库目录内容的前后哈希基线。
|
||||
|
||||
因此本轮代码与证据可审查,仍不标为“所有严格验收条件完成”,不自动发布版本或清除旧保护。
|
||||
@@ -0,0 +1,110 @@
|
||||
# 工单 BOM 原工程实机未覆盖清单
|
||||
|
||||
本清单按原 BOM 工程路径身份分组,只展示文件名与不可逆标识,避免发布客户目录。102 个有替换行的原工程均未取得可用于本轮完整实机替换的工程文件;其中 6 个仅有原生报告覆盖的 31 行回放。两个 Audio 全新样例的实机验收不能替代下列原工程验收。
|
||||
|
||||
其余 96 个工程的 406 行连报告回放也未覆盖。Excel 行号对应原 `reported-bom.xlsx`,不是删减后的新编号。
|
||||
|
||||
| 工程文件/路径身份摘要 | 原 BOM Excel 行 | 报告回放行数 | 原工程实机 |
|
||||
| --- | --- | --- | --- |
|
||||
| 1gphy_rtl8211f.prj · 9a3147d0e1 | 3, 4, 5, 6 | 4 | 未覆盖 |
|
||||
| 1gphy_rtl8211f_a.prj · 03b0761631 | 7, 8, 9, 10 | 4 | 未覆盖 |
|
||||
| 1gphy_yt8511c.prj · 2a63ba7f0c | 11, 12, 13, 14, 15 | 5 | 未覆盖 |
|
||||
| 2g5phy_gpy211.prj · 9f2961f1db | 30, 31, 32, 33, 34, 35 | 6 | 未覆盖 |
|
||||
| 2gphy_zx5201.prj · b704fb0870 | 16, 17, 18, 19 | 4 | 未覆盖 |
|
||||
| audio_d2128.prj · f5c5728ea2 | 37, 38, 39, 40, 41, 42, 43 | 0 | 未覆盖 |
|
||||
| audio_d2128_esd.prj · 0786c112bd | 44, 45, 46, 47, 48, 49, 50 | 0 | 未覆盖 |
|
||||
| audio_d2128_surge_esd.prj · 1326530805 | 51, 52, 53, 54, 55, 56, 57, 58 | 0 | 未覆盖 |
|
||||
| audio_t605a.prj · 6249e3b8e4 | 60, 61, 62, 63, 64, 65, 66 | 0 | 未覆盖 |
|
||||
| bob.prj · 1a40673ab4 | 67, 68, 69, 70, 71 | 0 | 未覆盖 |
|
||||
| bob_shield.prj · fc8d09c983 | 72, 73, 74 | 0 | 未覆盖 |
|
||||
| bob_xpon.prj · 943ccbc2f7 | 77, 78, 79 | 0 | 未覆盖 |
|
||||
| bt_rtl8761.prj · 6fdc0b230e | 80, 81, 82, 83, 84, 85, 86, 87 | 0 | 未覆盖 |
|
||||
| ca_card_high.prj · 6116093290 | 91, 92, 93, 94, 95, 96, 97 | 0 | 未覆盖 |
|
||||
| ca_card_low.prj · abd489c265 | 98, 99, 100 | 0 | 未覆盖 |
|
||||
| ca_nds_msd5s69.prj · 312be1ad3f | 101, 102, 103 | 0 | 未覆盖 |
|
||||
| dvbt_ocp.prj · 4c5e90a1be | 312, 313 | 0 | 未覆盖 |
|
||||
| dvbt_ocp_od_gate.prj · 7adda0c253 | 314, 315 | 0 | 未覆盖 |
|
||||
| ethernet_1g.prj · da6029740f | 322 | 0 | 未覆盖 |
|
||||
| ethernet_a.prj · 00d8b04fa6 | 324, 325 | 0 | 未覆盖 |
|
||||
| ethernet_a_emc.prj · ab351a144d | 326, 327 | 0 | 未覆盖 |
|
||||
| ethernet_v.prj · 1e78d4ad40 | 328, 329 | 0 | 未覆盖 |
|
||||
| ethernet_v_camera.prj · def269650f | 330, 331 | 0 | 未覆盖 |
|
||||
| fem_kct8529h.prj · 13586535a9 | 337, 338, 339, 340, 341, 342, 343 | 0 | 未覆盖 |
|
||||
| fem_sky85717.prj · 8c12fd9b42 | 353, 354, 355, 356, 357, 358, 359 | 0 | 未覆盖 |
|
||||
| ldo1117_to252.prj · 053f19cdcd | 367 | 0 | 未覆盖 |
|
||||
| ldo1117_to252_0.prj · 3c4b4ecc60 | 368 | 0 | 未覆盖 |
|
||||
| ldo1117_to252_a.prj · bbc4b07fe2 | 369 | 0 | 未覆盖 |
|
||||
| ldo1117_to252_b.prj · 1a1cdc8bfe | 370 | 0 | 未覆盖 |
|
||||
| ldo1117_to252_c.prj · 9f80a38c68 | 371 | 0 | 未覆盖 |
|
||||
| ldo1117_to252_d.prj · c5e2a54807 | 372 | 0 | 未覆盖 |
|
||||
| ldo_1117.prj · 4229b7c0a0 | 373 | 0 | 未覆盖 |
|
||||
| ldo_1117_1v5.prj · 3e886188ae | 374 | 0 | 未覆盖 |
|
||||
| ldo_1117_1v5.prj · ed5dace4ba | 375 | 0 | 未覆盖 |
|
||||
| ldo_1117_1v5.prj · 32c52f6437 | 376 | 0 | 未覆盖 |
|
||||
| ldo_1117_1v8.prj · 9ca917fe09 | 377 | 0 | 未覆盖 |
|
||||
| ldo_1117_1v8.prj · 009ab46382 | 378 | 0 | 未覆盖 |
|
||||
| ldo_1117_1v8.prj · fe1ea827e2 | 379 | 0 | 未覆盖 |
|
||||
| ldo_1117_3v3.prj · d594fc61a9 | 380 | 0 | 未覆盖 |
|
||||
| ldo_1117_3v3.prj · 56024698a7 | 381 | 0 | 未覆盖 |
|
||||
| ldo_1117_3v3.prj · 9a4d3ba5d0 | 382 | 0 | 未覆盖 |
|
||||
| ldo_1117_a.prj · 1c64ec79aa | 383 | 0 | 未覆盖 |
|
||||
| ldo_1117_b.prj · bcb4b4017a | 384 | 0 | 未覆盖 |
|
||||
| ldo_1117_c.prj · 8bcbbfbafe | 385 | 0 | 未覆盖 |
|
||||
| ldo_1117_d.prj · 546091705e | 386 | 0 | 未覆盖 |
|
||||
| ldo_s2032_sot23.prj · 65da610a4c | 392, 393, 394 | 0 | 未覆盖 |
|
||||
| ldo_s2032_sot23_1v5.prj · 986a46e1b8 | 395, 396, 397 | 0 | 未覆盖 |
|
||||
| ldo_s2032_sot23_1v5_a.prj · 65333edf53 | 398, 399, 400 | 0 | 未覆盖 |
|
||||
| ldo_s2032_sot23_1v8.prj · 151ac70306 | 401, 402, 403 | 0 | 未覆盖 |
|
||||
| ldo_s2032_sot23_1v8_a.prj · d65baa1d59 | 404, 405, 406 | 0 | 未覆盖 |
|
||||
| ldo_s2032_sot23_1v8_b.prj · f43fc74710 | 407, 408, 409 | 0 | 未覆盖 |
|
||||
| ldo_s2032_sot23_2v5.prj · 3b8ebfee28 | 410, 411, 412 | 0 | 未覆盖 |
|
||||
| ldo_s2032_sot23_2v5_a.prj · 76a6f10c07 | 413, 414, 415 | 0 | 未覆盖 |
|
||||
| ldo_s2032_sot23_a.prj · 9afe3eed88 | 416, 417, 418 | 0 | 未覆盖 |
|
||||
| ldo_wl2811ea_sot23_1v5.prj · 03b146975a | 419, 420, 421 | 0 | 未覆盖 |
|
||||
| ldo_wl2811ea_sot23_1v8.prj · 9152c392ee | 422, 423, 424 | 0 | 未覆盖 |
|
||||
| ldo_wl2811ea_sot23_2v5.prj · b701d5b2e4 | 425, 426, 427 | 0 | 未覆盖 |
|
||||
| ldo_wl2811ea_sot23_adj.prj · c9f627eb7d | 428, 429, 430 | 0 | 未覆盖 |
|
||||
| lnb_mp8124.prj · c10e7bd2c2 | 437, 438, 439, 440, 441 | 0 | 未覆盖 |
|
||||
| lnb_mp8124_nodec.prj · 3a4685a09b | 432, 433, 434, 435, 436 | 0 | 未覆盖 |
|
||||
| lnb_tps65233.prj · 7cebbb12e6 | 442, 443, 444, 445, 446, 447, 448 | 0 | 未覆盖 |
|
||||
| mos-integrated-nmos.prj · bb34f6614a | 450 | 0 | 未覆盖 |
|
||||
| nandflash_bga63.prj · 31807ad105 | 461, 462 | 0 | 未覆盖 |
|
||||
| nandflash_tsop48.prj · 3b2f668c42 | 463 | 0 | 未覆盖 |
|
||||
| nor_flash_sop8.prj · 2aa42f724f | 464 | 0 | 未覆盖 |
|
||||
| ovp_circuit.prj · 0219c48734 | 518 | 0 | 未覆盖 |
|
||||
| pef7071_phy.prj · 008a1a6507 | 20, 21, 22, 23, 24, 25, 26, 27 | 8 | 未覆盖 |
|
||||
| rtc5638he.prj · 778fb484d5 | 344, 345, 346, 347, 348, 349, 350, 351, 352 | 0 | 未覆盖 |
|
||||
| rtl8197x.prj · 86fcfef21c | 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529 | 0 | 未覆盖 |
|
||||
| sd_card_high_cost_esd.prj · cda8210a8c | 530, 531, 532 | 0 | 未覆盖 |
|
||||
| sd_card_low_cost_esd.prj · ef0d2bb5f5 | 533, 534, 535 | 0 | 未覆盖 |
|
||||
| sensor_gc2063_sc3335_sc200ai.prj · 981cd40966 | 536, 537, 538 | 0 | 未覆盖 |
|
||||
| speaker_class-d-audio-amplifier.prj · 206b1c3026 | 539, 540, 541 | 0 | 未覆盖 |
|
||||
| spi_nand_flash.prj · fafa5d4252 | 542 | 0 | 未覆盖 |
|
||||
| t18250_in_loop_filter_shield.prj · e4f2dc6748 | 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553 | 0 | 未覆盖 |
|
||||
| telephony_interface_voice_si32192.prj · 24086dd2ab | 554, 555 | 0 | 未覆盖 |
|
||||
| telephony_interface_voice_si32280.prj · 178a144ca1 | 556, 557, 558, 559, 560, 561, 562, 563, 564 | 0 | 未覆盖 |
|
||||
| tuner+demod_dvb-c_m88rc6800.prj · 0f840071d7 | 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575 | 0 | 未覆盖 |
|
||||
| tuner_atbm253.prj · 110dc6f5c0 | 587, 588, 589, 590, 591 | 0 | 未覆盖 |
|
||||
| tuner_demod_mxl248.prj · 26594f8a75 | 577, 578, 579, 580, 581, 582, 583, 584, 585, 586 | 0 | 未覆盖 |
|
||||
| tuner_demod_mxl248.prj · e299962e81 | 592, 593, 594, 595, 596, 597, 598, 599, 600, 601 | 0 | 未覆盖 |
|
||||
| tuner_mxl608_shield.prj · cf17607708 | 602, 603, 604, 605, 606, 607, 608, 609, 610 | 0 | 未覆盖 |
|
||||
| tuner_r58150.prj · 537ed3b2c1 | 611, 612, 613, 614, 615, 616 | 0 | 未覆盖 |
|
||||
| tuner_r836.prj · cca63e4916 | 617, 618, 619, 620, 621, 622, 623 | 0 | 未覆盖 |
|
||||
| tuner_r836_a.prj · e41cc11d66 | 624, 625, 626, 627, 628, 629, 630 | 0 | 未覆盖 |
|
||||
| tuner_r836_h_cbb.prj · 882836fa9e | 631, 632, 633, 634, 635, 636, 637, 638, 639, 640 | 0 | 未覆盖 |
|
||||
| tuner_rda5815_dip+snaky_lines.prj · 78145e0625 | 641, 642, 643, 644, 645, 646, 647, 648 | 0 | 未覆盖 |
|
||||
| tuner_rda5815_double_tuner.prj · 662d874266 | 649, 650, 651, 652, 653, 654, 655, 656 | 0 | 未覆盖 |
|
||||
| tuner_rda5815_smd+gdt+filter.prj · 6f23c09e9e | 657, 658, 659, 660, 661, 662, 663, 664 | 0 | 未覆盖 |
|
||||
| tuner_rda5815_smd+gdt.prj · 9583c3ea34 | 679, 680, 681, 682, 683, 684, 685 | 0 | 未覆盖 |
|
||||
| tuner_rda5815_smd+snaky_lines.prj · e08bababf6 | 504, 505, 506, 507, 508, 509, 510 | 0 | 未覆盖 |
|
||||
| tuner_rda5815_smd+snaky_lines.prj · f9a967caf1 | 665, 666, 667, 668, 669, 670, 671 | 0 | 未覆盖 |
|
||||
| tuner_rda5815_smd+snaky_lines_a.prj · 6b2d71dc48 | 490, 491, 492, 493, 494, 495, 496 | 0 | 未覆盖 |
|
||||
| tuner_rda5815_smd+snaky_lines_a.prj · 5e6177a7de | 497, 498, 499, 500, 501, 502, 503 | 0 | 未覆盖 |
|
||||
| tuner_rda5815_smd+snaky_lines_a.prj · fd2fe146f9 | 672, 673, 674, 675, 676, 677, 678 | 0 | 未覆盖 |
|
||||
| tuner_t18250.prj · 72c882b7d6 | 686, 687, 688, 689, 690, 691, 692, 693, 694 | 0 | 未覆盖 |
|
||||
| wifi-8192fr-2l.prj · be5eb866d0 | 722, 723 | 0 | 未覆盖 |
|
||||
| wifi-rtl8188ftv-1t1r-2l.prj · e33a176a9b | 724, 725, 726, 727 | 0 | 未覆盖 |
|
||||
| wifi_8192er.prj · d5c71c558b | 729, 730, 731, 732 | 0 | 未覆盖 |
|
||||
| wifi_rtl8192fc.prj · d5b6659208 | 733, 734, 735, 736, 737 | 0 | 未覆盖 |
|
||||
| wifi_rtl8723du.prj · 88e300dc79 | 738, 739, 740, 741 | 0 | 未覆盖 |
|
||||
| xview.prj · 460b5b6322 | 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753 | 0 | 未覆盖 |
|
||||
@@ -0,0 +1,13 @@
|
||||
# Supervisor safety regression evidence boundaries
|
||||
|
||||
These automated tests do not open CAD or certify schematic property writes.
|
||||
|
||||
| Test | Real behavior exercised | Replaced behavior |
|
||||
| --- | --- | --- |
|
||||
| `test_mock_native_read_recovery_spends_same_project_worker_retry_budget` | Durable source hashes and attempt proof, runtime rebuild decision, shared native/worker project budget | Desktop/CAD ownership and worker failure |
|
||||
| `test_mock_different_projects_each_get_one_retry_without_accumulating_budget` | Two project identities, one rebuild per project, successful execution cannot replenish a spent budget | Desktop/CAD ownership and monitored worker execution |
|
||||
| `test_real_supervisor_process_crash_reconciles_without_replaying_mock_business` | Separate Python child, production admission and one-shot claim, process creation identity, hard `os._exit`, durable saved-result fallback, uncertainty protection at legacy/project-task evidence roots, separate cleanup child | Business replacement writes a durable witness instead of using CAD; no private desktop or CAD resources are acquired |
|
||||
|
||||
The process test covers both an unknown outcome before publication and a completed business result published before a crash. Cleanup must neither execute the witness operation again nor alter an earlier completed result. Unknown outcomes retain their original protection marker after reconciliation; proven completed outcomes do not acquire an uncertainty marker.
|
||||
|
||||
Remaining physical acceptance: inject failures in the frozen executable before and after the actual first CAD mutation, prove marker/helper durability failure prevents every production write/save path, and confirm actual CAD/desktop release and independent schematic readback. The tests above do not provide that evidence.
|
||||
@@ -0,0 +1,134 @@
|
||||
# Day0:保存、关闭、退出全链路排查
|
||||
|
||||
2026-10-26,北京时间。源码基线 `b9391015650bf5c43a77a017c5484e9a8f352266`。承接[资源事故分析](2026-10-26-day0-resource-release-analysis.md),本轮以核心应用完成条件为主线。
|
||||
|
||||
## 结论
|
||||
|
||||
发现并验证了四个具体的生命周期问题:
|
||||
|
||||
1. **CAD 主进程正常退出后,程序会立即终止 Job 中的剩余辅助进程,没有先给予其自然退出窗口。** 本机实测 `vnsd.exe` 再等约 0.813 秒即可自然退出;这个等待可以避免该次强制终止。
|
||||
2. **退出阶段的记录写入失败会跳过正常 Quit。** 随后仍进入自有进程清理。用生产退出控制流和替身 CAD 复现。
|
||||
3. **保存调用返回、工程关闭失败时,“已保存”标记仍可能没有设置。** 实际 VBS 函数配合替身 CAD 复现,说明保存与关闭的状态记录边界混在一起。
|
||||
4. **物理资源复核通过后,上层可能返回已完成业务结果,同时不再向调用方抛出正常退出失败。** 生产运行时记录可以出现 `cad_shutdown.clean=false`、资源状态 `released`、监督记录 outcome 为 `error`,但函数返回 completed 任务结果。日志证据保留,调用方的返回语义却丢失了退出异常。
|
||||
|
||||
这些问题与“只盯桌面释放”的分析不同:资源消失不能代表应用正常退出,更不能取代数据保存确认。
|
||||
|
||||
同时,两份全新工程副本的真实替换、保存、退出及新 CAD 实例独立回读均通过,未发现本轮保存数据丢失。上述问题不是已经证明的工单 #1 唯一根因;原附件中的 #1 属于读取后的收尾失败,#3 尚未启动 CAD。现场版本、实际触发路径和完整诊断仍须对照。
|
||||
|
||||
## 一、实机正常链路
|
||||
|
||||
使用已有 Audio_D2128、Audio_T605A fixture 的全新副本,生产服务入口执行 BOM 导入及两工程队列,每工程仅 RV05:`4100-CA0000-T7 → 4100-CA0000-T0`,保留原生目标 Value 策略。原始 fixture 未修改。
|
||||
|
||||
证据目录:`build/day0-resource-analysis-20261026/live-chain-bbd9fba7ce444e3d8e5627a6f4a385d0/`。汇总:`build/day0-resource-analysis-20261026/live-chain-summary.json`。进程时间线为同级 `live-chain-bbd9fba7ce444e3d8e5627a6f4a385d0-process-timeline.jsonl`。
|
||||
|
||||
| 检查 | 本次结果 |
|
||||
| --- | --- |
|
||||
| BOM 导入 | 2 行通过,3.875 秒 |
|
||||
| 顺序执行 | 两任务 completed,155.843 秒,共用一个执行 CAD |
|
||||
| 保存关闭图页调用 | D2128 约 0.32 秒,T605A 约 0.21 秒 |
|
||||
| 保存后的 CloseProject | 两次返回 True,耗时约 1.68 / 1.33 秒;均先观察到 ProjectClosed 事件,再观察到调用返回 |
|
||||
| 同实例重开回读 | 每工程完成内容核验后才发布 saved_ok,随后关闭工程 |
|
||||
| CAD 自然退出 | 本轮五个 CAD 实例(前读 2、执行 1、后读 2)主进程均正常退出码 0,无 CAD 主进程 terminate_request |
|
||||
| CAD 退出等待 | Quit helper 成功后的主进程等待约 0.234–0.390 秒,不是整个 Quit 的总耗时 |
|
||||
| 退出后的独立回读 | 每工程用新 CAD 实例读取;57 器件、103 引脚连接,56 个非目标器件不变,目标身份、位置、连接和目标料号正确 |
|
||||
| 原件 | 两个源工程目录哈希不变,中央库 `.lmc` 哈希不变;未宣称整个库目录全部文件无变化 |
|
||||
| 前台与资源 | 观察器未发现自有 CAD 进入输入桌面或成为前台,已记录 CAD 退出和桌面消失 |
|
||||
|
||||
这轮运行的是源码服务层、真实 CAD 和加入边界日志的 VBS 副本;没有修改生产源码。不是完整冻结 GUI/监督进程验收,时序日志可能增加少量开销,耗时不能作为性能承诺。
|
||||
|
||||
第一轮记录 `live-chain-366340e7a6a942ccadaf2e1eedd9c4f4` 因探针复制 VBS 时引入 UTF-8 BOM,导致第 1 行编译失败,替换前停止。该失败属于探针,不是产品故障;保留原记录和阻断状态,修正编码后使用另一组全新副本,未重放该次失败任务。
|
||||
|
||||
## 二、已验证问题与含义
|
||||
|
||||
### A. 辅助进程尚未自然退出,就调用 TerminateJobObject
|
||||
|
||||
位置:`isolated_desktop.py:380` 的 `_Win32Process.close`。处理顺序为:确认/停止根进程 → 收集后代 → **TerminateJobObject** → 最多等待 5 秒确认进程退出。因此这 5 秒是强制终止后的确认窗口,不是辅助进程正常收尾的宽限期。
|
||||
|
||||
两工程实机中五次 CAD 主进程退出后,Job 都仍有一个成员。原时间线的映像查询使用了本机 pywin32 未提供的函数,查询错误已保留;不能凭 PID 将五个成员全部命名。独立 CIM 快照将最后一次回读的 CAD PID 55500、子进程 PID 45368 对应到实际 `vnsd.exe`。
|
||||
|
||||
随后单独进行空 CAD 实验,改用 Win32 `QueryFullProcessImageNameW` 确认成员身份。仅推迟探针中对已正常退出 CAD 的 Job 清理,最长观察预算 75 秒,未打开任何工程:
|
||||
|
||||
- CAD PID 60332 正常退出码 0。
|
||||
- 此时 `vnsd.exe` PID 34960 仍存活。
|
||||
- 约 **0.813 秒**后该辅助进程自行退出,随后原清理函数运行时已没有需终止的后代。
|
||||
- 最终自有资源全部释放,桌面检查耗时 0 秒,整个关闭阶段约 2.625 秒。
|
||||
|
||||
证据:`build/day0-resource-analysis-20261026/empty-cad-descendants-9fd000b5f0af48dc82e12b6b034d2917/report.json`;探针 `probe_descendant_exit.py` 位于同级分析目录。
|
||||
|
||||
既有原生进程研究将 `vnsd.exe` 识别为许可证辅助程序,另有工程数据库 `iCDBNetServer.exe` 和交叉探查 `xprobSvr.exe`。本次空 CAD 仅验证 vnsd 的自然退出,不证明数据库提交被终止,也不证明它就是工单现场残留桌面的持有者。
|
||||
|
||||
建议方向:对已经正常退出的根进程,其明确自有的后代先进行有界自然退出等待;到期才进入可审计的强制清理。区分根进程、数据库辅助进程、许可证辅助进程;记录终止对象、原因及发生时的业务阶段。不能只把等待常量变大,也不能对不明进程进行清理。
|
||||
|
||||
### B. 收尾记录的 I/O 错误会改变应用退出方式
|
||||
|
||||
位置:`isolated_cad.py:207`。正常 Quit 前的 `_record(state='closing')` 与 Quit 在同一个 try 内,记录失败会直接跳入异常处理,接着 finally 仍关闭自有资源。
|
||||
|
||||
故障注入:仅让这一次 closing 记录写入抛 PermissionError,其他记录正常。结果为:没有发出 Quit;写入 uncertain;调用资源 close。真实 CAD 由替身代替,因此本项证明控制流缺陷,没有实际杀死用户 CAD。
|
||||
|
||||
含义:目录权限、同步软件/安全软件的文件访问冲突、磁盘问题等不只影响日志,还可能改变应用本来可以正常退出的路径。上述环境来源只是候选,没有确定具体软件责任。
|
||||
|
||||
建议方向:隔离诊断/资源收尾记录错误与正常退出协议;写前业务保护失败仍应禁止写入,但不能混同为“所有诊断写入失败都必须跳过 Quit”。退出请求仍须满足实例身份、工程状态等原有条件。
|
||||
|
||||
### C. 保存状态在工程关闭成功之后才记录
|
||||
|
||||
位置:`QuickPartReplace.vbs:934`。调用 `QPCloseBatchProject(TargetPath, True)` 返回后才执行 `QP_BatchSaveCommitted=True`;这个子程序内部既保存图页,又关闭工程。
|
||||
|
||||
用真实 `QPFinishBatchItem` / `QPCloseBatchProject` 函数与 CAD 形状替身运行:图页的 SaveChanges=True 调用已经返回,随后工程拒绝关闭。观察到 `save_called=True`、`commit_flag=0`、错误已抛出,没有发布成功 checkpoint。
|
||||
|
||||
因此,这个标记不能独立表达“保存已发出/可能完成,而工程关闭失败”。某些后续错误文案依赖它,可能把已涉及保存的故障描述为未保存。`failed_native_result_uncertain` 仍会依据原生修改证据阻断重试,本轮没有发现借此自动重放替换;问题主要在恢复判断所需的状态粒度和事实描述。
|
||||
|
||||
建议方向:拆分 save_requested、save_returned、saved_readback_verified、project_closed 等证据;保存请求开始后发生异常应保留“可能已保存”的状态,不能因 CloseProject 失败回退成“未保存”。
|
||||
|
||||
### D. 资源消失后,正常退出异常不再向调用方抛出
|
||||
|
||||
位置:`batch_supervisor.py:159` 的 `_finish_response`,及 `batch_resources.py:117` 的重查逻辑。
|
||||
|
||||
用生产 BatchCadRuntime 创建合法资源记录,替身 CAD 在退出时抛出 Quit 超时,已保存业务结果独立保留;模拟拥有资源的监督进程结束后,再调用生产资源复核及返回函数。结果:
|
||||
|
||||
- 会话先 blocked;物理桌面已不存在后变为 released。
|
||||
- `cad_shutdown.clean=false` 和 `orderly_shutdown` 异常仍保留在 JSON。
|
||||
- 监督记录 `state=finished`、`outcome=error`。
|
||||
- 调用方收到含 completed 条目的 TaskQueueResult,没有收到退出异常。
|
||||
|
||||
这是状态返回语义不一致,不是原始错误日志被删除,也不证明已独立核验的保存结果应当被作废。应保留正确业务结果,同时显式暴露“业务完成、应用异常退出/强制清理”的收尾状态,不能仅凭物理资源消失将异常归为恢复成功。
|
||||
|
||||
上述 B/C/D 复现实物:`build/day0-resource-analysis-20261026/fault-chains-907a534cc6bb441e8cddf7670dd04aac/`,脚本 `probe_fault_chains.py`。较早的临时探针曾因日志文件句柄尚未关闭而无法删除临时目录;后续改为保留独立证据目录并关闭日志句柄,此探针清理错误不计入产品结论。
|
||||
|
||||
## 三、仍需验证的高影响风险
|
||||
|
||||
| 风险 | 已知机制 | 尚不能断言的部分 |
|
||||
| --- | --- | --- |
|
||||
| 慢保存被当成无响应 | 保存前仅发一次阶段进度;默认 150 秒请求停止、300 秒判无响应,safe_stop=False 不阻止监督器升级。保存没有类似原生快照的进度旁路 | 没有真实慢保存达到 300 秒的实验,不证明现场曾在保存中被终止 |
|
||||
| Quit/关闭响应延迟 | Quit helper 20 秒;成功后 CAD 15 秒;checkpoint 20 秒;项目会话关闭另有 60 秒宽限 | 本次正常样例均未超过这些时限,不能据此证明大工程也安全或必须统一加长 |
|
||||
| 同实例回读可能不足以覆盖持久性 | 生产路径在同一个 CAD 实例中重开回读 | 本次新实例读回通过,未发现缓存掩盖丢失;仍缺断电、数据库服务异常和大型工程覆盖 |
|
||||
| 关闭工程返回值被忽略 | 本机 TypeLib 表明 CloseProject 返回 Boolean;VBS 常直接调用并用工程路径为空作为补充判断 | 本次调用均为 True,尚未观察到 False 且空路径的真实异常,不能将其直接确定为事故根因 |
|
||||
| GUI/监督进程异常终止 | Job 关闭会清理受控进程,不能保证正在进行的保存完成 | 正常点击关闭时 GUI 会等待当前 worker,不能把所有 GUI 关闭行为描述成直接杀进程。崩溃/强制结束另需故障实验 |
|
||||
| 数据库和跨进程协作收尾 | 既有研究存在 iCDBNetServer、xprobSvr 等进程;仅确认 viewdraw 退出不足以描述全部应用状态 | 本轮没有捕获这些服务器在未提交数据时被终止;不能把 vnsd 的观察套用成数据库丢失证据 |
|
||||
|
||||
## 四、厂商接口核对的重要限制
|
||||
|
||||
实际安装的 7.9.5 `viewdraw.tlb` 已离线核对,结果保存在 `cad-lifecycle-typelib.json`:
|
||||
|
||||
- `IVdApp.CloseProject` 返回 Boolean。
|
||||
- `IVdApp.Quit`、`IVdSchematicSheetDocument.Close(SaveChanges, FileName)` 返回 void,不能虚构它们有保存成功布尔返回值。
|
||||
- `IVdDoc` 有 Saved 属性,但不能据此假定当前 `IVdSchematicSheetDocument` 也有同样的属性契约。
|
||||
- 事件接口包含 BeforeDocumentSave、AfterDocumentSave、ProjectClosed。
|
||||
|
||||
真实 VBS 日志已订阅上述事件:本轮 ProjectClosed 被正常观测,但在两次 SaveChanges=True 路径中**没有观测到 BeforeDocumentSave/AfterDocumentSave**。因此不能因为类型库列出了保存事件,就把等待该事件直接设为当前原理图保存路径的必经条件。需要核实它适用的文档类型、接口和触发条件。
|
||||
|
||||
本轮读取的安装帮助未取得足以证明上述调用异步/同步持久化语义的详细契约。类型库提供方法签名,不能替代持久化保证。
|
||||
|
||||
## 五、验证与修改范围
|
||||
|
||||
本轮补充回归:
|
||||
|
||||
```text
|
||||
python -m pytest -q tests/integration/test_quick_value_modes.py tests/v1_1/test_project_session.py tests/v1_1/test_failed_native_recovery_guard.py tests/v1_1/test_supervisor_result.py tests/v1_1/test_ui_operation_lifecycle.py
|
||||
94 passed in 34.11s
|
||||
```
|
||||
|
||||
上一轮已执行 IsolatedCad 和 worker monitor 的 60 项验证,本轮不重复当成新结果。测试通过说明已有行为与保护仍按测试约定运行,不证明上述异常路径合理。
|
||||
|
||||
仅增加分析报告和 `build/day0-resource-analysis-20261026/` 下的诊断脚本/证据。生产 Python、正式 VBS、版本号及发布包未修改,未向远端工单发消息或关闭工单。
|
||||
|
||||
下一轮修改应优先针对已复现的四个问题,并保留原有身份校验、写前保护和禁止不确定重放。验收必须分别报告数据结果、工程关闭结果、应用退出方式、后代进程退出方式和最终资源状态,不能汇成一个“释放成功”。
|
||||
@@ -0,0 +1,140 @@
|
||||
# Day0:资源释放工单原因分析
|
||||
|
||||
日期:2026-10-26(北京时间)。严重级别依据用户本次升级说明;未修改远端工单标签或状态。分析源码基线:`b9391015650bf5c43a77a017c5484e9a8f352266`。
|
||||
|
||||
后续已完成[核心应用生命周期专项排查](2026-10-26-application-lifecycle-investigation.md):包含两工程真实保存与独立读回、vnsd 自然退出对照及三类异常控制流复现。后续结论以该记录注明的证据和边界为准。
|
||||
|
||||
## 判断
|
||||
|
||||
工单 #1 的现场根因仍未闭环。根据用户对核心应用生命周期的补充,排查主线调整为“业务操作完成 → 保存确认 → 工程关闭确认 → 应用正常退出 → 进程及辅助资源释放 → 桌面回收”。桌面是隐藏操作的基础设施,其消失不能替代业务完成或进程正常退出证明。第一轮对桌面末端症状的侧重不足以覆盖保存与异常退出风险。
|
||||
|
||||
对已经观察到的桌面残留,需要继续追查自有清理范围以外的引用,包括本程序未登记的额外引用、无窗口线程、其他进程持有的桌面句柄和由系统或服务创建的辅助进程。这里的“范围以外”不等于已经证明是第三方软件造成,也不能将其提前确定为整个事故的业务根因。
|
||||
|
||||
工单 #3 在 CAD 未启动时出现同类残留,说明 CAD Quit 或 COM 释放不足不能解释全部现场现象。两个工单具有相同末端症状,但尚不能断言具体持有者或底层根因相同。
|
||||
|
||||
Beta 3 的进程隔离、批次复用和资源复核覆盖了部分故障机制。产品仍缺少现场持有者的完整识别能力,缺少对应现场版本的复测成功回执,不能凭本机通过将事故关闭。
|
||||
|
||||
## 补充核查:核心应用完成和退出链路
|
||||
|
||||
本节优先于后文仅针对桌面残留的原因排序。关闭桌面句柄不会自动结束进程;当前实现实际先清理受控进程、再关闭桌面句柄。应分别证明数据保存成功、工程关闭成功、应用正常退出、强制终止是否发生和资源是否消失。
|
||||
|
||||
### 正常路径已有保存回读,但完成语义仍需核实
|
||||
|
||||
- `QuickPartReplace.vbs:863` 的 `QPCloseBatchProject` 调用 `Document.Close(True, "")` 保存关闭图页,随后调用 `CloseProject`,立即查询工程路径为空。
|
||||
- `QuickPartReplace.vbs:934` 起会重新打开同一工程、校验目标及非目标内容,之后才给出 `saved_ok`。不能把现有程序描述为“完全没有等待或没有保存核验”。
|
||||
- COM 调用返回是现有的等待边界,但当前函数没有单独的保存完成事件、持久化提交状态或忙碌状态等待。是否需要增加这些机制,必须核对该版本 CAD 的 API 契约及真实行为;不能仅因缺少 sleep 就断言保存是异步或保存未完成。
|
||||
- 生产路径是在同一个 CAD 实例中重开工程进行回读。这提供了内容核验,但若要证明进程退出后的持久性,应增加正常退出后的独立新实例读取实验,并核查实际数据库服务的提交语义。不能仅凭同实例回读断言存在缓存问题,也不能将开发验收中的独立回读当成每次生产执行都有此保障。
|
||||
- 图页/工程关闭后立即查询一次状态,没有针对“调用已返回、关闭状态稍后才就绪”的有界状态等待。若厂商允许这种延迟,可能把仍在正常收尾的应用判为失败;目前还没有确认其 API 是这种行为。
|
||||
|
||||
### 明确存在的风险路径:应用未确认正常退出时进入强制清理
|
||||
|
||||
`isolated_cad.py:207` 的退出流程为:Quit helper 最多等待 20 秒;helper 成功才进一步等待 CAD 进程最多 15 秒。Quit helper 超时或失败时会跳过这次 CAD 正常退出等待,记录 uncertain,然后仍执行 `desktop.close()`。在批次模式中这里首先是 lease 的进程清理,随后才是批次拥有者的桌面关闭;底层 `_Win32Process.close()` 对存活自有进程/Job 有终止逻辑。
|
||||
|
||||
因此存在需要验证的链路:应用仍忙或关闭被拒绝 → 固定时限/单次状态检查失败 → 保护标记 → 强制终止自有进程 → 后续桌面释放检查。保护标记能避免无依据重放,不能保证被终止前未完成的保存可以安全完成。强制终止后的“资源清理成功”也不能用作“业务正常完成”的证据。
|
||||
|
||||
Quit helper 在发现工程仍打开时会拒绝退出,避免隐式保存或丢弃;但外层依然会进入自有进程清理兜底,所以必须检查当时是否有未完成的写操作。业务状态、退出方式和资源状态需要分开判断。
|
||||
|
||||
### 保存期间的无进度监控需要专项验证
|
||||
|
||||
`QuickPartReplace.vbs:874` 在进入保存关闭前发出一次 `save_and_close` 进度。若后续阻塞在 COM 调用中,脚本不能继续发送阶段进度。当前原生侧进度旁路只处理 `native_snapshot_read`,没有相同的保存进度旁路。
|
||||
|
||||
默认无进度时限为 150 秒。`ProgressWatch.action()` 在 150 秒请求停止、300 秒判定 unresponsive;这个判定不因 `safe_stop=False` 而停止升级。VBS 会在安全边界才响应协作停止,但监督器仍可在后续超时中终止 worker,并进入 CAD 收尾。真实慢保存是否能达到这个条件尚未实测;普通进程存活或无条件心跳也不能当成保存正在推进的证据。
|
||||
|
||||
### 本轮验证与证据边界
|
||||
|
||||
- `python -m pytest -q tests/v1_1/test_isolated_cad.py tests/trial_task_center/test_worker_monitor.py`:**60 passed,16.22 秒**。包括控制流替身和真实辅助进程测试,没有真实 CAD 慢保存实验。
|
||||
- 对生产 `IsolatedCadSession` 注入模拟 Quit helper 超时:确认等待参数为 20 秒、CAD wait 未被调用、uncertain 标记已写入、之后进入资源 close。未终止真实 CAD。
|
||||
- 对生产 `ProgressWatch` 输入模拟 `save_and_close / safe_stop=False`:150 秒为 request_stop,300 秒为 unresponsive。
|
||||
- 证据:`build/day0-resource-analysis-20261026/application-lifecycle-probe.json`。这是控制流证据,不能写成现场已发生保存中断或数据丢失。
|
||||
- 原始 #1 是库存读取后的收尾失败,四次日志记录 Quit helper/CAD 正常退出;#3 尚未启动 CAD。当前附件没有证明替换保存被提前打断。上述生命周期风险必须调查,但不能直接取代这两组现场证据。
|
||||
|
||||
优先实验应改为:在工程副本上记录保存调用前后、关闭调用前后、回读结果、Quit 请求与返回、CAD 自然退出、强制终止请求及原因的完整时间线;分别验证正常保存、长时间忙碌、关闭延迟和退出拒绝。数据正确性及退出契约查清后,再处理桌面末端残留。无需通过开启可见桌面或无界等待来替代这些完成条件。
|
||||
|
||||
## 已核实的证据
|
||||
|
||||
### 工单 #1:V1.1.3,四次资源释放确认失败
|
||||
|
||||
原件位置:`build/issue-1-20261021/evidence/`。四份失败的 `private-desktop.json` 一致记录:
|
||||
|
||||
- CAD 和退出辅助程序的退出码均为 0。
|
||||
- 所记录进程的 `job_active_processes=0`,已知后代句柄均已确认退出,自有进程及 Job 句柄关闭。
|
||||
- `desktop_handle_closed=true`,但 5 秒后 `released=false`。
|
||||
- 四次清理来自同一个主程序 PID 14608,调用线程不完全相同,调用线程桌面为 `Default`。
|
||||
- 另有一份采集中途取消的记录停在 `ready`,没有最终收尾证据;不能算作释放成功,也不能直接算作第五次同因泄漏。
|
||||
|
||||
这些证据降低了“已登记 CAD 主进程没有退出”“完全没等待终止”“已登记桌面句柄没有关闭”的优先级。它们不能证明进程所有线程、所有其他桌面句柄或所有系统辅助进程都已释放。
|
||||
|
||||
### 工单 #3:Beta 2,CAD 未启动也残留
|
||||
|
||||
本地 `build/issue-3-20261023/application.log` 与本次重新读取的远端附件逐字节一致。SHA256:`28d164039831973b7f6596a081d305421131f883514feae2fd652ff90ec54241`。
|
||||
|
||||
| 北京时间 | 日志位置 | 事实 |
|
||||
| --- | --- | --- |
|
||||
| 10-23 14:29:13 | 第 2 行 | 运行版本 `1.1.4-beta.2`,Windows 基础 build 26200 |
|
||||
| 14:29:34 | 第 14 行 | 开始整批 BOM 检查 |
|
||||
| 14:30:01 | 第 669 行 | 开始批末释放 |
|
||||
| 14:30:06 | 第 1098 行 | 桌面句柄关闭,桌面仍存在;CAD PID 为空,显示 CAD 未启动;窗口列表为空 |
|
||||
| 同一次失败的异常链 | 第 1102、1116 行及后续堆栈 | 首发错误为内部 attempt 目录创建的 `FileNotFoundError / WinError 3`,失败路径长 265 字符;释放错误发生在异常收尾期间 |
|
||||
| 14:30:47 | 第 1155 行 | 用户请求重新清理资源 |
|
||||
| 14:30:54 | 第 2013 行 | 同一个桌面仍存在,句柄关闭、CAD 未启动、窗口列表为空 |
|
||||
|
||||
前后失败样本相隔约 48 秒。未连续观测期间的状态,但相同随机桌面名两次均被枚举,明显削弱了“只需略微增加 5 秒超时”的解释。
|
||||
|
||||
`cleanup.processes=[]` 仅表示该次最终清理列表为空。原生 CLI 在批内执行后会从活动列表移除,不能据此说整批从未启动过子进程。
|
||||
|
||||
长路径是已记录的首发业务错误;桌面残留是收尾时另一个故障。修复路径问题不自动证明桌面引用来源已修复。
|
||||
|
||||
## 桌面残留的原因排序和判别办法
|
||||
|
||||
“优先级”表示调查顺序,不表示统计概率。
|
||||
|
||||
| 原因候选 | 优先级及证据 | 如何区分 |
|
||||
| --- | --- | --- |
|
||||
| 本程序的其他线程或额外桌面句柄仍持有引用 | 高;旧版 GUI 生命周期长,关闭登记句柄不能排除额外引用。四次 #1 来自同一主程序 | 现场保留桌面名,由独立观察进程在监督进程退出前后、主程序正常退出前后枚举;配合句柄和线程归属快照。随某进程退出而消失可缩小范围,但仍需持有者证据,不能单凭时间相关性定责 |
|
||||
| Job 外的无窗口辅助线程/进程 | 高;完全符合“Job 清空但桌面存在”。历史受控实验发现过无窗口 Python 和 conhost 线程 | 对目标桌面扫描全局线程,记录 PID/TID、映像、创建时间、会话及 Job 归属;与原生 CLI 启停时间对齐。历史 conhost 只是实验线索,现场未确认 |
|
||||
| 其他进程仅持有 OpenDesktop 句柄 | 高;可在不启动 CAD、没有窗口和目标线程的情况下复现相同症状 | 在线程扫描之外查询 Desktop 类型句柄。已有外部句柄实验复现阻断,持有者释放后可恢复;具体现场持有者未知 |
|
||||
| 原生 CLI、运行库、服务代理触发额外引用 | 中高;#3 没启动 CAD,但此前走过原生读取链 | 在现场副本依次运行空桌面、简单子进程、单个 icdb2ascii 读取、多个读取、CAD 回退,找出首次出现残留的阶段。普通子进程默认受 Job 约束,不能笼统断言所有后代都逃逸 |
|
||||
| 安全软件、录屏、远程协助、桌面管理组件等参与桌面访问 | 中,属于上一类的来源候选;当前没有具体软件或 PID 证据 | 先采集持有者或模块证据,再做单因素环境对照;没有证据时不能指定某个软件为元凶 |
|
||||
| Windows USER 引用延迟回收/系统环境差异 | 中低;短暂延迟有受控实验支持,但现场约 48 秒后的重查仍失败 | 使用独立进程记录 0、1、5、15、60 秒存在性,同时记录所有者退出状态。本机和 #3 均为基础 build 26200,仍需对照累计更新、运行库和注入组件,不能只按系统大版本归因 |
|
||||
| 句柄继承、Job 接管或异常清理分支缺陷 | 中低,需保留;当前代码在恢复运行前分配 Job,重定向使用明确的继承句柄清单,已有后代退出和句柄关闭失败测试 | 检查实际运行 EXE 哈希、Job 分配结果、句柄继承标志、失败时保留的所有权记录。当前源码机制不能倒推所有旧版或现场程序完全相同 |
|
||||
| 历史资源记录损坏或残留,形成逻辑阻断 | 对“升级后仍不能用”须优先区分;代码会保守阻断坏记录 | 对比当前物理桌面/进程与 `session.json`、`supervisor.json` 的状态。若物理对象已消失而记录无法校验,是证据恢复问题;不应归为仍有物理泄漏。原始 #1/#3 明确枚举到桌面,坏记录不能解释其最初残留 |
|
||||
| CAD COM 引用未释放 | 对 CAD 路径仍可查;作为统一解释优先级低 | 仅在已启动 CAD 的场景核对 COM、helper 与 CAD 生命周期。#3 的 CAD 未启动是其无法解释全部现象的直接证据 |
|
||||
| 工程数量上限、桌面堆耗尽、纯 BOM 匹配错误 | 当前证据弱 | 查桌面创建失败、内存资源错误和随批量增长的资源曲线。当前主要失败在销毁确认;BOM 行不匹配是独立业务结果,不能据此改资源配额或放宽匹配 |
|
||||
|
||||
微软文档确认:关闭一个桌面句柄与销毁所有引用不是一回事;线程的桌面连接不依赖存在可见窗口;Job 默认覆盖普通 CreateProcess 子进程,但不是整个系统的进程集合。例如 WMI `Win32_Process.Create` 创建的进程不属于这类默认继承范围。此机制说明需要查 Job 外所有者,不代表本软件已经被证明使用了 WMI 启动逃逸进程。
|
||||
|
||||
## 当前实现为何仍可能卡住
|
||||
|
||||
1. **判定严格,但归属诊断不足。** `isolated_desktop.py:66` 通过枚举确认桌面是否消失;失败时只收集窗口。`isolated_desktop.py:565` 明确将外部句柄持有者标为 unknown。空窗口不是无引用证明。独立工具 `tools/diagnose_private_desktop.py` 能查无窗口线程,但不能列出所有仅持有句柄的进程,权限错误也必须保留。
|
||||
2. **监督进程隔离只解决其覆盖的所有权。** `batch_supervisor.py:279` 等待并关闭受控 Job,随后 `_finish_response` 复核资源。这能够处理监督进程自身存活期间的引用;其他长寿命进程的引用不会因该监督进程退出而消失。
|
||||
3. **重新清理有能力边界。** `batch_resources.py:117` 对仍有 live owner 的会话可重试其关闭;没有 live owner 时只确认桌面消失和历史 PID 身份,不会接管或终止不明持有者。Beta 3 常见的是监督进程已经退出后的复核分支。反复点击不会凭空释放外部引用。
|
||||
4. **未释放门禁扩大可用性影响。** `guard_pending_resources` 阻止同一数据根的新批次。这一保护避免在旧资源不明时继续创建桌面或重放业务,却使一个释放问题阻断后续使用。恢复机制和持有者识别必须共同补齐。
|
||||
5. **损坏记录不会自动修复。** 无法校验的记录保持 blocked;无 session_id 时跳过自动资源操作。这是证据不足时的保护行为,但意味着资源已消失仍可能需要审计式人工核对。不能通过删除保护文件掩盖该状态。
|
||||
6. **诊断包不等于实时取证。** 当前导出函数主要打包已有文本,未自动执行全局线程或句柄扫描。上限为单文件 4 MiB、总计 32 MiB、512 个文件,超限写入 omissions;必须检查 manifest,不能把未导出的记录当成从未发生。
|
||||
|
||||
## 本次新验证
|
||||
|
||||
运行环境:Python 3.12.10、Windows 11 基础 build 26200。以下测试未打开或替换用户工程。
|
||||
|
||||
- `python -m pytest -q tests/v1_1/test_isolated_desktop.py tests/v1_1/test_desktop_diagnostics.py tests/v1_1/test_batch_runtime_windows.py tests/v1_1/test_batch_supervisor.py`:**44 passed,87.89 秒**。包含真实 Windows 资源测试与替身测试,覆盖无窗口引用、延迟释放、后代进程、诊断边界、监督恢复等;不等同于现场完整 EXE 验收。
|
||||
- `python -m pytest -q tests/v1_1/test_batch_runtime.py::test_unknown_resource_evidence_never_authorizes_cleanup tests/v1_1/test_batch_runtime.py::test_restart_reconciles_only_confirmed_disappearance_without_replacement`:**4 passed,1.22 秒**。确认坏证据继续阻断、重启后仅复核的代码行为;这两类为模拟边界测试。
|
||||
- 资源循环探针 `build/day0-resource-analysis-20261026/probe_cycles.py`:20 次空桌面、20 次带重定向的简单 Python 子进程,**40/40 正常释放**。自有桌面残留 0,观察前后没有新增桌面,调用线程桌面未改变。两组的释放枚举检查最大耗时均约 0.016 秒,该数字不包含完整子进程启动耗时。
|
||||
- 循环证据:`build/day0-resource-analysis-20261026/cycles-6819874fa1b04649a6dbb9c6b1992034.json`。它是源码 Python 基础路径实验,没有覆盖 Qt GUI、冻结 EXE、实际 icdb2ascii、CAD 或现场常驻组件,不排除这些组合中的问题。
|
||||
|
||||
这批结果降低了本机基础资源封装普遍失效的可能性,不能证明现场根因已修复,也不能证明 102 个原工程全部可用。
|
||||
|
||||
## 下一步应取得什么证据
|
||||
|
||||
1. **先确认事故实际版本和状态。** 当前收到的两组原件属于 V1.1.3 与 Beta 2;没有 Beta 3 的新失败诊断包。记录现场 EXE 哈希、是否完整配套 `_internal`、原始 data 是否迁移、故障是再次产生桌面还是旧记录阻断。Beta 3 公开 EXE 的历史记录哈希为 `df08cd328f6f4c9019f232c845e09627551e7b2d24790a466d53efcd291622d1`,以实际安装文件核对。
|
||||
2. **残留发生时立即取证。** 在原机器、原登录会话,从 session 记录取得准确桌面名;运行独立线程诊断并查询 Desktop 句柄持有者,保留 PID、创建时间、映像、线程、会话、Job 和时间戳。仅复制旧日志到开发机无法找回消失的 Windows 引用。
|
||||
3. **独立观察所有者退出前后。** 先保存结果及诊断,再观察监督进程退出、应用正常退出后的同名桌面变化。桌面随监督进程退出消失,优先追监督进程内部引用;随 GUI 退出消失,追 GUI 或其关联组件;GUI 退出后仍存在,追其他进程或系统引用。上述变化用于缩小范围,最终需结合持有者证据确认因果。
|
||||
4. **按最小场景逐层复现。** 空桌面 → 简单 worker → 单次原生 CLI → 多次原生 CLI → CAD 回退 → 批量混合。每层记录创建数量、已退出进程、最终桌面状态。实际读取使用工程副本,首次失败就保留证据,避免反复业务执行污染现场。
|
||||
5. **修复后验证恢复结果。** 对已识别的持有者修复生命周期;完成正常、异常、取消、重启和跨批次检查,确认只清理资源时业务结果不变、没有重复替换,随后在现场原目录和原批量范围验收。只有现场复测通过并留存回执,才具备关闭工单的依据。
|
||||
|
||||
技术交付首先补齐业务完成与应用退出的分阶段证据,并专项验证等待与强制清理边界;对完成业务后仍残留的桌面,再补自动捕获持有者的能力。单纯延长等待、反复要求重新清理或继续发布未取得现场证据的候选包,都不足以建立闭环。
|
||||
|
||||
## 关联记录
|
||||
|
||||
- [工单 #1](https://git.simgreek.com/simgreek/dxdesigner-part-replacement/issues/1)、[工单 #3](https://git.simgreek.com/simgreek/dxdesigner-part-replacement/issues/3)。
|
||||
- [首轮工单分析](2026-10-21-issue-1-bom-import.md)、[Windows 生命周期受控实验](2026-10-21-windows-desktop-lifecycle.md)、[外部句柄持有者实验](2026-10-23-issue-3-external-holder.md)、[Beta 3 验收边界](2026-10-23-issue-3-safe-recovery.md)。
|
||||
- 微软:[CloseDesktop](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-closedesktop)、[线程连接桌面的规则](https://learn.microsoft.com/en-us/windows/win32/winstation/thread-connection-to-a-desktop)、[Job Objects](https://learn.microsoft.com/en-us/windows/win32/procthread/job-objects)。本次重新核对官方页面。
|
||||
@@ -0,0 +1,59 @@
|
||||
# 用户停止与安全收尾实施验收
|
||||
|
||||
日期:2026-10-26;分支:`codex/day0-safe-stop`。实现用户在本会话批准的[停止流程](../superpowers/specs/2026-10-26-safe-user-stop.md),对应[全链路调查](2026-10-26-application-lifecycle-investigation.md)。
|
||||
|
||||
## 实现行为
|
||||
|
||||
- 普通暂停和关闭窗口不启动下一项,当前写入、保存和回读安全完成后停止。当前项并不等于整个工程。
|
||||
- 有写入可能的阶段长期没有进度时显示等待,不自动把超时升级成杀进程。纯只读采集保留有界取消。
|
||||
- 写入失败、保存结果不确定或 Quit 被拒绝/超时且 CAD 仍存活时,交互执行保留应用与工程,等待处理,不自动保存或丢弃。
|
||||
- “强制结束…”独立确认;先持久化业务保护及批次中断证据,再终止明确自有的监督进程及 Job。证据写入或 fsync 失败时拒绝该次 force,界面保留重试能力。
|
||||
- 保存请求、保存调用返回、保存回读和工程关闭分别记录,工程关闭失败不会丢失此前保存边界。
|
||||
- 收尾记录写入失败不跳过满足身份检查的正常 Quit。主进程自然退出后给予自有后代 2 秒自然退出窗口,之后的强制清理单独记录。
|
||||
- 资源消失不吞掉异常退出;调用方收到独立收尾错误,已核验业务结果仍附带保留。
|
||||
- 等待期间可独立导出诊断包。关闭窗口在操作结束前不退出;失败/强制结束后取消自动关闭,保留恢复提示。
|
||||
|
||||
## 自动验证与审查
|
||||
|
||||
针对安全边界先运行失败用例再实现,包括慢保存不会被 watchdog 终止、明确 force 的保护先行、保护写入失败保留进程、已有文件也重新 fsync、保存后工程关闭拒绝、窗口关闭不触发 force、确认取消无副作用。
|
||||
|
||||
真实辅助进程测试覆盖监督子进程强制中断、控制回调异常时保持子进程存活、拒绝第一次保护写入后仍允许后续明确重试、资源清理不重放业务。CAD 调用在这些故障测试中使用替身,不能据此声称真实保存中断无损。
|
||||
|
||||
退出协议独立审查修复了部分子进程查询失败时丢失已知强制终止 PID 的问题。整体验证另外修复:只读入口没有 force 出口却进入无限等待、证据首次 fsync 失败后因文件存在被误放行、已执行 force 被诊断异常降级为普通停止、控制通信异常绕过确认清理、直接执行 force 失败没有反馈,以及 force 意图与监控异常并发的竞态。复审未发现新增阻断问题。
|
||||
|
||||
首次完整实现回归 **1063 passed,1 条既有 pywinauto STA 警告,363.82 秒**。之后完成审查修正,最终扩大回归 **1147 passed,1 条既有 pywinauto STA 警告,325.64 秒**:
|
||||
|
||||
```powershell
|
||||
python -m pytest -q tests/v1_1 tests/trial_task_center/test_application.py tests/trial_task_center/test_execution_safety.py tests/part_replace/test_verification.py tests/integration/test_quick_value_modes.py tests/integration/test_quick_session_startup.py tests/integration/test_quick_part_replace_contract.py tests/integration/test_automatic_replacement_regression.py tests/trial_task_center/test_worker_monitor.py tests/trial_task_center/test_batch.py
|
||||
```
|
||||
|
||||
本命令包含项目发布脚本要求的源码测试范围,并补充此次受影响的 VBS、worker monitor 与批次测试。`git diff --check` 与新探针/停止模块语法检查通过。
|
||||
|
||||
两个旧 VBS fixture 在基线 `b939101` 也失败:未填 owned project path 且错误期望 no-match 保存、图页清单断言未使用规范化路径。修正的是 fixture 和断言,没有放宽生产所有权或保存规则;脚本契约组 72 项通过。
|
||||
|
||||
## 真实保存期间请求普通停止
|
||||
|
||||
工具:[probe_safe_stop_live.py](../../tools/probe_safe_stop_live.py)。本轮输出为 `build/safe-stop-live-a9113545bf/`,报告 `report.json`,最终资源复核 `final-resource-check.json`。
|
||||
|
||||
入口为源码 supervised service → 真实独立 batch worker → 生产 VBS → 真实 CAD,使用两份全新 Audio_D2128/Audio_T605A 副本。监听第一工程的生产 `save_requested` 日志后只设置普通停止 Event,不设置 force。此触发处于保存请求附近,不能声称精确暂停在 COM 内某一条指令。
|
||||
|
||||
| 检查 | 结果 |
|
||||
| --- | --- |
|
||||
| 第一个工程 | 当前 RV05 替换、保存和回读完成,任务 completed |
|
||||
| 第二个工程 | 保持 pending,没有继续替换 |
|
||||
| 队列 | paused=true,未请求强制结束 |
|
||||
| 第一工程新 CAD 独立读回 | 57 器件、103 引脚连接;目标 RV05 为新料号,56 个非目标器件保持;目标身份、位置和连接保持 |
|
||||
| 第二工程新 CAD 独立读回 | 57 个器件的完整属性及连接图与执行前一致 |
|
||||
| 执行批次退出 | orderly_shutdown=true、clean=true、forced_termination=false |
|
||||
| 资源 | 资源记录全部 released,最终枚举确认其桌面消失,没有本轮残留 CAD |
|
||||
| 原件 | 两个源工程目录哈希不变,中央库 `.lmc` 哈希不变 |
|
||||
|
||||
没有重放任何已经完成的替换;测试用的 before/after 独立读取使用新 CAD 实例。
|
||||
|
||||
## 边界
|
||||
|
||||
本轮没有构建或发布新 EXE,未做完整冻结 GUI 的保存中强制结束、掉电或原工单全量现场复测。GUI 行为使用 Qt 测试验证,真实保存停止使用源码监督入口验证;二者不能混写为冻结 GUI 全流程验收。
|
||||
|
||||
强制结束为避免切换任务竞态,保守标记本批可能涉及的目标;已完成业务证据和结果保留,但先前已完成任务也可能需要恢复核验。不能清除保护来继续。
|
||||
|
||||
保持应用等待不代表保存结果一定可以恢复。外部任务管理器强杀/系统掉电没有安全收尾保证,重启必须依赖原先写前证据核验。工单现场具体桌面持有者仍未查明,本实现不能当作现场根因已经闭环。
|
||||
@@ -1,5 +1,7 @@
|
||||
# R8:进度式超时与分阶段引脚索引
|
||||
|
||||
> 本文保留 R8 历史行为。2026-10-26 起,有写入可能的阶段无进度超时改为等待安全收尾,只有明确确认的强制结束才中断;当前停止与恢复规则见[停止、强制结束与恢复](safe-stop-and-recovery.md)。只读采集继续采用有界取消。
|
||||
|
||||
## 改变的行为
|
||||
|
||||
- 150 秒不再是整个任务的总时限,而是连续没有有效进度的观察窗口。有有效进度时可以继续执行超过 150 秒。
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
# 停止、强制结束与恢复
|
||||
|
||||
执行期间点击“完成当前项后暂停”,程序不再启动下一替换项。已经进入修改或保存的当前项会继续完成必要校验、保存、重开回读和工程关闭,然后正常退出 CAD,并等待自有辅助进程收尾。关闭主窗口也遵循这个流程,操作仍在进行时窗口保持打开。
|
||||
|
||||
“当前项”是当前图页和替换规则对应的执行单元,不是整个工程或整个批次。已经保存核验的结果保留,未开始的任务保持未执行。
|
||||
|
||||
## 保存或修改长时间没有进度
|
||||
|
||||
有写入可能的阶段,程序不会仅因超过无进度时限就自动终止应用。界面显示保存或核验尚未确认,可以继续等待并导出诊断包。等待不会启动下一项,也不会自动清除保护记录。
|
||||
|
||||
如果操作已经失败且保存结果不确定,程序保留当前应用和工程现场,不再自动保存或丢弃。应先导出诊断、保留原始工程与备份,再决定是否需要强制结束。此时“继续等待”不表示自动恢复执行。
|
||||
|
||||
纯读取的 BOM/库存采集仍采用有界取消;不存在写入需要完成时,不要求用户无限等待。确认未修改的启动失败也保留既有有界停止机制。
|
||||
|
||||
## 明确选择强制结束
|
||||
|
||||
“强制结束…”与普通暂停分开。确认框明确提示:当前操作可能正在修改或保存,强制结束可能留下未保存或部分保存结果,之后必须先核验恢复。
|
||||
|
||||
确认后,程序先持久化中断保护和批次记录,再终止自己拥有的监督进程及 Job。保护记录无法可靠保存时,不执行这次强制结束,界面提示原因并允许重试或导出诊断。取消确认没有终止副作用。
|
||||
|
||||
为避免强制请求与工程切换同时发生而漏记目标,强制结束会保守保护本批可能涉及的任务。先前已保存结果不会被覆盖或重放,但这些任务也可能显示需复核或被保留在当前列表。不要删除保护文件绕过核验。
|
||||
|
||||
## 程序重启之后
|
||||
|
||||
- 资源复核只处理进程和桌面状态,不重新替换。
|
||||
- 结果不确定的任务必须使用“核验并恢复”,按照已有快照和当前实际工程核对。
|
||||
- 已保存核验结果继续保留;资源清理成功不自动解除业务保护,也不自动继续队列。
|
||||
- 如果应用没有正常退出或后代进程需要强制清理,会单独报告收尾异常,不能把“资源已释放”理解为“保存和退出均正常”。
|
||||
|
||||
任务管理器强杀、系统关机或掉电可能不给程序写最终日志的机会。这些情况依赖修改前已经落盘的证据及下次启动的中断核验;程序不能保证被外部强杀时完成当前保存。
|
||||
@@ -0,0 +1,35 @@
|
||||
# beta.16 代码审查与修复记录
|
||||
|
||||
日期:2026-10-30。
|
||||
范围:工作区 BOM 导入/草稿/保存、工程切换、任务暂停/继续、只读 CAD 采集错误、后台资源复核。通过实际分支追踪、临时工程/Excel 回归用例和独立审查确认问题;不将推测作为已修复根因。
|
||||
|
||||
## 发现与修复
|
||||
|
||||
| 优先级 | 触发条件与影响 | 修复位置与行为 |
|
||||
|---|---|---|
|
||||
| P1 | 重新导入某工程时,监督器在读取报告产生前拒绝/取消;该工程原有草稿、预览和已保存计划的执行资格可能继续保留 | workspace_window.py `_error`、`_stage_import`:无报告错误也带回工程范围;撤销本次工程旧草稿/预览,添加待处理状态;工程路径标识统一大小写,执行时排除这些工程,其他工程保持可用 |
|
||||
| P2 | 逐份导入两个 CBB 且第一份未保存;第二次导入覆盖第一份的完整核验预览,保存时第一份被迫重新采集或因旧基线失败 | `_stage_import` 合并不受本次导入影响的预览,保留原始基线;仅更新当前清单涉及的工程,保存仍在事务内重新验证基线和工程身份 |
|
||||
| P2 | 导入后 current_id 已变,旧器件表尚未刷新且 dirty=true;旧行可能被保存到新工程草稿名下,造成串行显示/身份不符拒绝保存 | `_table_task_id` 绑定表格所属任务,记忆草稿前检查任务身份;导入切换时清空和禁止编辑旧表格,等待新上下文返回 |
|
||||
| P2 | 共享 TargetFilter 默认隐藏所有未选中行,手工配置页没有“显示未选中”开关,导致未勾选器件全部消失且无法勾选 | 共享器件表恢复默认显示全部;新版工作区显式保持默认隐藏未选中,并可用复选框展开 |
|
||||
| P2 | 在两个工程之间暂停,外层返回 paused=false 和临时随机 token;界面错误显示“运行结束”。在通知当前工程后、监督器启动前暂停,又会显示取消异常 | workspace_execution.py 正确返回暂停及下一工程;工程边界暂停没有内层 token,仅中途暂停保留真实 token;继续仅使用当前可见且校验可执行的工程,避免使用不存在的队列编号 |
|
||||
| P2 | 读取超时被统一显示成“工程损坏或无法读取”,误导排查 | batch_runtime.py 在确认只读会话释放后区分打开超时、其他读取超时、CAD 启动失败、身份不完整和一般读取失败;工程列表同步显示超时状态 |
|
||||
| P2 | 原生报告位号与属性冲突只记录计数和一句话,诊断包无法找出触发回退的器件 | native_inventory_protocol.py 在保留原有回退判定的同时,记录具体 UID、标题位号、属性位号、报告行号;未放宽身份/重复位号核验 |
|
||||
|
||||
## 验证与证据
|
||||
|
||||
- 新增导入回归:连续未保存导入、失败重导入、监督器提前拒绝、已有计划执行排除、旧表格编辑串入防护。
|
||||
- 新增暂停回归:工程边界暂停没有虚假 token,继续只启动剩余工程;启动前取消保留真实续跑 token。
|
||||
- 新增读取回归:超时仍关闭只读资源并保留释放证明,消息不推断损坏;报告冲突带回 UID 和两个字段。
|
||||
- 完整测试:1016 passed,6 failed,1 warning。日志:build/beta16-suite.log。
|
||||
- 6 个失败均在 fixture 的 Path.mkdir 阶段触发 WinError 206/3(当前 Windows 长路径策略限制),尚未执行产品逻辑:test_execution_metrics.py 的两项长证据路径用例,test_project_long_paths.py 的四项工程路径用例。未更改系统策略或跳过这些测试。
|
||||
- 两项资源日志用例更新了过期的 Win32 API 模拟接口;真实 Windows 用例保留外部窗口,确认仍会阻断未释放的桌面,不会回放已完成结果。
|
||||
- 便携 EXE 已通过 tools/verify_packaged_runtime.py 冻结版启动/监督进程/进程身份/资源释放检查;ZIP 完整性、校验和和不包含用户 data 均已核对。
|
||||
- 独立审查复查了导入合并、暂停 token、路径大小写、旧表任务身份与资源保护分支,未发现遗留的本次改动相关实质性问题。
|
||||
|
||||
## 仍需明确的范围
|
||||
|
||||
- 本次没有对用户真实 CAD 工程进行端到端替换。FEM 工程在 DxDesigner OpenProject 内部等待的原因仍未由当前诊断包证明;新版完善了读取错误分类和位号冲突证据,不宣称已修复工程本体。
|
||||
- Windows 源码从 .venv 的重定向 python.exe 直接启动监督器存在 PID 不同的研发运行限制;独立 EXE 不经过此路径且已自检。测试使用基解释器与 venv 依赖目录,未放宽精确进程身份校验。
|
||||
- 原生 Replace Part、Value/Part Label/NC 规则、保存核验、强制停止后的待核验保护未改写。
|
||||
|
||||
交付:dist/DxPartReplace-1.2.0-beta.16-Windows-x64.zip。升级先关闭旧程序,保留旧 data 文件夹,完整解压程序和 _internal,确认窗口版本为 beta.16。
|
||||
@@ -0,0 +1,40 @@
|
||||
# 诊断分析:DxPartReplace-诊断-20261030-164044
|
||||
|
||||
分析时间:2026-10-30。所有过程时间均换算为北京时间(日志 timestamp_utc 加 8 小时)。本次仅分析诊断记录和代码,未修改程序或工程。
|
||||
|
||||
## 已确认结论
|
||||
|
||||
1. 本次导入 8 份分表,共 32 行。前 5 个 ETHERNET 工程通过;FEM_KCT8529H 读取失败后已跳过并继续 RTC5638HE。
|
||||
2. FEM_KCT8529H 和 RTC5638HE 的直接阻塞点都是 QuickPartReplace.vbs 的 `QPEnsureProject`,`App.OpenProject(CStr(TargetPath))` 调用之后没有返回到 `session_ready`。
|
||||
3. 读取监控在 open_project 无进展 45 秒后请求停止;FEM_KCT8529H 再等待约 5 秒后结束只读会话,确认资源释放,继续下一工程。该故障发生在器件枚举和 BOM 匹配前。
|
||||
4. “工程损坏或无法读取”是 batch_runtime.py 将读取异常统一包装后的提示,不是 DxDesigner 返回的数据库损坏诊断。本包没有提供足够证据认定数据库损坏。
|
||||
5. 诊断包在第 7/8 个工程仍在读取时导出,supervisor.json 为 running,session.json 为 ready/generation 3,缺少最终 result.json。FEM_SKY85717 只有任务事件文件,没有本次读取过程。截图中的最终 3 个失败不能全部由本包核实。
|
||||
|
||||
## 逐工程证据
|
||||
|
||||
| 工程 | 原生报告解析 | CAD 路径 | 可确认的结论 |
|
||||
|---|---|---|---|
|
||||
| FEM_KCT8529H | 两次 icdb2ascii 均退出码 0;有效报告解析 67 个符号,29 个符号的标题位号与 Ref Designator 属性不一致;9 个命名端口被忽略 | 16:39:01 进入 open_project;16:39:47 无进展约 45 秒触发停止;16:39:52 已确认释放后台会话 | OpenProject 调用等待超时,未进入器件枚举或 BOM 匹配;数据库损坏未被证实 |
|
||||
| FEM_RTC5638HE / RTC5638HE.prj | 两次 icdb2ascii 均退出码 0;有效报告解析 65 个符号,21 个符号位号字段不一致;5 个命名端口被忽略 | 16:40:00 进入 open_project;16:40:45.823 已无进展 45.062 秒并请求停止;诊断快照到此截止 | 同样卡在 OpenProject,包内没有最终退出、释放和匹配结果 |
|
||||
| FEM_SKY85717 | 包内无本次解析记录 | 包内无本次 CAD 读取记录 | 截图显示失败,但本包不能确认具体阶段和原因 |
|
||||
| ETHERNET_1G(对照) | 同样出现 2 个位号字段不一致并回退 | 两次 CAD 核验均成功;OpenProject 分别约 6.219 秒、4.046 秒;读到 10 个器件 | 位号字段不一致并不必然导致工程无法打开 |
|
||||
|
||||
## 原生报告为什么回退
|
||||
|
||||
native_inventory_protocol.py 比较 FLAT BLOCKS 报告的符号标题 `ref des ...` 与属性 `Ref Designator`。两个字符串不一致时将 UID 放入 inconsistent_refs。随后 HIER BLOCKS 解析遇到涉及该 UID 的请求物料就转 CAD 核验。
|
||||
|
||||
工作区导入会请求旧料号、新料号和 `*`(全库存用于检测重复位号),因此未直接列入替换清单的其他器件也可能触发回退。记录中的 29/21 是字段不一致数量,不是缺少 UID 的数量,也不是清单错误数量。
|
||||
|
||||
原生工具正常输出报告,且摘要记录 source_hashes_unchanged=true,说明这一步能读取工程快照,并未修改源文件。它不能证明 CAD 能正常打开,也不能证明全部器件身份一致。
|
||||
|
||||
## 仍无法从本包确定的底层原因
|
||||
|
||||
OpenProject 未返回的内部原因尚不可见:可能是工程打开流程等待对话框、工程数据库/依赖问题,或正常加载超过 45 秒。这些都是待验证假设。本包没有对话框正文、打开阶段的内部 CAD 错误,不能将过去其他工程出现的 iCDB 报错直接套用到本次。
|
||||
|
||||
原生完整 scope.txt/effective.txt 被诊断包白名单排除(manifest 中标为 outside_allowlist);现有追踪只保存符号标题样本和不一致计数,没有保存触发失败的 UID 及两个位号值。因此本包不能继续确定究竟哪个器件的哪两个字段不同。
|
||||
|
||||
## 建议的下一步
|
||||
|
||||
先在前台 DxDesigner 单独打开这三个 FEM 工程,记录是否弹窗、具体正文,以及到可正常操作所需时间。若前台也无法打开,应根据实际 CAD 报错处理工程;若前台能很快打开,应调查后台 OpenProject 的等待窗口/会话差异;若正常加载确实超过 45 秒,则需要调整工程打开阶段的超时策略。
|
||||
|
||||
程序后续应记录触发回退的 UID、标题位号和属性位号;读取超时时捕获自有后台窗口的标题/正文;提示应区分“打开超时”“CAD 明确拒绝打开”“身份核验失败”,避免将超时直接呈现为工程损坏。若需要核对 SKY85717,请在整批结束后再次导出完整诊断包。
|
||||
@@ -0,0 +1,29 @@
|
||||
# 诊断分析:20261102-112907
|
||||
|
||||
日期:2026-11-02。诊断来源:工作目录内 `DxPartReplace-诊断-20261102-112907`。
|
||||
|
||||
## 导入结果
|
||||
|
||||
本次日志记录 9 个工程、27 行 BOM:24 行通过,3 行失败。失败行均属于 `LDO_S2032_SOT23_1V5`。完整导入约 7 分 47 秒,期间存在反复回退 CAD 采集和重复库存检查。
|
||||
|
||||
失败工程的一致性检查涉及 `database/icdb.dat` 与 `database/cdbsvr/sAddress.adr` 的内容变化。旧逻辑只容许前者作为读取会话变化候选,后者导致核对失败。这条失败证据不能直接证明原理图损坏。
|
||||
|
||||
## 为什么界面没有 UF?,日志却出现 UF?
|
||||
|
||||
日志中的“标题位号”指原生导出报告 Symbol 记录的 `ref des` 字段,不是窗口标题,也不是截图识别结果。同一 UID 的另一字段 `Prop Ref Designator` 是实例属性。日志记录前者为 `UF?`、后者为 `UP01`。
|
||||
|
||||
因此,画面显示 UP01 与导出报告还带有 UF? 可以同时发生。带问号的值呈现占位形式;它究竟来自库的默认属性、内部注释还是报告展开机制,当前证据不足,不能断言用户工程上的位号有误。
|
||||
|
||||
旧解析器要求两个字段完全一致,一旦不一致就放弃快速报告读取,改用较慢的 CAD 读取。这样的回退反复发生,是此次慢导入的可见原因之一。
|
||||
|
||||
## 本次调整
|
||||
|
||||
1. 对 UF?、C? 等占位标题,只有分层、展开两份报告对同一唯一 UID 的实际实例位号均一致,才采用实例属性继续快速读取。重复、嵌套 UID 和实际属性冲突仍不放行。规则对所有工程通用。
|
||||
2. 将精确的会话地址路径 `database/cdbsvr/sAddress.adr` 纳入已有的运行数据库变化判定;其余设计内容须一致,还需两次库存身份完全一致。缓存完整指纹仍包含这些文件,不全面忽略 database 目录。
|
||||
3. BOM 匹配本身已经使用位号等信息;保留 UID 作为报告关联和内部定位信息。本次优化减少不必要的回退,不删除身份核对。
|
||||
|
||||
不增加导入/保存阶段的中心库查询,维持替换失败后再查询的策略。
|
||||
|
||||
## 验证边界
|
||||
|
||||
相关解析、缓存和 BOM 导入回归共 107 项通过。覆盖占位标题与实际属性一致、真实属性冲突、会话地址变化、真实设计文件变化等。模拟回归和冻结程序自检不能代替全部真实 CBB 的现场验收;实际耗时改善需用同批 BOM 复测。
|
||||
@@ -0,0 +1,25 @@
|
||||
# 诊断分析:20261103-160621
|
||||
|
||||
日期:2026-11-03;现场版本:1.2.0-beta.30。
|
||||
|
||||
## 现场结果
|
||||
|
||||
工程 Xview 导入从 15:58:43 到 15:59:23,约 40 秒。原生报告解析本身约 0.4 秒,但因 CP? / CX05 位号字段差异两次回退 CAD 采集。
|
||||
|
||||
替换第 0 组目标 `4300-CF5610-7100` 未加载,DxDataBook 轮询预算为 30 秒,最终 batch_failed;该组工程关闭未保存。之后四组均记录 saved_ok:CX24、CX25/CX32、CX27、CX29/CX31,共 6 个器件。CX20/CX21 所属失败组没有保存成功证据。本次不能描述成整个任务从未继续。
|
||||
|
||||
第 0 组失败完成于 16:01:06;后续四组完成于 16:01:59、16:03:00、16:03:46、16:04:38。成功步骤仍包含原生替换、属性/引脚恢复、保存重开回读等耗时。末组记录 native_replace 约 24.1 秒,index_pins 约 4.8 秒,其余时间分布于快照、恢复和回读,不能全部归因于 UID 匹配。
|
||||
|
||||
用户确认中心库缺少目标料号;日志单独能证明的是未加载该目标并超时,不能据超时自动断言中心库确实缺料。
|
||||
|
||||
## beta.31 调整
|
||||
|
||||
- 按最新用户决定,取消替换失败后的中心库存在性查询。导入、保存和失败处理均不启动这类额外查询;具体旧/新料号、图页和原始错误保留,失败项留待人工处理,其他可执行项继续。显式目标封装选择及核心原生替换核验仍保留。
|
||||
- DxDataBook 目标列表轮询预算从 30 秒缩短到 8 秒,并记录目标、状态和实际耗时。8 秒是轮询预算;单次原生/UIA 调用如阻塞仍受外层看门狗约束,不承诺完整收尾仅用 8 秒。
|
||||
- 后续成功步骤不再让早先失败的目标与错误详情被“当前步骤”遮盖。
|
||||
- 分层属性保留与展开标题完全相同的占位位号时,允许同一唯一 UID 的展开实例生效位号参与快速读取;真正的具体位号冲突仍回退 CAD。诊断包没有完整报告字段,此次分层字段具体值仍需现场新日志确认;新增 scope_refdes 信息供后续核实。
|
||||
- 修正复选框鼠标命中区域:点击整个复选框单元格即可切换,不再必须点中小方框;已有目标、执行中和历史证据锁定规则保留。
|
||||
|
||||
## 验证范围
|
||||
|
||||
166 项解析、缓存、失败隔离、停止、目标执行与 Qt 鼠标交互回归通过。测试覆盖无目标料号的短轮询、失败后不查中心库且继续下一工程、后续成功不遮盖失败详情、复选框中央点击和锁定状态。真实 CBB 速度和库加载行为仍需现场复测;不减少保存回读核验来宣称提速。
|
||||
@@ -0,0 +1,38 @@
|
||||
# 诊断分析:LNB_TPS65233
|
||||
|
||||
日期:2026-11-03。诊断包:`DxPartReplace-诊断-20261103-164814`。任务:`9a224826-316c-4119-a36b-be5656aa486a`。本次仅诊断与记录,不修改运行代码或发布包。
|
||||
|
||||
## 结论
|
||||
|
||||
首发异常是软件执行结果交接阶段的 `ADODB.Stream` 文件写入错误,错误编号 3004(写入文件失败),不是日志已经证明的缺料号、位号或连接错误。
|
||||
|
||||
CN09 有保存返回、关闭、重新打开、回读验证通过及 saved_ok 状态证据。随后结果交接文件写入出错,被保守记为 batch_saved_unverified,工程因此停止。不能把整工程状态理解为所有器件均未替换。
|
||||
|
||||
## 逐项证据
|
||||
|
||||
| 器件 | 替换 | 日志证据 |
|
||||
| --- | --- | --- |
|
||||
| CN07、CN08 | 4300-CF1000-5200 → 4300-CF1000-5100 | 18:49:36 saved_readback_verified;saved_ok;事件包含实际料号和 Value=10pF/50V/NC,已保存回读成功 |
|
||||
| CN09,UID $1I1302 | 4300-CF1010-7200 → 4300-CF1010-7100 | 18:49:54 native_helper_exit code=0;18:50:02 save_returned;18:50:03 project_closed;18:50:11 saved_readback_verified;status.tsv 先有 saved_ok,随后写入 batch_saved_unverified/3004 |
|
||||
|
||||
CN09 的原 Value 是 `100PF/50V`。此包没有其独立 value-readback.tsv 或成功业务事件,不能仅凭预览替代实际最终 Value 记录;保存回读通过本身有日志和 status.tsv 双重证据。其他后续条目没有相应执行完成证据。
|
||||
|
||||
原始错误为:`ADODB.Stream: save was requested; persisted outcome requires reconciliation. 写入文件失败。`。日志位置:该任务 `quick-run/quick-part-replace.log:57` 为保存回读成功,紧接第 58 行出错;`status.tsv:5` 成功,第 6 行为后续异常。
|
||||
|
||||
18:50:17 随后记录 auto_project_timeout 和后台进程退出未确认。这些是首发文件写入异常之后的收尾记录,不是首先发生的替换故障。`stage=query_pins` 是保留的阶段标签;异常来源实际为 ADODB.Stream,不能据此判为引脚连接冲突。
|
||||
|
||||
## 定位与推断边界
|
||||
|
||||
对照 beta.31 代码 `QPFinishBatchItem`:保存重开核验后先记录 saved_readback_verified,再追加 saved_ok,然后调用 QPWriteUtf8 写 project-session-result.tsv。QPWriteUtf8 通过 ADODB.Stream.SaveToFile(..., 2) 直接覆盖文件。
|
||||
|
||||
Python 的 project_session.py 同时反复 read_text 轮询同一文件。根据已存在 saved_ok 和其后的 ADODB.Stream 错误,最符合执行顺序的失败位置是 project-session-result.tsv 的覆盖写入。代码没有给这次写入附带目标路径或底层占用信息,因此具体文件定位属于高可信推断,并非诊断包直接记录了文件路径。
|
||||
|
||||
本机最小实验:只在临时文件上使用真实 ADODB.Stream.SaveToFile;Python 持有读取句柄时写入失败,COM scode=-2146825284(低位 3004);释放句柄后同一路径同一内容写入成功。未访问 CAD 或修改用户工程。
|
||||
|
||||
这验证了读写竞争能够产生完全相同的错误,且与现有轮询实现吻合。现场到底由该轮询、其他进程占用或其他文件系统问题触发,包内证据不足以唯一确认;不声称已证实具体占用进程、磁盘满或工程损坏。
|
||||
|
||||
## 处理建议
|
||||
|
||||
先人工打开工程核对 CN09 的实际料号与 Value,再处理尚未完成条目;保留 CN07、CN08 的成功记录。不要因交接报错就重复认定这些器件换料失败。
|
||||
|
||||
后续代码修复应针对结果交接:避免读写同一文件发生覆盖冲突,增加受限重试或可靠的独立/原子交接,并记录具体失败路径和底层错误;区分“工程回读已通过、结果通知失败”与“CAD 换料失败”。本次未实施或发布此修复。
|
||||
@@ -0,0 +1,24 @@
|
||||
# 诊断分析:TUNER+DEMOD_DVB-C_M88RC6800
|
||||
|
||||
日期:2026-11-03。来源:`DxPartReplace-诊断-20261103-164814`,任务 `81210983-ea44-474a-a94c-e960fafce99e`,现场 beta.31。本次仅诊断,不改程序。
|
||||
|
||||
## 首发原因
|
||||
|
||||
失败组:`4300-CA4750-A200 → 4300-CA4750-A210`,包含 CT64($1I2612)、CT65($1I2614)、CT61($1I2616)。原理图 M88RC6800、图页 CVBS_BUFFER。
|
||||
|
||||
17:01:38 原生 helper 返回 code=0,随后进行属性恢复与回读。17:01:44 日志记录 `display_readback_mismatch uid=$1I2612 refdes=CT64 attribute=Part Label fields=font=13->0`。
|
||||
|
||||
这意味着程序按旧快照恢复 Part Label 显示字体后,实际读回的字体编号是 0,预期编号是 13。13/0 是 Font 属性值,不是字号,也不是 Part Label 的文字内容。源码 QPRestoreDisplay 写入保存的 Font,QPVerifyDisplay 要求数值完全一致;不一致抛出 vbObjectError+837,日志错误号为 -2147220667。
|
||||
|
||||
此例不是缺料号,也不是已记录的引脚网络对调;它在显示属性字体核验处失败。具体为何字体无法保持为 13,诊断不能确定:可能涉及属性继承、原生字体编号归一化或库符号行为,需要在同一 CAD 会话观察写入/读回或对照符号属性。不能直接断言电脑缺字体或库一定损坏。
|
||||
|
||||
## 结果范围
|
||||
|
||||
- CT34:4300-CA105E-T5 → 4300-CA1050-A100,saved_ok。
|
||||
- CT47、CT48:4300-NF150C-T5 → 4300-CF1500-5100,saved_ok。
|
||||
- CT51、CT55:4300-CF3300-5200 → 4300-CF3300-5100,saved_ok。
|
||||
- CT64、CT65、CT61 是同一失败组,未获得保存并重开回读成功证据,不能只把 CT64 一只视为未完成。
|
||||
|
||||
队列原有 7 组;前三组已确认成功,第 4 组因字体属性核验失败中断,后续 3 组未见启动状态。
|
||||
|
||||
失败后状态为 hard_failure / awaiting_reconciliation,收尾无法确认,17:01:58 触发自动超时并记录后台进程退出未确认。超时与释放失败是后续收尾问题;首发错误是 CT64 的 Part Label 字体 13 → 0 不一致。既不能把原生 helper 返回 0 当作全部成功,也不应把前三组已保存的成功记录抹掉。
|
||||
@@ -0,0 +1,29 @@
|
||||
# 诊断分析:T18250_IN_LOOP_Filter_Shield
|
||||
|
||||
日期:2026-11-03。来源:`DxPartReplace-诊断-20261103-164814`,现场版本 beta.31。本次仅分析,不修改程序、不打包。
|
||||
|
||||
## 结论与成功范围
|
||||
|
||||
导入的最终 9 行 BOM 均通过器件对应校验。本次队列有 2 个实际替换组:
|
||||
|
||||
- 16:46:46,第 0 组 `CT29`、`CT32`:`4300-CA2250-A200 → 4300-CA2250-A100`,状态 saved_ok,已保存并重开回读成功。
|
||||
- 第 1 组 `DT01`(UID `$9I3008`):`452F-7T0301-0S00 → 452N-7TUS03-0S00`。16:47:07 原生 helper 返回 code=0;16:47:10 连接校验失败,状态 hard_failure。没有该组保存并回读成功证据。
|
||||
|
||||
## 首发错误
|
||||
|
||||
图页为 `T18250 / TUNER_T18250`。quick-part-replace.log 给出:
|
||||
|
||||
| 引脚 | 替换前 | 替换后 |
|
||||
| --- | --- | --- |
|
||||
| 1 | (680,1120),`$9N4338 / GND` | (670,1130),`$9N2774 / LOOPOUT` |
|
||||
| 2 | (680,1180),`$9N2774 / LOOPOUT` | (670,1190),`$9N4338 / GND` |
|
||||
|
||||
两端网络按引脚号发生对调。当前 QPConnectionsMatch 允许统一平移,但要求已知引脚号、网络及相对几何匹配;此例无法匹配。因此不是单纯的坐标平移,也不是目标料号未找到。原生替换调用成功不等于连接关系验证通过。
|
||||
|
||||
更深层原因可能涉及新旧库符号的引脚编号/几何布局/方向,以及替换时的引脚对应关系。诊断包不能确定其中哪一项是库定义错误;需要对照两个料号的符号和真实引脚定义确认,不能仅凭日志判断应旋转还是修改库。
|
||||
|
||||
## 为什么随后停止
|
||||
|
||||
校验失败后进入 awaiting_reconciliation,safe_stop=false,程序无法确认这一组写入/保存的最终状态,保留 uncertain.flag。16:47:15 监督器自动超时停止;同时记录后台 CAD 进程退出未确认。因此“超时”和“后台释放失败”是首发连接冲突后的收尾问题,不是缺料号查询导致的首发错误。
|
||||
|
||||
建议人工检查 DT01 的实际料号及 1/2 脚网络,核对新旧符号对应关系后再决定处理方式。CT29、CT32 的成功证据应保留;不要将两组统称全部未替换,也不要跳过连接验证把 DT01 标为成功。
|
||||
@@ -28,7 +28,7 @@ Dim QP_ComponentUidIndex, QP_ComponentRefdesIndex, QP_ComponentLocationIndex
|
||||
Dim QP_ComponentIndexContext
|
||||
Dim QP_NativeCallActive
|
||||
Dim QP_BatchMode, QP_OwnedProject, QP_BatchState, QP_BatchCode, QP_BatchMessage
|
||||
Dim QP_BatchSaveCommitted
|
||||
Dim QP_BatchSaveCommitted, QP_BatchSaveRequested
|
||||
Dim QP_DiscoveryMode, QP_TargetSchematic, QP_TargetSheet
|
||||
Dim QP_FailureNumber, QP_FailureSource, QP_FailureDescription
|
||||
Dim QP_NcSyncSummary
|
||||
@@ -60,6 +60,7 @@ QP_BatchMode = False
|
||||
QP_OwnedProject = False
|
||||
QP_BatchState = ""
|
||||
QP_BatchSaveCommitted = False
|
||||
QP_BatchSaveRequested = False
|
||||
QP_DiscoveryMode = False
|
||||
QP_TargetSchematic = ""
|
||||
QP_TargetSheet = ""
|
||||
@@ -110,6 +111,10 @@ Else
|
||||
QP_FailureDescription = Err.Description
|
||||
If QP_DiscoveryMode Then QPCleanupDiscoveryFailure
|
||||
FailureState = "hard_failure"
|
||||
If QP_BatchSaveRequested Then
|
||||
FailureState = "batch_saved_unverified"
|
||||
QP_FailureDescription = "save was requested; persisted outcome requires reconciliation. " & QP_FailureDescription
|
||||
End If
|
||||
CloseError = ""
|
||||
If QP_BatchMode Or QP_SessionMode Then
|
||||
QPDiscardFailedBatchProject CloseError
|
||||
@@ -318,6 +323,7 @@ Sub QPSessionNext()
|
||||
QP_BatchMode = True
|
||||
QP_BatchState = ""
|
||||
QP_BatchSaveCommitted = False
|
||||
QP_BatchSaveRequested = False
|
||||
QP_NativeMutationPossible = False
|
||||
If Trim(QPReadUtf8(QP_Fso.BuildPath(QP_Root, "batch.request"))) <> QP_ExpectedJobId Then _
|
||||
Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "next batch authorization mismatch"
|
||||
@@ -709,7 +715,7 @@ End Sub
|
||||
Sub QPDiscoverInventory(ByRef Documents)
|
||||
Dim Requested, Schematics, Schematic, Sheets, Sheet, Document, View
|
||||
Dim Components, Comp, PartAttr, ValueAttr, PartNumber, PartKey, HitKey, Seen, Text, Count
|
||||
Dim ComponentText, ValueText, ComponentMode
|
||||
Dim ComponentText, ValueText, ComponentMode, Eligible, SkippedNoRef, ComponentUid, ComponentRef
|
||||
Set Requested = QPReadInventoryRequest()
|
||||
Set Seen = CreateObject("Scripting.Dictionary")
|
||||
Text = "project_path" & vbTab & "schematic_name" & vbTab & "sheet_number" & vbTab & "old_part" & vbCrLf
|
||||
@@ -717,6 +723,7 @@ Sub QPDiscoverInventory(ByRef Documents)
|
||||
ComponentText = "project_path" & vbTab & "schematic_name" & vbTab & "sheet_number" & vbTab & _
|
||||
"uid" & vbTab & "refdes" & vbTab & "old_part" & vbTab & "old_value" & vbCrLf
|
||||
Count = 0
|
||||
SkippedNoRef = 0
|
||||
Set Schematics = Documents.GetAvailableSchematics()
|
||||
For Each Schematic In Schematics
|
||||
Set Sheets = Documents.GetAvailableSheets(CStr(Schematic))
|
||||
@@ -739,24 +746,36 @@ Sub QPDiscoverInventory(ByRef Documents)
|
||||
Set PartAttr = QPFindCurrentAttribute(Comp, "Part Number")
|
||||
If Not PartAttr Is Nothing Then PartNumber = QPEffectiveAttributeValue(PartAttr)
|
||||
PartKey = LCase(CStr(PartNumber))
|
||||
If Requested.Exists(PartKey) Then
|
||||
If Len(PartNumber) > 0 And (Requested.Exists(PartKey) Or Requested.Exists("*")) Then
|
||||
Eligible = True
|
||||
If ComponentMode Then
|
||||
ComponentUid = CStr(Comp.UID)
|
||||
ComponentRef = CStr(Comp.Refdes)
|
||||
Eligible = QPInventoryEligible(ComponentUid, ComponentRef)
|
||||
If Not Eligible Then
|
||||
SkippedNoRef = SkippedNoRef + 1
|
||||
If SkippedNoRef <= 20 Then QPLog QP_Root, "WARN", _
|
||||
"inventory_skipped_no_ref uid=" & QPLogField(ComponentUid) & _
|
||||
" part=" & QPLogField(PartNumber) & " sheet=" & QPLogField(CStr(Sheet))
|
||||
End If
|
||||
End If
|
||||
If ComponentMode And Eligible Then
|
||||
ValueText = ""
|
||||
Set ValueAttr = QPFindCurrentAttribute(Comp, "Value")
|
||||
If Not ValueAttr Is Nothing Then ValueText = QPEffectiveAttributeValue(ValueAttr)
|
||||
If Len(CStr(Comp.UID)) = 0 Or Len(CStr(Comp.Refdes)) = 0 Then _
|
||||
Err.Raise vbObjectError + 872, "QuickPartReplace.Discovery", "component identity is incomplete"
|
||||
ComponentText = ComponentText & QPEncode(QPProjectPath()) & vbTab & _
|
||||
QPEncode(CStr(Schematic)) & vbTab & QPEncode(CStr(Sheet)) & vbTab & _
|
||||
QPEncode(CStr(Comp.UID)) & vbTab & QPEncode(CStr(Comp.Refdes)) & vbTab & _
|
||||
QPEncode(ComponentUid) & vbTab & QPEncode(ComponentRef) & vbTab & _
|
||||
QPEncode(CStr(PartNumber)) & vbTab & QPEncode(CStr(ValueText)) & vbCrLf
|
||||
End If
|
||||
HitKey = QPSheetKey(Schematic, Sheet) & Chr(30) & PartKey
|
||||
If Not Seen.Exists(HitKey) Then
|
||||
Seen.Add HitKey, True
|
||||
Text = Text & QPEncode(QPProjectPath()) & vbTab & _
|
||||
QPEncode(CStr(Schematic)) & vbTab & QPEncode(CStr(Sheet)) & vbTab & _
|
||||
QPEncode(CStr(Requested(PartKey))) & vbCrLf
|
||||
If Eligible Then
|
||||
HitKey = QPSheetKey(Schematic, Sheet) & Chr(30) & PartKey
|
||||
If Not Seen.Exists(HitKey) Then
|
||||
Seen.Add HitKey, True
|
||||
Text = Text & QPEncode(QPProjectPath()) & vbTab & _
|
||||
QPEncode(CStr(Schematic)) & vbTab & QPEncode(CStr(Sheet)) & vbTab & _
|
||||
QPEncode(CStr(PartNumber)) & vbCrLf
|
||||
End If
|
||||
End If
|
||||
End If
|
||||
Next
|
||||
@@ -768,8 +787,18 @@ Sub QPDiscoverInventory(ByRef Documents)
|
||||
Next
|
||||
QPWriteUtf8 QP_Fso.BuildPath(QP_Root, "inventory.tsv"), Text
|
||||
If ComponentMode Then QPWriteUtf8 QP_Fso.BuildPath(QP_Root, "components.tsv"), ComponentText
|
||||
If SkippedNoRef > 0 Then WScript.StdErr.WriteLine _
|
||||
"inventory: skipped " & CStr(SkippedNoRef) & " objects without Ref Designator; see quick-part-replace.log"
|
||||
End Sub
|
||||
|
||||
Function QPInventoryEligible(ByVal Uid, ByVal Refdes)
|
||||
QPInventoryEligible = False
|
||||
If Len(CStr(Refdes)) = 0 Then Exit Function
|
||||
If Len(CStr(Uid)) = 0 Then Err.Raise vbObjectError + 872, _
|
||||
"QuickPartReplace.Discovery", "component identity is incomplete: missing UID for refdes=" & CStr(Refdes)
|
||||
QPInventoryEligible = True
|
||||
End Function
|
||||
|
||||
Function QPReadInventoryRequest()
|
||||
Dim Path, Lines, Header, Result, Index, Fields, OldPart, Key
|
||||
Path = QP_Fso.BuildPath(QP_Root, "inventory-request.tsv")
|
||||
@@ -872,12 +901,21 @@ Sub QPCloseBatchProject(ByVal ExpectedPath, ByVal SaveChanges)
|
||||
If Documents.Count <> 1 Then Err.Raise vbObjectError + 871, "QuickPartReplace.Batch", "open sheet set changed; no automatic close"
|
||||
Set Document = Documents.Item(1)
|
||||
QPProgress "save_and_close", 0, 1
|
||||
If SaveChanges Then
|
||||
QP_BatchSaveRequested = True
|
||||
QPLog QP_Root, "INFO", "save_requested job=" & QP_CurrentJobId
|
||||
End If
|
||||
Document.Close CBool(SaveChanges), ""
|
||||
If SaveChanges Then
|
||||
QP_BatchSaveCommitted = True
|
||||
QPLog QP_Root, "INFO", "save_returned job=" & QP_CurrentJobId
|
||||
End If
|
||||
If QPCanonicalPath(QPProjectPath()) <> QPCanonicalPath(ExpectedPath) Then _
|
||||
Err.Raise vbObjectError + 871, "QuickPartReplace.Batch", "project changed during sheet save"
|
||||
QP_App.CloseProject
|
||||
If Len(CStr(QP_App.GetProjectData().GetProjectFilePath())) > 0 Then _
|
||||
Err.Raise vbObjectError + 871, "QuickPartReplace.Batch", "project did not close; queue stopped"
|
||||
QPLog QP_Root, "INFO", "project_closed job=" & QP_CurrentJobId
|
||||
QP_OwnedProject = False
|
||||
QP_OwnedProjectPath = ""
|
||||
QPInvalidatePinIndex
|
||||
@@ -888,6 +926,10 @@ Sub QPDiscardFailedBatchProject(ByRef ErrorDescription)
|
||||
Dim ErrorNumber, ErrorSource, Description
|
||||
ErrorDescription = ""
|
||||
If (Not QP_BatchMode And Not QP_SessionMode) Or Not QP_OwnedProject Or QP_App Is Nothing Then Exit Sub
|
||||
If QP_NativeMutationPossible Or QP_BatchSaveRequested Or QP_BatchSaveCommitted Then
|
||||
ErrorDescription = "write or save outcome requires reconciliation; owned project retained without automatic save or discard"
|
||||
Exit Sub
|
||||
End If
|
||||
On Error Resume Next
|
||||
QPCloseBatchProject QP_OwnedProjectPath, False
|
||||
ErrorNumber = Err.Number
|
||||
@@ -932,7 +974,6 @@ Sub QPFinishBatchItem()
|
||||
If FinalState = "restored_ok" Then
|
||||
QPMarkBatchMutation Command
|
||||
QPCloseBatchProject TargetPath, True
|
||||
QP_BatchSaveCommitted = True
|
||||
ElseIf Not QP_SessionMode Then
|
||||
QPCloseBatchProject TargetPath, False
|
||||
End If
|
||||
@@ -950,8 +991,10 @@ Sub QPFinishBatchItem()
|
||||
Plans.Add CStr(Index), Candidate
|
||||
Next
|
||||
QPVerifyRestoredPlans Command, Records, Plans, ValueStates
|
||||
QPRecordValueReadback Command, Records, Plans, "saved_ok"
|
||||
If Not QP_SessionMode Then QPCloseBatchProject TargetPath, False
|
||||
FinalState = "saved_ok"
|
||||
QPLog QP_Root, "INFO", "saved_readback_verified job=" & QP_CurrentJobId
|
||||
If QP_SessionMode Then
|
||||
QP_BatchMessage = QP_BatchMessage & " Saved and reopened for readback; owned project checkpoint verified."
|
||||
Else
|
||||
@@ -1670,6 +1713,7 @@ Sub QPRestoreAfterOperatorReplace(ByRef Command, ByVal SnapshotPath)
|
||||
End If
|
||||
ReplacementSummary = QPReplacementSummary(Records, Plans, CStr(Command("old_part_number")), _
|
||||
CStr(Command("new_part_number")))
|
||||
QPRecordValueReadback Command, Records, Plans, "restored_ok"
|
||||
SuccessMessage = "Native replacement and parameter readback passed on current sheet. Replacements: " & _
|
||||
ReplacementSummary & " " & QPDisplayVerificationSummary(Records)
|
||||
If Len(QPTargetCell(Command)) > 0 Then SuccessMessage = SuccessMessage & _
|
||||
@@ -1680,6 +1724,54 @@ Sub QPRestoreAfterOperatorReplace(ByRef Command, ByVal SnapshotPath)
|
||||
QPLog QP_Root, "INFO", "verified replacement count=" & Plans.Count & " value_mode=" & QPValueMode(Command)
|
||||
End Sub
|
||||
|
||||
Sub QPRecordValueReadback(ByRef Command, ByRef Records, ByRef Plans, ByVal State)
|
||||
' Reporting only: never restore an attribute, save, or open a transaction.
|
||||
Dim Text, Failure
|
||||
On Error Resume Next
|
||||
Text = QPValueReadbackText(Command, Records, Plans, State)
|
||||
If Err.Number = 0 Then QPWriteUtf8 QP_Fso.BuildPath(QP_Root, "value-readback.tsv"), Text
|
||||
If Err.Number <> 0 Then
|
||||
Failure = Err.Description
|
||||
Err.Clear
|
||||
QPLog QP_Root, "WARN", "Value readback report unavailable: " & Failure
|
||||
End If
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
End Sub
|
||||
|
||||
Function QPValueReadbackText(ByRef Command, ByRef Records, ByRef Plans, ByVal State)
|
||||
Dim Text, Index, AttributeIndex, Original, Candidate, Record, Attr, Ref, OldValue, Value
|
||||
Dim OldPresent, Present
|
||||
Text = "V" & vbTab & "1" & vbTab & QPEncode(CStr(Command("job_id"))) & vbTab & _
|
||||
QPEncode(State) & vbTab & QPEncode(CStr(Records.Item("meta")("project_path"))) & vbTab & _
|
||||
QPEncode(QP_TargetSchematic) & vbTab & QPEncode(QP_TargetSheet) & vbCrLf
|
||||
For Index = 0 To Plans.Count - 1
|
||||
Set Original = Records.Item("components").Item(CStr(Index))
|
||||
Set Candidate = Plans.Item(CStr(Index))
|
||||
OldValue = "": OldPresent = "0"
|
||||
For AttributeIndex = 0 To Records.Item("attributes").Count - 1
|
||||
Set Record = Records.Item("attributes").Item(CStr(AttributeIndex))
|
||||
If CStr(Record("uid")) = CStr(Original("uid")) And _
|
||||
StrComp(CStr(Record("name")), "Value", vbTextCompare) = 0 Then
|
||||
OldValue = QPSavedEffectiveValue(Record): OldPresent = "1"
|
||||
Exit For
|
||||
End If
|
||||
Next
|
||||
Value = "": Present = "0"
|
||||
Set Attr = QPFindCurrentAttribute(Candidate, "Value")
|
||||
If Not Attr Is Nothing Then
|
||||
Value = QPEffectiveAttributeValue(Attr): Present = "1"
|
||||
End If
|
||||
Ref = CStr(Original("refdes"))
|
||||
If Len(Ref) = 0 Then Ref = "UID=" & CStr(Original("uid"))
|
||||
Text = Text & "C" & vbTab & QPEncode(CStr(Original("uid"))) & vbTab & QPEncode(Ref) & vbTab & _
|
||||
QPEncode(CStr(Command("old_part_number"))) & vbTab & _
|
||||
QPEncode(QPRequiredAttributeValue(Candidate, "Part Number")) & vbTab & _
|
||||
QPEncode(OldValue) & vbTab & QPEncode(Value) & vbTab & OldPresent & vbTab & Present & vbCrLf
|
||||
Next
|
||||
QPValueReadbackText = Text
|
||||
End Function
|
||||
|
||||
Function QPReplacementSummary(ByRef Records, ByRef Plans, ByVal OldPartNumber, ByVal NewPartNumber)
|
||||
Dim Index, Candidate, ComponentRecord, Identity, Entry
|
||||
QPReplacementSummary = ""
|
||||
@@ -1832,6 +1924,7 @@ Sub QPRecoverSavedJob(ByRef Command, ByVal SnapshotPath)
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
If ErrorNumber = 0 Then
|
||||
QPRecordValueReadback Command, Records, Plans, "restored_ok"
|
||||
If QP_BatchMode Then
|
||||
If QP_SessionMode Then Err.Raise vbObjectError + 865, _
|
||||
"QuickPartReplace.Recovery", "read-only recovery cannot reuse a project session"
|
||||
@@ -1926,13 +2019,12 @@ Sub QPRestorePreflight(ByRef Comp, ByRef ComponentRecord, _
|
||||
Next
|
||||
Set LabelAttr = QPFindCurrentAttribute(Comp, "Part Label")
|
||||
If LabelAttr Is Nothing Then
|
||||
Err.Raise vbObjectError + 805, "QuickPartReplace", _
|
||||
"Part Label readback failed: attribute is unavailable; refdes=" & _
|
||||
QPComponentIdentity(Comp) & "; uid=" & CStr(Comp.UID)
|
||||
LabelValue = ""
|
||||
Else
|
||||
LabelValue = QPEffectiveAttributeValue(LabelAttr)
|
||||
End If
|
||||
LabelValue = QPEffectiveAttributeValue(LabelAttr)
|
||||
If Len(LabelValue) = 0 Then Err.Raise vbObjectError + 805, _
|
||||
"QuickPartReplace", "Part Label readback failed: value is blank; refdes=" & _
|
||||
If Len(Trim(LabelValue)) = 0 And Not HasOldValue Then Err.Raise vbObjectError + 805, _
|
||||
"QuickPartReplace", "Part Label and original Value are unavailable; refdes=" & _
|
||||
QPComponentIdentity(Comp) & "; uid=" & CStr(Comp.UID)
|
||||
Set ValueAttr = QPFindCurrentAttribute(Comp, "Value")
|
||||
If ValueAttr Is Nothing Then
|
||||
@@ -2049,6 +2141,7 @@ Sub QPRestoreComponent(ByRef Comp, ByRef ComponentRecord, ByRef Attributes, _
|
||||
Dim ValueVisible
|
||||
Dim DefaultedFields
|
||||
Dim HasOldNc
|
||||
Dim UsedOldValue
|
||||
|
||||
Comp.Orientation = CLng(ComponentRecord("orientation"))
|
||||
Comp.Scale = CDbl(ComponentRecord("scale"))
|
||||
@@ -2059,6 +2152,7 @@ Sub QPRestoreComponent(ByRef Comp, ByRef ComponentRecord, ByRef Attributes, _
|
||||
Err.Raise vbObjectError + 803, "QuickPartReplace", "Refdes restore failed"
|
||||
End If
|
||||
LabelValue = ""
|
||||
UsedOldValue = False
|
||||
HasOldNc = False
|
||||
Set ValueRecord = Nothing
|
||||
For Index = 0 To Attributes.Count - 1
|
||||
@@ -2108,16 +2202,25 @@ Sub QPRestoreComponent(ByRef Comp, ByRef ComponentRecord, ByRef Attributes, _
|
||||
LabelValue = QPRequiredAttributeValue(Comp, "Part Number")
|
||||
Else
|
||||
If LabelAttr Is Nothing Then
|
||||
Err.Raise vbObjectError + 805, "QuickPartReplace", _
|
||||
"Part Label readback failed: attribute is unavailable; refdes=" & _
|
||||
QPComponentIdentity(Comp) & "; uid=" & CStr(Comp.UID)
|
||||
LabelValue = ""
|
||||
Else
|
||||
LabelValue = QPEffectiveAttributeValue(LabelAttr)
|
||||
End If
|
||||
If Len(Trim(LabelValue)) = 0 Then
|
||||
If ValueRecord Is Nothing Then Err.Raise vbObjectError + 805, "QuickPartReplace", _
|
||||
"Part Label and original Value are unavailable; refdes=" & QPComponentIdentity(Comp)
|
||||
LabelValue = QPSavedEffectiveValue(ValueRecord)
|
||||
UsedOldValue = True
|
||||
QPLog QP_Root, "INFO", "value_source=original_value refdes=" & QPComponentIdentity(Comp) & _
|
||||
" reason=missing_or_blank_part_label"
|
||||
Else
|
||||
QPLog QP_Root, "INFO", "value_source=target_part_label refdes=" & QPComponentIdentity(Comp)
|
||||
End If
|
||||
LabelValue = QPEffectiveAttributeValue(LabelAttr)
|
||||
End If
|
||||
If Len(LabelValue) = 0 Then Err.Raise vbObjectError + 805, _
|
||||
If Len(LabelValue) = 0 And Not UsedOldValue Then Err.Raise vbObjectError + 805, _
|
||||
"QuickPartReplace", "Part Label readback failed: selected Value source is blank; refdes=" & _
|
||||
QPComponentIdentity(Comp) & "; uid=" & CStr(Comp.UID)
|
||||
If HasOldNc Then LabelValue = QPAppendNcMarker(LabelValue)
|
||||
If HasOldNc And Not UsedOldValue Then LabelValue = QPAppendNcMarker(LabelValue)
|
||||
End If
|
||||
If ValueAttr Is Nothing Then
|
||||
If ValueRecord Is Nothing Then
|
||||
@@ -2188,22 +2291,18 @@ End Function
|
||||
Function QPNativeAttributeAbsenceAllowed(ByVal Name, ByVal ValueMode)
|
||||
QPNativeAttributeAbsenceAllowed = _
|
||||
(StrComp(CStr(Name), "Value", vbTextCompare) = 0)
|
||||
If QPNativeAttributeAbsenceAllowed Or ValueMode <> "preserve" Then Exit Function
|
||||
If QPNativeAttributeAbsenceAllowed Then Exit Function
|
||||
If ValueMode <> "preserve" And ValueMode <> "part_label" And ValueMode <> "legacy_part_label" Then Exit Function
|
||||
QPNativeAttributeAbsenceAllowed = _
|
||||
(StrComp(CStr(Name), "Part Label", vbTextCompare) = 0)
|
||||
End Function
|
||||
|
||||
Function QPValueHasNcMarker(ByVal Value)
|
||||
Dim Parts, Index
|
||||
QPValueHasNcMarker = False
|
||||
If InStr(CStr(Value), "/") = 0 Then Exit Function
|
||||
Parts = Split(CStr(Value), "/")
|
||||
For Index = 1 To UBound(Parts)
|
||||
If StrComp(Trim(CStr(Parts(Index))), "NC", vbTextCompare) = 0 Then
|
||||
QPValueHasNcMarker = True
|
||||
Exit Function
|
||||
End If
|
||||
Next
|
||||
Dim Matcher
|
||||
Set Matcher = New RegExp
|
||||
Matcher.Pattern = "(^|[^A-Za-z0-9])nc($|[^A-Za-z0-9_])"
|
||||
Matcher.IgnoreCase = True
|
||||
QPValueHasNcMarker = Matcher.Test(CStr(Value))
|
||||
End Function
|
||||
|
||||
Function QPAppendNcMarker(ByVal Value)
|
||||
@@ -2221,12 +2320,15 @@ End Function
|
||||
Sub QPSetRequiredNc(ByRef State, ByRef ComponentRecord, ByRef Attributes, ByVal Enabled)
|
||||
Dim Index, Record
|
||||
State("nc_required") = False
|
||||
If Not CBool(Enabled) Then Exit Sub
|
||||
State("fallback_value") = ""
|
||||
State("fallback_exists") = False
|
||||
For Index = 0 To Attributes.Count - 1
|
||||
Set Record = Attributes.Item(CStr(Index))
|
||||
If CStr(Record("uid")) = CStr(ComponentRecord("uid")) And _
|
||||
StrComp(CStr(Record("name")), "Value", vbTextCompare) = 0 Then
|
||||
State("nc_required") = QPValueHasNcMarker(QPSavedEffectiveValue(Record))
|
||||
State("fallback_value") = QPSavedEffectiveValue(Record)
|
||||
State("fallback_exists") = True
|
||||
State("nc_required") = CBool(Enabled) And QPValueHasNcMarker(QPSavedEffectiveValue(Record))
|
||||
Exit Sub
|
||||
End If
|
||||
Next
|
||||
@@ -2355,7 +2457,8 @@ Function QPCaptureValueState(ByRef Comp)
|
||||
End Function
|
||||
|
||||
Sub QPVerifyValuePolicy(ByRef Comp, ByVal ValueMode, ByRef Before)
|
||||
Dim Current, SourceName, ExpectedValue, ExpectedExists
|
||||
Dim Current, SourceName, ExpectedValue, ExpectedExists, UsedFallback
|
||||
UsedFallback = False
|
||||
If ValueMode = "preserve" Then
|
||||
Set Current = QPCaptureValueState(Comp)
|
||||
ExpectedExists = Before("exists")
|
||||
@@ -2374,9 +2477,17 @@ Sub QPVerifyValuePolicy(ByRef Comp, ByVal ValueMode, ByRef Before)
|
||||
ExpectedValue = CStr(Before("custom_value"))
|
||||
Else
|
||||
If ValueMode = "part_number" Then SourceName = "Part Number"
|
||||
ExpectedValue = QPRequiredAttributeValue(Comp, SourceName)
|
||||
ExpectedValue = QPEffectiveComponentAttribute(Comp, SourceName)
|
||||
If SourceName = "Part Label" And Len(Trim(ExpectedValue)) = 0 Then
|
||||
If Not Before.Exists("fallback_exists") Then _
|
||||
Err.Raise vbObjectError + 818, "QuickPartReplace", "original Value verification context is missing"
|
||||
If Not Before("fallback_exists") Then _
|
||||
Err.Raise vbObjectError + 818, "QuickPartReplace", "Part Label and original Value are unavailable"
|
||||
ExpectedValue = CStr(Before("fallback_value"))
|
||||
UsedFallback = True
|
||||
End If
|
||||
End If
|
||||
If Before("nc_required") Then ExpectedValue = QPAppendNcMarker(ExpectedValue)
|
||||
If Before("nc_required") And Not UsedFallback Then ExpectedValue = QPAppendNcMarker(ExpectedValue)
|
||||
If QPRequiredAttributeValue(Comp, "Value") <> ExpectedValue Then _
|
||||
Err.Raise vbObjectError + 818, "QuickPartReplace", "final Value mismatch"
|
||||
End If
|
||||
|
||||
@@ -45,6 +45,11 @@ if (-not $PythonExecutable) {
|
||||
}
|
||||
$PythonExecutable = (Resolve-Path -LiteralPath $PythonExecutable -ErrorAction Stop).Path
|
||||
$env:PYTHONPATH = $sourceRoot
|
||||
$dependencyRoot = & $PythonExecutable -c "import sysconfig; print(sysconfig.get_path('purelib'))"
|
||||
$verificationPython = & $PythonExecutable -c "import sys; print(sys._base_executable)"
|
||||
# The venv redirector creates another PID on Windows. Supervisor identity
|
||||
# regressions must exercise the real Python process, as the frozen EXE does.
|
||||
$env:PYTHONPATH = $sourceRoot + [System.IO.Path]::PathSeparator + $dependencyRoot
|
||||
$env:QT_QPA_PLATFORM = "offscreen"
|
||||
$smokeRoot = $null
|
||||
$distRoot = [System.IO.Path]::GetFullPath((Join-Path $repositoryRoot "dist\DxPartReplace"))
|
||||
@@ -69,7 +74,7 @@ try {
|
||||
|
||||
Push-Location $repositoryRoot
|
||||
$locationPushed = $true
|
||||
& $PythonExecutable -m pytest -q tests\v1_1 tests\trial_task_center\test_application.py tests\trial_task_center\test_execution_safety.py tests\part_replace\test_verification.py
|
||||
& $verificationPython -m pytest -q tests\v1_1 tests\trial_task_center\test_application.py tests\trial_task_center\test_execution_safety.py tests\part_replace\test_verification.py tests\integration\test_workspace_value_policy.py tests\integration\test_quick_value_modes.py tests\integration\test_automatic_replacement_regression.py tests\packaging
|
||||
if ($LASTEXITCODE -ne 0) { throw "Release verification failed; build stopped" }
|
||||
Remove-VerifiedBuildTarget -RepositoryRoot $repositoryRoot -RelativeTarget "build\DxPartReplace"
|
||||
Remove-VerifiedBuildTarget -RepositoryRoot $repositoryRoot -RelativeTarget "dist\DxPartReplace"
|
||||
|
||||
@@ -10,12 +10,18 @@ import win32com.client.gencache
|
||||
project_root = Path(SPECPATH).parent
|
||||
generated_root = project_root / "build" / "DxPartReplace-generated"
|
||||
generated_root.mkdir(parents=True, exist_ok=True)
|
||||
viewdraw_api = win32com.client.gencache.EnsureModule(
|
||||
"{4ADEF4E1-690A-11CE-9261-0020C5E26659}", 0, 1, 0
|
||||
)
|
||||
if viewdraw_api is None:
|
||||
raise RuntimeError("DxDesigner EE 7.9.5 type library is required for packaging")
|
||||
shutil.copyfile(viewdraw_api.__file__, generated_root / "viewdraw_api.py")
|
||||
optional_bindings = []
|
||||
try:
|
||||
viewdraw_api = win32com.client.gencache.EnsureModule(
|
||||
"{4ADEF4E1-690A-11CE-9261-0020C5E26659}", 0, 1, 0
|
||||
)
|
||||
except Exception:
|
||||
viewdraw_api = None
|
||||
if viewdraw_api is not None:
|
||||
shutil.copyfile(viewdraw_api.__file__, generated_root / "viewdraw_api.py")
|
||||
optional_bindings.append("viewdraw_api")
|
||||
# Otherwise com_api generates equivalent bindings from the target machine's
|
||||
# installed DxDesigner typelib, independent of Python and frozen gen_py writes.
|
||||
legacy_runtime_datas = [
|
||||
(
|
||||
str(project_root / 'src/dx_productivity/trial_task_center/assets/app.ico'),
|
||||
@@ -36,8 +42,9 @@ a = Analysis(
|
||||
pathex=[str(project_root / "src"), str(generated_root)],
|
||||
binaries=[],
|
||||
datas=legacy_runtime_datas,
|
||||
hiddenimports=[
|
||||
"viewdraw_api",
|
||||
hiddenimports=optional_bindings + [
|
||||
"win32com.client.genpy",
|
||||
"win32com.client.build",
|
||||
"win32com.client",
|
||||
"win32com.client.dynamic",
|
||||
"win32con",
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
DxDesigner 物料替换 1.2.0-beta.31
|
||||
|
||||
运行
|
||||
将整个 DxPartReplace 文件夹解压到本机可写目录,再双击 DxPartReplace.exe。
|
||||
必须保留 _internal 文件夹;请勿只复制 EXE。已附带 Python、Qt、Excel 读写和 Windows 自动化依赖,无需安装 Python、Qt 或 Microsoft Excel。
|
||||
适用 Windows 10/11 64 位。目标电脑仍需安装可用且具有许可证的 DxDesigner,以及工程所用的器件库。本版沿用原软件的 DxDesigner EE 7.9.5 接口。
|
||||
|
||||
当前策略(beta.31,替代下文 beta.22~28 历史中心库存在性查询方案)
|
||||
导入、保存及替换失败后,均不再额外查询中心库料号存在性。失败项记录旧/新料号、图页及原始原因,跳过并留待人工处理;继续后续可执行项。目标料号列表轮询预算缩短为 8 秒,不把超时当作已证实缺料。核心原生替换与指定目标封装所需核验保留。
|
||||
|
||||
工作流程
|
||||
1. 选择“单工程替换”或“批量替换”,添加 .prj 或工程根目录。
|
||||
2. 导入一份总表、多份 CBB 分表或分表文件夹。旧路径失效时按唯一工程名称匹配,未找到的项目需要人工指定。
|
||||
3. 核对工程和器件明细。新读入的工程显示在列表前部,并保持本次读取顺序。已是目标料号的器件自动跳过;同位号存在歧义、当前料号冲突或缺失时按 Excel 行报告。有问题的工程保留待处理,通过的工程可先保存计划并执行。逐份导入只更新命中的工程,其他工程的计划和完成记录继续保留。
|
||||
4. 执行前保存并关闭本次处理的 CAD 工程。软件沿用原生 Replace Part / Library Wins,使用独立后台 CAD,并保留原来的连接、身份和显示属性核验。
|
||||
5. 查看“替换结果”,可以导出 Excel;新增“原 Value”和“实际回读 Value”,前者取替换前快照,后者取实际器件回读。旧历史未记录的 Value 标为“未记录”,不会根据计划推算。保存未确认、失败和未匹配记录单独标明。
|
||||
6. 工程列表按蓝色“正在替换”、浅橙色“未完成”、绿色“已完成”分组,点击标题可分别展开/收起。默认收起已完成,记住用户折叠设置;旧处理轮次保留在历史记录中。
|
||||
7. 执行时“安全暂停”等当前项收尾;“停止当前工程”直接结束本软件为当前项目创建的后台进程,不等待 COM 返回。该项目标红为“已停止 / 结果待核验”,保留日志、备份和已有结果;其余尚未启动的工程可继续处理。停止不代表回滚工程改动。
|
||||
|
||||
Value 与 NC
|
||||
默认取替换后器件的有效 Part Label。Part Label 缺少或空白时使用替换前快照中的旧 Value。
|
||||
识别独立的 NC、nc、/NC、/nc、_NC、_nc;旧 Value 含 NC 时,新 Value 保留 NC,已有标记不重复添加。NC_OPTION、NCM 等文本不当作 NC。
|
||||
自定义 Value 沿用原软件的逐行优先规则,可在器件明细中检查和修改。Value 的原位置、字体、方向和可见性继续保留。
|
||||
如 Part Label 与旧 Value 都不可用,工程会进入明确的错误或待核验状态,不应重复点击替换。
|
||||
|
||||
历史、日志与恢复
|
||||
“移出当前列表”保留历史结果和工程文件;重新导入是按当前工程状态核对的新一轮处理。
|
||||
进度条显示实际阶段与工程计数,不使用计时模拟百分比。“展开详情”查看过程,“日志”查看错误信息,“诊断包”导出 ZIP 后可发回排查。
|
||||
出现保存未确认或中断时先使用“核验恢复”。它会核查已有结果,不直接重复原生替换。后台资源释放异常时使用“检查后台会话”。如果主界面被强制关闭,后台监督进程会检测主进程退出,先请求安全停止并尝试正常关闭 CAD;若替换卡在不安全的写入阶段,经过等待后会留下待核验保护记录,再收尾自有进程。中断结果不会自动重放。下次启动先查看日志和“核验恢复”。
|
||||
运行记录、历史和配置保存在 EXE 旁的 data 文件夹。升级时先保留整个 data;仅替换程序和 _internal。
|
||||
beta.9 起,导入前会自动检查强制退出后遗留的后台记录;确认后台已退出即可继续,不需要删除 data。底部“检查后台会话”可手动复核,仍待处理时不会显示为成功。
|
||||
beta.10 对损坏或无法打开的工程不再自动恢复或重复读取:CAD 启动或读取无进展限时为45秒,读取超时后最多再给5秒合作退出时间,然后关闭本次只读会话、报告“工程损坏或无法读取,已跳过”,再处理其他工程。取消只读采集的合作退出限时为5秒,随后执行有界的自有进程收尾。重启后自动核验并关闭已失去主窗口的旧只读监督进程,要求请求、进程身份和启动记录一致;不会按进程名称清理其他 CAD。
|
||||
中断的实际替换/保存仍保留待核验保护;恢复导入不表示替换结果已经核验。
|
||||
|
||||
验证范围
|
||||
验证包括临时目录中的真实 Windows 进程、实际 Windows Script Host 上的模拟器件报告、界面交互与打包启动检查;未打开或修改用户真实 CAD 工程。
|
||||
本次没有对用户真实 CAD 工程进行端到端替换验收。
|
||||
当前开发机的 Windows 长路径策略未启用,6 项超长路径夹具测试未能完成;建议将程序和工程放在较短的本地路径。
|
||||
|
||||
第三方组件许可请见 THIRD_PARTY 目录。
|
||||
|
||||
诊断解析过程(beta.11)
|
||||
导入时自动记录报告解析、原始 UID、失败行附近片段、CAD 启动、工作进程阶段、5 秒等待快照、超时/取消/退出与资源释放。主日志记录导入进度、最终行数及失败原因。
|
||||
遇到问题时点击“诊断包”,发送完整 ZIP;不必仅复制 application.log。即使后台仍在等待也可以导出。新记录位于 data/quick-run-history 各次读取目录的 read-trace.jsonl 和 read-state.json。日志有限额并滚动保存;诊断包仅包含必要片段,不包含完整数据库或工程。新日志只能记录升级后发生的读取过程。
|
||||
本次仅增加诊断记录,不放宽 UID 检查,不调整替换及 Value/NC 规则。
|
||||
|
||||
电源端口与器件采集(beta.12)
|
||||
针对诊断包发现的 POWER_IN 电源端口导致采集失败问题,原生报告会识别明确的 POWER_IN/in.1 与 POWER_OUT/out.1,并交叉校验两份报告。CAD 采集跳过并记录无位号对象;带位号但缺少 UID 的对象仍报告身份不完整。其他无法确认的符号仍需 CAD 核验,替换逻辑及 Value/NC 属性规则不变。
|
||||
本版已通过报告模拟和 Windows Script Host 假对象验证;尚需在真实 DxDesigner 工程中验证。
|
||||
|
||||
工程读取与诊断包(beta.13)
|
||||
原生报告按 in.1/out.1 端口类型识别没有位号的命名端口,仍交叉核验两份报告。工程采集后若指纹不可读,仅在本软件的只读后台已确认关闭工程和工作进程时,先关闭该后台,再重新核验完整工程;数据仍不可读或确实变化时不会按通过处理。
|
||||
诊断包优先保留近期任务和日志;主日志过大时保留最新部分,文件和总容量仍有限制。替换及 Value/NC 规则未修改。
|
||||
|
||||
批量导入容错(beta.14)
|
||||
工作区 BOM 导入遇到无法认证释放的读取错误时停止后续采集,但保留此前已完整通过的工程计划草稿,可保存并执行这些已通过项目;失败和未检查工程不会生成替换计划。工程文件在两次读取间变化或无法验证时,只有监督器确认本软件的只读后台会话已释放,才会标记该工程跳过并继续批次;否则仍停止,避免带着未确认的 CAD 会话继续运行。
|
||||
|
||||
Value 中的 _NC(beta.13)
|
||||
旧 Value 含 _NC 或 _nc 时,默认以新 Part Label 为 Value,并补充 /NC;如果新 Part Label 已带 NC 标识,不重复添加。无 Part Label 时保留原 Value,NC_OPTION、NCM 等较长文本不作为 NC 标识。
|
||||
|
||||
后台会话复核(beta.15)
|
||||
修复暂停/强制停止遗留 cleanup=null 时,资源复核反复报 NoneType 错误并阻断后续导入的问题。启动检查或“检查后台会话”确认原进程和桌面已释放后可继续处理其他工程;原工程的待核验标记和历史结果保留。无需删除 data 或 session.json。
|
||||
|
||||
代码审查修复(beta.16)
|
||||
连续导入多个 CBB 时保留其他工程尚未保存的核验预览;重新导入失败时撤销受影响工程的旧草稿并阻止沿用旧计划执行,其他工程保留。切换工程时旧表格编辑不能记入新工程。工作台默认隐藏未选中器件,手工配置页仍可显示和勾选全部器件。工程之间或启动前暂停会正确显示暂停并从剩余工程继续,暂停位置不使用不存在的队列编号。
|
||||
读取超时区分打开工程超时和其他读取超时,不再直接推断工程损坏。位号与属性冲突记录具体 UID、标题位号、属性位号和报告行号,仍要求 CAD 核验;原生替换、Value/NC 和待核验保护规则保持。
|
||||
|
||||
beta.16 验证:完整测试 1016 项通过;6 项超长路径测试在建立夹具目录时被当前 Windows 策略限制(WinError 206/3),未进入产品逻辑。便携版独立监督进程启动和资源释放自检通过;未对用户真实 CAD 工程执行端到端替换。
|
||||
|
||||
beta.17:调整浅色工作台的渐变、卡片、字体和进度样式,左侧增加工程搜索;工程分组、器件明细和原操作流程保留。
|
||||
|
||||
beta.18:任意工程替换卡在结果待核验状态时,软件在确认写入保护记录后限时停止该工程所属的后台进程并标记自动跳过;确认资源释放后继续其他工程。已有待核验工程在导入时单独标记,其他工程继续核验;执行时跳过该工程。待核验记录保留,实际结果请人工检查。后台资源不能确认释放时仍会阻止下一工程启动。
|
||||
|
||||
目标料号预检(beta.22)
|
||||
工作台导入 BOM 时,在只读工程核对后检查该工程关联的中心库,批量查询目标新料号。不存在、重名和查询失败分别显示;失败条目在器件明细中标红并只供查看,所在工程不可保存执行,其他通过工程可继续处理。保存编辑后的计划时再次查询。查询只验证中心库料号存在性,原生替换时仍需实际器件和符号核验。
|
||||
|
||||
中心库副本与报告入口(beta.23)
|
||||
复制库的校验依据完整文件清单、大小与 SHA256,不再因文件系统时间戳精度差异拒绝内容一致的副本。源库或副本内容差异报告具体文件;诊断包包含脱敏校验明细,不包含库文件。顶部固定 BOM 校验报告入口可重复打开最近报告;选择记录可复制完整说明。
|
||||
|
||||
工程读取一致性(beta.24)
|
||||
读取前后以完整文件清单、大小与 SHA256 比较内容,消除只更新 mtime/ctime 或文件身份导致的读取拒绝;缓存仍以严格指纹失效。数据库会话内容变化仍要求连续两次相同 CAD 采集结果且其他设计文件内容稳定。实际内容变化或读取不完整时保留拦截,提示具体文件并把 discovery-checks 差异纳入诊断包。
|
||||
|
||||
表格复制(beta.25)
|
||||
器件明细单击旧料号或新料号后 Ctrl+C 复制当前列,多选行时逐行复制,Ctrl+A 后可复制当前列全部可见行。右键菜单可复制当前列、旧料号或新料号。只读、缺失物料和筛选状态均可复制完整单元格内容,不改变替换计划。
|
||||
|
||||
单元格复制与部分计划(beta.26)
|
||||
器件明细改为单元格选中,Ctrl+C 复制选择范围的 TSV,含复选框值;复制短暂虚线并在成功后消失,显示已复制提示。多选行的批量填料号继续根据选中单元格所在行处理。
|
||||
中心库校验失败项默认不勾选但仍显示原因,禁止直接重新勾选已知失败目标。工程位号核验通过时,可编辑同工程其余正常条目的勾选并保存执行;保存时仍复查所选新料号。取消勾选的清单行保留可见,便于重新选择,未列入替换计划的其他器件仍默认隐藏。已执行或中断待核验任务继续保持保护。
|
||||
|
||||
保存复用中心库证据(beta.27)
|
||||
中心库存在性查询结果按库路径与内容哈希保存,证据摘要、后台资源退出和目标料号覆盖范围均核验后可复用。保存只复核所选料号证据,禁止重新启动 Library Manager;库变化、证据失效或未检查的新目标明确提示重新导入 BOM。保存过程显示阶段信息,文件内容校验可取消,取消后不写入计划。升级后请重新导入一次 BOM 建立新版证据缓存。
|
||||
|
||||
中心库改为失败后诊断(beta.28,取代前置检查)
|
||||
导入 BOM 和保存计划不再调用额外的中心库检查。只有原生替换失败、后台会话结束且可确定失败步骤时,才查询该目标料号,报告未找到、存在但替换失败、重名或无法查询。原始错误与待核验保护保留;失败后的中心库查询异常不阻止其他工程继续处理。手动停止或已取消时不启动诊断查询。升级后重新导入 BOM 清除此前前置检查产生的旧草稿状态。
|
||||
|
||||
结果列宽和历史工程(beta.29)
|
||||
替换结果所有列均可拖动标题边界调整宽度,列边界可见,取消末列强制拉伸;长内容通过水平滚动查看。列宽自动保存,下次打开恢复,也可点击按内容调整列宽。点击左侧已完成工程即读取该任务的保存历史,显示原 Value 与实际回读 Value;切换工程立即清除旧结果并防止迟到的查询覆盖新选择。历史缺失字段仍显示未记录,不用计划值补造实际结果。
|
||||
|
||||
本版读取优化(beta.30)
|
||||
报告标题含 UF? 等占位值时,两份报告的实际位号一致即可继续原生读取;不会把占位标题当成工程显示的位号。读取期间仅会话地址文件和 iCDB 数据库变化时,仍须两次库存一致且其他设计内容不变才接受。不取消 UID 身份核对。
|
||||
|
||||
beta.31 读取优化补充
|
||||
分层报告仍保留与展开标题相同的占位位号,而展开报告携带实际实例位号时,按同一唯一 UID 的有效属性读取。其他具体位号冲突仍要求 CAD 核对。后续成功项不再遮盖先前失败项详情。
|
||||
|
||||
复选框(beta.31)
|
||||
点击“替换”整格即可勾选/取消,也可选中单元格按空格。运行期间、已是目标及历史证据锁定的条目仍受只读限制。
|
||||
@@ -1,8 +1,8 @@
|
||||
# UTF-8
|
||||
VSVersionInfo(
|
||||
ffi=FixedFileInfo(
|
||||
filevers=(1, 1, 4, 2),
|
||||
prodvers=(1, 1, 4, 2),
|
||||
filevers=(1, 2, 0, 31),
|
||||
prodvers=(1, 2, 0, 31),
|
||||
mask=0x3f,
|
||||
flags=0x2,
|
||||
OS=0x40004,
|
||||
@@ -15,11 +15,11 @@ VSVersionInfo(
|
||||
StringTable('040904B0', [
|
||||
StringStruct('CompanyName', 'DxProductivity'),
|
||||
StringStruct('FileDescription', 'DxDesigner Part Replacement'),
|
||||
StringStruct('FileVersion', '1.1.4.2'),
|
||||
StringStruct('FileVersion', '1.2.0.31'),
|
||||
StringStruct('InternalName', 'DxPartReplace'),
|
||||
StringStruct('OriginalFilename', 'DxPartReplace.exe'),
|
||||
StringStruct('ProductName', 'DxDesigner Part Replacement'),
|
||||
StringStruct('ProductVersion', '1.1.4-beta.2')
|
||||
StringStruct('ProductVersion', '1.2.0-beta.31')
|
||||
])
|
||||
]),
|
||||
VarFileInfo([VarStruct('Translation', [1033, 1200])])
|
||||
|
||||
+2
-2
@@ -4,9 +4,9 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "dx-productivity"
|
||||
version = "1.1.4b2"
|
||||
version = "1.2.0b31"
|
||||
requires-python = ">=3.12,<3.13"
|
||||
dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<1", "openpyxl>=3.1,<4"]
|
||||
dependencies = ["PySide6-Essentials>=6.8,<6.9", "pywin32>=306", "pywinauto>=0.6.9,<1", "openpyxl>=3.1,<4"]
|
||||
|
||||
[project.scripts]
|
||||
dx-part-replace = "dx_productivity.part_replace.cli:main"
|
||||
|
||||
@@ -24,14 +24,17 @@ _DEFAULT_HOME_PARTS = ("DxProductivity", "trial-task-center")
|
||||
|
||||
def _load_window():
|
||||
"""Import Qt widgets only after diagnostics are ready for UI construction."""
|
||||
from dx_productivity.trial_task_center.ui import TrialTaskCenterWindow
|
||||
from dx_productivity.trial_task_center.ui.workspace_window import WorkspaceWindow
|
||||
|
||||
return TrialTaskCenterWindow
|
||||
return WorkspaceWindow
|
||||
|
||||
|
||||
def configure_application_identity(application: QApplication) -> None:
|
||||
"""Use one stable Windows identity and icon for source and portable launches."""
|
||||
from dx_productivity import trial_task_center
|
||||
from dx_productivity.trial_task_center.ui.workspace_styles import light_palette
|
||||
application.setStyle('Fusion')
|
||||
application.setPalette(light_palette())
|
||||
|
||||
if os.name == 'nt':
|
||||
import ctypes
|
||||
@@ -48,6 +51,7 @@ def configure_application_identity(application: QApplication) -> None:
|
||||
def _parse_arguments(argv: Sequence[str] | None) -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(prog="DxPartReplace")
|
||||
parser.add_argument("--smoke-test", action="store_true", help=argparse.SUPPRESS)
|
||||
parser.add_argument('--batch-worker', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument("--data-root", type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument("--native-helper", action="store_true", help=argparse.SUPPRESS)
|
||||
parser.add_argument("--snapshot", type=Path, help=argparse.SUPPRESS)
|
||||
@@ -119,25 +123,32 @@ def _flush(context: LoggingContext) -> None:
|
||||
|
||||
def _smoke_batch_runtime(data_root: Path, context: LoggingContext) -> None:
|
||||
"""Exercise process tracking inside the frozen supervisor before releasing."""
|
||||
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
|
||||
|
||||
with BatchCadRuntime(data_root, 'packaged_runtime_smoke') as runtime:
|
||||
runtime.bind_logs(context, ())
|
||||
with runtime.native_scope(data_root / 'runtime-smoke') as lease:
|
||||
command = str(Path(os.environ['SystemRoot']) / 'System32/cmd.exe')
|
||||
process = lease.start_process((command, '/d', '/c', 'exit', '0'))
|
||||
if not runtime.record['processes'][0]['creation_time']:
|
||||
raise RuntimeError('Smoke process identity has no creation time')
|
||||
if process.wait(timeout=15) != 0:
|
||||
raise RuntimeError('Smoke worker did not exit successfully')
|
||||
if runtime.record['state'] != 'released':
|
||||
raise RuntimeError('Smoke resources were not released')
|
||||
context.logger.info('packaged_runtime_smoke_passed batch_id=%s', runtime.session_id)
|
||||
from dx_productivity.trial_task_center.batch_supervisor import run_supervised
|
||||
from dx_productivity.trial_task_center.com_api import registered_api
|
||||
api = registered_api('{420B2830-E718-11CF-893D-00A0C9054228}', required=('IDictionary',))
|
||||
import win32com.client
|
||||
probe = api.IDictionary(win32com.client.Dispatch('Scripting.Dictionary')._oleobj_)
|
||||
probe.Add('portable', 'ok')
|
||||
if probe.Item('portable') != 'ok':
|
||||
raise RuntimeError('Generated COM bindings failed the portable runtime check')
|
||||
context.logger.info('packaged_com_bindings_smoke_passed')
|
||||
with_store = TaskStore(data_root / 'task-center.db')
|
||||
try:
|
||||
service = TaskCenterService(with_store, context, recover_on_startup=False)
|
||||
result = run_supervised(service, 'runtime_smoke', {})
|
||||
if not result['process_identity_read']:
|
||||
raise RuntimeError('Smoke worker identity was not checked')
|
||||
finally:
|
||||
with_store.close()
|
||||
context.logger.info('packaged_runtime_smoke_passed supervisor_pid=%s', result['pid'])
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
"""Run the Qt shell, returning a conventional process status code."""
|
||||
arguments = _parse_arguments(argv)
|
||||
if arguments.batch_worker is not None:
|
||||
from dx_productivity.trial_task_center.batch_worker import run
|
||||
return run(arguments.batch_worker)
|
||||
if arguments.mark_batch_attempt:
|
||||
from dx_productivity.trial_task_center.native_helper import run_attempt_marker
|
||||
return run_attempt_marker(job_id=arguments.attempt_job, task_id=arguments.attempt_task,
|
||||
@@ -171,6 +182,7 @@ def main(argv: Sequence[str] | None = None) -> int:
|
||||
_smoke_batch_runtime(data_root, logging_context)
|
||||
store = TaskStore(database_path)
|
||||
service = TaskCenterService(store, logging_context)
|
||||
service._supervised = True
|
||||
qt_application = QApplication([sys.executable, *(argv or ())])
|
||||
configure_application_identity(qt_application)
|
||||
window = _load_window()(service)
|
||||
|
||||
@@ -9,6 +9,7 @@ import time
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .logging_setup import append_task_event
|
||||
from .value_readback import value_readback_details
|
||||
from .models import TaskStatus
|
||||
from .quick_run import (
|
||||
BATCH_FAILED_STATE,
|
||||
@@ -67,13 +68,21 @@ def execute_batch(
|
||||
if task.status is TaskStatus.PAUSED and not stop_event.is_set():
|
||||
service._store.set_task_status(task_id, TaskStatus.RUNNING, summary='automatic queue resumed after confirmation')
|
||||
with measure_phase(service._logging, task_id, 'prepare_queue', unit='step') as metric:
|
||||
session = preparer.begin_batch_session(
|
||||
task_id,
|
||||
projects,
|
||||
rules,
|
||||
copy_part_number_to_value=task.copy_part_number_to_value,
|
||||
**({'runtime': runtime} if runtime is not None else {}),
|
||||
)
|
||||
try:
|
||||
session = preparer.begin_batch_session(
|
||||
task_id,
|
||||
projects,
|
||||
rules,
|
||||
copy_part_number_to_value=task.copy_part_number_to_value,
|
||||
**({'runtime': runtime} if runtime is not None else {}),
|
||||
)
|
||||
except TaskCenterError as error:
|
||||
# Sheet discovery here precedes execution of the batch. Do not classify
|
||||
# the same error from a later execution stage as safe to continue.
|
||||
if error.code != 'quick_run_sheet_discovery':
|
||||
raise
|
||||
raise TaskCenterError('quick_run_preflight',
|
||||
f'工程只读检查失败,已跳过,请人工检查;{error.message}') from error
|
||||
metric['completed_units'] = len(session.commands)
|
||||
initial_progress = progress
|
||||
progress = session.progress
|
||||
@@ -184,7 +193,8 @@ def execute_batch(
|
||||
} else 'INFO'
|
||||
append_task_event(service._logging, level=event_level,
|
||||
task_id=task_id, project_id=project_id, operation='quick_run_executed', message=last_result.message,
|
||||
details={'state': last_result.state, 'continue_queue': not updated.queue_complete,
|
||||
details={**value_readback_details(last_result, service._logging.logger),
|
||||
'state': last_result.state, 'continue_queue': not updated.queue_complete,
|
||||
'timing': metric,
|
||||
'project_path': str(current),
|
||||
'schematic_name': progress.next_schematic_name,
|
||||
|
||||
@@ -8,15 +8,16 @@ import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import tempfile
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
from .path_access import canonical_path, internal_path, retry_sharing_violation
|
||||
|
||||
|
||||
_IDENTITY = ('session_id', 'generation', 'attempt_id', 'task_id', 'job_id', 'project_path')
|
||||
|
||||
|
||||
def _project(value):
|
||||
return os.path.normcase(os.path.abspath(value))
|
||||
return os.path.normcase(str(canonical_path(value)))
|
||||
|
||||
|
||||
def _validate(record):
|
||||
@@ -37,22 +38,14 @@ def _validate(record):
|
||||
|
||||
|
||||
def _publish(path, record):
|
||||
path = Path(path)
|
||||
path = internal_path(path)
|
||||
descriptor, temporary = tempfile.mkstemp(prefix=f'.{path.name}.', suffix='.tmp', dir=path.parent)
|
||||
try:
|
||||
with os.fdopen(descriptor, 'w', encoding='utf-8', newline='') as handle:
|
||||
json.dump(record, handle, ensure_ascii=False, indent=2)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
deadline = time.monotonic() + 1
|
||||
while True:
|
||||
try:
|
||||
os.replace(temporary, path)
|
||||
break
|
||||
except PermissionError:
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(.02)
|
||||
retry_sharing_violation(lambda: os.replace(temporary, path))
|
||||
# POSIX needs a directory sync for the atomic rename; Windows does not
|
||||
# expose fsync on directories through the CRT.
|
||||
if os.name != 'nt':
|
||||
@@ -69,13 +62,13 @@ def prepare_attempt(path, *, session_id, generation, task_id, job_id, project_pa
|
||||
record = _validate(dict(schema_version=1, session_id=str(session_id), generation=generation,
|
||||
task_id=str(task_id), job_id=str(job_id), project_path=_project(project_path),
|
||||
attempt_id=uuid4().hex if attempt_id is None else attempt_id, state='prepared'))
|
||||
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
||||
retry_sharing_violation(lambda: internal_path(path).parent.mkdir(parents=True, exist_ok=True))
|
||||
_publish(path, record)
|
||||
return record
|
||||
|
||||
|
||||
def read_attempt(path):
|
||||
return _validate(json.loads(Path(path).read_text(encoding='utf-8')))
|
||||
return _validate(json.loads(internal_path(path).read_text(encoding='utf-8')))
|
||||
|
||||
|
||||
def _bound_attempt(path=None, *, job_id=None, task_id=None, project_path=None):
|
||||
@@ -86,7 +79,7 @@ def _bound_attempt(path=None, *, job_id=None, task_id=None, project_path=None):
|
||||
raw_path = os.environ.get('DXPART_ATTEMPT_FILE') if path is None else os.fspath(path)
|
||||
if not raw_path or not Path(raw_path).is_absolute():
|
||||
raise ValueError('invalid batch attempt file')
|
||||
path = Path(raw_path)
|
||||
path = internal_path(raw_path)
|
||||
job_id = str(job_id) if job_id is not None else os.environ.get('DXPART_JOB_ID')
|
||||
task_id = str(task_id) if task_id is not None else os.environ.get('DXPART_TASK_ID')
|
||||
if path.is_dir():
|
||||
|
||||
@@ -5,9 +5,11 @@ import os
|
||||
from pathlib import Path
|
||||
|
||||
from .logging_setup import LoggingContext, append_task_event, configure_logging
|
||||
from .path_access import internal_path
|
||||
|
||||
|
||||
def _append_line(path, line):
|
||||
path = internal_path(path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with path.open('a', encoding='utf-8', newline='\n') as stream:
|
||||
stream.write(line + '\n')
|
||||
@@ -23,8 +25,7 @@ def write_release_event(root, path, record, phase, *, context=None, reason='batc
|
||||
confirmation = confirmation if isinstance(confirmation, dict) else {}
|
||||
cad = record.get('cad_shutdown') if isinstance(record.get('cad_shutdown'), dict) else {}
|
||||
disappeared = confirmation.get('released')
|
||||
if phase == 'succeeded' and record.get('reconciled'):
|
||||
disappeared = True
|
||||
release_accepted = confirmation.get('release_accepted') is True or disappeared is True
|
||||
details = {'batch_id': record.get('session_id'), 'batch_kind': record.get('kind'),
|
||||
'generation': record.get('generation'), 'desktop': record.get('desktop'),
|
||||
'cad_pid': record.get('cad_pid'), 'cad_guid': record.get('cad_guid'),
|
||||
@@ -32,7 +33,9 @@ def write_release_event(root, path, record, phase, *, context=None, reason='batc
|
||||
'released' if phase == 'succeeded' else 'blocked'),
|
||||
'elapsed_seconds': elapsed, 'record_path': str(path),
|
||||
'desktop_handle_closed': cleanup.get('desktop_handle_closed'),
|
||||
'desktop_disappeared': disappeared, 'cad_exit_code': cad.get('cad_exit_code'),
|
||||
'desktop_disappeared': disappeared, 'desktop_release_accepted': release_accepted,
|
||||
'desktop_residual_only': confirmation.get('residual_only') is True,
|
||||
'cad_exit_code': cad.get('cad_exit_code'),
|
||||
'quit_helper_exit_code': cad.get('quit_helper_exit_code'),
|
||||
'cad_shutdown': cad, 'shutdown_warning': record.get('shutdown_warning'),
|
||||
'retries': record.get('retries', {}), 'cleanup': cleanup, 'error': str(error)}
|
||||
@@ -49,6 +52,8 @@ def write_release_event(root, path, record, phase, *, context=None, reason='batc
|
||||
label = lambda value: '已确认' if value is True else '未确认'
|
||||
message += (f" · 桌面句柄关闭:{label(details['desktop_handle_closed'])}"
|
||||
f" · 桌面消失:{label(disappeared)}")
|
||||
if details['desktop_residual_only']:
|
||||
message += ' · 空桌面残留已记录,不阻塞后续任务'
|
||||
if cad:
|
||||
message += f" · CAD 退出码={details['cad_exit_code']},退出助手码={details['quit_helper_exit_code']}"
|
||||
if error:
|
||||
|
||||
@@ -9,6 +9,7 @@ import time
|
||||
from uuid import uuid4
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .path_access import canonical_path, internal_path, retry_sharing_violation
|
||||
|
||||
|
||||
# Recovery retains owned native handles after failed cleanup. This registry is
|
||||
@@ -17,29 +18,24 @@ LIVE_RESOURCES = {}
|
||||
|
||||
|
||||
class BatchResourceCleanupError(TaskCenterError):
|
||||
def __init__(self, message, *, completed_result=None):
|
||||
def __init__(self, message, *, completed_result=None, primary_error=None, cleanup_error=None):
|
||||
super().__init__('batch_resources_pending', message)
|
||||
self.completed_result = completed_result
|
||||
self.primary_error = primary_error
|
||||
self.cleanup_error = cleanup_error
|
||||
self.bom_report = getattr(primary_error, "bom_report", None)
|
||||
|
||||
|
||||
def write_record(path, record):
|
||||
path = Path(path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path = internal_path(path)
|
||||
retry_sharing_violation(lambda: path.parent.mkdir(parents=True, exist_ok=True))
|
||||
temporary = path.with_name(path.name + '.' + uuid4().hex + '.tmp')
|
||||
try:
|
||||
with temporary.open('w', encoding='utf-8', newline='\n') as stream:
|
||||
json.dump(record, stream, ensure_ascii=False, indent=2)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
deadline = time.monotonic() + 1.0
|
||||
while True:
|
||||
try:
|
||||
os.replace(temporary, path)
|
||||
break
|
||||
except PermissionError:
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(.02)
|
||||
retry_sharing_violation(lambda: os.replace(temporary, path))
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
@@ -70,9 +66,10 @@ def _valid_record(record, path):
|
||||
|
||||
def pending_resources(root):
|
||||
pending = []
|
||||
for path in sorted((Path(root).resolve() / 'batch-resources').glob('*/session.json')):
|
||||
for path in sorted(internal_path(canonical_path(root) / 'batch-resources').glob('*/session.json')):
|
||||
path = canonical_path(path)
|
||||
try:
|
||||
record = json.loads(path.read_text(encoding='utf-8'))
|
||||
record = json.loads(internal_path(path).read_text(encoding='utf-8'))
|
||||
if not _valid_record(record, path):
|
||||
raise ValueError('invalid resource ownership record')
|
||||
if record.get('state') != 'released':
|
||||
@@ -148,14 +145,36 @@ def cleanup_pending_resources(root, *, logging_context=None):
|
||||
if not record.get('session_id'):
|
||||
continue # Corrupt evidence cannot authorize resource actions.
|
||||
log('started')
|
||||
desktop = record.get('desktop')
|
||||
if desktop:
|
||||
_Win32Api().confirm_desktop_released(desktop)
|
||||
if not all(_process_gone(item) for item in record.get('processes', ())):
|
||||
log('failed', '记录中的进程仍未确认退出')
|
||||
continue
|
||||
# After restart only confirm disappearance. Never attach to COM,
|
||||
# close a project, or terminate a PID whose handles we no longer own.
|
||||
cad_pid = record.get('cad_pid')
|
||||
cad_identity = next((item for item in record.get('processes', ())
|
||||
if item['pid'] == cad_pid and item.get('creation_time')),
|
||||
{'pid': cad_pid, 'creation_time': None})
|
||||
if cad_pid is not None and not _process_gone(cad_identity):
|
||||
log('failed', '记录中的 CAD 进程仍未确认退出')
|
||||
continue
|
||||
# After restart, only inspect process identities and desktop state.
|
||||
# Never attach to COM, close a project, or terminate a PID whose
|
||||
# handles we no longer own. An empty desktop may remain enumerated
|
||||
# after every recorded process/handle is gone; retain that evidence
|
||||
# without making it a permanent execution lock.
|
||||
desktop = record.get('desktop')
|
||||
if desktop:
|
||||
api = _Win32Api()
|
||||
if _record_proves_owned_cleanup(record) or _orphan_owner_exited(record, path):
|
||||
api.confirm_desktop_released_or_empty(desktop)
|
||||
else:
|
||||
api.confirm_desktop_released(desktop)
|
||||
# An interrupted owner persists cleanup=null until it has a
|
||||
# receipt. setdefault does not replace an existing null value.
|
||||
cleanup = record.get('cleanup')
|
||||
if cleanup is None:
|
||||
cleanup = record['cleanup'] = {}
|
||||
if not isinstance(cleanup, dict):
|
||||
raise ValueError('invalid resource cleanup receipt')
|
||||
cleanup['desktop_confirmation'] = api.desktop_release_check
|
||||
record.pop('record_path', None)
|
||||
record = dict(record, state='released', reconciled=True, released_at=time.time())
|
||||
write_record(path, record)
|
||||
@@ -168,12 +187,53 @@ def cleanup_pending_resources(root, *, logging_context=None):
|
||||
return pending_resources(root)
|
||||
|
||||
|
||||
def project_checkpoint_released(root):
|
||||
root = Path(root).resolve()
|
||||
def _orphan_owner_exited(record, path):
|
||||
"""A crashed owner's process exit closes its handles without a final receipt.
|
||||
|
||||
Recorded workers and CAD have already been checked by the caller. This
|
||||
permits inspecting an empty desktop residue, never closing a live CAD.
|
||||
Old write uncertainty remains independent of this physical-resource proof.
|
||||
"""
|
||||
from .supervisor_protocol import READ_ONLY_OPERATIONS, valid_journal
|
||||
try:
|
||||
checkpoint = json.loads((root / 'project-checkpoint.json').read_text(encoding='utf-8'))
|
||||
owner = json.loads(internal_path(path.with_name('supervisor.json')).read_text(encoding='utf-8'))
|
||||
cleanup = owner.get('orphan_read_cleanup') or {}
|
||||
read_bootstrap_closed = (owner.get('operation') in READ_ONLY_OPERATIONS
|
||||
and cleanup.get('reason') == 'old_parent_exited_read_only'
|
||||
and cleanup.get('process') == owner.get('process')
|
||||
and cleanup.get('exit_confirmed') is True
|
||||
and _process_gone(owner['parent_process']))
|
||||
return (valid_journal(owner, record['session_id']) and owner.get('process') is not None
|
||||
and _process_gone(owner['process'])
|
||||
and (read_bootstrap_closed or not (
|
||||
record.get('cad_start_requested') and record.get('cad_pid') is None)))
|
||||
except (OSError, ValueError, TypeError, KeyError):
|
||||
return False
|
||||
|
||||
|
||||
def _record_proves_owned_cleanup(record):
|
||||
cleanup = record.get('cleanup')
|
||||
if (not isinstance(cleanup, dict) or cleanup.get('desktop_handle_closed') is not True
|
||||
or cleanup.get('errors')):
|
||||
return False
|
||||
history = cleanup.get('process_history')
|
||||
if not isinstance(history, list):
|
||||
return False
|
||||
return all(isinstance(item, dict)
|
||||
and isinstance(item.get('cleanup'), dict)
|
||||
and item['cleanup'].get('process_handle_closed') is True
|
||||
and item['cleanup'].get('job_handle_closed') is True
|
||||
and item['cleanup'].get('job_active_processes', 0) == 0
|
||||
and item['cleanup'].get('unconfirmed_descendant_handles', 0) == 0
|
||||
and not item['cleanup'].get('errors') for item in history)
|
||||
|
||||
|
||||
def project_checkpoint_released(root):
|
||||
root = canonical_path(root)
|
||||
try:
|
||||
checkpoint = json.loads(internal_path(root / 'project-checkpoint.json').read_text(encoding='utf-8'))
|
||||
path = Path(checkpoint['resource_record']).resolve()
|
||||
record = json.loads(path.read_text(encoding='utf-8'))
|
||||
record = json.loads(internal_path(path).read_text(encoding='utf-8'))
|
||||
key = str(root).casefold()
|
||||
return (_valid_record(record, path) and checkpoint.get('version') == 1
|
||||
and type(checkpoint.get('generation')) is int
|
||||
|
||||
@@ -6,11 +6,12 @@ import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
from uuid import uuid4
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from .batch_resources import (BatchResourceCleanupError, LIVE_RESOURCES, cleanup_pending_resources,
|
||||
guard_pending_resources, pending_resources, process_identity, project_checkpoint_released, write_record)
|
||||
from .errors import TaskCenterError
|
||||
from .path_access import canonical_path, internal_path, legacy_path
|
||||
from .isolated_desktop import PrivateDesktop
|
||||
from .operation_control import check_cancelled
|
||||
from .worker_monitor import WorkerMonitorError
|
||||
@@ -43,8 +44,12 @@ class _DesktopLease:
|
||||
return {'session_id': self.owner.session_id, 'generation': self.generation,
|
||||
'attempt_id': self.attempt_id}
|
||||
|
||||
def __exit__(self, *_exc):
|
||||
self.close()
|
||||
def __exit__(self, error_type, error, traceback):
|
||||
try:
|
||||
self.close()
|
||||
except BatchResourceCleanupError as cleanup:
|
||||
raise BatchResourceCleanupError(cleanup.message, primary_error=error,
|
||||
cleanup_error=cleanup) from cleanup
|
||||
|
||||
def start_process(self, command, **options):
|
||||
available = self.owner.record['state'] == 'ready' or (
|
||||
@@ -61,10 +66,11 @@ class _DesktopLease:
|
||||
for process in reversed(self.processes):
|
||||
try:
|
||||
self.owner._release_process(process, desktop=self.desktop, generation=self.generation)
|
||||
records.append(getattr(process, 'cleanup_record', {}))
|
||||
except Exception as error:
|
||||
errors.append(str(error))
|
||||
remaining.append(process)
|
||||
finally:
|
||||
records.append(getattr(process, 'cleanup_record', {}))
|
||||
self.processes = list(reversed(remaining))
|
||||
self.cleanup_record = {'scope': 'operation', 'processes': records,
|
||||
'workers_closed': not errors, 'desktop_retained_by_batch': True, 'errors': errors}
|
||||
@@ -78,10 +84,11 @@ class _DesktopLease:
|
||||
|
||||
|
||||
class BatchCadRuntime:
|
||||
def __init__(self, root, kind, stop_event=None, *, desktop_factory=None, cad_factory=None):
|
||||
self.root = Path(root).resolve()
|
||||
def __init__(self, root, kind, stop_event=None, *, desktop_factory=None, cad_factory=None, session_id=None):
|
||||
self.root = canonical_path(root)
|
||||
self.kind, self.stop_event = kind, stop_event
|
||||
self.session_id = uuid4().hex
|
||||
self.read_only = kind in {'bom_import', 'collect_target_inventory'}
|
||||
self.session_id = uuid4().hex if session_id is None else UUID(str(session_id)).hex
|
||||
self.path = self.root / 'batch-resources' / self.session_id / 'session.json'
|
||||
self.desktop_factory = desktop_factory or PrivateDesktop
|
||||
self.cad_factory = cad_factory
|
||||
@@ -89,11 +96,13 @@ class BatchCadRuntime:
|
||||
self.generation = 0
|
||||
self.result = None
|
||||
self.record = {'version': 1, 'session_id': self.session_id, 'kind': kind, 'state': 'new',
|
||||
'read_only': self.read_only,
|
||||
'generation': 0, 'desktop': None, 'cad_pid': None, 'cad_guid': None,
|
||||
'processes': [], 'checkpoints': {}, 'retries': {}, 'timings': [], 'native_operations': {}}
|
||||
self._retry_counts = {}
|
||||
self._project_attempts = {}
|
||||
self._logging = None
|
||||
self._active_evidence = None
|
||||
|
||||
def bind_logs(self, context, task_ids):
|
||||
"""Keep every participating task's final release outcome visible."""
|
||||
@@ -111,11 +120,31 @@ class BatchCadRuntime:
|
||||
return self
|
||||
|
||||
def __exit__(self, error_type, error, traceback):
|
||||
if error is not None and self._active_evidence is not None:
|
||||
attempts = [item for values in self._project_attempts.values() for item in values]
|
||||
try:
|
||||
self._retain_uncertain(self._active_evidence, None, attempts, error)
|
||||
except WorkerMonitorError:
|
||||
if not getattr(getattr(self.stop_event, 'force_event', None), 'is_set', lambda: False)():
|
||||
raise
|
||||
# Explicit force has durable protection; cleanup is now allowed.
|
||||
try:
|
||||
self.close()
|
||||
except Exception as cleanup:
|
||||
raise BatchResourceCleanupError('批次资源释放待处理;已核验任务结果保留。' + str(cleanup),
|
||||
completed_result=self.result) from cleanup
|
||||
def detail(failure):
|
||||
return {'type': type(failure).__name__, 'message': str(failure),
|
||||
'code': getattr(failure, 'code', None)}
|
||||
self.record['primary_error'] = detail(error) if error is not None else None
|
||||
self.record['cleanup_error'] = detail(cleanup)
|
||||
try:
|
||||
self._save()
|
||||
except Exception:
|
||||
pass # Journal failure must not replace either original failure.
|
||||
context = ('BOM 导入读取已停止;未生成可执行预览。'
|
||||
if self.kind == 'bom_import' else
|
||||
'已核验任务结果保留。' if self.result is not None else '本批操作已停止。')
|
||||
raise BatchResourceCleanupError('批次资源释放待处理;' + context + str(cleanup),
|
||||
completed_result=self.result, primary_error=error, cleanup_error=cleanup) from cleanup
|
||||
|
||||
def _save(self, **values):
|
||||
record = dict(self.record, **values)
|
||||
@@ -165,6 +194,27 @@ class BatchCadRuntime:
|
||||
def native_scope(self, evidence):
|
||||
return _DesktopLease(self, evidence, native=True)
|
||||
|
||||
def release_idle_for_fingerprint(self, project):
|
||||
"""Release only our checkpointed read session before hashing its files."""
|
||||
if (not self.read_only or self.cad is None or self._active_evidence is None
|
||||
or self.record.get('state') != 'ready'):
|
||||
return False
|
||||
root = canonical_path(self._active_evidence)
|
||||
try:
|
||||
checkpoint = json.loads(internal_path(root / 'project-checkpoint.json').read_text(encoding='utf-8'))
|
||||
if (canonical_path(checkpoint['project_path']) != canonical_path(project)
|
||||
or canonical_path(checkpoint['resource_record']) != canonical_path(self.path)
|
||||
or not project_checkpoint_released(root)):
|
||||
return False
|
||||
except (OSError, ValueError, TypeError, KeyError):
|
||||
return False
|
||||
# close() confirms our CAD, workers and desktop have exited. A failed
|
||||
# release propagates and never authorizes a hash or another project.
|
||||
self.close(reason='discovery_fingerprint')
|
||||
self.desktop = self.cad = None
|
||||
self._active_evidence = None
|
||||
return True
|
||||
|
||||
def _ensure_cad(self, abort_event=None):
|
||||
if self.cad is None:
|
||||
from .isolated_cad import IsolatedCadSession
|
||||
@@ -173,7 +223,10 @@ class BatchCadRuntime:
|
||||
started = time.monotonic()
|
||||
self._save(cad_start_requested=True)
|
||||
cad = factory(self.path.parent / f'generation-{self.generation + (self.desktop is None)}',
|
||||
abort_event=abort_event, desktop=lease)
|
||||
abort_event=abort_event, desktop=lease,
|
||||
**({'read_only': True} if self.read_only else {}),
|
||||
**({'stop_control': self.stop_event}
|
||||
if not self.read_only and hasattr(self.stop_event, 'force_event') else {}))
|
||||
self.cad = cad # Retain cleanup ownership even if startup fails.
|
||||
try:
|
||||
cad.__enter__()
|
||||
@@ -188,26 +241,26 @@ class BatchCadRuntime:
|
||||
self._save(state='ready', cad_pid=cad.binding.pid, cad_guid=cad.binding.guid)
|
||||
return self.cad
|
||||
|
||||
def _prepare_attempts(self, root, command, attempt_id):
|
||||
def _prepare_attempts(self, root, command, attempt_id, generation):
|
||||
from .batch_attempt import prepare_attempt
|
||||
from .quick_run import _read_commands
|
||||
rows = _read_commands(root / 'command.tsv')
|
||||
rows = _read_commands(internal_path(root / 'command.tsv'))
|
||||
selected_rows = [row for row in rows if row[1] == command[-1]]
|
||||
if len(selected_rows) != 1 or len({row[1] for row in rows}) != len(rows):
|
||||
raise TaskCenterError('target_identity', '批次工作命令身份缺失或重复,已停止。')
|
||||
selected = selected_rows[0]
|
||||
project = Path(selected[2]).resolve()
|
||||
self._save(active_project=str(project), active_task=selected[0], active_job=selected[1])
|
||||
directory = root / 'batch-attempts' / (self.session_id + f'-g{self.generation}-' + attempt_id)
|
||||
project = canonical_path(selected[2])
|
||||
self.record.update(active_project=str(project), active_task=selected[0], active_job=selected[1])
|
||||
directory = self.path.parent / 'attempts' / f'g{generation}' / attempt_id
|
||||
expected = []
|
||||
for row in rows:
|
||||
if Path(row[2]).resolve() == project:
|
||||
if canonical_path(row[2]) == project:
|
||||
path = directory / (row[1] + '.json')
|
||||
record = prepare_attempt(path, session_id=self.session_id, generation=self.generation,
|
||||
record = prepare_attempt(path, session_id=self.session_id, generation=generation,
|
||||
task_id=row[0], job_id=row[1], project_path=str(project), attempt_id=attempt_id)
|
||||
expected.append((path, record))
|
||||
self._project_attempts.setdefault(str(project).casefold(), []).extend(expected)
|
||||
return project, directory, expected
|
||||
return project, legacy_path(directory), expected
|
||||
|
||||
def _can_retry(self, project, expected):
|
||||
from .batch_attempt import can_retry_attempt
|
||||
@@ -229,51 +282,131 @@ class BatchCadRuntime:
|
||||
from .discovery_cache import project_fingerprint
|
||||
from .isolated_cad import PrivateCadStartupError, is_identity_conflict
|
||||
from .worker_monitor import run_monitored_process
|
||||
root = Path(command[3]).resolve()
|
||||
self._ensure_desktop(abort_event)
|
||||
# Operation provenance grants the read-only policy even when callers
|
||||
# do not expose a cancellation button/event.
|
||||
cooperative_abort = cooperative_abort or self.read_only
|
||||
root = canonical_path(command[3])
|
||||
from .read_trace import ReadTrace
|
||||
trace = ReadTrace(root, backend='cad-runtime')
|
||||
self._active_evidence = root
|
||||
while True:
|
||||
check_cancelled(abort_event or self.stop_event)
|
||||
attempt_id = uuid4().hex
|
||||
# No previous empty-project certificate may authorize continuation
|
||||
# once another operation could attach or open a project.
|
||||
self.record['checkpoints'].pop(str(root).casefold(), None)
|
||||
self._save(active_attempt=attempt_id)
|
||||
project, directory, expected = self._prepare_attempts(root, command, attempt_id)
|
||||
self.record['active_attempt'] = attempt_id
|
||||
if self.generation:
|
||||
self._save()
|
||||
generation = self.generation + (self.desktop is None)
|
||||
project, directory, expected = self._prepare_attempts(root, command, attempt_id, generation)
|
||||
self._ensure_desktop(abort_event)
|
||||
before = project_fingerprint(project, self.root)
|
||||
status = root / 'status.tsv'
|
||||
status = internal_path(root / 'status.tsv')
|
||||
status_before = status.read_bytes() if status.exists() else None
|
||||
started = time.monotonic()
|
||||
failure = None
|
||||
trace.project = str(project)
|
||||
trace.emit('cad_start', state='starting', session_id=self.session_id,
|
||||
attempt_id=attempt_id, job_id=command[-1], read_only=self.read_only)
|
||||
try:
|
||||
cad = self._ensure_cad(abort_event)
|
||||
trace.emit('cad_start', state='completed', cad_pid=self.record['cad_pid'],
|
||||
generation=self.generation, job_id=command[-1])
|
||||
cad.checkpoint(root / ('cad-ready-' + attempt_id + '.json'))
|
||||
environment = {'DXPART_ATTEMPT_FILE': str(directory), 'DXPART_ATTEMPT_ID': attempt_id,
|
||||
'DXPART_BATCH_SESSION_ID': self.session_id, 'DXPART_BATCH_GENERATION': str(self.generation)}
|
||||
def start_worker(launch, **options):
|
||||
return cad.start_worker(launch, extra_environment=environment, **options)
|
||||
result = run_monitored_process(command, timeout, abort_event=abort_event,
|
||||
cooperative_abort=cooperative_abort, process_factory=start_worker)
|
||||
cooperative_abort=cooperative_abort, process_factory=start_worker,
|
||||
owner_loss_path=self.path.parent / 'owner-loss.json',
|
||||
**({'force_control': self.stop_event} if hasattr(self.stop_event, 'force_event') else {}))
|
||||
if result.returncode and self.read_only and cooperative_abort:
|
||||
raise WorkerMonitorError(result.stderr or result.stdout or 'read worker failed')
|
||||
if result.returncode:
|
||||
self._retain_uncertain(root, project, expected,
|
||||
WorkerMonitorError(result.stderr or 'worker failed after possible mutation'))
|
||||
self._checkpoint(root, project, attempt_id)
|
||||
trace.emit('project_checkpoint', state='completed', job_id=command[-1],
|
||||
returncode=result.returncode)
|
||||
if result.returncode not in (2, 3):
|
||||
return result
|
||||
failure = WorkerMonitorError(result.stderr or 'pre-mutation worker startup failed')
|
||||
except (PrivateCadStartupError, WorkerMonitorError, subprocess.TimeoutExpired, OSError) as error:
|
||||
except Exception as error:
|
||||
from .worker_monitor import WorkerMonitorCancelled, WorkerMonitorSafeTimeout
|
||||
if not isinstance(error, (PrivateCadStartupError, WorkerMonitorError,
|
||||
subprocess.TimeoutExpired, OSError)):
|
||||
raise
|
||||
failure = error
|
||||
trace.emit('project_worker', state='failed', job_id=command[-1],
|
||||
error_type=type(error).__name__, error=str(error))
|
||||
finally:
|
||||
self._timing('project_worker', started, project=str(project), attempt_id=attempt_id,
|
||||
task_id=self.record['active_task'], job_id=self.record['active_job'])
|
||||
if self.read_only and cooperative_abort:
|
||||
# The whole session belongs to an import/read operation. A
|
||||
# stuck COM read has no pending authorized mutation to retain.
|
||||
# Do not report a failed project (or continue) until its owned
|
||||
# workers, CAD and desktop are positively released.
|
||||
trace.emit('read_session_release', state='starting', error=str(failure))
|
||||
self.close(reason='read_failure')
|
||||
trace.emit('read_session_release', state='completed', resources_released=True,
|
||||
error=str(failure))
|
||||
release = {'version': 1, 'session_id': self.session_id,
|
||||
'generation': self.generation, 'project_path': str(project),
|
||||
'resources_released': True, 'error': str(failure)}
|
||||
write_record(root / 'project-read-release.json', release)
|
||||
self.desktop = self.cad = None
|
||||
self._active_evidence = None
|
||||
check_cancelled(abort_event or self.stop_event)
|
||||
from .project_discovery import ReleasedProjectReadError
|
||||
if isinstance(failure, (subprocess.TimeoutExpired, WorkerMonitorSafeTimeout)):
|
||||
stage = getattr(failure, 'stage', '')
|
||||
try:
|
||||
stage = json.loads(internal_path(root / 'worker-progress.json').read_text(
|
||||
encoding='utf-8')).get('stage', stage)
|
||||
except (OSError, ValueError, TypeError, AttributeError):
|
||||
pass # Missing diagnostics cannot change release evidence.
|
||||
reason = '打开工程超时' if stage == 'open_project' else '工程读取超时'
|
||||
elif isinstance(failure, PrivateCadStartupError):
|
||||
reason = '后台 CAD 启动失败'
|
||||
else:
|
||||
reason = ('工程器件身份不完整' if 'component identity is incomplete' in str(failure)
|
||||
else '工程读取失败')
|
||||
raise ReleasedProjectReadError('quick_run_sheet_discovery',
|
||||
f'{reason},已跳过 / 无法处理:{project.name};'
|
||||
f'后台读取会话已释放;诊断原因:{failure}') from failure
|
||||
# Missing proof, changed inputs/status, cancellation or a previous
|
||||
# write anywhere in this project can never authorize replay.
|
||||
after = project_fingerprint(project, self.root)
|
||||
status_after = status.read_bytes() if status.exists() else None
|
||||
from .worker_monitor import WorkerMonitorCancelled, WorkerMonitorSafeTimeout
|
||||
if isinstance(failure, (WorkerMonitorCancelled, WorkerMonitorSafeTimeout)):
|
||||
read_only_stages = {'starting', 'session_startup', 'launch_designer', 'wait_designer',
|
||||
'check_project', 'open_project', 'open_sheet', 'query_components', 'snapshot_component'}
|
||||
cancel_proven = (failure.stage in read_only_stages and not failure.cleanup_notes
|
||||
and before is not None and before == after and status_before == status_after
|
||||
and self._can_retry(project, expected)
|
||||
and not internal_path(root / 'recovery.request').exists())
|
||||
if cancel_proven:
|
||||
if isinstance(failure, WorkerMonitorSafeTimeout):
|
||||
raise TaskCenterError('quick_run_project_open',
|
||||
f'打开工程超过安全等待时间,已停止该工程且未执行器件替换:{project.name}') from failure
|
||||
raise TaskCenterError('operation_cancelled',
|
||||
f'已在安全边界取消;未执行器件替换:{project.name}') from failure
|
||||
self._retain_uncertain(root, project, expected, failure)
|
||||
raise TaskCenterError('quick_run_uncertain',
|
||||
'取消时无法证明工程未发生变化,结果待核验;请保留工程和诊断后执行核验恢复。') from failure
|
||||
# Runtime database changes require separate identity evidence. Until
|
||||
# available for a failed read, use the stricter full fingerprint.
|
||||
safe = (not is_identity_conflict(failure) and before is not None and before == after
|
||||
and status_before == status_after and self._can_retry(project, expected)
|
||||
and not (root / 'recovery.request').exists()
|
||||
and not internal_path(root / 'recovery.request').exists()
|
||||
and not (abort_event is not None and abort_event.is_set())
|
||||
and not (self.stop_event is not None and self.stop_event.is_set()))
|
||||
if not safe:
|
||||
self._retain_uncertain(root, project, expected, failure)
|
||||
raise failure
|
||||
key = str(project).casefold()
|
||||
self._retry_counts[key] = 1
|
||||
@@ -281,18 +414,26 @@ class BatchCadRuntime:
|
||||
self._save(state='recycling')
|
||||
self.close(rebuilding=True) # Prove disappearance before creating another.
|
||||
self.desktop = self.cad = None
|
||||
self._ensure_desktop(abort_event)
|
||||
|
||||
def _retain_uncertain(self, root, project, expected, error):
|
||||
if self.read_only:
|
||||
return # Import/read sessions have no authorized CAD write to reconcile.
|
||||
from .batch_attempt import can_retry_attempt
|
||||
from .stop_control import wait_for_resolution
|
||||
attempts = self._project_attempts.get(str(project).casefold(), expected)
|
||||
if attempts and not all(can_retry_attempt(path, record) for path, record in attempts):
|
||||
wait_for_resolution(self.stop_event, root, error)
|
||||
|
||||
def recover_native_failure(self, project, evidence, reason):
|
||||
"""One read-only recovery, based on durable source and worker proof."""
|
||||
from .batch_attempt import can_retry_attempt
|
||||
project, evidence = Path(project).resolve(), Path(evidence).resolve()
|
||||
project, evidence = canonical_path(project), canonical_path(evidence)
|
||||
key = str(project).casefold()
|
||||
if (self._retry_counts.get(key) or self.record['state'] == 'blocked'
|
||||
if (self.read_only or self._retry_counts.get(key) or self.record['state'] == 'blocked'
|
||||
or self.stop_event is not None and self.stop_event.is_set()):
|
||||
return False
|
||||
try:
|
||||
proof = json.loads((evidence / 'native-retry-proof.json').read_text(encoding='utf-8'))
|
||||
proof = json.loads(internal_path(evidence / 'native-retry-proof.json').read_text(encoding='utf-8'))
|
||||
sources = proof['source_hashes']
|
||||
operation = self.record['native_operations'][str(evidence)]
|
||||
if (proof['version'] != 1 or proof['native_read_only'] is not True
|
||||
@@ -302,8 +443,8 @@ class BatchCadRuntime:
|
||||
or proof['workers_closed'] is not True or proof['project_path'] != str(project)
|
||||
or proof['evidence_root'] != str(evidence) or str(project) not in sources
|
||||
or len(sources) != 2
|
||||
or not all(Path(name).resolve().is_relative_to(project.parent) for name in sources)
|
||||
or not all(hashlib.sha256(Path(name).read_bytes()).hexdigest() == digest
|
||||
or not all(canonical_path(name).is_relative_to(project.parent) for name in sources)
|
||||
or not all(hashlib.sha256(internal_path(name).read_bytes()).hexdigest() == digest
|
||||
for name, digest in sources.items())
|
||||
or not all(can_retry_attempt(path, record)
|
||||
for path, record in self._project_attempts.get(key, ()))):
|
||||
@@ -368,7 +509,9 @@ class BatchCadRuntime:
|
||||
cad_record = cad_record if isinstance(cad_record, dict) else {}
|
||||
self.record['cad_shutdown'] = {key: cad_record[key] for key in (
|
||||
'state', 'clean', 'cad_exit_code', 'quit_helper_exit_code', 'cleanup_errors',
|
||||
'shutdown_seconds') if key in cad_record}
|
||||
'shutdown_seconds', 'orderly_shutdown', 'diagnostic_errors', 'forced_termination',
|
||||
'forced_root_termination', 'forced_descendant_pids', 'termination_reason',
|
||||
'read_only_released') if key in cad_record}
|
||||
if self.desktop is not None:
|
||||
try:
|
||||
self.desktop.close()
|
||||
|
||||
@@ -0,0 +1,608 @@
|
||||
"""GUI-side batch admission, process supervision and resource-only reconciliation."""
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import contextmanager
|
||||
import json
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import queue
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .path_access import canonical_path, internal_path, legacy_path
|
||||
from .supervisor_protocol import (VERSION, READ_ONLY_OPERATIONS, MessageGate, valid_journal,
|
||||
encode, decode, decode_error)
|
||||
|
||||
_WORKER_ROOT = None
|
||||
_LAUNCH_LOCK = threading.Lock()
|
||||
_LIVE_SUPERVISORS = {}
|
||||
AUTO_UNCERTAIN_GRACE_SECONDS = 5
|
||||
AUTO_PROJECT_IDLE_SECONDS = 360
|
||||
_WRITE_OPERATIONS = frozenset({'execute_task_queue', 'execute_quick_run_queue', 'execute_quick_run', 'recover_quick_run'})
|
||||
|
||||
|
||||
def _mark_interrupted(root, journal, reason):
|
||||
from .batch_resources import write_record, _valid_record
|
||||
from .stop_control import protect_interruption
|
||||
journal.update(state='blocked', outcome='interrupted', error=str(reason))
|
||||
if journal['operation'] in _WRITE_OPERATIONS:
|
||||
# A missing final result is not proof of no mutation. Publish the same
|
||||
# protection the existing recovery UI understands, without overwriting
|
||||
# any earlier, more specific marker.
|
||||
journal['business_uncertain'] = True
|
||||
task_ids = journal['task_ids']
|
||||
resource_path = Path(root) / 'batch-resources' / journal['batch_id'] / 'session.json'
|
||||
try:
|
||||
resource = json.loads(internal_path(resource_path).read_text(encoding='utf-8'))
|
||||
if (not journal.get('protect_all_targets') and _valid_record(resource, resource_path)
|
||||
and resource.get('active_task') in task_ids):
|
||||
task_ids = [resource['active_task']]
|
||||
except (OSError, ValueError, TypeError):
|
||||
pass # Without valid active ownership, protect every possible target.
|
||||
journal['protected_task_ids'] = list(task_ids)
|
||||
for task_id in task_ids:
|
||||
allowed = {canonical_path(root), canonical_path(Path(root) / 'tasks' / task_id)}
|
||||
actual = journal.get('uncertainty_roots', {}).get(task_id)
|
||||
roots = {canonical_path(actual)} if actual and canonical_path(actual) in allowed else allowed
|
||||
for evidence in roots:
|
||||
protect_interruption(evidence / 'quick-run',
|
||||
'reason=supervisor_interrupted; batch=' + journal['batch_id'] + '; manual reconciliation required\n')
|
||||
write_record(Path(root) / 'batch-resources' / journal['batch_id'] / 'supervisor.json', journal)
|
||||
|
||||
|
||||
def _worker_context(root):
|
||||
global _WORKER_ROOT
|
||||
_WORKER_ROOT = canonical_path(root)
|
||||
|
||||
|
||||
def _force_owned_supervisor(root, journal, process):
|
||||
"""Persist uncertainty before terminating the exact process/Job we own."""
|
||||
journal['stop_mode'] = 'forced'
|
||||
journal['force_requested_at'] = time.time()
|
||||
# The running worker can cross a task boundary while evidence is written.
|
||||
# Protect all possible targets before force; keep their saved results intact.
|
||||
journal['protect_all_targets'] = True
|
||||
reason = ('当前工程长时间无响应,自动结束;写入与保存结果须核验,禁止自动重放。'
|
||||
if journal.get('stop_initiator') == 'automatic_timeout' else
|
||||
'用户明确强制结束;写入与保存结果须核验,禁止自动重放。')
|
||||
_mark_interrupted(root, journal, reason)
|
||||
try:
|
||||
process.terminate()
|
||||
except Exception as error:
|
||||
if not getattr(process, 'cleanup_record', {}).get('forced_termination'):
|
||||
raise
|
||||
journal['force_cleanup_error'] = str(error)
|
||||
try:
|
||||
from .batch_resources import write_record
|
||||
write_record(Path(root) / 'batch-resources' / journal['batch_id'] / 'supervisor.json', journal)
|
||||
except OSError:
|
||||
pass # The forced intent and uncertainty were already durably saved.
|
||||
|
||||
|
||||
def _retain_supervisor_after_control_error(root, journal, process, control, error):
|
||||
"""Do not turn a GUI/transport exception into an unconfirmed Job kill."""
|
||||
from .batch_resources import write_record
|
||||
control.set()
|
||||
control.control_error = '控制通信异常,已请求安全停止并保留应用;可导出诊断或明确强制结束:' + str(error)
|
||||
journal['protect_all_targets'] = True
|
||||
try:
|
||||
_mark_interrupted(root, journal, error)
|
||||
except Exception as failure:
|
||||
control.control_error += ';中断证据尚未落盘:' + str(failure)
|
||||
try:
|
||||
write_record(Path(root) / 'batch-resources' / journal['batch_id'] / 'cancel.json',
|
||||
{'version': VERSION, 'batch_id': journal['batch_id'], 'attempt_id': journal['attempt_id']})
|
||||
except OSError:
|
||||
pass # Keep ownership; failure to request stop is not permission to kill.
|
||||
while True:
|
||||
if control.force_event.is_set():
|
||||
try:
|
||||
_force_owned_supervisor(root, journal, process)
|
||||
except Exception as failure:
|
||||
control.force_event.clear()
|
||||
control.control_error = '强制结束未确认,应用仍保留:' + str(failure)
|
||||
else:
|
||||
return True
|
||||
try:
|
||||
process.wait(timeout=.2)
|
||||
return False
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
except Exception as failure:
|
||||
control.control_error = '无法确认应用退出,保留所有权等待处理:' + str(failure)
|
||||
threading.Event().wait(.2)
|
||||
|
||||
|
||||
def _file_lock(handle, acquire):
|
||||
from .task_queue import _os_lock
|
||||
_os_lock(handle, acquire)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def supervisor_lease(root):
|
||||
root = internal_path(root)
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
if not _LAUNCH_LOCK.acquire(blocking=False):
|
||||
raise TaskCenterError('supervisor_busy', '另一批操作正在运行,请先安全收尾。')
|
||||
handle = None
|
||||
acquired = False
|
||||
try:
|
||||
handle = (root / '.batch-supervisor.execution.lock').open('a+b')
|
||||
if handle.seek(0, os.SEEK_END) == 0:
|
||||
handle.write(b'\0')
|
||||
handle.flush()
|
||||
try:
|
||||
_file_lock(handle, True)
|
||||
acquired = True
|
||||
except OSError as error:
|
||||
raise TaskCenterError('supervisor_busy', '另一窗口的批次监督进程尚未结束。') from error
|
||||
yield
|
||||
finally:
|
||||
if handle is not None:
|
||||
if acquired:
|
||||
_file_lock(handle, False)
|
||||
handle.close()
|
||||
_LAUNCH_LOCK.release()
|
||||
|
||||
|
||||
def assert_supervisor_idle(root):
|
||||
if _WORKER_ROOT == canonical_path(root):
|
||||
return
|
||||
with supervisor_lease(root):
|
||||
pass
|
||||
|
||||
|
||||
@contextmanager
|
||||
def mutation_lease(root):
|
||||
if _WORKER_ROOT == canonical_path(root):
|
||||
yield
|
||||
else:
|
||||
with supervisor_lease(root):
|
||||
yield
|
||||
|
||||
|
||||
def pending_supervisors(root):
|
||||
from .batch_resources import _process_gone
|
||||
pending = []
|
||||
for path in (internal_path(root) / 'batch-resources').glob('*/supervisor.json'):
|
||||
try:
|
||||
value = json.loads(path.read_text(encoding='utf-8'))
|
||||
if not valid_journal(value, path.parent.name):
|
||||
raise ValueError('invalid supervisor ownership record')
|
||||
if value.get('state') == 'finished':
|
||||
continue
|
||||
identity = value.get('process') or value.get('parent_process')
|
||||
if (value.get('state') in {'starting', 'running'} and identity and not _process_gone(identity)
|
||||
and value.get('parent_process') and not _process_gone(value['parent_process'])):
|
||||
continue
|
||||
pending.append(dict(value, record_path=str(canonical_path(path)), state='blocked'))
|
||||
except (OSError, ValueError, TypeError, KeyError) as error:
|
||||
pending.append({'state': 'blocked', 'record_path': str(canonical_path(path)), 'error': str(error)})
|
||||
return tuple(pending)
|
||||
|
||||
|
||||
def reconcile_supervisors(root):
|
||||
"""Recheck orphan ownership only; this never launches or replays a job."""
|
||||
from .batch_resources import _process_gone, pending_resources, write_record
|
||||
physical = pending_resources(root)
|
||||
for record in pending_supervisors(root):
|
||||
identity = record.get('process')
|
||||
if not record.get('batch_id') or (identity and not _process_gone(identity)):
|
||||
continue
|
||||
if record.get('outcome') not in {'interrupted', 'completed_resources_pending'}:
|
||||
_mark_interrupted(root, record, 'Supervisor ended without a reconciled final result')
|
||||
if any(item.get('session_id') == record['batch_id'] or not item.get('session_id') for item in physical):
|
||||
continue
|
||||
path = Path(record.pop('record_path'))
|
||||
outcome = 'completed' if record.get('outcome') == 'completed_resources_pending' else 'interrupted'
|
||||
record.update(state='finished', reconciled=True, outcome=outcome, reconciled_at=time.time())
|
||||
write_record(path, record)
|
||||
return pending_supervisors(root)
|
||||
|
||||
|
||||
def recheck_abandoned_resources(root, context, *, on_progress=None):
|
||||
"""Called with the admission lease held; never replays business work."""
|
||||
from .batch_resources import cleanup_pending_resources, pending_resources
|
||||
before = (*pending_resources(root), *pending_supervisors(root))
|
||||
if not before and not _LIVE_SUPERVISORS:
|
||||
return ()
|
||||
if on_progress is not None:
|
||||
on_progress('正在检查上次运行的后台会话;不会重复替换器件…')
|
||||
context.logger.info('resource_preflight_started pending=%d', len(before))
|
||||
for record in pending_supervisors(root):
|
||||
try:
|
||||
_close_orphan_read_supervisor(root, record)
|
||||
except Exception as error:
|
||||
context.logger.error('orphan_read_cleanup_failed batch_id=%s error=%s',
|
||||
record.get('batch_id'), error)
|
||||
for key, (owned_api, owned_process) in tuple(_LIVE_SUPERVISORS.items()):
|
||||
if key.parent.parent != root / 'batch-resources':
|
||||
continue
|
||||
try:
|
||||
owned_process.wait(timeout=0)
|
||||
except subprocess.TimeoutExpired:
|
||||
continue # A current process is not abandoned ownership.
|
||||
owned_process.close()
|
||||
owned_api.close_pending()
|
||||
_LIVE_SUPERVISORS.pop(key)
|
||||
physical = cleanup_pending_resources(root, logging_context=context)
|
||||
supervisors = reconcile_supervisors(root)
|
||||
remaining = (*physical, *supervisors)
|
||||
context.logger.info('resource_preflight_finished pending=%d business_replayed=false', len(remaining))
|
||||
return remaining
|
||||
|
||||
|
||||
def _read_request_proves_operation(root, record):
|
||||
"""Cross-check the actual one-shot request before abandoned-process action."""
|
||||
from .batch_resources import _valid_record
|
||||
directory = internal_path(Path(root) / 'batch-resources' / record['batch_id'])
|
||||
try:
|
||||
raw = (directory / 'request.json').read_bytes()
|
||||
request = json.loads(raw)
|
||||
if (not isinstance(request, dict)
|
||||
or hashlib.sha256(raw).hexdigest() != record['request_sha256']
|
||||
or request.get('version') != VERSION
|
||||
or request.get('batch_id') != record['batch_id']
|
||||
or request.get('attempt_id') != record['attempt_id']
|
||||
or request.get('operation') != record['operation']
|
||||
or request.get('task_ids') != record['task_ids']
|
||||
or canonical_path(request['root']) != canonical_path(root)):
|
||||
return False
|
||||
claim = json.loads((directory / 'claim.json').read_text(encoding='utf-8'))
|
||||
if not isinstance(claim, dict) or any(claim.get(key) != value for key, value in {
|
||||
'version': VERSION, 'batch_id': record['batch_id'],
|
||||
'attempt_id': record['attempt_id'], 'process': record['process']}.items()):
|
||||
return False
|
||||
path = directory / 'session.json'
|
||||
if path.exists():
|
||||
resource = json.loads(path.read_text(encoding='utf-8'))
|
||||
expected_kind = ('collect_target_inventory' if record['operation'] == 'collect_target_inventory'
|
||||
else 'bom_import')
|
||||
if (not _valid_record(resource, path) or resource.get('kind') != expected_kind
|
||||
or resource.get('read_only') is False):
|
||||
return False
|
||||
return True
|
||||
except (OSError, ValueError, TypeError, KeyError):
|
||||
return False
|
||||
|
||||
|
||||
def _close_orphan_read_supervisor(root, record):
|
||||
"""Admission-lease-only recovery of a legacy blocked read owner.
|
||||
|
||||
Keep a handle to the exact creation identity across the final checks and
|
||||
termination. Closing that supervisor releases its own child Job handles;
|
||||
physical child/desktop cleanup is independently checked by the caller.
|
||||
"""
|
||||
from .batch_resources import _process_gone, write_record
|
||||
if (not valid_journal(record, record.get('batch_id'))
|
||||
or record['operation'] not in READ_ONLY_OPERATIONS
|
||||
or record.get('process') is None
|
||||
or not _read_request_proves_operation(root, record)
|
||||
or not _process_gone(record['parent_process'])):
|
||||
return False
|
||||
import win32api
|
||||
import win32event
|
||||
import win32process
|
||||
identity = record['process']
|
||||
try:
|
||||
handle = win32api.OpenProcess(0x101001, False, identity['pid'])
|
||||
except Exception as error:
|
||||
code = getattr(error, 'winerror', error.args[0] if error.args else None)
|
||||
if code == 87:
|
||||
return False
|
||||
raise
|
||||
try:
|
||||
if (str(win32process.GetProcessTimes(handle)['CreationTime']) != identity['creation_time']
|
||||
or win32event.WaitForSingleObject(handle, 0) == 0
|
||||
or not _process_gone(record['parent_process'])):
|
||||
return False
|
||||
record['orphan_read_cleanup'] = {'reason': 'old_parent_exited_read_only',
|
||||
'process': identity, 'requested_at': time.time(), 'exit_confirmed': False}
|
||||
_mark_interrupted(root, record, '只读后台会话的原窗口已退出;正在释放其自有资源。')
|
||||
# A live parent never grants permission, even if other evidence changed
|
||||
# while the interruption diagnostic was flushed to disk.
|
||||
if not _process_gone(record['parent_process']):
|
||||
return False
|
||||
win32api.TerminateProcess(handle, 1)
|
||||
if win32event.WaitForSingleObject(handle, 5000) != 0:
|
||||
raise TimeoutError('orphan read supervisor exit was not confirmed within 5 seconds')
|
||||
record['orphan_read_cleanup'].update(exit_confirmed=True, confirmed_at=time.time())
|
||||
path = Path(root) / 'batch-resources' / record['batch_id'] / 'supervisor.json'
|
||||
write_record(path, record)
|
||||
return True
|
||||
finally:
|
||||
handle.Close()
|
||||
|
||||
|
||||
def _command(request):
|
||||
if bool(getattr(sys, 'frozen', False)):
|
||||
return (sys.executable, '--batch-worker', str(request))
|
||||
return (sys.executable, '-m', 'dx_productivity.trial_task_center.batch_worker', '--request', str(request))
|
||||
|
||||
|
||||
def _environment():
|
||||
environment = dict(os.environ)
|
||||
if bool(getattr(sys, 'frozen', False)):
|
||||
for key in ('PYTHONPATH', 'PYTHONHOME'):
|
||||
environment.pop(key, None)
|
||||
else:
|
||||
environment['PYTHONPATH'] = str(Path(__file__).resolve().parents[2])
|
||||
return environment
|
||||
|
||||
|
||||
def _finish_response(root, journal, response, context):
|
||||
"""A supervisor exit may release its last USER reference. Never repeat work."""
|
||||
from .batch_resources import cleanup_pending_resources, write_record
|
||||
from .supervisor_result import validated_outcome, resource_pending_error
|
||||
result, error, primary = validated_outcome(journal['operation'], response)
|
||||
pending = cleanup_pending_resources(root, logging_context=context)
|
||||
related = tuple(item for item in pending if item.get('session_id') == journal['batch_id'] or not item.get('session_id'))
|
||||
journal['state'] = 'blocked' if related else 'finished'
|
||||
journal['outcome'] = ('completed_resources_pending' if related and response.get('business_succeeded')
|
||||
else response.get('status', 'interrupted'))
|
||||
journal['resource_recheck'] = {'pending': bool(related), 'checked_at': time.time()}
|
||||
write_record(Path(root) / 'batch-resources' / journal['batch_id'] / 'supervisor.json', journal)
|
||||
if related:
|
||||
raise resource_pending_error(journal['operation'], result, error, primary)
|
||||
resource_path = internal_path(Path(root) / 'batch-resources' / journal['batch_id'] / 'session.json')
|
||||
try:
|
||||
resource = json.loads(resource_path.read_text(encoding='utf-8'))
|
||||
except FileNotFoundError:
|
||||
resource = {}
|
||||
shutdown = resource.get('cad_shutdown') or {}
|
||||
cleanup = resource.get('cleanup') or {}
|
||||
confirmation = cleanup.get('desktop_confirmation') or {}
|
||||
read_release = (journal['operation'] in READ_ONLY_OPERATIONS
|
||||
and resource.get('read_only') is True and resource.get('state') == 'released'
|
||||
and shutdown.get('read_only_released') is True
|
||||
and not shutdown.get('diagnostic_errors')
|
||||
and all(item.get('stage') in {'orderly_shutdown', 'forced_cleanup'}
|
||||
for item in shutdown.get('cleanup_errors', ()))
|
||||
and cleanup.get('desktop_handle_closed') is True and not cleanup.get('errors')
|
||||
and (confirmation.get('released') is True or confirmation.get('release_accepted') is True))
|
||||
if not read_release and (shutdown.get('orderly_shutdown') is False or shutdown.get('forced_termination')
|
||||
or shutdown.get('diagnostic_errors')
|
||||
or any(item.get('stage') != 'desktop_release' for item in shutdown.get('cleanup_errors', ()))):
|
||||
failure = TaskCenterError('application_shutdown_failed',
|
||||
'已核验业务结果保留,但应用未正常收尾;请查看退出诊断,不能将资源消失视为正常退出。')
|
||||
failure.completed_result, failure.cleanup_error = result, error
|
||||
raise failure
|
||||
if response.get('business_succeeded'):
|
||||
if response.get('error'):
|
||||
context.logger.info('supervisor_resource_recovery_passed batch_id=%s business_replayed=false', journal['batch_id'])
|
||||
return result
|
||||
if response.get('operation_error'):
|
||||
if error is not None and hasattr(error, 'bom_report') and not hasattr(primary, 'bom_report'):
|
||||
primary.bom_report = error.bom_report
|
||||
raise primary
|
||||
if response.get('error'):
|
||||
raise error
|
||||
raise TaskCenterError('supervisor_interrupted', '批次监督进程异常退出;未重放任务,请检查已有结果和保护记录。')
|
||||
|
||||
|
||||
def run_supervised(service, operation, arguments, *, stop_event=None, on_progress=None, on_phase=None):
|
||||
from .batch_resources import write_record, process_identity
|
||||
from .isolated_desktop import _Win32Api
|
||||
from .stop_control import StopControl
|
||||
root = canonical_path(service._logging.root)
|
||||
if stop_event is not None and stop_event.is_set():
|
||||
raise TaskCenterError('operation_cancelled', '本批操作已取消,未启动监督进程。')
|
||||
with supervisor_lease(root):
|
||||
remaining = recheck_abandoned_resources(root, service._logging, on_progress=on_progress)
|
||||
if operation == 'cleanup_batch_resources':
|
||||
return remaining # Resource inspection needs no new supervisor.
|
||||
if remaining:
|
||||
raise TaskCenterError('batch_resources_pending',
|
||||
'上次运行的后台会话仍未确认退出,暂不能连接 CAD。'
|
||||
'请检查后台会话或导出诊断包;已保存结果和待核验保护均已保留。')
|
||||
if stop_event is not None and stop_event.is_set():
|
||||
raise TaskCenterError('operation_cancelled', '后台会话检查已结束,本次操作已取消。')
|
||||
batch_id, attempt_id = uuid4().hex, uuid4().hex
|
||||
directory = root / 'batch-resources' / batch_id
|
||||
request = directory / 'request.json'
|
||||
journal = {'version': VERSION, 'batch_id': batch_id, 'attempt_id': attempt_id,
|
||||
'operation': operation, 'state': 'starting', 'started_at': time.time(),
|
||||
'task_ids': list(arguments.get('task_ids', ())) or ([arguments['task_id']] if arguments.get('task_id') else []),
|
||||
'process': None}
|
||||
if any(not isinstance(value, str) or Path(value).name != value or value in {'.', '..'}
|
||||
for value in journal['task_ids']):
|
||||
raise TaskCenterError('target_identity', '监督进程任务编号无效。')
|
||||
journal['uncertainty_roots'] = {task_id: str(canonical_path(
|
||||
service._project_task_service(task_id)._quick_run_preparer.data_root))
|
||||
for task_id in journal['task_ids'] if operation in _WRITE_OPERATIONS}
|
||||
import win32api
|
||||
parent = type('ParentIdentity', (), {'pid': os.getpid(), 'handle': win32api.GetCurrentProcess()})()
|
||||
journal['parent_process'] = process_identity(parent)
|
||||
write_record(request, {'version': VERSION, 'batch_id': batch_id, 'attempt_id': attempt_id,
|
||||
'root': str(root), 'database': str(canonical_path(service._store.path)),
|
||||
'operation': operation, 'arguments': encode(arguments), 'task_ids': journal['task_ids'],
|
||||
'interactive_stop': isinstance(stop_event, StopControl)})
|
||||
journal['request_sha256'] = hashlib.sha256(internal_path(request).read_bytes()).hexdigest()
|
||||
write_record(directory / 'supervisor.json', journal)
|
||||
gate, messages = MessageGate(batch_id, attempt_id), queue.Queue()
|
||||
api, process, reader = _Win32Api(), None, None
|
||||
sent_cancel, last_heartbeat = False, time.monotonic()
|
||||
uncertain_since, auto_force_accepted = None, False
|
||||
last_project_progress, last_progress_signature = time.monotonic(), None
|
||||
transport_error = None
|
||||
force_accepted = False
|
||||
def receive():
|
||||
try:
|
||||
while line := process.stdout.readline(1024 * 1024):
|
||||
try:
|
||||
messages.put(json.loads(line))
|
||||
except (ValueError, UnicodeError):
|
||||
messages.put({'type': 'invalid'})
|
||||
finally:
|
||||
messages.put(None)
|
||||
try:
|
||||
# A normal input-desktop supervisor owns its private-desktop children.
|
||||
# Only the supervisor, never the GUI, creates a private desktop.
|
||||
# Keep the guardian alive if the GUI is forcibly closed. It watches
|
||||
# the parent identity and can still ask its owned CAD session to
|
||||
# close through the normal Quit path.
|
||||
process = api.create_process(_command(internal_path(request)), None, legacy_path(root),
|
||||
_environment(), stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
|
||||
survive_parent_exit=True)
|
||||
journal.update(state='running', process=process_identity(process))
|
||||
write_record(directory / 'supervisor.json', journal)
|
||||
reader = threading.Thread(target=receive, daemon=True)
|
||||
reader.start()
|
||||
while process.poll() is None or not messages.empty():
|
||||
if (operation == 'execute_task_queue' and getattr(stop_event, 'auto_skip_uncertain', False)
|
||||
and process.poll() is None):
|
||||
signature = []
|
||||
for project_root in journal['uncertainty_roots'].values():
|
||||
try:
|
||||
progress = json.loads(internal_path(Path(project_root) / 'quick-run' / 'worker-progress.json').read_text(encoding='utf-8'))
|
||||
signature.append(tuple(progress.get(k) for k in ('token', 'job_id', 'sequence', 'stage', 'done', 'total', 'native_progress_frames')))
|
||||
except (OSError, ValueError, AttributeError):
|
||||
signature.append(None)
|
||||
signature = tuple(signature)
|
||||
if signature != last_progress_signature:
|
||||
last_progress_signature, last_project_progress = signature, time.monotonic()
|
||||
if time.monotonic() - last_project_progress >= AUTO_PROJECT_IDLE_SECONDS:
|
||||
try:
|
||||
journal['stop_initiator'] = 'automatic_timeout'
|
||||
_force_owned_supervisor(root, journal, process)
|
||||
except Exception as error:
|
||||
service._logging.logger.error('auto_idle_cleanup_failed batch_id=%s error=%s', batch_id, error)
|
||||
last_project_progress = time.monotonic()
|
||||
else:
|
||||
service._logging.logger.warning('auto_skip_idle_project batch_id=%s', batch_id)
|
||||
force_accepted = auto_force_accepted = True
|
||||
break
|
||||
if (uncertain_since is not None and time.monotonic() - uncertain_since >= AUTO_UNCERTAIN_GRACE_SECONDS
|
||||
and process.poll() is None
|
||||
and not getattr(getattr(stop_event, 'force_event', None), 'is_set', lambda: False)()):
|
||||
try:
|
||||
journal['stop_initiator'] = 'automatic_timeout'
|
||||
_force_owned_supervisor(root, journal, process)
|
||||
except Exception as error:
|
||||
service._logging.logger.error('auto_skip_cleanup_failed batch_id=%s error=%s', batch_id, error)
|
||||
uncertain_since = time.monotonic()
|
||||
else:
|
||||
service._logging.logger.warning('auto_skip_uncertain_project batch_id=%s', batch_id)
|
||||
force_accepted = auto_force_accepted = True
|
||||
break
|
||||
force = getattr(stop_event, 'force_event', None)
|
||||
if force is not None and force.is_set() and process.poll() is None:
|
||||
try:
|
||||
journal['stop_initiator'] = 'user'
|
||||
_force_owned_supervisor(root, journal, process)
|
||||
except Exception as error:
|
||||
force.clear()
|
||||
stop_event.control_error = '强制结束未执行或未确认;请保留窗口和诊断:' + str(error)
|
||||
service._logging.logger.error('force_stop_failed batch_id=%s error=%s', batch_id, error)
|
||||
else:
|
||||
force_accepted = True
|
||||
break
|
||||
if stop_event is not None and stop_event.is_set() and not sent_cancel:
|
||||
try:
|
||||
write_record(directory / 'cancel.json', {'version': VERSION, 'batch_id': batch_id, 'attempt_id': attempt_id})
|
||||
journal.update(stop_mode='safe', stop_requested_at=time.time())
|
||||
write_record(directory / 'supervisor.json', journal)
|
||||
sent_cancel = True
|
||||
except OSError as error:
|
||||
if hasattr(stop_event, 'control_error'):
|
||||
stop_event.control_error = '停止请求尚未成功记录,正在重试:' + str(error)
|
||||
try:
|
||||
value = messages.get(timeout=.1)
|
||||
except queue.Empty:
|
||||
if time.monotonic() - last_heartbeat > 15:
|
||||
service._logging.logger.warning('supervisor_heartbeat_delayed batch_id=%s; no automatic replay', batch_id)
|
||||
last_heartbeat = time.monotonic()
|
||||
continue
|
||||
if value is None or not gate.accept(value):
|
||||
continue
|
||||
last_heartbeat = time.monotonic()
|
||||
if value['type'] == 'progress' and on_progress is not None:
|
||||
last_project_progress = time.monotonic()
|
||||
on_progress(value['payload'])
|
||||
elif value['type'] == 'phase' and on_phase is not None:
|
||||
payload = decode(value['payload'])
|
||||
on_phase(*payload)
|
||||
elif value['type'] == 'state':
|
||||
state = decode(value['payload'])
|
||||
service._task_queue_feedback = state['queue']
|
||||
service._batch_feedback = state['batch']
|
||||
service._supervisor_waiting = bool(state.get('waiting_for_resolution'))
|
||||
if (operation == 'execute_task_queue' and getattr(stop_event, 'auto_skip_uncertain', False)
|
||||
and service._supervisor_waiting):
|
||||
uncertain_since = uncertain_since or time.monotonic()
|
||||
else:
|
||||
uncertain_since = None
|
||||
if on_phase is not None and state['phase'] in {'recycling', 'closing'}:
|
||||
from .bom_import_state import BomImportPhase
|
||||
on_phase(BomImportPhase.RECOVERING if state['phase'] == 'recycling' else BomImportPhase.RELEASING,
|
||||
'正在安全恢复读取会话…' if state['phase'] == 'recycling' else '正在释放后台资源…')
|
||||
process.wait(timeout=15)
|
||||
except Exception as error:
|
||||
transport_error = error
|
||||
if process is not None and isinstance(stop_event, StopControl):
|
||||
force_accepted = _retain_supervisor_after_control_error(root, journal, process, stop_event, error)
|
||||
finally:
|
||||
service._task_queue_feedback = None
|
||||
service._batch_feedback = None
|
||||
service._supervisor_waiting = False
|
||||
try:
|
||||
if process is not None:
|
||||
process.close() # Waits, and confines termination to the owned Job.
|
||||
api.close_pending()
|
||||
except Exception as error:
|
||||
if process is not None:
|
||||
_LIVE_SUPERVISORS[directory / 'supervisor.json'] = (api, process)
|
||||
transport_error = error if transport_error is None else TaskCenterError(
|
||||
'batch_resources_pending', f'监督进程错误:{transport_error};收尾错误:{error}')
|
||||
if reader is not None:
|
||||
reader.join(3)
|
||||
if force_accepted:
|
||||
from .batch_resources import cleanup_pending_resources
|
||||
try:
|
||||
cleanup_pending_resources(root, logging_context=service._logging)
|
||||
except Exception as error:
|
||||
service._logging.logger.error('forced_stop_cleanup_pending batch_id=%s error=%s', batch_id, error)
|
||||
raise TaskCenterError('auto_project_timeout' if auto_force_accepted else 'user_forced_stop',
|
||||
('当前工程超时,已保护待核验记录并结束所属后台会话。' if auto_force_accepted else
|
||||
'已按确认强制结束;已保存的执行证据保留,当前结果待核验。请先核验恢复,不要重复替换。'))
|
||||
try:
|
||||
try:
|
||||
response = json.loads(internal_path(directory / 'result.json').read_text(encoding='utf-8'))
|
||||
except FileNotFoundError:
|
||||
saved = json.loads(internal_path(directory / 'business-result.json').read_text(encoding='utf-8'))
|
||||
if (saved.get('version') != VERSION or saved.get('batch_id') != batch_id
|
||||
or saved.get('attempt_id') != attempt_id or not saved['payload'].get('business_succeeded')):
|
||||
raise ValueError('Untrusted saved business result')
|
||||
response = dict(saved, type='result', sequence=gate.sequence + 1)
|
||||
service._logging.logger.warning('supervisor_final_missing_saved_result_retained batch_id=%s', batch_id)
|
||||
if (response.get('version') != VERSION or response.get('batch_id') != batch_id
|
||||
or response.get('attempt_id') != attempt_id or response.get('type') != 'result'
|
||||
or type(response.get('sequence')) is not int or response['sequence'] < gate.sequence
|
||||
or type(response.get('generation')) is not int or response['generation'] < gate.generation):
|
||||
raise ValueError('stale or invalid final supervisor result')
|
||||
from .supervisor_result import validated_outcome, resource_pending_error
|
||||
decoded_result, decoded_error, decoded_primary = validated_outcome(operation, response['payload'])
|
||||
except (OSError, ValueError, KeyError, TypeError, AttributeError) as error:
|
||||
_mark_interrupted(root, journal, transport_error or error)
|
||||
# Recheck physical resources even when final business results are
|
||||
# missing; this never authorizes repeating the interrupted job.
|
||||
from .batch_resources import cleanup_pending_resources
|
||||
cleanup_pending_resources(root, logging_context=service._logging)
|
||||
failure = TaskCenterError('supervisor_interrupted',
|
||||
'批次监督进程未留下可信结果;保留保护记录,不自动重试。' +
|
||||
(f' 首发原因:{transport_error}' if transport_error else ''))
|
||||
failure.primary_error = transport_error or error
|
||||
raise failure from (transport_error or error)
|
||||
if transport_error is not None:
|
||||
if response['payload']['business_succeeded']:
|
||||
journal.update(state='blocked', outcome='completed_resources_pending', error=str(transport_error))
|
||||
write_record(directory / 'supervisor.json', journal)
|
||||
else:
|
||||
_mark_interrupted(root, journal, transport_error)
|
||||
raise resource_pending_error(operation, decoded_result, transport_error, decoded_primary)
|
||||
return _finish_response(root, journal, response['payload'], service._logging)
|
||||
@@ -0,0 +1,235 @@
|
||||
"""One request, one resource-owning supervisor process, no Qt application."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
from uuid import UUID
|
||||
|
||||
from .path_access import internal_path, canonical_path
|
||||
from .supervisor_protocol import VERSION, OPERATIONS, valid_journal, encode, decode, encode_error
|
||||
|
||||
|
||||
def record_owner_exit(path, record, control, context, reason):
|
||||
"""A broken pipe requests stop; only proven GUI exit permits orphan cleanup."""
|
||||
from .batch_resources import _process_gone, write_record
|
||||
from .stop_control import StopControl
|
||||
control.set()
|
||||
try:
|
||||
if not _process_gone(record['parent_process']):
|
||||
context.logger.warning('batch_control_lost_parent_alive batch_id=%s reason=%s',
|
||||
record['batch_id'], reason)
|
||||
return False
|
||||
if not internal_path(path).exists():
|
||||
write_record(path, dict(record, reason=reason, detected_at=time.time()))
|
||||
if isinstance(control, StopControl):
|
||||
control.owner_lost_event.set()
|
||||
context.logger.error('batch_owner_lost batch_id=%s reason=%s', record['batch_id'], reason)
|
||||
return True
|
||||
except Exception as error:
|
||||
context.logger.exception('batch_owner_loss_record_failed batch_id=%s error=%s', record['batch_id'], error)
|
||||
return False
|
||||
|
||||
|
||||
def _output_stream():
|
||||
if sys.stdout is not None:
|
||||
return sys.stdout, False
|
||||
# Windowed PyInstaller deliberately sets sys.stdout=None. The supervisor
|
||||
# still has the explicit inherited pipe from STARTUPINFO; duplicate it so
|
||||
# closing this Python stream cannot close an unrelated borrowed handle.
|
||||
import msvcrt
|
||||
import win32api
|
||||
import win32con
|
||||
source = win32api.GetStdHandle(win32con.STD_OUTPUT_HANDLE)
|
||||
handle = win32api.DuplicateHandle(win32api.GetCurrentProcess(), source,
|
||||
win32api.GetCurrentProcess(), 0, False, win32con.DUPLICATE_SAME_ACCESS)
|
||||
descriptor = msvcrt.open_osfhandle(handle.Detach(), os.O_WRONLY | os.O_BINARY)
|
||||
return os.fdopen(descriptor, 'w', encoding='utf-8', buffering=1), True
|
||||
|
||||
|
||||
def _admit_request(directory, request, request_bytes):
|
||||
from .batch_resources import _process_gone, process_identity
|
||||
import win32api
|
||||
deadline = time.monotonic() + 5
|
||||
while True:
|
||||
journal = json.loads(internal_path(directory / 'supervisor.json').read_text(encoding='utf-8'))
|
||||
if (not valid_journal(journal, request['batch_id'])
|
||||
or journal.get('attempt_id') != request['attempt_id']
|
||||
or journal.get('operation') != request.get('operation')
|
||||
or journal.get('task_ids') != request.get('task_ids')
|
||||
or canonical_path(request['root']) != canonical_path(directory.parent.parent)
|
||||
or journal.get('state') not in {'starting', 'running'}
|
||||
or journal.get('request_sha256') != hashlib.sha256(request_bytes).hexdigest()
|
||||
or not journal.get('parent_process', {}).get('creation_time')
|
||||
or _process_gone(journal['parent_process'])):
|
||||
raise ValueError('Stale or unowned supervisor request')
|
||||
if journal.get('process'):
|
||||
break
|
||||
if time.monotonic() >= deadline:
|
||||
raise ValueError('Supervisor launch identity was not published')
|
||||
time.sleep(.02)
|
||||
own = process_identity(type('WorkerIdentity', (), {'pid': os.getpid(), 'handle': win32api.GetCurrentProcess()})())
|
||||
if journal['process'] != own:
|
||||
raise ValueError('Supervisor request belongs to another process')
|
||||
# Atomic exclusive publication makes requests one-shot, including retained
|
||||
# requests invoked manually or racing a delayed/duplicate launch.
|
||||
with internal_path(directory / 'claim.json').open('x', encoding='utf-8') as stream:
|
||||
json.dump({'version': VERSION, 'batch_id': request['batch_id'], 'attempt_id': request['attempt_id'],
|
||||
'process': own}, stream)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
return journal['parent_process']
|
||||
|
||||
|
||||
def run(request_path):
|
||||
from .batch_resources import write_record
|
||||
from .batch_runtime import BatchCadRuntime
|
||||
from .batch_supervisor import _worker_context
|
||||
from .logging_setup import configure_logging
|
||||
from .service import TaskCenterService
|
||||
from .store import TaskStore
|
||||
|
||||
output, owns_output = _output_stream()
|
||||
request_path = canonical_path(request_path, strict=True)
|
||||
request_bytes = internal_path(request_path).read_bytes()
|
||||
request = json.loads(request_bytes)
|
||||
batch_id, attempt_id = request['batch_id'], request['attempt_id']
|
||||
if (request.get('version') != VERSION or UUID(batch_id).hex != batch_id or UUID(attempt_id).hex != attempt_id
|
||||
or request['operation'] not in OPERATIONS or type(request.get('interactive_stop', False)) is not bool):
|
||||
raise ValueError('Invalid batch supervisor request')
|
||||
root = canonical_path(request['root'])
|
||||
directory = root / 'batch-resources' / batch_id
|
||||
if request_path != directory / 'request.json':
|
||||
raise ValueError('Supervisor request ownership path mismatch')
|
||||
parent_identity = _admit_request(directory, request, request_bytes)
|
||||
_worker_context(root)
|
||||
from .stop_control import StopControl
|
||||
stop = StopControl() if request.get('interactive_stop', False) else threading.Event()
|
||||
finished, output_lock = threading.Event(), threading.Lock()
|
||||
kind = {'inspect_bom_batch': 'bom_import', 'preview_bom_batch': 'bom_import',
|
||||
'execute_task_queue': 'task_queue', 'execute_quick_run_queue': 'quick_run_queue'}.get(request['operation'], request['operation'])
|
||||
runtime = BatchCadRuntime(root, kind, stop, session_id=batch_id)
|
||||
owner_loss_path = directory / 'owner-loss.json'
|
||||
parent_exited = threading.Event()
|
||||
sequence = 0
|
||||
def mark_owner_lost(reason):
|
||||
if record_owner_exit(owner_loss_path, {'version': VERSION, 'batch_id': batch_id,
|
||||
'attempt_id': attempt_id, 'parent_process': parent_identity}, stop, context, reason):
|
||||
parent_exited.set()
|
||||
def emit(kind, payload=None, *, persist=False):
|
||||
nonlocal sequence
|
||||
with output_lock:
|
||||
sequence += 1
|
||||
envelope = {'version': VERSION, 'batch_id': batch_id, 'attempt_id': attempt_id,
|
||||
'generation': max(1, runtime.generation), 'sequence': sequence,
|
||||
'type': kind, 'payload': payload}
|
||||
if persist:
|
||||
write_record(directory / 'result.json', envelope)
|
||||
try:
|
||||
output.write(json.dumps(envelope, ensure_ascii=True, allow_nan=False) + '\n')
|
||||
output.flush()
|
||||
except (BrokenPipeError, OSError):
|
||||
mark_owner_lost('control_pipe_disconnected')
|
||||
def monitor():
|
||||
while not finished.is_set():
|
||||
try:
|
||||
if not parent_exited.is_set():
|
||||
from .batch_resources import _process_gone
|
||||
if _process_gone(parent_identity):
|
||||
mark_owner_lost('parent_process_exited')
|
||||
cancel = internal_path(directory / 'cancel.json')
|
||||
if cancel.is_file():
|
||||
value = json.loads(cancel.read_text(encoding='utf-8'))
|
||||
if value == {'version': VERSION, 'batch_id': batch_id, 'attempt_id': attempt_id}:
|
||||
stop.set()
|
||||
emit('heartbeat')
|
||||
feedback = getattr(service, '_task_queue_feedback', None)
|
||||
emit('state', encode({'phase': runtime.record['state'], 'queue': feedback,
|
||||
'batch': service.batch_feedback(),
|
||||
'waiting_for_resolution': getattr(stop, 'waiting_for_resolution', False),
|
||||
'resolution_error': getattr(stop, 'resolution_error', '')}))
|
||||
except Exception:
|
||||
stop.set() # Lost control evidence cannot authorize new work.
|
||||
finished.wait(1)
|
||||
context = configure_logging(root, log_path=directory / 'supervisor.log')
|
||||
store = TaskStore(Path(request['database']))
|
||||
service = TaskCenterService(store, context, recover_on_startup=False)
|
||||
thread = threading.Thread(target=monitor, daemon=True)
|
||||
thread.start()
|
||||
response = {'business_succeeded': False, 'status': 'error'}
|
||||
try:
|
||||
arguments = decode(request['arguments'])
|
||||
operation = request['operation']
|
||||
def progress(message):
|
||||
emit('progress', str(message))
|
||||
def phase(value, message):
|
||||
emit('phase', encode((value, str(message))))
|
||||
if operation == 'cleanup_batch_resources':
|
||||
result = service.cleanup_batch_resources()
|
||||
response.update(status='ok', business_succeeded=True, result=encode(result))
|
||||
else:
|
||||
with runtime:
|
||||
runtime.bind_logs(context, request['task_ids'])
|
||||
try:
|
||||
if operation == 'probe':
|
||||
result = {'pid': os.getpid(), 'resource_state': 'not_acquired'}
|
||||
elif operation == 'runtime_smoke':
|
||||
with runtime.native_scope(directory / 'runtime-smoke') as lease:
|
||||
child = lease.start_process((str(Path(os.environ['SystemRoot'])/'System32/cmd.exe'), '/d', '/c', 'exit', '0'))
|
||||
if not runtime.record['processes'][0]['creation_time'] or child.wait(timeout=15):
|
||||
raise RuntimeError('Supervisor process-identity smoke failed')
|
||||
result = {'pid': os.getpid(), 'process_identity_read': True}
|
||||
elif operation == 'execute_task_queue':
|
||||
from .task_queue import execute_task_queue
|
||||
result = execute_task_queue(service, **arguments, stop_event=stop, runtime=runtime)
|
||||
elif operation in {'inspect_bom_batch', 'preview_bom_batch'}:
|
||||
controls = {'stop_event': stop, 'on_progress': progress, 'runtime': runtime}
|
||||
if operation == 'inspect_bom_batch':
|
||||
controls['on_phase'] = phase
|
||||
result = getattr(service, operation)(**arguments, **controls)
|
||||
elif operation == 'collect_target_inventory':
|
||||
result = service.collect_target_inventory(**arguments, stop_event=stop, on_progress=progress, runtime=runtime)
|
||||
elif operation == 'execute_quick_run_queue':
|
||||
result = service.execute_quick_run_queue(**arguments, stop_event=stop, runtime=runtime)
|
||||
elif operation == 'target_cell_choices':
|
||||
result = service.target_cell_choices(**arguments)
|
||||
else:
|
||||
result = getattr(service, operation)(**arguments, runtime=runtime)
|
||||
runtime.result = result
|
||||
response.update(status='ok', business_succeeded=True, result=encode(result))
|
||||
write_record(directory / 'business-result.json', {'version': VERSION, 'batch_id': batch_id,
|
||||
'attempt_id': attempt_id, 'generation': max(1, runtime.generation), 'payload': response})
|
||||
if operation == 'inspect_bom_batch':
|
||||
from .bom_import_state import BomImportPhase
|
||||
phase(BomImportPhase.RELEASING, '本批位号核验结束,正在释放后台资源…')
|
||||
except Exception as error:
|
||||
response['operation_error'] = encode_error(error)
|
||||
raise
|
||||
except Exception as error:
|
||||
context.report_exception('batch_supervisor', error)
|
||||
response.update(status='error', error=encode_error(error))
|
||||
finally:
|
||||
finished.set()
|
||||
thread.join(3)
|
||||
store.close()
|
||||
emit('result', response, persist=True)
|
||||
if owns_output:
|
||||
output.close()
|
||||
return 0
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--request', required=True, type=Path)
|
||||
args = parser.parse_args()
|
||||
return run(args.request)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -14,6 +14,7 @@ class BomProjectPreview:
|
||||
baseline: tuple
|
||||
inventory: tuple
|
||||
rows: tuple
|
||||
fresh_inventory: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -21,6 +22,7 @@ class BomBatchPreview:
|
||||
anchor_task_id: str
|
||||
scope: tuple
|
||||
projects: tuple[BomProjectPreview, ...]
|
||||
explicit_scope: bool = False
|
||||
|
||||
|
||||
def _scope(store, task_id):
|
||||
@@ -42,6 +44,21 @@ def _identity(scope):
|
||||
return tuple(sorted((task.task_id, str(project.path.resolve()).casefold()) for task, project in scope))
|
||||
|
||||
|
||||
def explicit_scope(store, task_ids):
|
||||
result = []
|
||||
if len(set(task_ids)) != len(task_ids):
|
||||
raise TaskCenterError('project_binding', '本次工程列表存在重复任务')
|
||||
for task_id in task_ids:
|
||||
task = store.get_task(task_id)
|
||||
projects = store.list_projects(task_id)
|
||||
if task.status is TaskStatus.DELETED or len(projects) != 1:
|
||||
raise TaskCenterError('project_binding', '本次工程已移除或不是独立工程任务')
|
||||
result.append((task, projects[0]))
|
||||
if len({str(p.path.resolve()).casefold() for _, p in result}) != len(result):
|
||||
raise TaskCenterError('project_binding', '本次列表不能重复处理同一个工程')
|
||||
return tuple(result)
|
||||
|
||||
|
||||
def export_template(store, task_id, path):
|
||||
records = () if task_id is None else tuple({'project_name': task.name, 'project_path': str(project.path),
|
||||
'enabled': True, 'sync_nc': True} for task, project in _scope(store, task_id))
|
||||
@@ -50,6 +67,8 @@ def export_template(store, task_id, path):
|
||||
|
||||
def _assert_editable(service, task_id):
|
||||
context = service.task_context(task_id)
|
||||
if context.interrupted:
|
||||
raise TaskCenterError('quick_run_uncertain', f'工程 {context.task.name} 有未核验结果,请先核验恢复')
|
||||
if (context.task.status not in {TaskStatus.DRAFT, TaskStatus.READY} or context.has_evidence
|
||||
or context.interrupted or not context.project or not context.project.available):
|
||||
raise TaskCenterError('target_plan_locked', f'工程任务当前不能修改 BOM 计划:{context.task.name}')
|
||||
@@ -76,13 +95,20 @@ def save_batch(service, preview, rows_by_task):
|
||||
raise TaskCenterError('bom_import', '本批 BOM 预览的工程范围已改变')
|
||||
result = {}
|
||||
with store.transaction():
|
||||
if _identity(_scope(store, preview.anchor_task_id)) != preview.scope:
|
||||
current_scope = (explicit_scope(store, tuple(t for t, _ in preview.scope)) if preview.explicit_scope else
|
||||
_scope(store, preview.anchor_task_id))
|
||||
if _identity(current_scope) != preview.scope:
|
||||
raise TaskCenterError('project_binding', '本批工程范围已改变,请重新导入 BOM')
|
||||
for project in preview.projects:
|
||||
_assert_editable(service, project.task_id)
|
||||
if tuple(store.list_target_plan(project.task_id)) != project.baseline:
|
||||
raise TaskCenterError('target_identity', '工程位号计划在 BOM 预览后已改变,请重新导入')
|
||||
for project in preview.projects:
|
||||
if project.fresh_inventory:
|
||||
# The immutable preview baseline was checked above under this
|
||||
# same transaction. A new live inventory replaces stale edits,
|
||||
# never an in-flight or executed task (guarded by _assert_editable).
|
||||
store._connection.execute('DELETE FROM target_plan WHERE task_id = ?', (project.task_id,))
|
||||
store.record_target_inventory(project.task_id, project.inventory)
|
||||
result[project.task_id] = store.replace_target_plan(project.task_id, rows_by_task[project.task_id])
|
||||
return result
|
||||
@@ -7,13 +7,13 @@ from zipfile import BadZipFile
|
||||
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from .bom_batch import BomBatchPreview, BomProjectPreview, _assert_editable, _identity, _scope
|
||||
from .bom_batch import BomBatchPreview, BomProjectPreview, _assert_editable, _identity, _scope, explicit_scope
|
||||
from .bom_plan import BomMatcher, _normal_headers, _text, parse_bom_row
|
||||
from .errors import TaskCenterError
|
||||
from .project_discovery import ReleasedProjectReadError
|
||||
from .bom_import_state import BomImportPhase
|
||||
from .store_target_plan import merge_target_inventory
|
||||
from .target_plan import ProjectIdentityResolver, compile_target_rules
|
||||
from .target_plan import ProjectIdentityResolver, TargetPlanRow, compile_target_rules
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -39,6 +39,8 @@ class BomImportReport:
|
||||
projects: tuple[BomProjectResult, ...]
|
||||
preview: BomBatchPreview | None = None
|
||||
errors: tuple[str, ...] = ()
|
||||
inspection_projects: tuple[BomProjectPreview, ...] = ()
|
||||
library_issues: tuple[tuple[str, str, str], ...] = ()
|
||||
|
||||
@property
|
||||
def total_rows(self):
|
||||
@@ -82,7 +84,7 @@ class BomInspectionError(TaskCenterError):
|
||||
self.bom_report = report
|
||||
|
||||
|
||||
def _report(rows, preview=None, errors=()):
|
||||
def _report(rows, preview=None, errors=(), inspection_projects=(), library_issues=()):
|
||||
grouped = {}
|
||||
for row in rows:
|
||||
grouped.setdefault((row.project_path, row.project_name), []).append(row)
|
||||
@@ -90,7 +92,7 @@ def _report(rows, preview=None, errors=()):
|
||||
'failed' if any(row.status == 'failed' for row in items) else
|
||||
'unchecked' if any(row.status == 'unchecked' for row in items) else 'passed',
|
||||
tuple(row.excel_row for row in items)) for (path, name), items in grouped.items())
|
||||
return BomImportReport(tuple(rows), projects, preview, tuple(errors))
|
||||
return BomImportReport(tuple(rows), projects, preview, tuple(errors), tuple(inspection_projects), tuple(library_issues))
|
||||
|
||||
|
||||
def _check_record_conflicts(rows, records, indices):
|
||||
@@ -123,7 +125,8 @@ def _check_record_conflicts(rows, records, indices):
|
||||
rows[index] = replace(rows[index], status='failed', reason=reason)
|
||||
|
||||
|
||||
def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None, on_phase=None, runtime=None):
|
||||
def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None, on_phase=None, runtime=None,
|
||||
workspace_mode=False, workspace_tasks=None):
|
||||
"""Validate all independent rows; never persist inventory or return partial plans.
|
||||
|
||||
Operational failures (including cancellation and native cleanup) propagate so
|
||||
@@ -136,7 +139,8 @@ def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None,
|
||||
with BatchCadRuntime(service._logging.root, 'bom_import', stop_event) as owned_runtime:
|
||||
try:
|
||||
report = inspect_batch(service, task_id, path, stop_event=stop_event,
|
||||
on_progress=on_progress, on_phase=on_phase, runtime=owned_runtime)
|
||||
on_progress=on_progress, on_phase=on_phase, runtime=owned_runtime, workspace_mode=workspace_mode,
|
||||
workspace_tasks=workspace_tasks)
|
||||
except BomInspectionError as error:
|
||||
report = error.bom_report
|
||||
raise
|
||||
@@ -159,7 +163,7 @@ def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None,
|
||||
|
||||
check_cancelled()
|
||||
notify('正在读取并校验 BOM Excel 表格…', BomImportPhase.READING)
|
||||
scope = _scope(service._store, task_id)
|
||||
scope = explicit_scope(service._store, workspace_tasks) if workspace_mode and workspace_tasks else _scope(service._store, task_id)
|
||||
runtime.bind_logs(service._logging, tuple(task.task_id for task, _ in scope))
|
||||
routing = ProjectIdentityResolver()
|
||||
owners = {routing.project(project.path): (task, project) for task, project in scope}
|
||||
@@ -241,25 +245,40 @@ def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None,
|
||||
for key, indices in grouped.items():
|
||||
check_cancelled()
|
||||
_check_record_conflicts(rows, records, indices)
|
||||
if workspace_mode and any(row.status == 'failed' and row.project_path
|
||||
and routing.project(row.project_path) == key for row in rows):
|
||||
for index in indices:
|
||||
if rows[index].status != 'failed':
|
||||
rows[index] = replace(rows[index], status='failed', reason='本工程其他行未通过校验,工程整体保留待处理')
|
||||
try:
|
||||
_assert_editable(service, owners[key][0].task_id)
|
||||
except TaskCenterError as error:
|
||||
for index in indices:
|
||||
rows[index] = replace(rows[index], status='failed', reason=error.message)
|
||||
if any(row.status == 'failed' for row in rows):
|
||||
if any(row.status == 'failed' for row in rows) and not workspace_mode:
|
||||
return _report(rows)
|
||||
notify(f'BOM 表格校验通过,共 {len(rows)} 行、涉及 {len(grouped)} 个工程;开始核验工程位号。')
|
||||
previews = []
|
||||
inspection_projects, library_issues, library_cache = [], [], {}
|
||||
for position, (key, indices) in enumerate(grouped.items(), 1):
|
||||
check_cancelled()
|
||||
if workspace_mode and any(rows[index].status == 'failed' for index in indices):
|
||||
for index in indices:
|
||||
if rows[index].status == 'unchecked':
|
||||
rows[index] = replace(rows[index], status='failed', reason='本工程其他行未通过校验,工程整体保留待处理')
|
||||
continue
|
||||
task, project = owners[key]
|
||||
def progress(message, phase=None):
|
||||
notify(f'工程 {position}/{len(grouped)} · {message}', phase)
|
||||
progress(f'正在核验「{task.name}」的位号库存…', BomImportPhase.INVENTORY)
|
||||
baseline = tuple(service._store.list_target_plan(task.task_id))
|
||||
requested = tuple(dict.fromkeys(records[index].old for index in indices))
|
||||
if workspace_mode:
|
||||
# Full inventory is necessary to see duplicate refdes whose current
|
||||
# part number is neither the old nor the target part number.
|
||||
requested = tuple(dict.fromkeys((*requested, *(records[index].new for index in indices), '*')))
|
||||
known = tuple(dict.fromkeys(row.target.old_part_number for row in baseline))
|
||||
if baseline and {part.casefold() for part in requested} <= {part.casefold() for part in known}:
|
||||
if not workspace_mode and baseline and {part.casefold() for part in requested} <= {part.casefold() for part in known}:
|
||||
progress(f'「{task.name}」复用已有位号库存,无需启动 CAD')
|
||||
inventory = tuple(row.target for row in baseline)
|
||||
else:
|
||||
@@ -289,14 +308,17 @@ def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None,
|
||||
for index, row in enumerate(rows):
|
||||
if row.status == 'unchecked':
|
||||
rows[index] = replace(row, reason='前序工程采集异常,已停止后续核验')
|
||||
partial_preview = (BomBatchPreview(task_id, _identity(scope), tuple(previews), True)
|
||||
if workspace_mode and workspace_tasks and previews else None)
|
||||
report = _report(rows, errors=(
|
||||
f'已停止批量采集:{task.name};{error.message}(错误编号:{error.error_id})',))
|
||||
f'已停止批量采集:{task.name};{error.message}(错误编号:{error.error_id})',),
|
||||
preview=partial_preview)
|
||||
raise BomInspectionError(error, report) from error
|
||||
check_cancelled()
|
||||
progress(f'「{task.name}」正在匹配 {len(indices)} 行 BOM 与工程位号…', BomImportPhase.MATCHING)
|
||||
merged = merge_target_inventory(baseline, inventory)
|
||||
merged = tuple(TargetPlanRow(target) for target in inventory) if workspace_mode else merge_target_inventory(baseline, inventory)
|
||||
matched_rows, touched = {}, {}
|
||||
matcher = BomMatcher(merged, service.rules(task.task_id)) if merged else None
|
||||
matcher = BomMatcher(merged, service.rules(task.task_id), allow_target=workspace_mode) if merged else None
|
||||
for index in indices:
|
||||
check_cancelled()
|
||||
try:
|
||||
@@ -308,7 +330,9 @@ def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None,
|
||||
for target_key, row in matched.items():
|
||||
touched.setdefault(target_key, []).append(index)
|
||||
matched_rows[target_key] = row
|
||||
rows[index] = replace(rows[index], status='passed', reason='校验通过')
|
||||
skipped = sum(r.target.old_part_number.casefold() == r.new_part_number.casefold() for r in matched.values())
|
||||
reason = f'校验通过;{skipped} 个器件已是目标料号,自动跳过' if skipped else '校验通过'
|
||||
rows[index] = replace(rows[index], status='passed', reason=reason)
|
||||
except TaskCenterError as error:
|
||||
rows[index] = replace(rows[index], status='failed', reason=error.message)
|
||||
for target, indices_for_target in touched.items():
|
||||
@@ -323,9 +347,10 @@ def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None,
|
||||
for index in indices:
|
||||
if rows[index].status == 'passed':
|
||||
rows[index] = replace(rows[index], status='failed', reason=error.message)
|
||||
previews.append(BomProjectPreview(task.task_id, project.path, baseline, inventory, combined))
|
||||
if not workspace_mode or all(rows[index].status == 'passed' for index in indices):
|
||||
previews.append(BomProjectPreview(task.task_id, project.path, baseline, inventory, combined, workspace_mode))
|
||||
progress(f'「{task.name}」校验完成')
|
||||
check_cancelled()
|
||||
preview = None if any(row.status != 'passed' for row in rows) else BomBatchPreview(
|
||||
task_id, _identity(scope), tuple(previews))
|
||||
return _report(rows, preview)
|
||||
preview = (BomBatchPreview(task_id, _identity(scope), tuple(previews), bool(workspace_mode and workspace_tasks)) if previews and
|
||||
(workspace_mode or all(row.status == 'passed' for row in rows)) else None)
|
||||
return _report(rows, preview, inspection_projects=inspection_projects, library_issues=library_issues)
|
||||
@@ -17,6 +17,8 @@ class BomImportPhase(Enum):
|
||||
VALIDATING = 'validating'
|
||||
INVENTORY = 'inventory'
|
||||
MATCHING = 'matching'
|
||||
RECOVERING = 'recovering'
|
||||
RELEASING = 'releasing'
|
||||
CANCELLING = 'cancelling'
|
||||
PREVIEW_READY = 'preview_ready'
|
||||
REJECTED = 'rejected'
|
||||
@@ -30,6 +32,11 @@ _NEXT = {
|
||||
BomImportPhase.INVENTORY: {BomImportPhase.INVENTORY, BomImportPhase.MATCHING},
|
||||
BomImportPhase.MATCHING: {BomImportPhase.MATCHING, BomImportPhase.INVENTORY},
|
||||
}
|
||||
_RECOVERY_PHASES = {BomImportPhase.RECOVERING, BomImportPhase.RELEASING}
|
||||
for _phase in tuple(_NEXT):
|
||||
_NEXT[_phase] |= _RECOVERY_PHASES
|
||||
for _phase in _RECOVERY_PHASES:
|
||||
_NEXT[_phase] = _RECOVERY_PHASES | {BomImportPhase.INVENTORY, BomImportPhase.MATCHING}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
|
||||
@@ -163,12 +163,14 @@ def parse_bom_row(cells, positions):
|
||||
class BomMatcher:
|
||||
"""Index one immutable inventory once, then match independent Excel rows."""
|
||||
|
||||
def __init__(self, baseline, rules=()):
|
||||
def __init__(self, baseline, rules=(), *, allow_target=False):
|
||||
if not baseline:
|
||||
raise TaskCenterError('target_inventory', '未采集到可匹配的工程位号')
|
||||
self.by_key = {}
|
||||
self.projects = set()
|
||||
self.by_identity = {}
|
||||
self.by_refdes = {}
|
||||
self.allow_target = allow_target
|
||||
self.cell_defaults = {(rule.old_part_number.casefold(), rule.new_part_number): rule.target_cell
|
||||
for rule in rules if rule.enabled}
|
||||
self.identities = ProjectIdentityResolver()
|
||||
@@ -180,22 +182,28 @@ class BomMatcher:
|
||||
self.by_key[key] = row
|
||||
self.projects.add(key[0])
|
||||
self.by_identity.setdefault((target.old_part_number.casefold(), target.refdes.casefold()), []).append((key, target))
|
||||
self.by_refdes.setdefault(target.refdes.casefold(), []).append((key, target))
|
||||
|
||||
def match_record(self, record):
|
||||
if record.project_path and self.identities.project(record.project_path) not in self.projects:
|
||||
raise TaskCenterError('bom_import', 'BOM 工程与当前任务不一致')
|
||||
matched = {}
|
||||
for refdes in record.refs:
|
||||
candidates = [(key, target) for key, target in self.by_identity.get((record.old.casefold(), refdes.casefold()), ())
|
||||
pool = (self.by_refdes.get(refdes.casefold(), ()) if self.allow_target else
|
||||
self.by_identity.get((record.old.casefold(), refdes.casefold()), ()))
|
||||
candidates = [(key, target) for key, target in pool
|
||||
if (not record.schematic or target.schematic_name.casefold() == record.schematic.casefold())
|
||||
and (not record.sheet or target.sheet_number.casefold() == record.sheet.casefold())
|
||||
and (not record.uid or target.uid == record.uid)]
|
||||
if len(candidates) != 1:
|
||||
raise TaskCenterError('bom_import', f'位号 {refdes} 无法唯一匹配当前采集清单')
|
||||
key, target = candidates[0]
|
||||
already_target = self.allow_target and target.old_part_number.casefold() == record.new.casefold()
|
||||
if self.allow_target and not already_target and target.old_part_number.casefold() != record.old.casefold():
|
||||
raise TaskCenterError('bom_import', f'位号 {refdes} 当前料号为 {target.old_part_number},不是旧料号或目标新料号')
|
||||
if key in matched:
|
||||
raise TaskCenterError('bom_import', f'位号 {refdes} 在 BOM 中重复')
|
||||
matched[key] = TargetPlanRow(target, record.enabled, record.new,
|
||||
matched[key] = TargetPlanRow(target, record.enabled and not already_target, record.new,
|
||||
bool(record.custom), record.custom, record.sync_nc,
|
||||
(self.by_key[key].target_cell if self.by_key[key].new_part_number == record.new else '')
|
||||
or self.cell_defaults.get((target.old_part_number.casefold(), record.new), ''))
|
||||
|
||||
@@ -46,8 +46,16 @@ def _write_json(path, value):
|
||||
temporary.replace(path)
|
||||
|
||||
|
||||
def _hash(path):
|
||||
def _hash(path, *, stop_event=None):
|
||||
with path.open('rb') as stream:
|
||||
if stop_event is not None:
|
||||
from .operation_control import check_cancelled
|
||||
digest = hashlib.sha256()
|
||||
while chunk := stream.read(1024 * 1024):
|
||||
check_cancelled(stop_event)
|
||||
digest.update(chunk)
|
||||
check_cancelled(stop_event)
|
||||
return digest.hexdigest()
|
||||
return hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
|
||||
|
||||
@@ -55,7 +63,7 @@ def _hidden(path):
|
||||
return path.name.startswith('.') or bool(getattr(path.stat(), 'st_file_attributes', 0) & 2)
|
||||
|
||||
|
||||
def _library_manifest(library):
|
||||
def _library_manifest(library, *, stop_event=None):
|
||||
"""Complete proven clone recipe: all root metadata and every physical PDB/CEL."""
|
||||
library = Path(library).resolve()
|
||||
if library.suffix.lower() != '.lmc' or not library.is_file():
|
||||
@@ -86,10 +94,13 @@ def _library_manifest(library):
|
||||
_fail(f'missing physical dependency: {name}')
|
||||
manifest = {}
|
||||
for path in sorted(paths, key=lambda p: p.relative_to(root).as_posix()):
|
||||
if stop_event is not None:
|
||||
from .operation_control import check_cancelled
|
||||
check_cancelled(stop_event)
|
||||
if path.is_symlink() or getattr(path.lstat(), 'st_file_attributes', 0) & 0x400:
|
||||
_fail('library dependency cannot be a reparse point')
|
||||
before = path.stat()
|
||||
digest = _hash(path)
|
||||
digest = _hash(path, **({'stop_event': stop_event} if stop_event is not None else {}))
|
||||
after = path.stat()
|
||||
if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
|
||||
_fail('source library changed while fingerprinting')
|
||||
@@ -103,8 +114,8 @@ def _fingerprint(manifest):
|
||||
|
||||
|
||||
def _content_fingerprint(manifest):
|
||||
# LM normally touches the copied cfg timestamp while opening. Source proof
|
||||
# and prelaunch copy proof include timestamps; post-open proof binds bytes.
|
||||
# Copying between file systems may round timestamps. Content identity
|
||||
# still requires the exact file list, size and SHA256 for every file.
|
||||
return _fingerprint({name: {key: value for key, value in row.items() if key != 'mtime_ns'}
|
||||
for name, row in manifest.items()})
|
||||
|
||||
@@ -117,8 +128,19 @@ def _clone_library(library, root, manifest):
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(library.parent / name, target)
|
||||
clone = destination / library.name
|
||||
if _library_manifest(clone) != manifest or _library_manifest(library) != manifest:
|
||||
_fail('source library changed or clone dependency proof failed')
|
||||
copied, current = _library_manifest(clone), _library_manifest(library)
|
||||
def differences(actual):
|
||||
return [name for name in sorted(set(manifest) | set(actual))
|
||||
if name not in manifest or name not in actual or any(
|
||||
manifest[name].get(key) != actual[name].get(key) for key in ('size', 'sha256'))]
|
||||
clone_changes, source_changes = differences(copied), differences(current)
|
||||
_write_json(root / 'clone-proof.json', {'source': str(library), 'before': manifest,
|
||||
'clone': copied, 'source_after': current, 'clone_content_differences': clone_changes,
|
||||
'source_content_differences': source_changes})
|
||||
if source_changes:
|
||||
_fail('复制期间中心库文件内容发生变化,请关闭库编辑后重试:' + '、'.join(source_changes[:8]))
|
||||
if clone_changes:
|
||||
_fail('中心库副本内容校验失败,请检查磁盘和文件权限:' + '、'.join(clone_changes[:8]))
|
||||
return clone
|
||||
|
||||
|
||||
@@ -153,7 +175,10 @@ def _catalog_from_evidence(evidence, library, part, partition, fingerprint, path
|
||||
|
||||
|
||||
def _require_cleanup(cleanup):
|
||||
if not isinstance(cleanup, dict) or cleanup.get('errors') or not cleanup.get('desktop_handle_closed') or not cleanup.get('desktop_confirmation', {}).get('released'):
|
||||
confirmation = cleanup.get('desktop_confirmation', {}) if isinstance(cleanup, dict) else {}
|
||||
if (not isinstance(cleanup, dict) or cleanup.get('errors')
|
||||
or not cleanup.get('desktop_handle_closed')
|
||||
or not (confirmation.get('released') or confirmation.get('release_accepted'))):
|
||||
_fail('catalog private desktop cleanup was not proven')
|
||||
if not cleanup.get('processes'):
|
||||
_fail('catalog owned process cleanup is missing')
|
||||
@@ -241,6 +266,75 @@ def read_library_cell_catalog(library_path: Path, part_number: str, evidence_roo
|
||||
raise
|
||||
|
||||
|
||||
def read_library_part_presence(library_path, part_numbers, evidence_root, *, allow_cold_read=True, stop_event=None):
|
||||
"""Batch existence query, without requiring Cell associations or mutating the source."""
|
||||
library = Path(library_path).resolve()
|
||||
requested = tuple(dict.fromkeys(part_numbers))
|
||||
if not requested:
|
||||
return {}
|
||||
evidence_root = Path(evidence_root).resolve()
|
||||
if evidence_root == library.parent or library.parent in evidence_root.parents:
|
||||
_fail('catalog evidence must be outside the source library')
|
||||
from .operation_control import check_cancelled
|
||||
check_cancelled(stop_event)
|
||||
manifest = _library_manifest(library, **({'stop_event': stop_event} if stop_event is not None else {}))
|
||||
content = _content_fingerprint(manifest)
|
||||
cache = evidence_root / 'presence-cache' / (hashlib.sha256(_json_bytes([str(library), content])).hexdigest() + '.json')
|
||||
previous_values = {}
|
||||
if cache.is_file():
|
||||
try:
|
||||
index = json.loads(cache.read_text(encoding='utf-8'))
|
||||
evidence = (evidence_root / index['evidence']).resolve()
|
||||
evidence.relative_to(evidence_root)
|
||||
if _hash(evidence) != index['sha256']:
|
||||
raise ValueError('changed part evidence')
|
||||
record = json.loads(evidence.read_text(encoding='utf-8'))
|
||||
values = record['parts']
|
||||
_require_cleanup(record['cleanup'])
|
||||
if (record.get('library') != str(library) or record.get('source_content_fingerprint') != content
|
||||
or record.get('schema') != 1 or not isinstance(values, dict)
|
||||
or any(value not in {'found', 'missing', 'ambiguous'} for value in values.values())):
|
||||
raise ValueError('invalid part evidence binding')
|
||||
if _content_fingerprint(_library_manifest(library, **({'stop_event': stop_event} if stop_event is not None else {}))) != content:
|
||||
_fail('中心库在校验期间发生变化,请重新导入 BOM。')
|
||||
previous_values = values
|
||||
if set(requested) <= set(values):
|
||||
return {part: values[part] for part in requested}
|
||||
except (OSError, ValueError, KeyError, TypeError, AttributeError):
|
||||
check_cancelled(stop_event)
|
||||
pass
|
||||
if not allow_cold_read:
|
||||
_fail('中心库已变化、目标料号未校验或校验证据失效,请重新导入 BOM 后保存;保存不会重新启动中心库扫描。')
|
||||
root = evidence_root / 'part-checks' / uuid.uuid4().hex
|
||||
root.mkdir(parents=True)
|
||||
started = False
|
||||
try:
|
||||
clone = _clone_library(library, root, manifest)
|
||||
started = True
|
||||
result = _run_isolated_reader(clone, list(requested), None, root)
|
||||
_require_cleanup(result.get('cleanup'))
|
||||
if (_content_fingerprint(_library_manifest(library)) != _content_fingerprint(manifest) or result.get('library') != str(clone)
|
||||
or not result.get('verified') or not result.get('quit_verified')):
|
||||
_fail('library part check identity or consistency could not be verified')
|
||||
values = result.get('parts')
|
||||
if not isinstance(values, dict) or set(values) != set(requested) or any(
|
||||
value not in {'found', 'missing', 'ambiguous'} for value in values.values()):
|
||||
_fail('library part check returned incomplete results')
|
||||
proof_path = root / 'verified-parts.json'
|
||||
_write_json(proof_path, {'schema': 1, 'library': str(library),
|
||||
'source_fingerprint': _fingerprint(manifest), 'source_content_fingerprint': content,
|
||||
'parts': previous_values | values, 'cleanup': result['cleanup']})
|
||||
finally:
|
||||
cleanup = root / 'desktop-cleanup.json'
|
||||
if started and cleanup.is_file():
|
||||
_require_cleanup(json.loads(cleanup.read_text(encoding='utf-8')))
|
||||
_dispose_clone(root)
|
||||
elif not started:
|
||||
_dispose_clone(root)
|
||||
_write_json(cache, {'evidence': proof_path.relative_to(evidence_root).as_posix(), 'sha256': _hash(proof_path)})
|
||||
return values
|
||||
|
||||
|
||||
def project_library_path(project: Path) -> Path:
|
||||
project = Path(project).resolve()
|
||||
try:
|
||||
|
||||
@@ -112,6 +112,21 @@ def _read_associations(library, part_number, selected_partition, root):
|
||||
'part_partition_count': int(parts.Count)}
|
||||
|
||||
|
||||
def _read_part_presence(library, requested, root):
|
||||
found = {part: [] for part in requested}
|
||||
parts = library.Partitions(1)
|
||||
for index in range(1, int(parts.Count) + 1):
|
||||
partition = parts.Item(index)
|
||||
name = str(partition.Name)
|
||||
_physical(root, 'PartsDBLibs', name, '.pdb')
|
||||
for position in range(1, int(partition.Count) + 1):
|
||||
part = str(partition.Item(position).Name)
|
||||
if part in found:
|
||||
found[part].append(name)
|
||||
return {'parts': {part: ('found' if len(rows) == 1 else 'missing' if not rows else 'ambiguous')
|
||||
for part, rows in found.items()}}
|
||||
|
||||
|
||||
def _verify_clone_content(clone, expected):
|
||||
if _content_fingerprint(_library_manifest(clone)) != expected:
|
||||
_fail('clone dependency content changed during library read')
|
||||
@@ -151,7 +166,10 @@ def run(request_path: Path) -> int:
|
||||
_verify_clone_content(clone, request['clone_content_fingerprint'])
|
||||
_verify_app(app, request)
|
||||
report['phase'] = 'associations'
|
||||
result = _read_associations(library, request['part_number'], request['partition'], clone.parent)
|
||||
if isinstance(request['part_number'], list):
|
||||
result = _read_part_presence(library, request['part_number'], clone.parent)
|
||||
else:
|
||||
result = _read_associations(library, request['part_number'], request['partition'], clone.parent)
|
||||
_verify_app(app, request)
|
||||
_verify_clone_content(clone, request['clone_content_fingerprint'])
|
||||
report.update(result, library=str(clone), desktop=request['desktop'], pid=request['pid'], verified=True, phase='complete')
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Load generated COM bindings without requiring a writable frozen gen_py cache."""
|
||||
from io import BytesIO, TextIOWrapper
|
||||
import sys
|
||||
from types import ModuleType
|
||||
|
||||
|
||||
def registered_api(typelib_id, *, required=()):
|
||||
import pythoncom
|
||||
from win32com.client import genpy
|
||||
|
||||
typelib = pythoncom.LoadRegTypeLib(typelib_id, 1, 0, 0)
|
||||
buffer = BytesIO()
|
||||
stream = TextIOWrapper(buffer, encoding='utf-8')
|
||||
genpy.Generator(typelib, None, genpy.GeneratorProgress()).generate(stream)
|
||||
module = ModuleType('_dx_registered_' + typelib_id.strip('{}').replace('-', '_'))
|
||||
sys.modules[module.__name__] = module
|
||||
try:
|
||||
stream.flush()
|
||||
exec(compile(buffer.getvalue().decode('utf-8'), '<registered COM type library>', 'exec'), module.__dict__)
|
||||
for name in required:
|
||||
if not hasattr(module, name):
|
||||
raise RuntimeError(f'DxDesigner COM 接口不兼容,缺少 {name}')
|
||||
except BaseException:
|
||||
sys.modules.pop(module.__name__, None)
|
||||
raise
|
||||
return module
|
||||
@@ -0,0 +1,210 @@
|
||||
"""Allowlisted, bounded support export; never packages project or CAD inputs."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import stat
|
||||
import zipfile
|
||||
|
||||
from .path_access import canonical_path, internal_path
|
||||
|
||||
MAX_FILE_BYTES = 4 * 1024 * 1024
|
||||
MAX_BUNDLE_BYTES = 32 * 1024 * 1024
|
||||
MAX_FILES = 4096
|
||||
_BATCH_NAMES = {'session.json', 'supervisor.json', 'request.json', 'result.json',
|
||||
'business-result.json', 'supervisor.log', 'resource-release.log', 'cancel.json'}
|
||||
_QUICK_NAMES = {'private-desktop.json', 'checkpoint.json', 'status.json',
|
||||
'uncertain.flag', 'resolved-uncertain.flag', 'protection.json', 'cleanup.json',
|
||||
'project-session.json', 'project-checkpoint.json', 'status.tsv',
|
||||
'read-state.json', 'read-trace.jsonl', 'read-trace.jsonl.1', 'read-trace.jsonl.2',
|
||||
'native-inventory.json', 'worker-progress.json', 'worker-output.txt', 'project-read-release.json',
|
||||
'quick-part-replace.log'}
|
||||
_SECRET_KEY = re.compile(r'(?:password|passwd|(?:client[_-]?)?secret|credentials?|authorization|api[_-]?key|access[_-]?token|refresh[_-]?token|token)', re.I)
|
||||
_USER_KEY = re.compile(r'(?:user(?:[_-]?name)?|login[_-]?name)', re.I)
|
||||
_SECRET_TEXT = re.compile(r'''(?ix)(\b(?:password|passwd|(?:client[_-]?)?secret|credentials?|authorization|api[_-]?key|access[_-]?token|refresh[_-]?token|token)\b["']?\s*[=:]\s*)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,;}]+)''')
|
||||
|
||||
|
||||
def _scrub_text(text):
|
||||
# Scrub other users as well as the exporting user's home, including JSON
|
||||
# escaped Windows paths. Preserve suffixes useful for fault diagnosis.
|
||||
text = re.sub(r'(?i)(?:[A-Z]:[\\/]+Users[\\/]+|/Users/|/home/)[^\\/\s"\']+', '<USER_HOME>', text)
|
||||
home = str(Path.home())
|
||||
for prefix in {home, home.replace('\\', '/'), home.replace('\\', '\\\\')}:
|
||||
text = re.sub(re.escape(prefix), '<USER_HOME>', text, flags=re.I)
|
||||
username = os.environ.get('USERNAME') or os.environ.get('USER')
|
||||
if username and len(username) > 2:
|
||||
text = re.sub(r'(?<![\w])' + re.escape(username) + r'(?![\w])', '<USER>', text, flags=re.I)
|
||||
text = re.sub(r'(?i)\bBearer\s+[A-Za-z0-9._~+/-]+=*', 'Bearer <REDACTED>', text)
|
||||
text = _SECRET_TEXT.sub(r'\1<REDACTED>', text)
|
||||
text = re.sub(r'''(?ix)(\b(?:user(?:[_-]?name)?|login[_-]?name)\b["']?\s*[=:]\s*)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,;}]+)''', r'\1<USER>', text)
|
||||
text = re.sub(r'(?i)(https?://)[^\s/@:]+:[^\s/@]+@', r'\1<REDACTED>@', text)
|
||||
return text
|
||||
|
||||
|
||||
def _scrub_json(value):
|
||||
if isinstance(value, dict):
|
||||
return {_scrub_text(str(key)): ('<REDACTED>' if _SECRET_KEY.fullmatch(str(key))
|
||||
else '<USER>' if _USER_KEY.fullmatch(str(key)) else _scrub_json(item))
|
||||
for key, item in value.items()}
|
||||
if isinstance(value, list):
|
||||
return [_scrub_json(item) for item in value]
|
||||
return _scrub_text(value) if isinstance(value, str) else value
|
||||
|
||||
|
||||
def _allowed(parts):
|
||||
if parts[-1].endswith('.json') and ((len(parts) == 2 and parts[0] == 'discovery-checks')
|
||||
or (len(parts) == 4 and parts[0] == 'tasks' and parts[2] == 'discovery-checks')):
|
||||
return True
|
||||
if len(parts) == 4 and parts[0] == 'cell-catalog' and parts[1] in {'part-checks', 'reads'}:
|
||||
return parts[-1] in {'clone-proof.json', 'failure.json', 'desktop-cleanup.json',
|
||||
'worker-result.json', 'verified-parts.json', 'source-hashes.json'}
|
||||
if len(parts) == 2 and parts[0] == 'logs':
|
||||
return bool(re.fullmatch(r'[^/]+\.log(?:\.\d+)?', parts[-1]))
|
||||
if len(parts) == 3 and parts[0] == 'batch-resources':
|
||||
return parts[-1] in _BATCH_NAMES
|
||||
if len(parts) >= 5 and parts[0] == 'batch-resources' and parts[2] == 'attempts':
|
||||
return parts[-1].endswith('.json')
|
||||
if len(parts) >= 2 and parts[0] == 'attempts':
|
||||
return parts[-1].endswith('.json')
|
||||
if len(parts) == 3 and parts[0] == 'tasks':
|
||||
return bool(re.fullmatch(r'events\.jsonl(?:\.\d+)?', parts[-1]))
|
||||
if len(parts) >= 2 and parts[0] in {'queue', 'queues', 'task-queues'}:
|
||||
return parts[-1].endswith('.json')
|
||||
if len(parts) >= 2 and any(value in parts for value in ('quick-run', 'quickrun', 'quick-run-history')):
|
||||
return parts[-1] in _QUICK_NAMES
|
||||
return False
|
||||
|
||||
|
||||
def _recent_task_activity(path):
|
||||
"""Rank recent task evidence without following links or junctions."""
|
||||
stamps = []
|
||||
def inspect(candidate, *, directory=False):
|
||||
try:
|
||||
info = candidate.lstat()
|
||||
if stat.S_ISLNK(info.st_mode) or getattr(info, 'st_file_attributes', 0) & 0x400:
|
||||
return False
|
||||
stamps.append(info.st_mtime_ns)
|
||||
return stat.S_ISDIR(info.st_mode) if directory else True
|
||||
except OSError:
|
||||
return False
|
||||
inspect(path)
|
||||
inspect(path / 'events.jsonl')
|
||||
if inspect(path / 'quick-run', directory=True):
|
||||
inspect(path / 'quick-run' / 'read-state.json')
|
||||
history = path / 'quick-run-history'
|
||||
if inspect(history, directory=True):
|
||||
try:
|
||||
for child in history.iterdir():
|
||||
if inspect(child, directory=True):
|
||||
inspect(child / 'read-state.json')
|
||||
except OSError:
|
||||
pass
|
||||
return max(stamps, default=0)
|
||||
|
||||
|
||||
def export_diagnostic_bundle(data_root, destination: Path) -> Path:
|
||||
"""Write a new ZIP, excluding links, binaries, inputs and credential configs.
|
||||
|
||||
This is a point-in-time best-effort read: active writers may produce partial
|
||||
log lines. Unsupported/unreadable items are documented, never dereferenced.
|
||||
"""
|
||||
root, destination = canonical_path(data_root), canonical_path(destination)
|
||||
if destination.suffix.lower() != '.zip':
|
||||
raise ValueError('diagnostic destination must have a .zip suffix')
|
||||
manifest = {'version': 1, 'included': [], 'omissions': [], 'truncated': [], 'unknowns': [
|
||||
'External desktop handle holders are unknown; empty window/thread lists do not prove release.',
|
||||
'Active logs and metadata are point-in-time reads; no source CAD, libraries, BOM, database or environment configuration is included.'],
|
||||
'limits': {'max_file_bytes': MAX_FILE_BYTES, 'max_bundle_bytes': MAX_BUNDLE_BYTES, 'max_files': MAX_FILES}}
|
||||
total = 0
|
||||
physical = internal_path(root)
|
||||
# os.walk does not descend symlinks; explicitly prune Windows junctions too.
|
||||
with zipfile.ZipFile(internal_path(destination), 'x', compression=zipfile.ZIP_DEFLATED) as archive:
|
||||
for directory, folders, files in os.walk(physical, followlinks=False):
|
||||
base = Path(directory)
|
||||
safe_folders = []
|
||||
for name in sorted(folders):
|
||||
entry = base / name
|
||||
relative = entry.relative_to(physical).as_posix()
|
||||
info = entry.lstat()
|
||||
if stat.S_ISLNK(info.st_mode) or getattr(info, 'st_file_attributes', 0) & 0x400:
|
||||
manifest['omissions'].append({'path': _scrub_text(relative), 'reason': 'link_or_reparse_point'})
|
||||
elif base == physical and name not in {'logs', 'batch-resources', 'attempts', 'tasks', 'queue', 'queues', 'task-queues', 'quick-run', 'quick-run-history', 'cell-catalog', 'discovery-checks'}:
|
||||
manifest['omissions'].append({'path': _scrub_text(relative), 'reason': 'outside_allowlist'})
|
||||
elif relative.startswith('cell-catalog/') and name == 'library':
|
||||
manifest['omissions'].append({'path': _scrub_text(relative), 'reason': 'library_input_excluded'})
|
||||
else:
|
||||
safe_folders.append(name)
|
||||
if base == physical:
|
||||
priority = {'logs': 0, 'tasks': 1, 'quick-run-history': 2, 'batch-resources': 3}
|
||||
safe_folders.sort(key=lambda name: (priority.get(name, 3), name))
|
||||
elif base == physical / 'tasks':
|
||||
safe_folders.sort(key=lambda name: _recent_task_activity(base / name), reverse=True)
|
||||
elif base == physical / 'batch-resources':
|
||||
def batch_activity(name):
|
||||
try:
|
||||
return (base / name / 'supervisor.json').lstat().st_mtime_ns
|
||||
except OSError:
|
||||
try:
|
||||
return (base / name).lstat().st_mtime_ns
|
||||
except OSError:
|
||||
return 0
|
||||
safe_folders.sort(key=batch_activity, reverse=True)
|
||||
elif base.name == 'quick-run-history':
|
||||
# Keep the latest failed parse before old evidence exhausts the cap.
|
||||
def modified(name):
|
||||
try:
|
||||
return (base / name).lstat().st_mtime_ns
|
||||
except OSError:
|
||||
return 0
|
||||
safe_folders.sort(key=modified, reverse=True)
|
||||
folders[:] = safe_folders
|
||||
for name in sorted(files):
|
||||
path = base / name
|
||||
relative = path.relative_to(physical)
|
||||
label = _scrub_text(relative.as_posix())
|
||||
reason = None
|
||||
try:
|
||||
info = path.lstat()
|
||||
tail = (relative.parts == ('logs', 'application.log')
|
||||
and info.st_size > MAX_FILE_BYTES and MAX_FILE_BYTES >= 1024)
|
||||
read_size = min(info.st_size, min(MAX_FILE_BYTES, 1024 * 1024)) if tail else info.st_size
|
||||
if not _allowed(relative.parts):
|
||||
reason = 'outside_allowlist'
|
||||
elif stat.S_ISLNK(info.st_mode) or getattr(info, 'st_file_attributes', 0) & 0x400 or info.st_nlink != 1:
|
||||
reason = 'link_or_reparse_point'
|
||||
elif not stat.S_ISREG(info.st_mode):
|
||||
reason = 'not_regular_file'
|
||||
elif (info.st_size > MAX_FILE_BYTES and not tail) or total + read_size > MAX_BUNDLE_BYTES or len(manifest['included']) >= MAX_FILES:
|
||||
reason = 'size_or_count_limit'
|
||||
else:
|
||||
with path.open('rb') as source:
|
||||
if tail:
|
||||
source.seek(-read_size, os.SEEK_END)
|
||||
payload = source.read(MAX_FILE_BYTES + 1 if not tail else read_size)
|
||||
if tail and b'\n' in payload:
|
||||
payload = payload.split(b'\n', 1)[1]
|
||||
if len(payload) > MAX_FILE_BYTES or b'\x00' in payload:
|
||||
reason = 'binary_or_size_limit'
|
||||
else:
|
||||
text = payload.decode('utf-8-sig', errors='replace' if tail else 'strict')
|
||||
if relative.suffix == '.json':
|
||||
text = json.dumps(_scrub_json(json.loads(text)), ensure_ascii=False, indent=2)
|
||||
elif '.jsonl' in relative.name:
|
||||
text = '\n'.join(json.dumps(_scrub_json(json.loads(line)), ensure_ascii=False)
|
||||
for line in text.splitlines() if line.strip()) + '\n'
|
||||
else:
|
||||
text = _scrub_text(text)
|
||||
archive.writestr(label, text)
|
||||
total += len(payload)
|
||||
manifest['included'].append(label)
|
||||
if tail:
|
||||
manifest['truncated'].append({'path': label, 'original_bytes': info.st_size,
|
||||
'included_tail_bytes': len(payload)})
|
||||
except (OSError, UnicodeError, ValueError):
|
||||
reason = 'unreadable_or_invalid_text'
|
||||
if reason:
|
||||
manifest['omissions'].append({'path': label, 'reason': reason})
|
||||
archive.writestr('manifest.json', json.dumps(manifest, ensure_ascii=False, indent=2))
|
||||
return destination
|
||||
@@ -100,8 +100,29 @@ def _unsafe(info):
|
||||
def _without_runtime_database(stamp):
|
||||
if stamp is None or len(stamp) != 2:
|
||||
return None
|
||||
return (stamp[0], tuple(row for row in stamp[1]
|
||||
if row[0].replace('\\', '/').casefold() != 'database/icdb.dat'))
|
||||
return (stamp[0], tuple((row[0], row[3], row[-1]) for row in stamp[1]
|
||||
if row[0].replace('\\', '/').casefold() not in {
|
||||
'database/icdb.dat', 'database/cdbsvr/saddress.adr'}))
|
||||
|
||||
|
||||
def _same_content(before, after):
|
||||
if before is None or after is None or len(before) != 2 or len(after) != 2:
|
||||
return False
|
||||
return before[0] == after[0] and tuple((r[0], r[3], r[-1]) for r in before[1]) == tuple(
|
||||
(r[0], r[3], r[-1]) for r in after[1])
|
||||
|
||||
|
||||
def _fingerprint_difference(before, after):
|
||||
if before is None or after is None or len(before) != 2 or len(after) != 2:
|
||||
return {'unverifiable': True, 'content_changed': [], 'metadata_changed': []}
|
||||
old, new = ({r[0]: r for r in value[1]} for value in (before, after))
|
||||
content, metadata = [], []
|
||||
for name in sorted(set(old) | set(new)):
|
||||
if name not in old or name not in new or (old[name][3], old[name][-1]) != (new[name][3], new[name][-1]):
|
||||
content.append(name)
|
||||
elif old[name] != new[name]:
|
||||
metadata.append(name)
|
||||
return {'unverifiable': False, 'content_changed': content, 'metadata_changed': metadata}
|
||||
|
||||
|
||||
def _only_database_changed(before, after):
|
||||
@@ -130,8 +151,68 @@ class DiscoveryCache:
|
||||
def invalidate(self, project: Path):
|
||||
with self.lock:
|
||||
self._entries.pop(_key(project), None)
|
||||
self._disk_path(project).unlink(missing_ok=True)
|
||||
|
||||
def discover(self, project, parts, collect_components, loader, *, stop_event=None):
|
||||
def _disk_path(self, project):
|
||||
from .path_access import internal_path
|
||||
return internal_path(Path(self.data_root) / 'discovery-cache' /
|
||||
(hashlib.sha256(_key(project).encode('utf-8')).hexdigest() + '.json'))
|
||||
|
||||
def _disk_entry(self, project, stamp):
|
||||
import json
|
||||
from uuid import uuid4
|
||||
from .supervisor_protocol import decode
|
||||
path = self._disk_path(project)
|
||||
if stamp is None or not path.exists():
|
||||
return None
|
||||
try:
|
||||
if path.stat().st_size > 32 * 1024 * 1024:
|
||||
raise ValueError('inventory cache exceeds size limit')
|
||||
record = json.loads(path.read_text(encoding='utf-8'))
|
||||
checksum = record.pop('record_sha256')
|
||||
if (record.get('version') != 2 or not isinstance(checksum, str)
|
||||
or checksum != hashlib.sha256(json.dumps(record, ensure_ascii=True, sort_keys=True).encode()).hexdigest()
|
||||
or type(record.get('collect_components')) is not bool
|
||||
or not isinstance(record.get('parts'), list)
|
||||
or not all(isinstance(part, str) for part in record['parts'])):
|
||||
raise ValueError('invalid discovery cache coverage or identity')
|
||||
payload = json.dumps(record['discovery'], ensure_ascii=True, sort_keys=True).encode('utf-8')
|
||||
if record['payload_sha256'] != hashlib.sha256(payload).hexdigest():
|
||||
raise ValueError('invalid discovery cache')
|
||||
if record['project'] != _key(project) or record['fingerprint'] != hashlib.sha256(repr(stamp).encode()).hexdigest():
|
||||
return None
|
||||
discovery = decode(record['discovery'])
|
||||
from .quick_run_protocol import ProjectDiscovery
|
||||
if not isinstance(discovery, ProjectDiscovery):
|
||||
raise ValueError('unexpected discovery cache type')
|
||||
_discovery_identity(discovery)
|
||||
return stamp, frozenset(record['parts']), record['collect_components'], discovery
|
||||
except (OSError, ValueError, TypeError, KeyError):
|
||||
try:
|
||||
path.replace(path.with_name(path.name + '.bad-' + uuid4().hex))
|
||||
except OSError:
|
||||
pass # A bad cache is never authoritative, even if quarantine fails.
|
||||
return None
|
||||
|
||||
def _save_disk(self, project, stamp, requested, components, discovery):
|
||||
import json
|
||||
from .batch_resources import write_record
|
||||
from .supervisor_protocol import encode
|
||||
try:
|
||||
payload = encode(discovery)
|
||||
record = {'version': 2, 'project': _key(project),
|
||||
'fingerprint': hashlib.sha256(repr(stamp).encode()).hexdigest(), 'parts': sorted(requested),
|
||||
'collect_components': components, 'discovery': payload,
|
||||
'payload_sha256': hashlib.sha256(json.dumps(payload, ensure_ascii=True, sort_keys=True).encode()).hexdigest()}
|
||||
record['record_sha256'] = hashlib.sha256(json.dumps(record, ensure_ascii=True, sort_keys=True).encode()).hexdigest()
|
||||
write_record(self._disk_path(project), record)
|
||||
files = sorted(self._disk_path(project).parent.glob('*.json'), key=lambda path: path.stat().st_mtime_ns, reverse=True)
|
||||
for stale in files[self.capacity:]:
|
||||
stale.unlink(missing_ok=True)
|
||||
except (OSError, ValueError, TypeError):
|
||||
pass # Cache persistence is optional, unlike execution write-ahead proof.
|
||||
|
||||
def discover(self, project, parts, collect_components, loader, *, stop_event=None, release_unverifiable=None):
|
||||
with self.lock:
|
||||
check_cancelled(stop_event)
|
||||
def fingerprint():
|
||||
@@ -140,7 +221,7 @@ class DiscoveryCache:
|
||||
key = _key(project)
|
||||
requested = frozenset(part.casefold() for part in parts)
|
||||
before = fingerprint()
|
||||
entry = self._entries.pop(key, None)
|
||||
entry = self._entries.pop(key, None) or self._disk_entry(project, before)
|
||||
if entry is not None:
|
||||
stamp, covered, has_components, discovery = entry
|
||||
if (before is not None and before == stamp and requested <= covered
|
||||
@@ -163,7 +244,9 @@ class DiscoveryCache:
|
||||
previous = None
|
||||
previous_design = None
|
||||
attempt, limit = 0, 2
|
||||
last_released = False
|
||||
while attempt < limit:
|
||||
last_released = False
|
||||
if attempt:
|
||||
before = fingerprint()
|
||||
check_cancelled(stop_event)
|
||||
@@ -171,7 +254,23 @@ class DiscoveryCache:
|
||||
check_cancelled(stop_event)
|
||||
identity = _discovery_identity(discovery)
|
||||
after = fingerprint()
|
||||
if before is not None and before == after:
|
||||
if after is None and release_unverifiable is not None:
|
||||
# A positively checkpointed read-only owned CAD may retain
|
||||
# an exclusive iCDB handle even after closing the project.
|
||||
# Release it before retrying the full fingerprint; never
|
||||
# treat an unreadable database as equal or cacheable.
|
||||
if release_unverifiable(project):
|
||||
last_released = True
|
||||
check_cancelled(stop_event)
|
||||
after = fingerprint()
|
||||
difference = _fingerprint_difference(before, after)
|
||||
try:
|
||||
from .batch_resources import write_record
|
||||
write_record(self.data_root / 'discovery-checks' / (hashlib.sha256(key.encode()).hexdigest() + '.json'),
|
||||
{'project': str(project), 'attempt': attempt + 1, **difference})
|
||||
except OSError:
|
||||
pass
|
||||
if _same_content(before, after):
|
||||
break
|
||||
if _only_database_changed(before, after):
|
||||
design = _without_runtime_database(after)
|
||||
@@ -186,6 +285,18 @@ class DiscoveryCache:
|
||||
previous = previous_design = None
|
||||
attempt += 1
|
||||
else:
|
||||
# A readable fingerprint that keeps changing is just as
|
||||
# unverifiable as an unreadable one. If this read-only CAD
|
||||
# session has positive release evidence, close it before
|
||||
# allowing the batch importer to skip this project.
|
||||
if not last_released and release_unverifiable is not None:
|
||||
last_released = bool(release_unverifiable(project))
|
||||
if last_released:
|
||||
from .project_discovery import ReleasedProjectReadError
|
||||
raise ReleasedProjectReadError('quick_run_sheet_discovery',
|
||||
'工程读取后无法确认一致,已跳过;后台读取会话已释放。' +
|
||||
('无法完整读取工程文件指纹,请检查文件占用及读取权限。' if difference['unverifiable'] else
|
||||
'内容发生变化的文件:' + '、'.join(difference['content_changed'][:8])))
|
||||
raise TaskCenterError("quick_run_sheet_discovery",
|
||||
"project contents changed or could not be verified during discovery; retry read-only discovery")
|
||||
# Refuse incomplete inventories and bound both projects and row count.
|
||||
@@ -197,6 +308,7 @@ class DiscoveryCache:
|
||||
and (len(getattr(discovery, 'components', ())) + len(sheets)
|
||||
+ sum(len(parts) for parts in matches.values())) <= 100000):
|
||||
self._entries[key] = (after, requested, collect_components, deepcopy(discovery))
|
||||
self._save_disk(project, after, requested, collect_components, discovery)
|
||||
while len(self._entries) > self.capacity:
|
||||
self._entries.popitem(last=False)
|
||||
return discovery
|
||||
|
||||
@@ -13,6 +13,10 @@ class ExecutionFeedback:
|
||||
message: str = '正在准备执行'
|
||||
stage: str = ''
|
||||
stage_seconds: float = 0.0
|
||||
waiting_for_safe_completion: bool = False
|
||||
stage_done: int = 0
|
||||
stage_total: int = 0
|
||||
last_update_seconds: float = 0.0
|
||||
|
||||
|
||||
def read_feedback(task_id, position, total, message, root: Path, started_after: float):
|
||||
@@ -27,15 +31,20 @@ def read_feedback(task_id, position, total, message, root: Path, started_after:
|
||||
except (OSError, ValueError, TypeError, AttributeError):
|
||||
pass
|
||||
path = root / 'quick-run' / 'worker-progress.json'
|
||||
stage, seconds = '', 0.0
|
||||
stage, seconds, waiting = '', 0.0, False
|
||||
done, total_units, last_update = 0, 0, 0.0
|
||||
try:
|
||||
modified = path.stat().st_mtime
|
||||
if modified >= started_after:
|
||||
record = json.loads(path.read_text(encoding='utf-8'))
|
||||
done = max(0, int(record.get('done', 0)))
|
||||
total_units = max(0, int(record.get('total', 0)))
|
||||
last_update = max(0, time.time() - modified)
|
||||
waiting = record.get('waiting_for_safe_completion') is True
|
||||
candidate = record.get('stage', '')
|
||||
if candidate and candidate != 'finished':
|
||||
seconds = float(record.get('stage_seconds', {}).get(candidate, 0)) + max(0, time.time() - modified)
|
||||
stage = candidate
|
||||
except (OSError, ValueError, TypeError, AttributeError):
|
||||
pass # Display feedback is optional; it never changes execution state.
|
||||
return ExecutionFeedback(task_id, position, total, message, stage, seconds)
|
||||
return ExecutionFeedback(task_id, position, total, message, stage, seconds, waiting, done, total_units, last_update)
|
||||
@@ -12,6 +12,7 @@ from uuid import uuid4
|
||||
from .cad_identity import CadBinding, current_desktop_name, verify_application, project_file_path
|
||||
from .isolated_desktop import PrivateDesktop
|
||||
from .worker_monitor import WorkerMonitorError
|
||||
from .path_access import internal_path, canonical_path, retry_sharing_violation
|
||||
|
||||
|
||||
class PrivateCadStartupError(WorkerMonitorError):
|
||||
@@ -27,6 +28,8 @@ class PrivateCadIdentityError(PrivateCadStartupError, CadIdentityConflict):
|
||||
|
||||
|
||||
PRIVATE_CAD_IDENTITY_EXIT_CODE = 4
|
||||
READ_ONLY_STARTUP_TIMEOUT_SECONDS = 45
|
||||
READ_ONLY_QUIT_TIMEOUT_SECONDS = 5
|
||||
|
||||
|
||||
def is_identity_conflict(error):
|
||||
@@ -47,6 +50,7 @@ def is_identity_conflict(error):
|
||||
|
||||
|
||||
def _helper_command(action, evidence, pid):
|
||||
evidence = internal_path(evidence)
|
||||
if getattr(sys, 'frozen', False):
|
||||
return (sys.executable, '--private-cad-action', action, '--private-cad-evidence', str(evidence),
|
||||
'--private-cad-pid', str(pid))
|
||||
@@ -64,15 +68,7 @@ def _replace_record(temporary, target):
|
||||
# Windows readers can temporarily deny delete access to the old JSON.
|
||||
# Keep the complete old record until replacement succeeds, with a finite
|
||||
# retry budget so persistent permissions failures still reach the caller.
|
||||
deadline = time.monotonic() + 1.0
|
||||
while True:
|
||||
try:
|
||||
temporary.replace(target)
|
||||
return
|
||||
except PermissionError:
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(0.02)
|
||||
retry_sharing_violation(lambda: internal_path(temporary).replace(internal_path(target)), target=target)
|
||||
|
||||
|
||||
def _designer_executable():
|
||||
@@ -93,8 +89,8 @@ def _designer_executable():
|
||||
|
||||
class IsolatedCadSession:
|
||||
"""The supervisor never attaches to COM on the user's input desktop."""
|
||||
def __init__(self, root, *, abort_event=None, desktop=None):
|
||||
self.root = Path(root).resolve()
|
||||
def __init__(self, root, *, abort_event=None, desktop=None, stop_control=None, read_only=False):
|
||||
self.root = canonical_path(root)
|
||||
self.token = uuid4().hex
|
||||
self.borrowed_desktop = desktop is not None
|
||||
self.desktop = desktop if desktop is not None else PrivateDesktop('dx-' + self.token, enabled=True)
|
||||
@@ -102,16 +98,18 @@ class IsolatedCadSession:
|
||||
self.binding = None
|
||||
self.started = time.monotonic()
|
||||
self.abort_event = abort_event
|
||||
self.stop_control = stop_control
|
||||
self.read_only = read_only
|
||||
self.record = {'desktop': self.desktop.name, 'token': self.token, 'state': 'starting'}
|
||||
|
||||
def _record(self, **values):
|
||||
self.record.update(values)
|
||||
self.root.mkdir(parents=True, exist_ok=True)
|
||||
target = self.root / 'private-desktop.json'
|
||||
internal_path(self.root).mkdir(parents=True, exist_ok=True)
|
||||
target = internal_path(self.root / 'private-desktop.json')
|
||||
temporary = target.with_suffix('.tmp')
|
||||
temporary.write_text(json.dumps(self.record, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
_replace_record(temporary, target)
|
||||
history = self.root / 'private-desktop-sessions'
|
||||
history = internal_path(self.root / 'private-desktop-sessions')
|
||||
history.mkdir(exist_ok=True)
|
||||
archived = history / (self.token + '.json')
|
||||
pending = archived.with_suffix('.tmp')
|
||||
@@ -131,9 +129,12 @@ class IsolatedCadSession:
|
||||
probe = self.desktop.start_process(_helper_command('probe', bootstrap, self.cad.pid), env=_child_environment(environment),
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
try:
|
||||
deadline = time.monotonic() + 120
|
||||
deadline = time.monotonic() + (READ_ONLY_STARTUP_TIMEOUT_SECONDS if self.read_only else 120)
|
||||
while probe.poll() is None:
|
||||
self._check_abort()
|
||||
cad_exit = self.cad.poll()
|
||||
if cad_exit is not None:
|
||||
raise WorkerMonitorError(f'owned private CAD exited during startup: exit code {cad_exit}')
|
||||
if time.monotonic() >= deadline:
|
||||
raise WorkerMonitorError('private CAD bootstrap timed out')
|
||||
time.sleep(0.05)
|
||||
@@ -144,7 +145,7 @@ class IsolatedCadSession:
|
||||
finally:
|
||||
probe.close()
|
||||
try:
|
||||
result = json.loads(bootstrap.read_text(encoding='utf-8'))
|
||||
result = json.loads(internal_path(bootstrap).read_text(encoding='utf-8'))
|
||||
binding = CadBinding(**result)
|
||||
if (type(binding.pid) is not int or not isinstance(binding.guid, str) or not binding.guid
|
||||
or (binding.pid, binding.desktop, binding.token) != (self.cad.pid, self.desktop.name, self.token)):
|
||||
@@ -185,7 +186,7 @@ class IsolatedCadSession:
|
||||
if self.binding is None or self.cad.poll() is not None:
|
||||
raise WorkerMonitorError('owned CAD unavailable at project checkpoint')
|
||||
evidence = Path(evidence)
|
||||
evidence.parent.mkdir(parents=True, exist_ok=True)
|
||||
internal_path(evidence.parent).mkdir(parents=True, exist_ok=True)
|
||||
process = self.start_worker(_helper_command('checkpoint', evidence, self.cad.pid),
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
try:
|
||||
@@ -195,7 +196,7 @@ class IsolatedCadSession:
|
||||
raise failure_type('project close checkpoint failed: ' +
|
||||
process.stderr.read().decode('utf-8', errors='replace'))
|
||||
try:
|
||||
result = json.loads(evidence.read_text(encoding='utf-8'))
|
||||
result = json.loads(internal_path(evidence).read_text(encoding='utf-8'))
|
||||
if (not isinstance(result, dict) or result.get('binding') != asdict(self.binding)
|
||||
or result.get('project_path') != '' or result.get('project_closed') is not True):
|
||||
raise ValueError('project close checkpoint identity mismatch')
|
||||
@@ -209,52 +210,141 @@ class IsolatedCadSession:
|
||||
|
||||
def __exit__(self, error_type, error, traceback):
|
||||
closing_started = time.monotonic()
|
||||
cleanup_error = None
|
||||
cleanup_errors = []
|
||||
diagnostic_errors = []
|
||||
failures = []
|
||||
exit_codes = {}
|
||||
closing = None
|
||||
|
||||
def remember(stage, failure):
|
||||
cleanup_errors.append({'stage': stage, 'message': str(failure)})
|
||||
message = '; '.join(f"{item['stage']}: {item['message']}" for item in cleanup_errors)
|
||||
self._uncertain(message, cleanup_errors=cleanup_errors,
|
||||
failures.append(failure)
|
||||
|
||||
def diagnose(stage, action):
|
||||
try:
|
||||
action()
|
||||
except Exception as failure:
|
||||
diagnostic_errors.append({'stage': stage, 'message': str(failure)})
|
||||
failures.append(failure)
|
||||
self.record['clean'] = False
|
||||
|
||||
def failure_message():
|
||||
return '; '.join(f"{item['stage']}: {item['message']}"
|
||||
for item in cleanup_errors + diagnostic_errors)
|
||||
|
||||
def persist_uncertain():
|
||||
message = failure_message() or str(error)
|
||||
self.record.update(state='uncertain', clean=False, error=message,
|
||||
cleanup_errors=cleanup_errors, diagnostic_errors=diagnostic_errors,
|
||||
shutdown_seconds=time.monotonic() - closing_started,
|
||||
desktop_cleanup=getattr(self.desktop, 'cleanup_record', None), **exit_codes)
|
||||
# Read-only shutdown faults remain diagnostics, without presenting
|
||||
# a write/save decision that an import caller cannot answer.
|
||||
record_failure = (lambda message, **details: self._record(
|
||||
state='closing', error=message, read_only=True, **details)) if self.read_only else self._uncertain
|
||||
diagnose('uncertain_record', lambda: record_failure(message,
|
||||
cleanup_errors=cleanup_errors, diagnostic_errors=diagnostic_errors,
|
||||
clean=False, orderly_shutdown=self.record['orderly_shutdown'],
|
||||
shutdown_seconds=time.monotonic() - closing_started,
|
||||
desktop_cleanup=getattr(self.desktop, 'cleanup_record', None), **exit_codes))
|
||||
|
||||
self.record.update(clean=False, orderly_shutdown=False, forced_termination=False,
|
||||
forced_root_termination=False, forced_descendant_pids=[], termination_reason=None,
|
||||
cleanup_errors=cleanup_errors, diagnostic_errors=diagnostic_errors)
|
||||
diagnose('closing_record', lambda: self._record(state='closing', clean=False,
|
||||
cleanup_errors=cleanup_errors, diagnostic_errors=diagnostic_errors))
|
||||
try:
|
||||
self._record(state='closing', cleanup_errors=cleanup_errors)
|
||||
if error is not None:
|
||||
self._uncertain(str(error))
|
||||
if self.cad is not None and self.cad.poll() is not None:
|
||||
raise WorkerMonitorError('owned CAD exited before the authorized quit request')
|
||||
if self.cad is not None and self.binding is not None:
|
||||
closing = self.desktop.start_process(_helper_command('quit', self.root / 'private-desktop.json', self.cad.pid),
|
||||
env=_child_environment(self.binding.environment()), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
try:
|
||||
quit_code = closing.wait(timeout=20)
|
||||
exit_codes['quit_helper_exit_code'] = quit_code
|
||||
if quit_code:
|
||||
raise WorkerMonitorError('owned CAD refused orderly exit: ' + closing.stderr.read().decode('utf-8', errors='replace'))
|
||||
cad_code = self.cad.wait(timeout=15)
|
||||
exit_codes['cad_exit_code'] = cad_code
|
||||
if cad_code != 0:
|
||||
raise WorkerMonitorError('owned CAD returned a nonzero exit code after quit')
|
||||
finally:
|
||||
closing.close()
|
||||
quit_code = closing.wait(timeout=READ_ONLY_QUIT_TIMEOUT_SECONDS if self.read_only else 20)
|
||||
exit_codes['quit_helper_exit_code'] = quit_code
|
||||
if quit_code:
|
||||
raise WorkerMonitorError('owned CAD refused orderly exit: ' + closing.stderr.read().decode('utf-8', errors='replace'))
|
||||
cad_code = self.cad.wait(timeout=READ_ONLY_QUIT_TIMEOUT_SECONDS if self.read_only else 15)
|
||||
exit_codes['cad_exit_code'] = cad_code
|
||||
if cad_code != 0:
|
||||
raise WorkerMonitorError('owned CAD returned a nonzero exit code after quit')
|
||||
self.record['orderly_shutdown'] = True
|
||||
except Exception as failure:
|
||||
cleanup_error = failure
|
||||
remember('orderly_shutdown', failure)
|
||||
finally:
|
||||
if error is not None or failures:
|
||||
# Evidence failure must never prevent the identity-checked Quit
|
||||
# above or release of the handles we own below.
|
||||
persist_uncertain()
|
||||
if not self.read_only and self.stop_control is not None and cleanup_errors and self.cad is not None:
|
||||
cad_running = True
|
||||
try:
|
||||
cad_running = self.cad.poll() is None
|
||||
except Exception as failure:
|
||||
remember('cad_exit_check', failure)
|
||||
if cad_running:
|
||||
# A refused/timed-out Quit may still be saving or closing.
|
||||
# Keep both CAD and its helper owned and alive until the
|
||||
# interactive caller confirms force, including ordinary stop.
|
||||
from .stop_control import wait_for_resolution
|
||||
try:
|
||||
wait_for_resolution(self.stop_control, self.root, failure_message())
|
||||
except WorkerMonitorError as failure:
|
||||
force_event = getattr(self.stop_control, 'force_event', None)
|
||||
if force_event is None or not force_event.is_set():
|
||||
raise
|
||||
remember('forced_stop', failure)
|
||||
if closing is not None:
|
||||
try:
|
||||
closing.close()
|
||||
except Exception as failure:
|
||||
remember('quit_helper_release', failure)
|
||||
try:
|
||||
self.desktop.close()
|
||||
self._record(state='session_closed' if self.borrowed_desktop else 'released',
|
||||
desktop_retained_by_batch=self.borrowed_desktop,
|
||||
clean=error is None and cleanup_error is None,
|
||||
shutdown_seconds=time.monotonic() - closing_started,
|
||||
desktop_cleanup=getattr(self.desktop, 'cleanup_record', None), **exit_codes)
|
||||
except Exception as failure:
|
||||
cleanup_error = failure
|
||||
remember('desktop_release', failure)
|
||||
if cleanup_error is not None:
|
||||
message = '; '.join(f"{item['stage']}: {item['message']}" for item in cleanup_errors)
|
||||
raise WorkerMonitorError('private CAD cleanup requires reconciliation: ' + message) from cleanup_error
|
||||
desktop_cleanup = getattr(self.desktop, 'cleanup_record', None) or {}
|
||||
forced = [item for item in desktop_cleanup.get('processes', []) if item.get('forced_termination')]
|
||||
self.record.update(forced_termination=bool(forced),
|
||||
forced_root_termination=any(item.get('forced_root_termination') for item in forced),
|
||||
termination_reason=next((item.get('termination_reason') for item in forced
|
||||
if item.get('termination_reason')), None),
|
||||
forced_descendant_pids=sorted({pid for item in forced for pid in item.get('forced_descendant_pids', [])}))
|
||||
if forced:
|
||||
remember('forced_cleanup', WorkerMonitorError('owned processes required forced termination'))
|
||||
if self.read_only:
|
||||
confirmation = desktop_cleanup.get('desktop_confirmation') or {}
|
||||
released = ((desktop_cleanup.get('workers_closed') is True
|
||||
and not desktop_cleanup.get('errors')) if self.borrowed_desktop else
|
||||
(desktop_cleanup.get('desktop_handle_closed') is True
|
||||
and not desktop_cleanup.get('errors')
|
||||
and (confirmation.get('released') is True
|
||||
or confirmation.get('release_accepted') is True)))
|
||||
allowed = {'orderly_shutdown', 'forced_cleanup'}
|
||||
if (released and not diagnostic_errors
|
||||
and all(item['stage'] in allowed for item in cleanup_errors)):
|
||||
diagnose('released_record', lambda: self._record(
|
||||
state='session_closed' if self.borrowed_desktop else 'released',
|
||||
desktop_retained_by_batch=self.borrowed_desktop, read_only=True,
|
||||
read_only_released=True, clean=not cleanup_errors,
|
||||
shutdown_seconds=time.monotonic() - closing_started,
|
||||
desktop_cleanup=desktop_cleanup, **exit_codes))
|
||||
if not diagnostic_errors:
|
||||
return
|
||||
elif not released:
|
||||
remember('read_release_confirmation', WorkerMonitorError(
|
||||
'read-only owned resource release was not confirmed'))
|
||||
if error is not None or failures:
|
||||
persist_uncertain()
|
||||
else:
|
||||
diagnose('released_record', lambda: self._record(
|
||||
state='session_closed' if self.borrowed_desktop else 'released',
|
||||
desktop_retained_by_batch=self.borrowed_desktop, clean=True,
|
||||
shutdown_seconds=time.monotonic() - closing_started,
|
||||
desktop_cleanup=desktop_cleanup, **exit_codes))
|
||||
if failures:
|
||||
persist_uncertain()
|
||||
if failures:
|
||||
raise WorkerMonitorError('private CAD cleanup requires reconciliation: ' + failure_message()) from failures[0]
|
||||
|
||||
def _uncertain(self, message, **details):
|
||||
from .quick_run import _write_uncertain_flag
|
||||
@@ -294,7 +384,7 @@ def _run_native_action(action, evidence, expected_pid):
|
||||
# COM startup can block inside a native call, so keep diagnostics outside
|
||||
# the redirected pipes and retain them when the supervisor ends the child.
|
||||
import faulthandler
|
||||
with Path(str(evidence) + '.fault.txt').open('a', encoding='utf-8') as trace:
|
||||
with internal_path(str(evidence) + '.fault.txt').open('a', encoding='utf-8') as trace:
|
||||
faulthandler.dump_traceback_later(20, repeat=True, file=trace)
|
||||
try:
|
||||
return _native_action(action, evidence, expected_pid)
|
||||
@@ -339,7 +429,7 @@ def _native_action(action, evidence, expected_pid):
|
||||
verify_application(app, binding, require_view=False)
|
||||
except ValueError as error:
|
||||
raise CadIdentityConflict(str(error)) from error
|
||||
Path(evidence).write_text(json.dumps(asdict(binding)), encoding='utf-8')
|
||||
internal_path(evidence).write_text(json.dumps(asdict(binding)), encoding='utf-8')
|
||||
elif action in {'quit', 'checkpoint'}:
|
||||
try:
|
||||
binding = CadBinding.from_environment()
|
||||
|
||||
@@ -8,6 +8,7 @@ from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from contextlib import ExitStack
|
||||
from copy import deepcopy
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
import math
|
||||
@@ -22,6 +23,20 @@ from .errors import TaskCenterError
|
||||
|
||||
|
||||
DESKTOP_RELEASE_TIMEOUT_SECONDS = 5.0
|
||||
DESCENDANT_EXIT_GRACE_SECONDS = 2.0
|
||||
|
||||
|
||||
def _native_handle(handle):
|
||||
try:
|
||||
return int(handle) if handle is not None else None
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _resource_event(operation, handle, success, error=None):
|
||||
return {'operation': operation, 'handle': _native_handle(handle), 'success': success,
|
||||
'pid': os.getpid(), 'thread_id': get_native_id(), 'time_ns': time.time_ns(),
|
||||
'error': str(error) if error is not None else None}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
@@ -50,6 +65,18 @@ class _Win32Api:
|
||||
return self.service.CreateDesktop(name, 0, self.con.GENERIC_ALL, None)
|
||||
|
||||
def confirm_desktop_released(self, name: str):
|
||||
return self._confirm_desktop_released(name, accept_empty_residual=False)
|
||||
|
||||
def confirm_desktop_released_or_empty(self, name: str):
|
||||
"""Accept an empty desktop residue after its owned processes are gone.
|
||||
|
||||
The caller must first prove every owned process and native handle is
|
||||
closed. A residual desktop with windows still follows the strict,
|
||||
bounded confirmation path.
|
||||
"""
|
||||
return self._confirm_desktop_released(name, accept_empty_residual=True)
|
||||
|
||||
def _confirm_desktop_released(self, name: str, *, accept_empty_residual: bool):
|
||||
started = time.monotonic()
|
||||
# USER references can outlive the owned processes briefly. Allow a
|
||||
# bounded grace period, without delaying the usual immediate release
|
||||
@@ -68,6 +95,20 @@ class _Win32Api:
|
||||
'caller_pid': os.getpid(), 'caller_thread_id': get_native_id()}
|
||||
if not present:
|
||||
return
|
||||
if accept_empty_residual:
|
||||
try:
|
||||
windows = self._desktop_windows(name)
|
||||
self.desktop_release_check.update(remaining_windows=windows,
|
||||
desktop_present=True, release_accepted=not windows,
|
||||
residual_only=not windows,
|
||||
acceptance_reason='owned processes closed; no desktop windows remain' if not windows else None)
|
||||
except Exception as error:
|
||||
self.desktop_release_check['window_query_error'] = str(error)
|
||||
windows = None
|
||||
if windows == []:
|
||||
# This does not claim the USER desktop object disappeared:
|
||||
# only that no owned process or visible desktop work remains.
|
||||
return
|
||||
if time.monotonic() >= deadline:
|
||||
try:
|
||||
from .cad_identity import current_desktop_name
|
||||
@@ -76,6 +117,9 @@ class _Win32Api:
|
||||
self.desktop_release_check['caller_desktop_error'] = str(error)
|
||||
try:
|
||||
self.desktop_release_check['remaining_windows'] = self._desktop_windows(name)
|
||||
self.desktop_release_check['desktop_present'] = True
|
||||
self.desktop_release_check['release_accepted'] = False
|
||||
self.desktop_release_check['residual_only'] = False
|
||||
except Exception as error:
|
||||
self.desktop_release_check['window_query_error'] = str(error)
|
||||
raise TaskCenterError('private_desktop_cleanup', 'owned private desktop still exists after cleanup')
|
||||
@@ -109,7 +153,7 @@ class _Win32Api:
|
||||
return windows
|
||||
|
||||
def create_process(self, command: Sequence[str], desktop: str, cwd: Path | None, env: Mapping[str, str] | None,
|
||||
*, stdout=None, stderr=None):
|
||||
*, stdout=None, stderr=None, survive_parent_exit=False):
|
||||
startup = self.process.STARTUPINFO()
|
||||
startup.lpDesktop = desktop
|
||||
flags = self.con.CREATE_NO_WINDOW | self.con.CREATE_SUSPENDED
|
||||
@@ -131,8 +175,9 @@ class _Win32Api:
|
||||
open_process=getattr(self, 'open_process', None))
|
||||
process.stdout, process.stderr = streams
|
||||
process.thread = thread
|
||||
self.job.AssignProcessToJobObject(job, handle)
|
||||
process.job_assigned = True
|
||||
if not survive_parent_exit:
|
||||
self.job.AssignProcessToJobObject(job, handle)
|
||||
process.job_assigned = True
|
||||
self.process.ResumeThread(thread)
|
||||
thread.Close()
|
||||
process.thread = None
|
||||
@@ -178,7 +223,10 @@ def _stop_and_wait(process):
|
||||
errors.append(error)
|
||||
if running:
|
||||
try:
|
||||
process.terminate()
|
||||
if isinstance(process, _Win32Process):
|
||||
process.terminate(reason='root_process_active')
|
||||
else:
|
||||
process.terminate()
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
try:
|
||||
@@ -299,7 +347,9 @@ class _Win32Process:
|
||||
self.job_assigned = False
|
||||
self.returncode = None
|
||||
self.stdout = self.stderr = None
|
||||
self.cleanup_record = {'pid': self.pid}
|
||||
self.cleanup_record = {'pid': self.pid, 'forced_termination': False,
|
||||
'forced_root_termination': False, 'forced_descendant_pids': [],
|
||||
'termination_reason': None}
|
||||
|
||||
def poll(self):
|
||||
if self.returncode is not None or self.handle is None:
|
||||
@@ -326,34 +376,59 @@ class _Win32Process:
|
||||
self.returncode = self._process_api.GetExitCodeProcess(self.handle)
|
||||
return self.returncode
|
||||
|
||||
def terminate(self):
|
||||
def terminate(self, *, reason='explicit_termination'):
|
||||
if self.handle is None:
|
||||
return
|
||||
errors = []
|
||||
root_active = True
|
||||
try:
|
||||
root_active = self.poll() is None
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
self.cleanup_record.setdefault('root_exit_before_cleanup', not root_active)
|
||||
if not self.job_assigned:
|
||||
self._process_api.TerminateProcess(self.handle, 1)
|
||||
self._record_termination(reason, root_active, ())
|
||||
_raise_cleanup_errors(errors)
|
||||
return
|
||||
errors = []
|
||||
descendants = set()
|
||||
try:
|
||||
self._remember_descendants()
|
||||
# Keep confirmed members of this snapshot even if opening a later
|
||||
# member fails; the Job termination below still includes them.
|
||||
self._remember_descendants(active=descendants)
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
try:
|
||||
self._job_api.TerminateJobObject(self.job, 1)
|
||||
self._record_termination(reason, root_active, descendants)
|
||||
except Exception:
|
||||
self._process_api.TerminateProcess(self.handle, 1)
|
||||
self._record_termination(reason, root_active, ())
|
||||
_raise_cleanup_errors(errors)
|
||||
|
||||
kill = terminate
|
||||
|
||||
def _remember_descendants(self):
|
||||
def _record_termination(self, reason, root_active, descendants):
|
||||
self.cleanup_record.update(forced_termination=True,
|
||||
forced_root_termination=self.cleanup_record['forced_root_termination'] or root_active,
|
||||
forced_descendant_pids=sorted(set(self.cleanup_record['forced_descendant_pids']) | set(descendants)),
|
||||
termination_reason=self.cleanup_record['termination_reason'] or reason)
|
||||
|
||||
def _remember_descendants(self, *, active=None):
|
||||
if active is None:
|
||||
active = set()
|
||||
if self._open_process is None or self.job is None:
|
||||
return
|
||||
return active
|
||||
for pid in self._job_api.QueryInformationJobObject(self.job, self._job_api.JobObjectBasicProcessIdList):
|
||||
if pid == self.pid or pid in self._descendant_pids:
|
||||
if pid == self.pid:
|
||||
continue
|
||||
if pid in self._descendant_pids:
|
||||
active.add(pid)
|
||||
continue
|
||||
try:
|
||||
self._descendant_handles.append(self._open_process(0x100000, False, pid))
|
||||
self._descendant_pids.add(pid)
|
||||
active.add(pid)
|
||||
except Exception as error:
|
||||
# pywintypes.error is not an OSError. A child that exited
|
||||
# between the job snapshot and OpenProcess reports error 87.
|
||||
@@ -362,22 +437,47 @@ class _Win32Process:
|
||||
code = error.args[0]
|
||||
if code != 87:
|
||||
raise
|
||||
return active
|
||||
|
||||
def close(self):
|
||||
errors = []
|
||||
job_empty = not self.job_assigned or self.job is None
|
||||
if self.handle is not None:
|
||||
if 'root_exit_before_cleanup' not in self.cleanup_record:
|
||||
try:
|
||||
self.cleanup_record['root_exit_before_cleanup'] = self.poll() is not None
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
errors.extend(_stop_and_wait(self))
|
||||
deadline = time.monotonic() + 5.0
|
||||
if self.job is not None and self.job_assigned:
|
||||
try:
|
||||
# A completed root can leave grandchildren holding the desktop.
|
||||
self._remember_descendants()
|
||||
self._job_api.TerminateJobObject(self.job, 1)
|
||||
grace_started = time.monotonic()
|
||||
grace_deadline = grace_started + DESCENDANT_EXIT_GRACE_SECONDS
|
||||
# A completed root may leave children finishing normal shutdown.
|
||||
# An empty job takes no grace delay; an active root was already
|
||||
# stopped above and does not receive this normal-exit allowance.
|
||||
while True:
|
||||
active = self._job_api.QueryInformationJobObject(
|
||||
self.job, self._job_api.JobObjectBasicAccountingInformation)['ActiveProcesses']
|
||||
self.cleanup_record['job_active_processes'] = active
|
||||
if not active:
|
||||
job_empty = True
|
||||
break
|
||||
self._remember_descendants()
|
||||
if (self.cleanup_record.get('root_exit_before_cleanup') is not True
|
||||
or self.cleanup_record['forced_termination'] or time.monotonic() >= grace_deadline):
|
||||
self.terminate(reason='descendant_grace_expired')
|
||||
break
|
||||
time.sleep(min(0.01, max(0, grace_deadline - time.monotonic())))
|
||||
self.cleanup_record['descendant_grace_seconds'] = time.monotonic() - grace_started
|
||||
deadline = time.monotonic() + 5.0
|
||||
while True:
|
||||
active = self._job_api.QueryInformationJobObject(
|
||||
self.job, self._job_api.JobObjectBasicAccountingInformation)['ActiveProcesses']
|
||||
self.cleanup_record['job_active_processes'] = active
|
||||
if not active:
|
||||
job_empty = True
|
||||
break
|
||||
if time.monotonic() >= deadline:
|
||||
raise TimeoutError('owned job descendants did not exit within 5 seconds')
|
||||
@@ -403,6 +503,10 @@ class _Win32Process:
|
||||
self._descendant_handles = retained
|
||||
for name in ('job', 'thread', 'handle'):
|
||||
handle = getattr(self, name)
|
||||
if name in ('job', 'handle') and not job_empty:
|
||||
# Closing a KILL_ON_JOB_CLOSE job would silently force remaining
|
||||
# children and discard the capability needed for cleanup retry.
|
||||
continue
|
||||
if name == 'handle' and self.returncode is None:
|
||||
# Keep the only termination/wait capability until cleanup can retry.
|
||||
continue
|
||||
@@ -435,6 +539,8 @@ class PrivateDesktop:
|
||||
self._processes: list[subprocess.Popen[str]] = []
|
||||
self._api = api
|
||||
self.cleanup_record = None
|
||||
self._desktop_handle_history = []
|
||||
self._process_history = []
|
||||
|
||||
def __enter__(self) -> "PrivateDesktop":
|
||||
if not self.enabled:
|
||||
@@ -451,7 +557,12 @@ class PrivateDesktop:
|
||||
if os.name != "nt" and self._api is None:
|
||||
return
|
||||
self._api = self._api or _Win32Api()
|
||||
self._handle = self._api.create_desktop(self.name)
|
||||
try:
|
||||
self._handle = self._api.create_desktop(self.name)
|
||||
except Exception as error:
|
||||
self._desktop_handle_history.append(_resource_event('create', None, False, error))
|
||||
raise
|
||||
self._desktop_handle_history.append(_resource_event('create', self._handle, self._handle is not None))
|
||||
|
||||
def start_process(
|
||||
self,
|
||||
@@ -471,8 +582,20 @@ class PrivateDesktop:
|
||||
options = {} if stdout is None and stderr is None else {'stdout': stdout, 'stderr': stderr}
|
||||
process = self._api.create_process(command, build_startup_info(self.name).lpDesktop, cwd, env, **options)
|
||||
self._processes.append(process)
|
||||
self._process_history.append({'pid': getattr(process, 'pid', None),
|
||||
'owner_pid': os.getpid(), 'owner_thread_id': get_native_id(),
|
||||
'started_time_ns': time.time_ns(), 'process_handle': _native_handle(getattr(process, 'handle', None)),
|
||||
'job_handle': _native_handle(getattr(process, 'job', None)), 'forgotten': False})
|
||||
return process
|
||||
|
||||
def _remember_process_cleanup(self, process, *, forgotten=False):
|
||||
for record in reversed(self._process_history):
|
||||
if record['pid'] == getattr(process, 'pid', None) and not record['forgotten']:
|
||||
record['cleanup'] = deepcopy(getattr(process, 'cleanup_record', {}))
|
||||
record['forgotten'] = forgotten
|
||||
record['observed_time_ns'] = time.time_ns()
|
||||
break
|
||||
|
||||
def forget_closed_process(self, process):
|
||||
"""Drop a worker only after its owning wrapper confirmed all cleanup."""
|
||||
record = getattr(process, 'cleanup_record', {})
|
||||
@@ -482,6 +605,7 @@ class PrivateDesktop:
|
||||
or record.get('errors') or process.poll() is None):
|
||||
raise OSError('cannot forget a worker with unconfirmed owned resources')
|
||||
self._processes = [item for item in self._processes if item is not process]
|
||||
self._remember_process_cleanup(process, forgotten=True)
|
||||
|
||||
def close(self) -> None:
|
||||
errors, remaining = [], []
|
||||
@@ -497,6 +621,7 @@ class PrivateDesktop:
|
||||
failed = True
|
||||
self.cleanup_record['processes'].append(getattr(process, 'cleanup_record', {
|
||||
'pid': getattr(process, 'pid', None), 'exit_code': getattr(process, 'returncode', None)}))
|
||||
self._remember_process_cleanup(process)
|
||||
if failed:
|
||||
remaining.append(process)
|
||||
self._processes = list(reversed(remaining))
|
||||
@@ -508,18 +633,85 @@ class PrivateDesktop:
|
||||
errors.append(error)
|
||||
close_desktop = getattr(self._handle, "CloseDesktop", None)
|
||||
if close_desktop:
|
||||
event = _resource_event('close', self._handle, False)
|
||||
try:
|
||||
close_desktop()
|
||||
event['success'] = True
|
||||
self._handle = None
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
event['error'] = str(error)
|
||||
self._desktop_handle_history.append(event)
|
||||
confirm = getattr(self._api, 'confirm_desktop_released', None)
|
||||
if confirm and self._handle is None:
|
||||
try:
|
||||
confirm(self.name)
|
||||
accept_empty = (not errors and not self._processes
|
||||
and not getattr(self._api, '_pending_cleanup', ())
|
||||
and all(self._process_cleanup_confirmed(item)
|
||||
for item in self._process_history))
|
||||
if accept_empty:
|
||||
confirm_empty = getattr(self._api, 'confirm_desktop_released_or_empty', None)
|
||||
(confirm_empty or confirm)(self.name)
|
||||
else:
|
||||
confirm(self.name)
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
self.cleanup_record.update(desktop_handle_closed=self._handle is None,
|
||||
desktop_confirmation=getattr(self._api, 'desktop_release_check', None),
|
||||
desktop_handle_history=deepcopy(self._desktop_handle_history),
|
||||
process_history=deepcopy(self._process_history),
|
||||
diagnostic_scope={'external_handle_holders': 'unknown',
|
||||
'thread_desktops': 'unknown unless observed through residual windows; no exhaustive holder scan',
|
||||
'empty_windows_prove_no_holders': False},
|
||||
errors=[str(error) for error in errors])
|
||||
if errors:
|
||||
self.cleanup_record['owned_resource_diagnostics'] = self._owned_resource_diagnostics()
|
||||
_raise_cleanup_errors(errors)
|
||||
|
||||
@staticmethod
|
||||
def _process_cleanup_confirmed(history):
|
||||
cleanup = history.get('cleanup') if isinstance(history, dict) else None
|
||||
return (isinstance(cleanup, dict)
|
||||
and cleanup.get('process_handle_closed') is True
|
||||
and cleanup.get('job_handle_closed') is True
|
||||
and cleanup.get('job_active_processes', 0) == 0
|
||||
and cleanup.get('unconfirmed_descendant_handles', 0) == 0
|
||||
and not cleanup.get('errors'))
|
||||
|
||||
def _owned_resource_diagnostics(self):
|
||||
"""Bounded queries of our handles only; never terminate/query foreign PIDs.
|
||||
|
||||
GetThreadDesktop can introduce borrowed USER references. Do not run a
|
||||
global thread scan in this long-lived owner while retrying release.
|
||||
Window observations identify only window-owning threads, not every
|
||||
thread or an external OpenDesktop handle holder.
|
||||
"""
|
||||
resources = []
|
||||
for process in self._processes:
|
||||
item = {'pid': getattr(process, 'pid', None),
|
||||
'process_handle': _native_handle(getattr(process, 'handle', None)),
|
||||
'job_handle': _native_handle(getattr(process, 'job', None)),
|
||||
'thread_handle': _native_handle(getattr(process, 'thread', None)),
|
||||
'cleanup': deepcopy(getattr(process, 'cleanup_record', {}))}
|
||||
try:
|
||||
item['exit_code'] = process.poll()
|
||||
except Exception as error:
|
||||
item['poll_error'] = str(error)
|
||||
job = getattr(process, 'job', None)
|
||||
job_api = getattr(process, '_job_api', None)
|
||||
if job is not None and job_api is not None:
|
||||
try:
|
||||
item['job_accounting'] = job_api.QueryInformationJobObject(
|
||||
job, job_api.JobObjectBasicAccountingInformation)
|
||||
except Exception as error:
|
||||
item['job_query_error'] = str(error)
|
||||
resources.append(item)
|
||||
confirmation = getattr(self._api, 'desktop_release_check', None) or {}
|
||||
return {'owned_processes': resources,
|
||||
'pending_launch_cleanup_count': len(getattr(self._api, '_pending_cleanup', [])),
|
||||
'residual_windows': deepcopy(confirmation.get('remaining_windows')),
|
||||
'window_query_error': confirmation.get('window_query_error'),
|
||||
'external_handle_holders': 'unknown',
|
||||
'thread_desktops': {'observations': deepcopy(confirmation.get('remaining_windows', [])),
|
||||
'complete': False, 'unobserved_threads': 'unknown'},
|
||||
'empty_windows_prove_no_holders': False}
|
||||
@@ -11,6 +11,7 @@ import tempfile
|
||||
from threading import RLock
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .path_access import canonical_path, internal_path, retry_sharing_violation, strip_extended_prefix
|
||||
|
||||
|
||||
def _short_path(path: Path) -> str | None:
|
||||
@@ -18,8 +19,8 @@ def _short_path(path: Path) -> str | None:
|
||||
function.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint]
|
||||
function.restype = ctypes.c_uint
|
||||
buffer = ctypes.create_unicode_buffer(32768)
|
||||
count = function(str(path), buffer, len(buffer))
|
||||
return buffer.value if count and count < len(buffer) else None
|
||||
count = function(str(internal_path(path)), buffer, len(buffer))
|
||||
return strip_extended_prefix(buffer.value) if count and count < len(buffer) else None
|
||||
|
||||
|
||||
def _fits(root) -> bool:
|
||||
@@ -34,12 +35,13 @@ class _AliasPool:
|
||||
self.lock = RLock()
|
||||
|
||||
def alias(self, root: Path) -> Path:
|
||||
root = canonical_path(root, strict=True)
|
||||
import _winapi
|
||||
with self.lock:
|
||||
if self.directory is None:
|
||||
local = Path(os.environ.get('LOCALAPPDATA') or tempfile.gettempdir())
|
||||
parent = local / 'DxProductivity' / 'path-links'
|
||||
parent.mkdir(parents=True, exist_ok=True)
|
||||
internal_path(parent).mkdir(parents=True, exist_ok=True)
|
||||
self.directory = Path(tempfile.mkdtemp(prefix='dxp-', dir=parent))
|
||||
key = hashlib.sha256(os.path.normcase(str(root)).encode('utf-8')).hexdigest()[:20]
|
||||
link = self.directory / key
|
||||
@@ -48,9 +50,11 @@ class _AliasPool:
|
||||
if link not in self.links:
|
||||
# Junction creation needs no symbolic-link privilege. The
|
||||
# junction contains no copies and never changes the target.
|
||||
_winapi.CreateJunction(str(root), str(link))
|
||||
# CPython's junction helper expects a DOS path, not a \\?\
|
||||
# target. An existing 8.3 name also avoids its MAX_PATH limit.
|
||||
_winapi.CreateJunction(_short_path(root) or str(root), str(link))
|
||||
self.links[link] = root
|
||||
if not link.is_junction() or link.resolve(strict=True) != root:
|
||||
if not link.is_junction() or canonical_path(link, strict=True) != root:
|
||||
raise OSError('compatibility directory no longer points to the confirmed evidence')
|
||||
return link
|
||||
|
||||
@@ -60,7 +64,7 @@ class _AliasPool:
|
||||
for link, target in tuple(self.links.items()):
|
||||
try:
|
||||
if link.is_junction():
|
||||
if link.resolve() != target:
|
||||
if canonical_path(link) != target:
|
||||
raise OSError('refusing to remove a redirected compatibility directory')
|
||||
link.rmdir() # Remove only the link, never the target tree.
|
||||
elif link.exists():
|
||||
@@ -88,11 +92,12 @@ atexit.register(cleanup_worker_aliases)
|
||||
|
||||
|
||||
def worker_paths(script: Path, root: Path) -> tuple[str, str]:
|
||||
script, root = canonical_path(script), canonical_path(root)
|
||||
if os.name == 'nt':
|
||||
_prepare_project_access(root)
|
||||
if os.name != 'nt' or _fits(root):
|
||||
return str(script), str(root)
|
||||
canonical = root.resolve(strict=True)
|
||||
canonical = canonical_path(internal_path(root), strict=True)
|
||||
short = _short_path(canonical)
|
||||
if short and _fits(short):
|
||||
return str(Path(short) / script.name), short
|
||||
@@ -106,7 +111,7 @@ def worker_paths(script: Path, root: Path) -> tuple[str, str]:
|
||||
|
||||
def _prepare_project_access(root: Path):
|
||||
"""Keep command identities canonical while giving legacy CAD short entry paths."""
|
||||
command = root / 'command.tsv'
|
||||
command = internal_path(root / 'command.tsv')
|
||||
if not command.is_file():
|
||||
return
|
||||
rows = []
|
||||
@@ -117,32 +122,32 @@ def _prepare_project_access(root: Path):
|
||||
if not value or value in seen:
|
||||
continue
|
||||
seen.add(value)
|
||||
project = Path(value).resolve(strict=False)
|
||||
if (_fits(project.parent) and len(str(project)) < 260) or not project.is_file():
|
||||
project = canonical_path(internal_path(value))
|
||||
if (_fits(project.parent) and len(str(project)) < 260) or not internal_path(project).is_file():
|
||||
continue
|
||||
short = _short_path(project)
|
||||
if short and _fits(Path(short).parent) and len(short) < 260:
|
||||
access = Path(short)
|
||||
else:
|
||||
access = _aliases.alias(project.parent) / project.name
|
||||
if not _fits(access.parent) or len(str(access)) >= 260 or access.resolve(strict=True) != project:
|
||||
if not _fits(access.parent) or len(str(access)) >= 260 or canonical_path(access, strict=True) != project:
|
||||
raise TaskCenterError('quick_run_path_length', '工程短路径入口不能与原工程身份对应,未启动 CAD 操作。')
|
||||
pair = (str(project), str(access))
|
||||
if pair not in rows:
|
||||
rows.append(pair)
|
||||
target = root / 'project-access.tsv'
|
||||
target = internal_path(root / 'project-access.tsv')
|
||||
if rows or target.exists():
|
||||
temporary = target.with_suffix('.tmp')
|
||||
with temporary.open('w', encoding='utf-8', newline='') as stream:
|
||||
writer = csv.writer(stream, delimiter='\t', lineterminator='\n')
|
||||
writer.writerow(('project_path', 'access_path'))
|
||||
writer.writerows(rows)
|
||||
temporary.replace(target)
|
||||
retry_sharing_violation(lambda: temporary.replace(target))
|
||||
|
||||
|
||||
def validate_project_access(root: Path):
|
||||
"""Reject disappeared/redirected entry paths before and after a native worker."""
|
||||
target = Path(root) / 'project-access.tsv'
|
||||
target = internal_path(Path(root) / 'project-access.tsv')
|
||||
if not target.is_file():
|
||||
return
|
||||
with target.open(encoding='utf-8-sig', newline='') as stream:
|
||||
@@ -151,7 +156,7 @@ def validate_project_access(root: Path):
|
||||
raise TaskCenterError('target_identity', '工程路径入口清单格式已改变')
|
||||
for row in reader:
|
||||
try:
|
||||
same = Path(row['access_path']).resolve(strict=True) == Path(row['project_path']).resolve(strict=True)
|
||||
same = canonical_path(internal_path(row['access_path']), strict=True) == canonical_path(internal_path(row['project_path']), strict=True)
|
||||
except (OSError, ValueError, KeyError):
|
||||
same = False
|
||||
if not same:
|
||||
|
||||
@@ -18,6 +18,7 @@ import traceback
|
||||
from typing import Any, Mapping
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .path_access import internal_path
|
||||
from .retention import rotate_text_log
|
||||
|
||||
|
||||
@@ -75,24 +76,28 @@ class LoggingContext:
|
||||
return reported
|
||||
|
||||
|
||||
def configure_logging(root: Path) -> LoggingContext:
|
||||
def configure_logging(root: Path, *, log_path: Path | None = None) -> LoggingContext:
|
||||
"""Create storage directories and a UTF-8 rotating application log handler."""
|
||||
storage_root = Path(root).resolve()
|
||||
log_path = storage_root / "logs" / "application.log"
|
||||
log_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
(storage_root / "tasks").mkdir(parents=True, exist_ok=True)
|
||||
from .path_access import canonical_path, internal_path
|
||||
storage_root = canonical_path(root)
|
||||
separate_log = log_path is not None
|
||||
log_path = canonical_path(log_path) if separate_log else storage_root / "logs" / "application.log"
|
||||
internal_path(log_path.parent).mkdir(parents=True, exist_ok=True)
|
||||
internal_path(storage_root / "tasks").mkdir(parents=True, exist_ok=True)
|
||||
logger_name = "dx_productivity.trial_task_center." + hashlib.sha256(
|
||||
str(storage_root.resolve()).encode("utf-8")
|
||||
).hexdigest()[:16]
|
||||
if separate_log:
|
||||
logger_name += '.' + hashlib.sha256(str(log_path).encode('utf-8')).hexdigest()[:12]
|
||||
logger = logging.getLogger(logger_name)
|
||||
logger.setLevel(logging.DEBUG)
|
||||
logger.propagate = False
|
||||
if not any(
|
||||
isinstance(handler, RotatingFileHandler) and Path(handler.baseFilename) == log_path
|
||||
isinstance(handler, RotatingFileHandler) and canonical_path(handler.baseFilename) == log_path
|
||||
for handler in logger.handlers
|
||||
):
|
||||
handler = RotatingFileHandler(
|
||||
log_path,
|
||||
internal_path(log_path),
|
||||
maxBytes=_MAX_LOG_BYTES,
|
||||
backupCount=_BACKUP_COUNT,
|
||||
encoding="utf-8",
|
||||
@@ -151,11 +156,11 @@ def append_task_event(
|
||||
encoded = json.dumps(event, ensure_ascii=False, separators=(",", ":"), allow_nan=False) + "\n"
|
||||
try:
|
||||
rotate_text_log(
|
||||
path,
|
||||
internal_path(path),
|
||||
max_bytes=_MAX_EVENT_LOG_BYTES,
|
||||
backup_count=_EVENT_BACKUP_COUNT,
|
||||
)
|
||||
with path.open("a", encoding="utf-8", newline="\n") as handle:
|
||||
with internal_path(path).open("a", encoding="utf-8", newline="\n") as handle:
|
||||
handle.write(encoded)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
@@ -183,7 +188,7 @@ def append_task_event(
|
||||
|
||||
def _event_file_stamp(path):
|
||||
try:
|
||||
info = path.stat()
|
||||
info = internal_path(path).stat()
|
||||
return info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns
|
||||
except OSError:
|
||||
return None
|
||||
@@ -226,15 +231,15 @@ def _task_directory(context: LoggingContext, task_id: str) -> Path:
|
||||
if not task_id or Path(task_id).name != task_id or task_id in {".", ".."}:
|
||||
raise TaskCenterError("task_id", "task event requires a safe task identifier")
|
||||
path = context.root / "tasks" / task_id
|
||||
if not path.is_dir():
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
if not internal_path(path).is_dir():
|
||||
internal_path(path).mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def _next_event_sequence(path: Path) -> int:
|
||||
try:
|
||||
for candidate in (path, path.with_name(f"{path.name}.1")):
|
||||
if not candidate.exists():
|
||||
if not internal_path(candidate).exists():
|
||||
continue
|
||||
lines = _tail_utf8_lines(candidate, 1)
|
||||
if lines:
|
||||
@@ -248,7 +253,7 @@ def _next_event_sequence(path: Path) -> int:
|
||||
def _tail_utf8_lines(path: Path, limit: int) -> tuple[str, ...]:
|
||||
if limit < 1:
|
||||
return ()
|
||||
with Path(path).open("rb") as handle:
|
||||
with internal_path(Path(path)).open("rb") as handle:
|
||||
handle.seek(0, os.SEEK_END)
|
||||
cursor = handle.tell()
|
||||
chunks = []
|
||||
|
||||
@@ -230,7 +230,7 @@ def wait_for(callback, description, timeout=15):
|
||||
raise TimeoutError(description)
|
||||
|
||||
|
||||
def wait_for_library_rows(callback, target, timeout=30, stable_for=0.45, poll_interval=0.15):
|
||||
def wait_for_library_rows(callback, target, timeout=8, stable_for=0.45, poll_interval=0.15):
|
||||
deadline = time.monotonic() + timeout
|
||||
previous = None
|
||||
stable_since = None
|
||||
@@ -338,8 +338,8 @@ def attach():
|
||||
try:
|
||||
import viewdraw_api as api
|
||||
except ImportError:
|
||||
api = win32com.client.gencache.EnsureModule(
|
||||
"{4ADEF4E1-690A-11CE-9261-0020C5E26659}", 0, 1, 0)
|
||||
from .com_api import registered_api
|
||||
api = registered_api("{4ADEF4E1-690A-11CE-9261-0020C5E26659}", required=('IVdApp', 'IVdComp'))
|
||||
app = api.IVdApp(win32com.client.GetActiveObject("Viewdraw.Application")._oleobj_)
|
||||
from .cad_identity import verify_application, project_file_path
|
||||
verify_application(app)
|
||||
@@ -511,11 +511,9 @@ def replacement_matches(components, records, target, require_part_label, *, libr
|
||||
f"Native replacement Part Name readback failed; refdes={identity}; uid={candidate.UID}"
|
||||
)
|
||||
part_label = attribute_value(candidate, 'Part Label') if require_part_label or expected_label else ''
|
||||
if require_part_label and not part_label:
|
||||
raise ValueError(
|
||||
f"Native replacement Part Label readback failed; refdes={identity}; uid={candidate.UID}; "
|
||||
"Part Label is required by the selected Value policy"
|
||||
)
|
||||
# A missing label is valid for parts without that library attribute.
|
||||
# VBS restores the original Value snapshot; a recorded nonblank library
|
||||
# label must still match below, so an actual lost attribute is rejected.
|
||||
if expected_name is not None and (part_name != expected_name
|
||||
or (expected_label and part_label != expected_label)):
|
||||
raise ValueError(f'Native replacement does not match the selected target library identity; uid={candidate.UID}')
|
||||
@@ -703,7 +701,17 @@ def run_native(snapshot, report):
|
||||
def current_library_rows():
|
||||
return [(row, [text.window_text() for text in row.children(control_type="Text")])
|
||||
for row in desktop.window(handle=list_handle).descendants(control_type="ListItem")]
|
||||
rows = wait_for_library_rows(current_library_rows, metadata[3])
|
||||
report['library_lookup'] = {'target': metadata[3], 'state': 'loading', 'timeout_seconds': 8}
|
||||
save_report(snapshot, report)
|
||||
lookup_started = time.monotonic()
|
||||
try:
|
||||
rows = wait_for_library_rows(current_library_rows, metadata[3])
|
||||
except TimeoutError:
|
||||
report['library_lookup'].update(state='unavailable_or_timeout',
|
||||
elapsed_seconds=round(time.monotonic() - lookup_started, 3))
|
||||
raise
|
||||
report['library_lookup'].update(state='loaded',
|
||||
elapsed_seconds=round(time.monotonic() - lookup_started, 3))
|
||||
row, columns = exact_target(rows, metadata[3])
|
||||
report["library_row"] = columns
|
||||
symbol_parts = columns[2].split(":", 1)
|
||||
|
||||
Loaded 100 of 205 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user