Compare commits

..
Author SHA1 Message Date
阿白叔 818fb9a695 release: prepare 1.3.3-beta.1 for issue 42 field scoring
Core regression / Python core, intervention UI and release configuration (push) Waiting to run
Core regression / JavaScript syntax (push) Waiting to run
2026-11-25 11:21:20 +08:00
abaishu0730 f80127e7bd Merge pull request 'fix: 任务搜索与筛选提供空状态(#33 D4)' (#36) from codex/issue33-d4 into main
Core regression / Python core, intervention UI and release configuration (push) Waiting to run
Core regression / JavaScript syntax (push) Waiting to run
2026-11-25 11:01:56 +08:00
abaishu0730 ec2591ac75 Merge pull request 'fix: 主窗口位置、尺寸和最大化跨重启恢复(#33 D3)' (#39) from codex/issue33-d3 into main
Core regression / Python core, intervention UI and release configuration (push) Waiting to run
Core regression / JavaScript syntax (push) Waiting to run
2026-11-25 11:01:32 +08:00
abaishu0730 22442e03ae Merge pull request 'fix: BOM 导入提示忽略列及近义表头(#33 D5)' (#38) from codex/issue33-d5 into main
Core regression / Python core, intervention UI and release configuration (push) Waiting to run
Core regression / JavaScript syntax (push) Waiting to run
2026-11-25 11:00:58 +08:00
abaishu0730 9d9b316634 Merge pull request 'fix: 资源释放后续跑原工程队列(#33 D8)' (#41) from codex/issue33-d8 into main
Core regression / JavaScript syntax (push) Waiting to run
Core regression / Python core, intervention UI and release configuration (push) In progress
2026-11-25 11:00:28 +08:00
阿白叔 6d45ea1fa0 fix: resume frozen task queue after verified resource release
Core regression / Python core, intervention UI and release configuration (push) Successful in 5m2s
Core regression / JavaScript syntax (push) Successful in 7s
Core regression / Python core, intervention UI and release configuration (pull_request) Successful in 5m32s
Core regression / JavaScript syntax (pull_request) Successful in 8s
2026-11-25 10:58:53 +08:00
abaishu0730 d0bbc73da3 Merge pull request 'fix: 按自有写进程退出证据复核资源释放(#33 D7,关联 #20)' (#40) from codex/issue33-d7 into main
Core regression / Python core, intervention UI and release configuration (push) Successful in 4m47s
Core regression / JavaScript syntax (push) Successful in 7s
2026-11-25 10:37:48 +08:00
阿白叔 4fb715507e fix: recheck private desktop release with writer exit proof
Core regression / Python core, intervention UI and release configuration (push) Successful in 5m4s
Core regression / JavaScript syntax (push) Successful in 8s
Core regression / Python core, intervention UI and release configuration (pull_request) Successful in 5m25s
Core regression / JavaScript syntax (pull_request) Successful in 11s
2026-11-25 10:35:39 +08:00
abaishu0730 c114db9f31 Merge pull request 'fix: DxDataBook 写入前加载、超时证据与有限重试(#33 D6)' (#37) from codex/issue33-d6 into main
Core regression / Python core, intervention UI and release configuration (push) Successful in 4m56s
Core regression / JavaScript syntax (push) Successful in 6s
2026-11-25 10:12:30 +08:00
阿白叔 7d4f6bde0b test: record native DxDataBook redraw evidence
Core regression / Python core, intervention UI and release configuration (push) Successful in 4m22s
Core regression / JavaScript syntax (push) Successful in 6s
Core regression / Python core, intervention UI and release configuration (pull_request) Successful in 4m22s
Core regression / JavaScript syntax (pull_request) Successful in 14s
2026-11-25 10:11:26 +08:00
阿白叔 ad3ee4151c fix: recover DxDataBook control redraw races
Core regression / Python core, intervention UI and release configuration (push) Failing after 4m30s
Core regression / JavaScript syntax (push) Successful in 7s
Core regression / Python core, intervention UI and release configuration (pull_request) Successful in 4m36s
Core regression / JavaScript syntax (pull_request) Successful in 8s
2026-11-25 10:08:25 +08:00
阿白叔 650dfd5491 fix: restore the main window geometry across sessions
Core regression / Python core, intervention UI and release configuration (push) Successful in 5m28s
Core regression / JavaScript syntax (push) Successful in 6s
Core regression / Python core, intervention UI and release configuration (pull_request) Successful in 5m27s
Core regression / JavaScript syntax (pull_request) Successful in 9s
2026-11-25 09:58:38 +08:00
阿白叔 ba69f86628 fix: surface ignored BOM headers during import
Core regression / Python core, intervention UI and release configuration (push) Successful in 4m41s
Core regression / JavaScript syntax (push) Successful in 7s
Core regression / Python core, intervention UI and release configuration (pull_request) Successful in 4m50s
Core regression / JavaScript syntax (pull_request) Successful in 9s
2026-11-25 09:58:17 +08:00
abaishu0730 8ccc9716de Merge pull request 'fix: 同一数据目录只启动一个主窗口(#33 D1)' (#35) from codex/issue33-d1 into main
Core regression / Python core, intervention UI and release configuration (push) Successful in 5m28s
Core regression / JavaScript syntax (push) Successful in 8s
2026-11-25 09:57:58 +08:00
阿白叔 3187b304c6 fix: retry DxDataBook lookup before native mutation
Core regression / Python core, intervention UI and release configuration (push) Successful in 5m20s
Core regression / JavaScript syntax (push) Successful in 6s
Core regression / Python core, intervention UI and release configuration (pull_request) Failing after 5m54s
Core regression / JavaScript syntax (pull_request) Successful in 11s
2026-11-25 09:57:37 +08:00
abaishu0730 29b40a5370 Merge pull request 'fix: 工程路径错误给出可执行提示(#33 D2)' (#34) from codex/issue33-d2 into main
Core regression / Python core, intervention UI and release configuration (push) Successful in 5m20s
Core regression / JavaScript syntax (push) Successful in 7s
2026-11-25 09:57:37 +08:00
阿白叔 315d2e85b3 fix: limit the desktop app to one instance per data root
Core regression / Python core, intervention UI and release configuration (push) Successful in 5m36s
Core regression / JavaScript syntax (push) Successful in 9s
Core regression / Python core, intervention UI and release configuration (pull_request) Successful in 5m30s
Core regression / JavaScript syntax (pull_request) Successful in 11s
2026-11-25 09:50:12 +08:00
阿白叔 d954b527f5 fix: report actionable project path errors
Core regression / Python core, intervention UI and release configuration (push) Successful in 4m25s
Core regression / JavaScript syntax (push) Successful in 8s
Core regression / Python core, intervention UI and release configuration (pull_request) Successful in 5m7s
Core regression / JavaScript syntax (pull_request) Successful in 7s
2026-11-25 09:49:54 +08:00
阿白叔 63999b7bfd fix: explain empty task searches and filters (#33 D4)
Core regression / Python core, intervention UI and release configuration (push) Successful in 5m27s
Core regression / JavaScript syntax (push) Successful in 8s
Core regression / JavaScript syntax (pull_request) Successful in 6s
Core regression / Python core, intervention UI and release configuration (pull_request) Successful in 4m54s
2026-11-25 09:48:10 +08:00
abaishu0730 46deb9cec8 Merge pull request 'feat: 升级 DeepSeek Harness 并支持运行时更新' (#32) from codex/dsh-runtime-update into main
Core regression / Python core, intervention UI and release configuration (push) Failing after 20m55s
Core regression / JavaScript syntax (push) Successful in 10s
2026-11-20 17:21:04 +08:00
64 changed files with 3433 additions and 106 deletions

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
# DxPartReplace 1.3.3-beta.1 实机评分包
此 Windows x64 便携版包含 #33 的八项修复,供六套固定试卷重新评分。更新内容包括同数据目录单实例、工程路径报错、窗口恢复、搜索空状态、BOM 表头警告,以及 DxDataBook 加载、资源回收和队列续跑。
退出旧程序后将 ZIP 完整解压到新目录,双击 `启动程序.cmd`。核对窗口标题为 `DxDesigner 器件替换 · 1.3.3-beta.1`。需要复测旧任务时,使用旧 `data` 的备份副本。
优先用现场库复测 BOB、BOB_Shield 的 `4885-S033D0-M220` 和 WiFi LWB01 的 `4885-S018D0-M220`。记录能否打开工程、加载料号、保存回读及释放桌面。卷四测试 8 工程混合批次,另跑 100 工程队列。卷六记录暂停、跨进程恢复和已保存项的派发次数。原始分数为 373/600,本包成绩以实机逐题结果为准。[实机评分工单 #42](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/issues/42)
@@ -0,0 +1,37 @@
# Issue 33 D2 · 工程路径错误提示验收
工程读取和任务创建的路径检查直接调用 `lstat()`。目录不存在或扫描后工程移走时,文件系统异常进入统一兜底,现场报告仅能看到“发生未处理异常”。目录存在且能读取属性时,`scandir()` 仍可能因缺少列目录权限失败。
修复在路径检查和读取处分类处理这些预期错误。读取对话框和创建任务的错误提示均显示完整路径、分类代码、处理建议和可关联日志的 `DXT` 编号。预期错误写入一条应用日志。未知异常保留 traceback。
## Windows 11 实测
使用 Qt 按钮启动读取、真实文件系统与任务库。第五例在成功扫描两个候选工程后重命名其中一个文件,从实际服务入口创建选定任务并检查主窗口所用的错误格式和任务数据库。
| 输入 | 基线 `46deb9c` | 修复后代码 | 修复后错误编号 |
| --- | --- | --- | --- |
| 不存在的目录 | 通用兜底 | `path_missing` | `DXT-20261125-3EE8F667` |
| 普通文件作为目录 | 英文非目录文案 | `path_not_directory` | `DXT-20261125-92876D74` |
| 路径中途遇到普通文件 | 通用兜底 | `path_not_directory` | `DXT-20261125-0C615FE8` |
| ACL 拒绝列目录 | 通用兜底 | `path_denied` | `DXT-20261125-ED64EEA9` |
| 工程在扫描后被移走 | 通用兜底 | `path_missing` | `DXT-20261125-CA48D2FF` |
ACL 测试对临时目录中的当前用户拒绝 `FILE_LIST_DIRECTORY`,两个版本的文件系统操作均触发原生 `WinError 5`。创建任务失败后库中仍有 0 条任务。五个路径输入的通用兜底率从 4/5 降到 0/5。额外注入的 `RuntimeError` 对照组仍触发一次 `unhandled_exception`,并保留 traceback。
## 复跑
在仓库根目录运行。使用未占用的临时目录保存测试日志。
```powershell
$env:PYTHONUTF8 = '1'
python -m pytest -q -s tests/v1_1/test_project_path_errors.py tests/v1_1/test_scan_responsiveness.py tests/v1_1/test_project_long_paths.py tests/v1_1/test_path_access.py tests/trial_task_center/test_logging_setup.py --basetemp build/issue33-d2
```
实测 35 项通过。以下命令按错误记录统计扫描和创建任务的通用兜底率。路径用例与故障对照分别统计时,从相应测试目录读取日志。
```powershell
$rows = Get-ChildItem build/issue33-d2 -Recurse -Filter application.log |
Select-String 'error_id=\S+ operation=(scan_project_directory|create_project_tasks) (code=\S+ )?message='
$generic = $rows | Where-Object { $_.Line -match 'code=unhandled_exception |message=发生未处理异常$' }
'{0}/{1}' -f @($generic).Count, @($rows).Count
```
@@ -0,0 +1,31 @@
# Issue 33 D5 · BOM 未知列验收
现场 B3 的 `INVALID_C1_bad_header_extra_col.xlsx` 带有 `extra_column`。名称归一化将未知列映射为空,后续只复制模板定义的列。导入成功时,工作区原先只报告保存行数与失败行数。
现在 BOM 导入保留模板列的精确映射,并为每个被忽略的具名列显示来源文件、原始列名与警告计数。详情和任务事件同时记录这些警告。缺失必需列时,导入停止,错误详情列出具体缺失项并对相近列名给出改名建议。
## Windows 11 重放
通过 Qt 工作区的“导入 BOM”按钮和真实任务服务运行,测试替换的是文件选择对话框的返回值。现场文件复制到临时目录,仅把第一条记录的工程名称与路径绑定到临时工程,保留了原始表头和替换字段。
| 工作簿 | 结果 |
| --- | --- |
| 两个额外列「供应商」「备注」 | 保存 1 行、失败 0 行、警告 2 项。详情逐列列名,任务事件记录同一组警告 |
| 现场 B3 `extra_column` | 保存 1 行、失败 0 行、警告 1 项。详情保留该列名 |
| 用「新料号编码」替换必需的「新料号」 | 指出缺少「新料号」,并建议将「新料号编码」改为「新料号」 |
| 缺少「新料号」 | 指出具体缺失项 |
| 表头公式与额外列中的数据公式 | 分别拒绝表头公式和第 2 行公式 |
| 原模板 | 保存 1 行、失败 0 行,无警告 |
BOM 草稿导入时未启动工程位号采集。回归还检查了由监督子进程返回的真实预览报告能携带同样的警告。包含现场工作簿重放的定向回归共通过 110 项。
## 复跑
在仓库根目录运行。现场文件从工单附件 `05_实测证据/paper2_bom` 解出。普通回归可省略 `DX_ISSUE33_D5_FIELD`,此时跳过现场文件重放。
```powershell
$env:PYTHONUTF8 = '1'
$env:PYTHONPATH = (Resolve-Path src).Path
$env:DX_ISSUE33_D5_FIELD = 'C:/path/to/INVALID_C1_bad_header_extra_col.xlsx'
python -m pytest -q -s tests/v1_1/test_bom_header_feedback.py tests/v1_1/test_bom_import_report.py tests/v1_1/test_bom_pending.py tests/v1_1/test_bom_sources_supervision.py tests/trial_task_center/test_bom_import_review.py tests/trial_task_center/test_item_value_and_bom_sources.py
```
@@ -0,0 +1,26 @@
# Issue #33 D6 · DxDataBook 加载失败验证
现场 `WIFI_RTL8723DU` 的 `LWB01` 在加载目标 `4885-S018D0-M220` 时超时。原报告记录了可见列表窗口,阶段为 `preflight`,本项写入凭据为 `prepared`。同代次此前的项已有写入凭据,项目进入保留和对账流程。类似的失败也出现在 `BOB` 与 `BOB_SHIELD` 的目标 `4885-S033D0-M220` 上。现场空标题窗口 `10750260` 属于同批后续 `WIFI_RTL8192FC` 会话的启动阶段。它与 `LWB01` 超时分属不同 CAD 进程和代次。现场日志能定位超时阶段及保留原因,库服务状态和窗口复建情况仍待同代次采样。
加载阶段根据 DxDataBook 控件是否已存在采用 45 秒或 20 秒窗口。加载过程重新发现同一窗口下的列表与筛选器,控件重建后重发筛选并重新验证行稳定性。超时前写下本项凭据状态,超时后至多重试一次。重试要求本项仍有身份匹配的 `prepared` 凭据。空窗口处理进一步要求窗口在本次浏览后出现,属于同一 CAD 进程、线程和替换对话框,且替换对话框已被禁用。窗口和子控件证据先写盘,随后才发送关闭消息并观察结果。替换提交、属性恢复和保存继续使用既有的写入凭据与关闭检查点。
## Windows 验证
| 场景 | 观测结果 |
| --- | --- |
| 冷加载列表重建注入 | 原列表 `10` 更新为 `20`,筛选器从 `11` 切换到 `21`,稳定性窗口重新计时,最终使用新列表。 |
| 控件枚举与访问之间发生重建 | 筛选消息返回 Win32 `1400`,或列表读取返回 UIA `0x80040201`。两种故障都在当前加载时限内重取控件,访问新筛选器并选中正确的行。 |
| 真实 Win32 空窗口,凭据 `prepared` | 私有桌面创建的 HWND `19728876` 属于替换对话框,保存窗口树后只关闭该窗口。加载重试一次后返回目标,原有同 PID 无关窗口仍打开,凭据仍为 `prepared`。 |
| 真实 Win32 空窗口,凭据 `mutation_possible` | 窗口 `1183362` 具备同样的结构和归属,仅留下诊断。未重试,窗口与写入凭据均保留。 |
| 先前已有暂存写入,当前项失败 | Windows `cscript.exe` 执行生产 VBS 清理过程。当前未写且无暂存项时经过原始状态核验并以 `SaveChanges=False` 关闭。已有前项暂存写入、当前项写入状态无法确认或保存已请求时,保留工程供对账。 |
真实 HWND 注入运行生产窗口检查和加载重试代码,测试用 Win32 窗口模拟 DxDataBook 的无按钮提示。测试将等待时间缩短到 1.5 秒,筛选响应由测试控制。原始诊断见 [prepared.json](evidence/2026-11-25-issue33-d6/prepared.json) 和 [mutation_possible.json](evidence/2026-11-25-issue33-d6/mutation_possible.json)。
另一组注入使用原生 ListView、Edit、UIA 行读取和消息驱动生产 `run_native`,CAD COM 属性与菜单资源由替身提供。先销毁筛选框触发 Win32 `1400`,再销毁列表触发 UIA `0x80040201`。程序复取新列表和筛选器,扫描两行后命中精确料号。提交回调只触发一次并读到持久化状态 `mutation_possible`。只有相似料号的对照执行两次筛选后超时,提交数为零,凭据仍为 `prepared`。 [精确命中](evidence/2026-11-25-issue33-d6/native-controls-positive.json) [没有精确命中](evidence/2026-11-25-issue33-d6/native-controls-negative.json)
定向回归 114 项通过,包含加载、窗口归属、写入凭据、VBS 失败收尾和现有目标 Cell 路径。另执行扩展集成测试时,丢失 UID 的旧测试出现保存回读证明缺失,用 `origin/main` 的原始 VBS 同例复现。
## 真实工程副本
- 现场备份 `WIFI_RTL8723DU` 使用本机 `Skyworth_Lib` 中央库替代现场 `S:\mentor_lib.lmc`,BOM 核验找到 `LWB01` 并确认 UID。执行停在 `open_project` 249 秒,回到 `open_sheet` 安全边界时停止,关闭检查点仍观测到工程打开。写入凭据为 `prepared`,工程保护标记保留。此次在进入 DxDataBook 前结束,现场目标件换料及保存回读尚待验证。 [现场副本记录](evidence/2026-11-25-issue33-d6/field-copy.json)
- `Audio_D2128` 副本上,`RV05` 从 `4100-CA0000-T7` 换为 `4100-CA0000-T0`。已存在的 DxDataBook 控件在 2.703 秒内返回目标。原生替换报告成功,保存请求和返回各一次,工程完成关闭及重新读取,状态为 `saved_ok/project_committed`,独立网表比对为 `verified`。关闭整个 CAD 进程时超出 15 秒并触发资源释放保护标记,任务目录未产生业务不确定标记。 [正常副本记录](evidence/2026-11-25-issue33-d6/normal-copy.json)
@@ -0,0 +1,14 @@
# Issue #33 D7 · 已保存工程的资源收尾验证
Audio_D2128 历史副本的 `RV05` 换料已保存并通过独立网表核验。Quit 助手退出码为 0,CAD 根进程 15 秒内未退出。执行自有 Job 强退后,Job 活动进程数降到 0,两条后代进程的退出句柄已核验,根进程句柄在随后 5 秒内仍未发出信号。批次保留了根进程的创建时间和强退记录,桌面还未进入关闭阶段。首次失败后,运行时缺少自动复核这一迟到的退出结果的路径。
运行时在已请求强退的收尾失败后等待 0.5、1、2 秒,最多复核三次原有进程树。进程树仍活跃时保留原句柄与阻塞,确认退出时再收尾该代桌面。Windows 进程已收到强退请求后只等待原句柄。已保存工程的任务状态和独立网表回执继续作为业务证据。
历史记录通过 PID 和创建时间确认写进程退出,还要求自有清理记录或绑定到该代 CAD 的空 Job 证明。桌面存在性通过枚举核验。同名受管理桌面经槽位互斥锁检查,新的活动租约在观察期间保持运行。资源记录和业务保护独立持久化。启动和批次收尾的自动观察耗尽后保留已有保护,下一次资源清理可重新取证。
## Windows 证据
- 用原始受阻历史数据的独立副本运行资源清理。槽位锁内确认桌面已经消失,六个已绑定进程均退出,批次由 `blocked` 更新为 `released`。比较前后 SHA-256,任务状态、保存回读、独立网表、关闭检查点和原有 `uncertain.flag` 保持逐字节一致。 [历史副本记录](evidence/2026-11-25-issue33-d7/historical.json)
- 用真实 Win32 私有桌面和独立 Job 验证晚退出。故障注入使 CAD 收尾在子进程实际退出前返回异常,之后自动等待并证明原进程退出,随后退还同一租约。原异常和注入的强退诊断均保留。外部持有者场景确认外部进程存活,桌面先保持隔离,外部持有者退出后复核到物理释放。 [晚退出](evidence/2026-11-25-issue33-d7/delayed-owned-exit.json) [外部持有](evidence/2026-11-25-issue33-d7/external-reference.json)
- 真实 Mentor 7.9.5 空闲会话运行正常退出。Quit 助手和 CAD 根进程的退出码均为 0,约 4.375 秒完成关停,桌面释放后资源待处理数为 0。 [正常退出](evidence/2026-11-25-issue33-d7/mentor-idle.json)
- 新建的 Audio_D2128 真实 Mentor 对照在本机完成 BOM 位号核验,执行时停在 `open_project` 276 秒,到 `open_sheet` 安全检查点才返回。工程仍打开,任务保持保护。本轮未在该副本复现保存后的 Mentor 退出,保存侧证据来自上述真实历史数据。
@@ -0,0 +1,21 @@
# Issue #33 D8 · 原批次资源恢复验证
现场 100 工程按同一个任务队列执行。第 10 项已经隔离,第 11 项留下业务阻断回执,原队列仍有 89 项待派发。后台资源复核完成后,应用界面更新了资源状态,队列执行入口未再次读取原检查点。现场归档队列编号为 `55e1032ac965453b8adf307da1400511`。
候选在延续执行前核对监督进程与结束回执、原始请求摘要、队列编号、有序任务范围和计划哈希。现有写入资源和监督进程须通过释放核验。新暂停记录保存每个工程的写入源,恢复时重新读取工程声明,源不明确或变更时保留暂停。已经出具结果待核验回执的工程与共享其写入源的后续工程继续隔离。队列租约内消费原暂停记录并保存隔离状态,防止重复接续。同一用户授权运行可在资源释放后继续,用户主动暂停仍走原确认流程。
| Windows 场景 | 验证结果 |
| --- | --- |
| D7 基线,100 工程 | Windows 写进程退出后,首次返回 9 项完成、2 项阻断、89 项待执行。 [基线记录](evidence/2026-11-25-issue33-d8/baseline-100.json) |
| D8 候选,100 工程 | 写进程存活时,89 项仍待执行。退出后原队列自动继续,最终 97 项完成、3 项阻断。第 10、11 项各保留一条待核验回执,第 12 项共享数据库且零次替换派发。成功项各保存一次。 [候选记录](evidence/2026-11-25-issue33-d8/candidate-100.json) |
| D8 候选,8 工程 | 人工在第 3 项保存后暂停,保留 5 项待执行。启动不同 PID 的 Python 进程,以同一队列及冻结计划恢复到 8 项完成。每个作业 ID 仅派发一次。 [重启记录](evidence/2026-11-25-issue33-d8/candidate-8-restart.json) |
夹具使用生产任务服务、队列、SQLite、监督协议和 Windows 进程退出检查。CAD 替换与保存结果使用故障注入回执。验收覆盖调度和恢复路径,真实 Mentor 批量替换另有实机环境依赖。
```powershell
$env:PYTHONPATH = (Resolve-Path src).Path
py -3.12 tools/verify_issue33_queue.py --projects 100 --output <新候选目录>
py -3.12 tools/verify_issue33_queue.py --projects 8 --output <新暂停目录>
```
将 `PYTHONPATH` 指向 D7 基线源码,并在 100 项命令追加 `--expect-baseline`,即可复跑基线。输出目录首次运行时应当不存在。
@@ -0,0 +1,17 @@
# Issue #33 D1 同数据目录单实例
`application.main` 原先直接配置日志、打开 `task-center.db` 并执行启动恢复。现场 `data_lock` 日志有两次同根 `application_start`,两实例均成功读取任务列表。现有执行租约只在执行操作中生效。
GUI 现在先取得 `.gui-instance.lock` 的内核文件锁,再打开日志和数据库。第二次启动经 Qt 本地套接字请求激活现有窗口,该窗口写入 `instance_conflict` 并在状态栏提示。锁保持到 SQLite 和后台读线程关闭,进程强制结束时由操作系统回收。启动参数中的工作进程和 CLI 在 GUI 文件锁之前分流。
## Windows 复测
```powershell
$env:QT_QPA_PLATFORM = 'offscreen'
python -m pytest -q tests/v1_1/test_single_instance.py
```
- 四个真实 GUI 子进程并发打开同一目录,其中两个使用大写路径。日志有一次 `application_start`、一次启动恢复和三次 `instance_conflict`,三个转发进程均返回 0。
- 另一个数据目录的窗口与持锁窗口同时存活。同根 `--native-helper` 执行自身参数校验并返回 2,冲突计数仍为三次。
- 强制结束持锁进程后,同根 `--smoke-test` 成功启动并正常关闭,预先写入的任务 ID 仍在 SQLite。另一数据目录的进程继续运行。
- 修改前运行同一并发场景时,三个竞争进程没有退出,测试失败。测试使用 Qt offscreen,验证激活请求已处理。Windows 桌面前台切换和实际 CAD 写入需通过交互式验收复核。
@@ -0,0 +1,21 @@
# Issue #33 D3 主窗口布局恢复
原来的 `ui-layout.ini` 只保存分栏、表头与排序,`TrialTaskCenterWindow` 每次启动都会重用默认窗口尺寸。复现时,保存进程关闭前的普通窗口为 `(45, 55, 1200, 760)` 且已最大化,重启后普通窗口变为 `(2, 2, 1280, 880)` 且未最大化。
正常接受关闭后,现通过 Qt `saveGeometry()` 持久化普通窗口几何和最大化状态。启动时调用 `restoreGeometry()`。若配置损坏、DPI 改变导致 Qt 拒绝恢复,或普通窗口超出当前可用屏幕,窗口会在当前可用屏幕内重新定位,并保留产品定义的最小尺寸。
## Windows 原生窗口实测
```powershell
$env:QT_QPA_PLATFORM = 'windows'
python -m pytest -q -s tests/v1_1/test_window_geometry.py
```
| 场景 | 结果 |
| --- | --- |
| 正常退出并启动新进程 | 普通窗口几何保持 `(45, 55, 1200, 760)`,最大化状态保持为真 |
| 新进程设 `QT_SCALE_FACTOR=1.5` | 普通窗口回退为 `(8, 36, 1008, 700)`,窗口位于可用屏幕,采用普通状态 |
| 配置值为错误类型或截断的字节 | 窗口仍能打开,普通窗口位置可达 |
| 配置保存位置为 `(50000, 50000)` | 窗口回到可用屏幕 |
测试通过 4 项。屏外场景用坐标模拟显示器移除,DPI 变化由 Qt 环境设置触发。
@@ -0,0 +1,36 @@
{
"mode": "field",
"environment": "Windows, DxDesigner 7.9.5, source runtime",
"library_mapping": "Skyworth_Lib",
"library_lmc_unchanged": true,
"project": "WIFI_RTL8723DU.prj",
"request_old_new_refdes": [
"483C-S018D0-M210",
"4885-S018D0-M220",
"LWB01"
],
"attempt": {
"session_id": "bf846ff076254e5fbb3bc7ccf1ee859d",
"generation": 1,
"attempt_id": "44a747ec3c5d440fb60d5a2a407b8037",
"job_id": "08d6ebdc6cc540f7b2296a2ef737947a_0",
"state": "prepared"
},
"native": [],
"status_log": [
"job_id\tstate\tcode\tmessage"
],
"operation_log_excerpt": [
"2026/11/25 9:57:21\tINFO\tstage=open_project target=<copy-root>\\project\\WIFI_RTL8723DU.prj",
"2026/11/25 10:01:30\tERROR\tstage=open_sheet number=-2147220644 source=QuickPartReplace.SafeStop description=stopped at a safe boundary before native mutation after inactivity; prewrite pause closure was not proven: %7F3A%5C11%5BF9%8C61",
"quick_run_uncertain monitor_failure error=project close checkpoint failed: owned CAD still has a project open; no implicit save or discard\\r\\n"
],
"independent_verification": [
"not_completed"
],
"uncertain_flags_relative_to_data_root": [
"batch-resources/bf846ff076254e5fbb3bc7ccf1ee859d/generation-1/uncertain.flag",
"tasks/546160ef-0e8f-4b15-8394-e35f8c562366/quick-run/uncertain.flag"
],
"queue_outcome": "project remained open at the close checkpoint"
}
@@ -0,0 +1,33 @@
[
{
"stage": "preflight",
"databook": {
"loads": [
{
"mode": "warm",
"timeout_seconds": 20,
"attempt_state_before_load": "mutation_possible",
"list_handle": 17,
"filter_handle": 18,
"error": "Native DxDataBook did not finish loading target part: NEW",
"elapsed_seconds": 1.594,
"dialogs": [
{
"hwnd": 1183362,
"owner": 200514,
"pid": 56180,
"title": "",
"children": [],
"browser": false,
"dismissible": true
}
],
"attempt_state": "mutation_possible",
"retry": false
}
]
},
"window_closed": [],
"marker_state": "mutation_possible"
}
]
@@ -0,0 +1,91 @@
{
"attempt": "prepared",
"events": [
{
"controls": [
21630720,
528470
]
},
{
"edit_hwnd": 528470,
"text": "NEW"
},
{
"read_list": 21630720,
"row_count": 1
},
{
"read_list": 21630720,
"row_count": 1
},
{
"edit_hwnd": 528470,
"text": "NEW"
},
{
"read_list": 21630720,
"row_count": 1
},
{
"read_list": 21630720,
"row_count": 1
}
],
"report": {
"native_command": {
"id": 33977,
"executable": "C:\\Users\\ABS_Windows\\AppData\\Local\\Programs\\Python\\Python312\\python.exe",
"trigger": "resource_command"
},
"native_options": {
"1704": {
"text": "Option",
"checked": true
},
"1105": {
"text": "Option",
"checked": true
},
"1697": {
"text": "Option",
"checked": true
},
"1700": {
"text": "Option",
"checked": true
}
},
"databook": {
"main_visible_before_browse": true,
"browse_button": 3017658,
"loads": [
{
"mode": "cold",
"timeout_seconds": 45,
"attempt_state_before_load": "prepared",
"list_handle": 21630720,
"filter_handle": 528470,
"error": "Native DxDataBook did not finish loading target part: NEW",
"elapsed_seconds": 3.437,
"dialogs": [],
"attempt_state": "prepared",
"retry": true
},
{
"mode": "warm",
"timeout_seconds": 20,
"attempt_state_before_load": "prepared",
"list_handle": 21630720,
"filter_handle": 528470,
"error": "Native DxDataBook did not finish loading target part: NEW",
"elapsed_seconds": 3.344,
"dialogs": [],
"attempt_state": "prepared",
"retry": false
}
]
}
},
"error": "TimeoutError('Native DxDataBook did not finish loading target part: NEW')"
}
@@ -0,0 +1,143 @@
{
"attempt": "mutation_possible",
"events": [
{
"controls": [
21696256,
594006
]
},
{
"controls": [
21761792,
659542
]
},
{
"dead_edit": 594006,
"winerror": 1400
},
{
"edit_hwnd": 659542,
"text": "NEW"
},
{
"read_list": 21761792,
"row_count": 2
},
{
"controls": [
21827328,
725078
]
},
{
"dead_ui_list": 21761792,
"hresult": -2147220991,
"exception": "COMError(-2147220991, '\u4e8b\u4ef6\u65e0\u6cd5\u8c03\u7528\u4efb\u4f55\u8ba2\u6237', (None, None, None, 0, None))"
},
{
"edit_hwnd": 725078,
"text": "NEW"
},
{
"read_list": 21827328,
"row_count": 2
},
{
"read_list": 21827328,
"row_count": 2
},
{
"submit": "mutation_possible"
}
],
"report": {
"native_command": {
"id": 33977,
"executable": "C:\\Users\\ABS_Windows\\AppData\\Local\\Programs\\Python\\Python312\\python.exe",
"trigger": "resource_command"
},
"native_options": {
"1704": {
"text": "Option",
"checked": true
},
"1105": {
"text": "Option",
"checked": true
},
"1697": {
"text": "Option",
"checked": true
},
"1700": {
"text": "Option",
"checked": true
}
},
"databook": {
"main_visible_before_browse": true,
"browse_button": 3017658,
"loads": [
{
"mode": "warm",
"timeout_seconds": 20,
"attempt_state_before_load": "prepared",
"list_handle": 21827328,
"filter_handle": 725078,
"elapsed_seconds": 6.125
}
],
"list_handle": 21827328,
"list_visible": true,
"main_visible_after_load": true
},
"library_row": [
"DATA",
"NEW",
"LIB:EXACT",
"",
"Exact",
"Target"
],
"slot_count": 1,
"row_rectangle": [
157,
398,
769,
422
],
"list_handle": 21827328,
"target_text": "NEW",
"symbol_text": "LIB:EXACT",
"target_submit_enabled": true,
"transaction": {
"snapshot_sha256": "d36e0c485331eac7b3c0d25de6dbfc5e915b761dd7eb738caf49b69d89640daa",
"project_path": "g:\\dx33\\acceptance\\d6-native-controls-03\\positive\\synthetic.prj",
"sheet_identity": "MAIN:1",
"old_part_number": "OLD",
"new_part_number": "NEW",
"source_uids": [
"uid"
],
"target_selectors": null,
"library_row": [
"DATA",
"NEW",
"LIB:EXACT",
"",
"Exact",
"Target"
],
"target_symbol": "LIB:EXACT",
"slot_count": 1
},
"stage": "native_replace_verified",
"replaced_uids": [
"uid"
],
"promoted_pins": []
},
"error": null
}
@@ -0,0 +1,78 @@
{
"mode": "normal",
"environment": "Windows, DxDesigner 7.9.5, source runtime",
"library_mapping": "Skyworth_CBB_Lib",
"library_lmc_unchanged": true,
"project": "Audio_D2128.prj",
"request_old_new_refdes": [
"4100-CA0000-T7",
"4100-CA0000-T0",
"RV05"
],
"attempt": {
"session_id": "588db35caf664589a499f02800559ff0",
"generation": 1,
"attempt_id": "65d0375a0a3e4e02a0e0225f5cd7da1d",
"job_id": "3fd4cca09997419cbf0850fe2907f1b5_0",
"state": "mutation_possible"
},
"native": [
{
"ok": true,
"stage": "native_replace_applied",
"databook": {
"main_visible_before_browse": true,
"browse_button": 1577092,
"loads": [
{
"mode": "warm",
"timeout_seconds": 20,
"attempt_state_before_load": "prepared",
"list_handle": 266464,
"filter_handle": 266532,
"elapsed_seconds": 2.703
}
],
"list_handle": 266464,
"list_visible": true,
"main_visible_after_load": true
},
"library_row": [
"RESISTOR",
"4100-CA0000-T0",
"skyworth:res01",
"unassigned",
"RESC1608N",
"0R",
""
],
"replaced_uids": [
"$2I2014"
],
"pin_promotion_phase": "promotion_complete"
}
],
"status_log": [
"job_id\tstate\tcode\tmessage",
"3fd4cca09997419cbf0850fe2907f1b5_0\tawaiting_native_replace\t\tSnapshot captured; automatic native replacement is starting.",
"3fd4cca09997419cbf0850fe2907f1b5_0\tpending_save\tsession_staged\tWrites staged; awaiting engineering project save and saved native data verification.",
"3fd4cca09997419cbf0850fe2907f1b5_0\tpending_save\tproject_saved\tEngineering project saved and closed; awaiting saved native data verification.",
"3fd4cca09997419cbf0850fe2907f1b5_0\tsaved_ok\tproject_committed\t%5DE5%7A0B%7EDF%4E00%4FDD%5B58%FF0C%539F%751F%6570%636E%6838%9A8C%901A%8FC7%3002"
],
"operation_log_excerpt": [
"2026/11/25 10:03:45\tINFO\tstage=open_project target=<copy-root>\\project\\Audio_D2128.prj",
"2026/11/25 10:03:59\tINFO\tstage=open_sheet schematic=Audio-D2128 sheet=S905L CVBS-LR",
"2026/11/25 10:04:49\tINFO\tnative_helper_exit code=0",
"2026/11/25 10:05:16\tINFO\treplacement RV05 4100-CA0000-T7 -> 4100-CA0000-T0",
"2026/11/25 10:05:17\tINFO\tsave_requested job=3fd4cca09997419cbf0850fe2907f1b5_0",
"2026/11/25 10:05:17\tINFO\tsave_returned job=3fd4cca09997419cbf0850fe2907f1b5_0",
"2026/11/25 10:05:22\tINFO\tproject_closed job=3fd4cca09997419cbf0850fe2907f1b5_0"
],
"independent_verification": [
"verified"
],
"uncertain_flags_relative_to_data_root": [
"batch-resources/588db35caf664589a499f02800559ff0/generation-1/uncertain.flag"
],
"queue_outcome": "CAD exit exceeded 15 seconds during batch resource cleanup after the saved business receipt"
}
@@ -0,0 +1,44 @@
[
{
"stage": "preflight",
"databook": {
"loads": [
{
"mode": "warm",
"timeout_seconds": 20,
"attempt_state_before_load": "prepared",
"list_handle": 17,
"filter_handle": 18,
"error": "Native DxDataBook did not finish loading target part: NEW",
"elapsed_seconds": 1.547,
"dialogs": [
{
"hwnd": 19728876,
"owner": 134972,
"pid": 5004,
"title": "",
"children": [],
"browser": false,
"dismissible": true
}
],
"attempt_state": "prepared",
"retry": true,
"closed_dialog": 19728876
},
{
"mode": "warm",
"timeout_seconds": 20,
"attempt_state_before_load": "prepared",
"list_handle": 17,
"filter_handle": 18,
"elapsed_seconds": 0.187
}
]
},
"window_closed": [
19728876
],
"marker_state": "prepared"
}
]
@@ -0,0 +1,74 @@
{
"state": "released",
"generation": 1,
"desktop": "dx-7f3f2f5227fc2de985373cc53acedcd9",
"release_proof": {
"session_id": "61c734f3d79d42579ca635bbdb996673",
"generation": 1,
"desktop": "dx-7f3f2f5227fc2de985373cc53acedcd9",
"desktop_handle_closed": true,
"desktop_released": true,
"processes_exited": true,
"processes": [
{
"pid": 11236,
"creation_time": "2026-11-25 02:26:52.007000+00:00"
}
],
"observed_at": 1795573613.951475,
"method": "owned_cleanup"
},
"release_rechecks": [
{
"attempt": 1,
"delay_seconds": 0.5
},
{
"attempt": 2,
"delay_seconds": 1
}
],
"event_timeline": [
{
"phase": "releasing",
"desktop_disappeared": null,
"release_rechecks": []
},
{
"phase": "blocked",
"desktop_disappeared": null,
"release_rechecks": []
},
{
"phase": "releasing",
"desktop_disappeared": null,
"release_rechecks": [
{
"attempt": 1,
"delay_seconds": 0.5
},
{
"attempt": 2,
"delay_seconds": 1
}
]
},
{
"phase": "released",
"desktop_disappeared": true,
"release_rechecks": [
{
"attempt": 1,
"delay_seconds": 0.5
},
{
"attempt": 2,
"delay_seconds": 1
}
]
}
],
"shutdown": {
"forced_termination": true
}
}
@@ -0,0 +1,36 @@
{
"state": "released",
"generation": 1,
"desktop": "dx-7f3f2f5227fc2de985373cc53acedcd9",
"release_proof": {
"generation": 1,
"desktop_released": true,
"processes_exited": true,
"processes": [],
"method": "restart_observation"
},
"release_rechecks": [],
"event_timeline": [
{
"phase": "releasing",
"desktop_disappeared": null,
"release_rechecks": []
},
{
"phase": "isolated",
"desktop_disappeared": false,
"release_rechecks": []
},
{
"phase": "releasing",
"desktop_disappeared": false,
"release_rechecks": []
},
{
"phase": "released",
"desktop_disappeared": true,
"release_rechecks": []
}
],
"shutdown": null
}
@@ -0,0 +1,88 @@
{
"original_state": "blocked",
"confirmed_state": "released",
"desktop": "dx-7f3f2f5227fc2de985373cc53acedcd9",
"desktop_absent_under_slot_mutex": true,
"owned_root_observations": [
{
"pid": 62180,
"creation_time": "2026-11-25 02:02:37.882000+00:00",
"gone": true
},
{
"pid": 59508,
"creation_time": "2026-11-25 02:02:38.250000+00:00",
"gone": true
},
{
"pid": 58980,
"creation_time": "2026-11-25 02:03:40.779000+00:00",
"gone": true
},
{
"pid": 60628,
"creation_time": "2026-11-25 02:03:43.660000+00:00",
"gone": true
},
{
"pid": 23736,
"creation_time": "2026-11-25 02:05:22.446000+00:00",
"gone": true
},
{
"pid": 54872,
"creation_time": "2026-11-25 02:05:44.928000+00:00",
"gone": true
}
],
"original_shutdown": {
"orderly_shutdown": false,
"forced_termination": true,
"forced_root_termination": true,
"forced_descendant_pids": [
5216,
51620
],
"quit_helper_exit_code": 0
},
"release_proof": {
"generation": 1,
"desktop_released": true,
"processes_exited": true,
"processes": [
{
"pid": 62180,
"creation_time": "2026-11-25 02:02:37.882000+00:00"
},
{
"pid": 59508,
"creation_time": "2026-11-25 02:02:38.250000+00:00"
},
{
"pid": 58980,
"creation_time": "2026-11-25 02:03:40.779000+00:00"
},
{
"pid": 60628,
"creation_time": "2026-11-25 02:03:43.660000+00:00"
},
{
"pid": 23736,
"creation_time": "2026-11-25 02:05:22.446000+00:00"
},
{
"pid": 54872,
"creation_time": "2026-11-25 02:05:44.928000+00:00"
}
],
"method": "restart_observation"
},
"preserved_sha256": {
"batch-resources/588db35caf664589a499f02800559ff0/generation-1/uncertain.flag": "4a131c344827d0bbe9667dc5534af3d52e472737ec1d1c1c44a792c1ac66f360",
"tasks/d5810026-3117-4b2e-9eca-c16b22396dc3/quick-run/status.tsv": "2afdeacd43812445f616f89da425efe6adf565ff75052e7f587e332b70066338",
"tasks/d5810026-3117-4b2e-9eca-c16b22396dc3/execution-proof/saved-netlist-6f55dbc86cc94adeb3561dfedd30e44a/export/verification.json": "3579e55e5987f9aababe167801c127f4404511f96cc0334de663fc449990b955",
"tasks/d5810026-3117-4b2e-9eca-c16b22396dc3/netlist-checks/2af39a6d4d6143afa3352b8cbe4e4180/verification.json": "f0ed2209fa9de4c97a01da3079da1097e8ab2dc091631c625440a299e23728e3",
"tasks/d5810026-3117-4b2e-9eca-c16b22396dc3/quick-run/project-checkpoint.json": "04d6b04e85b23671b2ce92dd2adc64d673b8c3209813a148214a7322bf0e7e4a"
},
"project_descriptor_sha256_unchanged": true
}
@@ -0,0 +1,36 @@
{
"state": "released",
"desktop": "dx-7f3f2f5227fc2de985373cc53acedcd9",
"shutdown": {
"state": "session_closed",
"clean": true,
"cad_exit_code": 0,
"quit_helper_exit_code": 0,
"cleanup_errors": [],
"shutdown_seconds": 4.375,
"orderly_shutdown": true,
"diagnostic_errors": [],
"forced_termination": false,
"forced_root_termination": false,
"forced_descendant_pids": [],
"termination_reason": null,
"dialog_supervision": {
"evidence_path": "G:\\dx33\\acceptance\\d7-mentor-idle\\batch-resources\\765ec10f41134b80b4d2d7a49ef01fe5\\generation-1\\cad-dialogs-408b2726a75547929b58a0f1fe3bcfbe.json",
"dialogs_seen": 2,
"blocked": false,
"blocking_titles": [],
"current_dialogs": [],
"error": "",
"monitor_error": ""
},
"release_state": "released",
"project_close_policy": "saved_only"
},
"release_results": {
"mentor_released": true,
"desktop_released": true
},
"release_rechecks": [],
"error": null,
"pending": 0
}
@@ -0,0 +1,80 @@
{
"projects": 100,
"first_return": {
"completed": 9,
"blocked": 2,
"pending": 89
},
"before_release": {
"completed": 9,
"blocked": 2,
"pending": 89
},
"queue_id": "d935388f7bab4bf98c882280ec6c76a3",
"writer_pid": 56064,
"writer_gone": true,
"calls": [
{
"project": 1,
"job_id": "c959a1eba7fb46f9b22d95f9afdff465_0",
"result": "saved_ok"
},
{
"project": 2,
"job_id": "ab1fb1a7058a4b41b5886c3c01008aa7_0",
"result": "saved_ok"
},
{
"project": 3,
"job_id": "490c1abb2a9441d8b5a8d70cbe5c0aa8_0",
"result": "saved_ok"
},
{
"project": 4,
"job_id": "56b8dfaacb514a94ab506c632b37b647_0",
"result": "saved_ok"
},
{
"project": 5,
"job_id": "d0d223381b9e4a01ababa484fcc07e82_0",
"result": "saved_ok"
},
{
"project": 6,
"job_id": "abe6fa9a9919494ba433983cd125d1ac_0",
"result": "saved_ok"
},
{
"project": 7,
"job_id": "2f103677ed4347938888e03b9b26b87f_0",
"result": "saved_ok"
},
{
"project": 8,
"job_id": "5d4eeaed50bd46e89fd6830b51e8c3fb_0",
"result": "saved_ok"
},
{
"project": 9,
"job_id": "ff4f78bf6e834c758fcb0fe9382a28fe_0",
"result": "saved_ok"
},
{
"project": 10,
"job_id": "31ad660420e74b8499bd54abfbe250f5_0",
"result": "batch_saved_unverified"
},
{
"project": 11,
"job_id": "321e40d86fe147bb977ba9865c1d24b9_0",
"result": "batch_saved_unverified"
}
],
"supervisor_calls": [
{
"batch_id": "d31e906c280e4849a22a3176ced4bee0",
"queue_id": null,
"resource_batch_id": null
}
]
}
@@ -0,0 +1,542 @@
{
"projects": 100,
"first_return": {
"completed": 97,
"blocked": 3
},
"before_release": {
"completed": 9,
"blocked": 2,
"pending": 89
},
"final": {
"completed": 97,
"blocked": 3
},
"supervisor_calls": [
{
"batch_id": "15fcc3425d5f4a9ea172b7725023dd91",
"queue_id": null,
"resource_batch_id": null
},
{
"batch_id": "78718bb8a02147358b441c540c902899",
"queue_id": "af07e3269bcd4a08afbf064af9126123",
"resource_batch_id": "15fcc3425d5f4a9ea172b7725023dd91"
},
{
"batch_id": "862fad3b3d754c4a944135ff8256b1d8",
"queue_id": "af07e3269bcd4a08afbf064af9126123",
"resource_batch_id": null
},
{
"batch_id": "69c5a03140bc4c5ca7d9bb52f6ff528f",
"queue_id": "af07e3269bcd4a08afbf064af9126123",
"resource_batch_id": null
}
],
"queue_id": "af07e3269bcd4a08afbf064af9126123",
"shared_source_blocked": 12,
"writer_pid": 25028,
"release_checks": [
10,
11
],
"calls": [
{
"project": 1,
"job_id": "388bad5bafc54ae3b766a574f07feb44_0",
"result": "saved_ok"
},
{
"project": 2,
"job_id": "78c6aa3632484ef795705071c4f6871e_0",
"result": "saved_ok"
},
{
"project": 3,
"job_id": "b1e96b8625df4e8cb50f44c2faed14be_0",
"result": "saved_ok"
},
{
"project": 4,
"job_id": "1c1419a896374821ac7c51a3117b75e1_0",
"result": "saved_ok"
},
{
"project": 5,
"job_id": "df4e71b52bf842f093029d4dad56f797_0",
"result": "saved_ok"
},
{
"project": 6,
"job_id": "1fcb7b6d75f44cdcbaed93accaa1c07d_0",
"result": "saved_ok"
},
{
"project": 7,
"job_id": "6eeb02803cde4b2483ee776c9afeba1c_0",
"result": "saved_ok"
},
{
"project": 8,
"job_id": "84c54eeb256d404582eda32019de17d8_0",
"result": "saved_ok"
},
{
"project": 9,
"job_id": "05cf0fb9ad8b4c7d90d039d466de25a7_0",
"result": "saved_ok"
},
{
"project": 10,
"job_id": "7c2ea733df924c1a9e04750f22134738_0",
"result": "batch_saved_unverified"
},
{
"project": 11,
"job_id": "807cafae32bc495a894f5b35a6d1cb5e_0",
"result": "batch_saved_unverified"
},
{
"project": 13,
"job_id": "304752f4d4c64e1bbabcbf55bff365fb_0",
"result": "saved_ok"
},
{
"project": 14,
"job_id": "2040d066abc4482da2323b1b313e6e0e_0",
"result": "saved_ok"
},
{
"project": 15,
"job_id": "908898c13c47472bb6f115f4910cccf4_0",
"result": "saved_ok"
},
{
"project": 16,
"job_id": "3abda0f30178471c9af61afd5738b530_0",
"result": "saved_ok"
},
{
"project": 17,
"job_id": "6c7365afea284aa3854b66af096bd098_0",
"result": "saved_ok"
},
{
"project": 18,
"job_id": "f210b5d510344eb08f8d93ce05d001fe_0",
"result": "saved_ok"
},
{
"project": 19,
"job_id": "eaaa69c064f0433fbab3874e0b331090_0",
"result": "saved_ok"
},
{
"project": 20,
"job_id": "edc20d8c922f4bbaad379a3ce0db6891_0",
"result": "saved_ok"
},
{
"project": 21,
"job_id": "f5cdef2f94b54d7da8c9c9c730557b8e_0",
"result": "saved_ok"
},
{
"project": 22,
"job_id": "1dfc6665bfcf455e9246e212f92c689c_0",
"result": "saved_ok"
},
{
"project": 23,
"job_id": "75385b75cf9140629f9aa1022bb2c53c_0",
"result": "saved_ok"
},
{
"project": 24,
"job_id": "809cef1ba35b44d9be4ffd1dbd1ab000_0",
"result": "saved_ok"
},
{
"project": 25,
"job_id": "367c3ffd715c4ef586f2e8824bbef491_0",
"result": "saved_ok"
},
{
"project": 26,
"job_id": "bf5f3bdd3fb14fcc9740436fa464be37_0",
"result": "saved_ok"
},
{
"project": 27,
"job_id": "a60a8566d058464495773969e6a99017_0",
"result": "saved_ok"
},
{
"project": 28,
"job_id": "0c4c8103d7104788a5da9f017c0f1ace_0",
"result": "saved_ok"
},
{
"project": 29,
"job_id": "eaa9e2e922e44c39a012af2519d951cf_0",
"result": "saved_ok"
},
{
"project": 30,
"job_id": "e84022b8f6f949ddaee69e8067b9a795_0",
"result": "saved_ok"
},
{
"project": 31,
"job_id": "8ab8ba8bad0e4b859e4720d0af2d56d8_0",
"result": "saved_ok"
},
{
"project": 32,
"job_id": "0e7d3863480e4382b6b07ededa94f012_0",
"result": "saved_ok"
},
{
"project": 33,
"job_id": "fbe7d3bf153644859f9b6a785fc98d64_0",
"result": "saved_ok"
},
{
"project": 34,
"job_id": "6e1e4e3e44ad4aeeb51896837e6b84fb_0",
"result": "saved_ok"
},
{
"project": 35,
"job_id": "efe7a9fb23944560bdac2212b2154cbe_0",
"result": "saved_ok"
},
{
"project": 36,
"job_id": "50ef7be31e7740bbbf337e570690de86_0",
"result": "saved_ok"
},
{
"project": 37,
"job_id": "8696162e1e7b4169b562f5454f8ddfb0_0",
"result": "saved_ok"
},
{
"project": 38,
"job_id": "657ca58af33a4b7db33b19007e1ce071_0",
"result": "saved_ok"
},
{
"project": 39,
"job_id": "a18f78199fd74601a007e8eb9ee15433_0",
"result": "saved_ok"
},
{
"project": 40,
"job_id": "badd43d9a5624a689cc693bb7ea31652_0",
"result": "saved_ok"
},
{
"project": 41,
"job_id": "bab81db14eb54782b869252fac15e570_0",
"result": "saved_ok"
},
{
"project": 42,
"job_id": "92617c885ead4d838432c68e2255f7d0_0",
"result": "saved_ok"
},
{
"project": 43,
"job_id": "216b4cda3f4148e7bc9d75ee5be8b6cb_0",
"result": "saved_ok"
},
{
"project": 44,
"job_id": "3d57183d53304ce69933c982311b0f35_0",
"result": "saved_ok"
},
{
"project": 45,
"job_id": "528549b58fd64769bc5016d3a4357aab_0",
"result": "saved_ok"
},
{
"project": 46,
"job_id": "f8d51cf682604a08bd046123ab6a509a_0",
"result": "saved_ok"
},
{
"project": 47,
"job_id": "c73cc80bbc35445b8e4ffbb26a884bb0_0",
"result": "saved_ok"
},
{
"project": 48,
"job_id": "40a362b535034d15b4c89c4bc9af0c91_0",
"result": "saved_ok"
},
{
"project": 49,
"job_id": "4df4aafeb2c841b494b9949c8ca230d2_0",
"result": "saved_ok"
},
{
"project": 50,
"job_id": "7064b1e06df642c9a6c2fca037287ec4_0",
"result": "saved_ok"
},
{
"project": 51,
"job_id": "f6caf03914f74a26b769873941506bd1_0",
"result": "saved_ok"
},
{
"project": 52,
"job_id": "a2dea8f52ac04ed6ac1a2a28d9f8ef63_0",
"result": "saved_ok"
},
{
"project": 53,
"job_id": "42e312a4cf6d453a88ee9b2163b191b5_0",
"result": "saved_ok"
},
{
"project": 54,
"job_id": "45dbef10be42411c9a2a0248946d9037_0",
"result": "saved_ok"
},
{
"project": 55,
"job_id": "2d6bfff0905149659324f152a5a37053_0",
"result": "saved_ok"
},
{
"project": 56,
"job_id": "687a85f8e4684ebb99ae3371f08da745_0",
"result": "saved_ok"
},
{
"project": 57,
"job_id": "f03c1b7e292d458fa1cf34fa32fcc6dc_0",
"result": "saved_ok"
},
{
"project": 58,
"job_id": "2ddfbc06b4864f6cb76f7253fa35fab5_0",
"result": "saved_ok"
},
{
"project": 59,
"job_id": "14e6219fdebe4b54bbd95cd95d82fe27_0",
"result": "saved_ok"
},
{
"project": 60,
"job_id": "328b84460d394545a8b3a1701bb4668e_0",
"result": "saved_ok"
},
{
"project": 61,
"job_id": "932ee1968d8548cb9b20d2205cbda07f_0",
"result": "saved_ok"
},
{
"project": 62,
"job_id": "d61878a4fb6b42f69bc29d5a9039151f_0",
"result": "saved_ok"
},
{
"project": 63,
"job_id": "df606318c32a445f83fe0aaafa47dd8b_0",
"result": "saved_ok"
},
{
"project": 64,
"job_id": "810306d724314216b533239129fa5f00_0",
"result": "saved_ok"
},
{
"project": 65,
"job_id": "95d51023c87b4fa6be5ed8c36b884b02_0",
"result": "saved_ok"
},
{
"project": 66,
"job_id": "490361523d184a738048546ad39c5051_0",
"result": "saved_ok"
},
{
"project": 67,
"job_id": "d51096842332404b97c5bd9b320e2b72_0",
"result": "saved_ok"
},
{
"project": 68,
"job_id": "07beb872e39e4ed99bd63520b0b6f9e9_0",
"result": "saved_ok"
},
{
"project": 69,
"job_id": "7fd5188c1c1d4eb3874c45629db474b2_0",
"result": "saved_ok"
},
{
"project": 70,
"job_id": "b1690759022045288b9e3cec1089284f_0",
"result": "saved_ok"
},
{
"project": 71,
"job_id": "f7e247a2619642f2a1f881891e8eeb57_0",
"result": "saved_ok"
},
{
"project": 72,
"job_id": "aea8b540c89842d6869bc34564aa8a8f_0",
"result": "saved_ok"
},
{
"project": 73,
"job_id": "1deab0ea04ee4ee2be2bf8a5564fcf7c_0",
"result": "saved_ok"
},
{
"project": 74,
"job_id": "8808d235aba149bd8651675f2b10ceed_0",
"result": "saved_ok"
},
{
"project": 75,
"job_id": "30505f56d58848be97ce2af31bf8590d_0",
"result": "saved_ok"
},
{
"project": 76,
"job_id": "1aceadb5a89d4d068f318f8eeed650e4_0",
"result": "saved_ok"
},
{
"project": 77,
"job_id": "b75a90feeb3f4737a3bbc31c55aa418c_0",
"result": "saved_ok"
},
{
"project": 78,
"job_id": "21fe6401ceb34a80865a0d548ef707e5_0",
"result": "saved_ok"
},
{
"project": 79,
"job_id": "4ca98380c3494062bbca254f3efb91e6_0",
"result": "saved_ok"
},
{
"project": 80,
"job_id": "2eee50b616934bf9849d116fe4e313f4_0",
"result": "saved_ok"
},
{
"project": 81,
"job_id": "32cf6eb628bd4039a6d591682c96c661_0",
"result": "saved_ok"
},
{
"project": 82,
"job_id": "966a29d95f7040ceb044d818e0abcde0_0",
"result": "saved_ok"
},
{
"project": 83,
"job_id": "8aa901efbd6149bc9744714992fd6021_0",
"result": "saved_ok"
},
{
"project": 84,
"job_id": "9e6b5ecf9b714354b191e92add01d6c3_0",
"result": "saved_ok"
},
{
"project": 85,
"job_id": "08bd3aac43aa4b7ea9dd980540951c8f_0",
"result": "saved_ok"
},
{
"project": 86,
"job_id": "b70f927d89354785939daa703ae65dc3_0",
"result": "saved_ok"
},
{
"project": 87,
"job_id": "e1f98f7188b6446c8218d83a2041d906_0",
"result": "saved_ok"
},
{
"project": 88,
"job_id": "9c75b996f185424d9507fd00f2262fae_0",
"result": "saved_ok"
},
{
"project": 89,
"job_id": "2671fb1be481453cbd382973d8d3807c_0",
"result": "saved_ok"
},
{
"project": 90,
"job_id": "20044c501cf84140bc54114f903d40fd_0",
"result": "saved_ok"
},
{
"project": 91,
"job_id": "a5eda4530b8940178dabf9f8e85b1a2a_0",
"result": "saved_ok"
},
{
"project": 92,
"job_id": "fafda99d5f8344f18c574d4440c57518_0",
"result": "saved_ok"
},
{
"project": 93,
"job_id": "b3247626d9e441208779273cd3e607bc_0",
"result": "saved_ok"
},
{
"project": 94,
"job_id": "4dc0c755982f4fc1bd63803b83466aab_0",
"result": "saved_ok"
},
{
"project": 95,
"job_id": "b41bcead3e0c45fe855f2fa08dfc668b_0",
"result": "saved_ok"
},
{
"project": 96,
"job_id": "397b58aa73b042719410592f9b6ed4a1_0",
"result": "saved_ok"
},
{
"project": 97,
"job_id": "012bde1609484512b83f23809f333c9d_0",
"result": "saved_ok"
},
{
"project": 98,
"job_id": "00a4507a1c1f45f797e3f9e466c633b1_0",
"result": "saved_ok"
},
{
"project": 99,
"job_id": "300db9dee9b947be85a596b9f538128e_0",
"result": "saved_ok"
},
{
"project": 100,
"job_id": "c748b639f5034e8baaa0b2a6bed638ae_0",
"result": "saved_ok"
}
]
}
@@ -0,0 +1,55 @@
{
"projects": 8,
"first_return": {
"completed": 3,
"pending": 5
},
"final": {
"completed": 8
},
"queue_id": "6bbbdf75c72e4a21844c51d1938ee725",
"calls": [
{
"project": 1,
"job_id": "d4a210a4bea9478dbbe552f6fe87e125_0",
"result": "saved_ok"
},
{
"project": 2,
"job_id": "b595108e12e24858ae8faa006b63c103_0",
"result": "saved_ok"
},
{
"project": 3,
"job_id": "c74e034af94c4fdabaedee1b1d482771_0",
"result": "saved_ok"
},
{
"project": 4,
"job_id": "1a7c1b81b15844f2bce705755164e2d9_0",
"result": "saved_ok"
},
{
"project": 5,
"job_id": "267ea09123c44f20be66b0141f94177c_0",
"result": "saved_ok"
},
{
"project": 6,
"job_id": "8d9f2932a57846da8d087d80ddaed2fb_0",
"result": "saved_ok"
},
{
"project": 7,
"job_id": "a7e1d97f74d6495aa112831364ec47cc_0",
"result": "saved_ok"
},
{
"project": 8,
"job_id": "6a77966ac69a47c1b8c984bcc655cd7e_0",
"result": "saved_ok"
}
],
"paused_in_pid": 54160,
"resumed_in_pid": 60636
}
@@ -1123,7 +1123,8 @@ Sub QPDiscardFailedBatchProject(ByRef ErrorDescription)
If (Not QP_BatchMode And Not QP_SessionMode) Or Not QP_OwnedProject Or QP_App Is Nothing Then Exit Sub If (Not QP_BatchMode And Not QP_SessionMode) Or Not QP_OwnedProject Or QP_App Is Nothing Then Exit Sub
HasStagedItems = False HasStagedItems = False
If IsObject(QP_SessionItems) Then HasStagedItems = (QP_SessionItems.Count > 0) If IsObject(QP_SessionItems) Then HasStagedItems = (QP_SessionItems.Count > 0)
If QP_NativeMutationPossible Or QP_BatchSaveRequested Or QP_BatchSaveCommitted Or HasStagedItems Then If QP_NativeMutationPossible Or QP_NativeCallActive Or QP_RestoreTransactionOpen Or _
QP_BatchSaveRequested Or QP_BatchSaveCommitted Or HasStagedItems Then
ErrorDescription = "write or save outcome requires reconciliation; owned project retained without automatic save or discard" ErrorDescription = "write or save outcome requires reconciliation; owned project retained without automatic save or discard"
Exit Sub Exit Sub
End If End If
@@ -1658,6 +1659,7 @@ Sub QPNativeReplace(ByRef Command, ByVal SnapshotPath)
End If End If
CommandLine = CommandLine & " --native-helper --snapshot " & Chr(34) & SnapshotPath & Chr(34) CommandLine = CommandLine & " --native-helper --snapshot " & Chr(34) & SnapshotPath & Chr(34)
Set Shell = CreateObject("WScript.Shell") Set Shell = CreateObject("WScript.Shell")
QP_Stage = "native_replace"
QP_NativeCallActive = True QP_NativeCallActive = True
QPProgress "native_replace", 0, 1 QPProgress "native_replace", 0, 1
ExitCode = Shell.Run(CommandLine, 0, True) ExitCode = Shell.Run(CommandLine, 0, True)
+4 -4
View File
@@ -1,8 +1,8 @@
# UTF-8 # UTF-8
VSVersionInfo( VSVersionInfo(
ffi=FixedFileInfo( ffi=FixedFileInfo(
filevers=(1, 3, 1, 0), filevers=(1, 3, 3, 1),
prodvers=(1, 3, 1, 0), prodvers=(1, 3, 3, 1),
mask=0x3f, mask=0x3f,
flags=0x0, flags=0x0,
OS=0x40004, OS=0x40004,
@@ -15,11 +15,11 @@ VSVersionInfo(
StringTable('040904B0', [ StringTable('040904B0', [
StringStruct('CompanyName', 'DxProductivity'), StringStruct('CompanyName', 'DxProductivity'),
StringStruct('FileDescription', 'DxDesigner Part Replacement'), StringStruct('FileDescription', 'DxDesigner Part Replacement'),
StringStruct('FileVersion', '1.3.1.0'), StringStruct('FileVersion', '1.3.3.1'),
StringStruct('InternalName', 'DxPartReplace'), StringStruct('InternalName', 'DxPartReplace'),
StringStruct('OriginalFilename', 'DxPartReplace.exe'), StringStruct('OriginalFilename', 'DxPartReplace.exe'),
StringStruct('ProductName', 'DxDesigner Part Replacement'), StringStruct('ProductName', 'DxDesigner Part Replacement'),
StringStruct('ProductVersion', '1.3.1') StringStruct('ProductVersion', '1.3.3-beta.1')
]) ])
]), ]),
VarFileInfo([VarStruct('Translation', [1033, 1200])]) VarFileInfo([VarStruct('Translation', [1033, 1200])])
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project] [project]
name = "dx-productivity" name = "dx-productivity"
version = "1.3.1" version = "1.3.3b1"
requires-python = ">=3.12,<3.13" requires-python = ">=3.12,<3.13"
dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<1", "openpyxl>=3.1,<4"] dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<1", "openpyxl>=3.1,<4"]
+10 -1
View File
@@ -87,10 +87,12 @@ def _execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, res
else: else:
journal.begin(run_id, task_ids, report['plan_hashes'], schedule_id=schedule['schedule_id'] if schedule else None) journal.begin(run_id, task_ids, report['plan_hashes'], schedule_id=schedule['schedule_id'] if schedule else None)
initialized = True initialized = True
resource_batch_id = inspected.get('resource_batch_id') if resume else None
result = execute_task_queue(service, tuple(task_ids), stop_event=stop, result = execute_task_queue(service, tuple(task_ids), stop_event=stop,
expected_plan_hashes=report['plan_hashes'], expected_plan_hashes=report['plan_hashes'],
queue_id=run_id if resume and resume['queue_available'] else None, queue_id=run_id if resume and resume['queue_available'] else None,
checkpoint_id=None if resume and resume['queue_available'] else run_id) checkpoint_id=None if resume and resume['queue_available'] else run_id,
**({'resource_batch_id': resource_batch_id} if resource_batch_id else {}))
except Exception as error: except Exception as error:
failure = {**(_failure_evidence(service, journal, run_id, baseline) if initialized else {}), failure = {**(_failure_evidence(service, journal, run_id, baseline) if initialized else {}),
'status': 'interrupted', 'run_id': run_id, 'queue_id': run_id, 'status': 'interrupted', 'run_id': run_id, 'queue_id': run_id,
@@ -118,6 +120,13 @@ def _finish_execution_run(service, root, task_ids, stop, run_id, result, *, base
'user_pause_requested': bool(stop.is_set()), 'awaiting_user_resume': bool(result.paused and stop.is_set()), 'user_pause_requested': bool(stop.is_set()), 'awaiting_user_resume': bool(result.paused and stop.is_set()),
'entries': entries, 'tasks': [], 'reporting_errors': [], 'entries': entries, 'tasks': [], 'reporting_errors': [],
'message': '请按每项实际计数判断;未命中不表示已替换保存。'} 'message': '请按每项实际计数判断;未命中不表示已替换保存。'}
batch_id = getattr(service, '_last_supervisor_batch_id', None)
if result.paused and not stop.is_set() and batch_id:
from ..trial_task_center.task_queue import resource_pause_admitted
run = journal.get(run_id)
if (run and resource_pause_admitted(root, batch_id, tuple(task_ids), run['plan_hashes'],
result, require_released=False)):
receipt['resource_batch_id'] = batch_id
if result.netlist_verification: if result.netlist_verification:
receipt['netlist_verification'] = result.netlist_verification receipt['netlist_verification'] = result.netlist_verification
# Persist the executor's known outcome before optional readback/enrichment. # Persist the executor's known outcome before optional readback/enrichment.
+28 -1
View File
@@ -332,6 +332,31 @@ class RunJournal:
released_primary = {key for key, entry in (queue['entries'].items() if workspace and queue else ()) released_primary = {key for key, entry in (queue['entries'].items() if workspace and queue else ())
if entry['released'] and entry['state'] in {'completed', 'failed', 'skipped', 'blocked'}} if entry['released'] and entry['state'] in {'completed', 'failed', 'skipped', 'blocked'}}
isolated = {key for key in released_primary if queue['entries'][key]['state'] == 'blocked'} isolated = {key for key in released_primary if queue['entries'][key]['state'] == 'blocked'}
resource_batch_id = None
if queue and not workspace:
isolated.update(key for key in queue.get('isolated_tasks', {})
if key in queue['entries'] and queue['entries'][key]['state'] == 'blocked')
receipt = row.get('result') or {}
if (receipt.get('paused') is True and receipt.get('user_pause_requested') is False
and any(entry['state'] == 'blocked' and key not in isolated
for key, entry in queue['entries'].items())):
from ..trial_task_center.task_queue import resource_pause_admitted
pause = queue.get('resource_pause') or {}
known_batch = receipt.get('resource_batch_id') or pause.get('batch_id')
candidates = (known_batch,) if known_batch else (
path.parent.name for path in (self.data_root / 'batch-resources').glob('*/result.json'))
matches = []
for batch_id in candidates:
paused = resource_pause_admitted(self.data_root, batch_id,
tuple(row['task_ids']), row['plan_hashes'])
if paused and paused.queue_id == run_id:
matches.append((batch_id, paused))
if len(matches) > 1:
break
if len(matches) == 1:
resource_batch_id, paused = matches[0]
isolated.add(paused.current_task_id)
released_primary.update(isolated)
safe_continuations = set() safe_continuations = set()
for task_id in row["task_ids"]: for task_id in row["task_ids"]:
item = {"task_id": task_id, "status": "unknown", "saved_items": 0, "failed_items": 0, "no_match_items": 0} item = {"task_id": task_id, "status": "unknown", "saved_items": 0, "failed_items": 0, "no_match_items": 0}
@@ -380,7 +405,8 @@ class RunJournal:
counters["completed"] = sum(queue["entries"][task_id]["state"] in {"completed", "failed", "skipped"} for task_id in row["task_ids"]) counters["completed"] = sum(queue["entries"][task_id]["state"] in {"completed", "failed", "skipped"} for task_id in row["task_ids"])
remaining = [task_id for task_id in row["task_ids"] if not queue or queue["entries"][task_id]["state"] not in {"completed", "failed", "skipped"}] remaining = [task_id for task_id in row["task_ids"] if not queue or queue["entries"][task_id]["state"] not in {"completed", "failed", "skipped"}]
if queue and not workspace and queue.get('phase') in {'primary', 'problems'}: if queue and not workspace and queue.get('phase') in {'primary', 'problems'}:
remaining = [key for key in row['task_ids'] if key in remaining or key in released_primary] remaining = [key for key in row['task_ids'] if key not in isolated and
(key in remaining or key in released_primary)]
if workspace and queue: if workspace and queue:
primary_exhausted = all(entry['state'] in {'completed', 'failed', 'skipped', 'blocked'} for entry in queue['entries'].values()) primary_exhausted = all(entry['state'] in {'completed', 'failed', 'skipped', 'blocked'} for entry in queue['entries'].values())
remaining = [key for key in row['task_ids'] if key not in isolated and ( remaining = [key for key in row['task_ids'] if key not in isolated and (
@@ -407,6 +433,7 @@ class RunJournal:
blockers.append("resources_pending") blockers.append("resources_pending")
blockers = list(dict.fromkeys(blockers)) blockers = list(dict.fromkeys(blockers))
value = {**row, "queue_available": queue is not None, "tasks": tasks, "counters": counters, value = {**row, "queue_available": queue is not None, "tasks": tasks, "counters": counters,
'resource_batch_id': resource_batch_id,
'isolated_task_ids': [key for key in row['task_ids'] if key in isolated], 'isolated_task_ids': [key for key in row['task_ids'] if key in isolated],
'released_primary_task_ids': [key for key in row['task_ids'] if key in released_primary], 'released_primary_task_ids': [key for key in row['task_ids'] if key in released_primary],
'safe_continuation_task_ids': [key for key in row['task_ids'] if key in safe_continuations], 'safe_continuation_task_ids': [key for key in row['task_ids'] if key in safe_continuations],
@@ -9,12 +9,13 @@ import platform
import sys import sys
from typing import Sequence from typing import Sequence
from PySide6.QtCore import QTimer, QThreadPool from PySide6.QtCore import QTimer, QThreadPool, Qt
from PySide6.QtGui import QIcon from PySide6.QtGui import QIcon
from PySide6.QtWidgets import QApplication from PySide6.QtWidgets import QApplication
from dx_productivity.trial_task_center.logging_setup import LoggingContext, configure_logging, install_exception_hooks from dx_productivity.trial_task_center.logging_setup import LoggingContext, configure_logging, install_exception_hooks
from dx_productivity.trial_task_center.service import TaskCenterService from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.single_instance import InstanceUnavailable, gui_instance, listen_for_activation
from dx_productivity.trial_task_center.store import TaskStore from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.version import VERSION from dx_productivity.trial_task_center.version import VERSION
@@ -161,10 +162,28 @@ def main(argv: Sequence[str] | None = None) -> int:
from dx_productivity.trial_task_center.sceneos_cli import run from dx_productivity.trial_task_center.sceneos_cli import run
return run(data_root) return run(data_root)
try:
with gui_instance(data_root) as endpoint:
if endpoint is None:
return 0
return _run_gui(argv, arguments, data_root, endpoint)
except (OSError, InstanceUnavailable) as error:
message = f'无法打开 DxPartReplace。\n{data_root}\n{error}'
if sys.stderr is not None:
print(message, file=sys.stderr)
if os.name == 'nt' and bool(getattr(sys, 'frozen', False)):
import ctypes
ctypes.windll.user32.MessageBoxW(None, message, 'DxPartReplace', 0x30)
return 1
def _run_gui(argv, arguments, data_root, endpoint):
logging_context = configure_logging(data_root) logging_context = configure_logging(data_root)
install_exception_hooks(logging_context) install_exception_hooks(logging_context)
store: TaskStore | None = None store: TaskStore | None = None
window = None window = None
activation_server = None
try: try:
database_path = data_root / "task-center.db" database_path = data_root / "task-center.db"
_log_startup(logging_context, data_root, database_path) _log_startup(logging_context, data_root, database_path)
@@ -177,6 +196,16 @@ def main(argv: Sequence[str] | None = None) -> int:
configure_application_identity(qt_application) configure_application_identity(qt_application)
window = _load_window()(service) window = _load_window()(service)
window.show() window.show()
def activate():
logging_context.logger.info('instance_conflict data_root=%s', data_root)
window.setWindowState(window.windowState() & ~Qt.WindowState.WindowMinimized)
window.show()
window.raise_()
window.activateWindow()
window.statusBar().showMessage('此数据目录已在使用,已切换到现有窗口。', 6000)
activation_server = listen_for_activation(endpoint, activate)
if arguments.smoke_test: if arguments.smoke_test:
QTimer.singleShot(0, lambda: (window.close(), qt_application.quit())) QTimer.singleShot(0, lambda: (window.close(), qt_application.quit()))
exit_code = qt_application.exec() exit_code = qt_application.exec()
@@ -187,6 +216,8 @@ def main(argv: Sequence[str] | None = None) -> int:
logging_context.report_exception("startup", error) logging_context.report_exception("startup", error)
return 1 return 1
finally: finally:
if activation_server is not None:
activation_server.close()
if store is not None: if store is not None:
# The window invalidates queued UI results on close. Finish the # The window invalidates queued UI results on close. Finish the
# remaining read before releasing the shared SQLite connection. # remaining read before releasing the shared SQLite connection.
@@ -37,11 +37,13 @@ def write_release_event(root, path, record, phase, *, context=None, reason='batc
'desktop_disappeared': disappeared, 'cad_exit_code': cad.get('cad_exit_code'), 'desktop_disappeared': disappeared, 'cad_exit_code': cad.get('cad_exit_code'),
'quit_helper_exit_code': cad.get('quit_helper_exit_code'), 'quit_helper_exit_code': cad.get('quit_helper_exit_code'),
'cad_shutdown': cad, 'shutdown_warning': record.get('shutdown_warning'), 'cad_shutdown': cad, 'shutdown_warning': record.get('shutdown_warning'),
'retries': record.get('retries', {}), 'cleanup': cleanup, 'error': str(error)} 'retries': record.get('retries', {}), 'release_rechecks': record.get('release_rechecks', []),
'cleanup': cleanup, 'error': str(error)}
title = {'started': '开始释放后台资源', 'succeeded': '后台资源释放成功', title = {'started': '开始释放后台资源', 'succeeded': '后台资源释放成功',
'failed': '后台资源释放失败,资源释放待处理', 'failed': '后台资源释放失败,资源释放待处理',
'isolated': '后台写入进程已退出,残留桌面已隔离(未确认释放)'}[phase] 'isolated': '后台写入进程已退出,残留桌面已隔离(未确认释放)'}[phase]
purpose = {'batch_end': '批次结束', 'rebuild': '安全重建', 'manual_retry': '重新清理', purpose = {'batch_end': '批次结束', 'rebuild': '安全重建', 'manual_retry': '重新清理',
'automatic_recheck': '自动复核释放',
'restart_recheck': '重启后重新检查'}.get(reason, reason) 'restart_recheck': '重启后重新检查'}.get(reason, reason)
cad_text = f"CAD PID={details['cad_pid']}" if details['cad_pid'] else ( cad_text = f"CAD PID={details['cad_pid']}" if details['cad_pid'] else (
'CAD 未启动' if record.get('cad_start_requested') is False else 'CAD 未启动' if record.get('cad_start_requested') is False else
@@ -15,6 +15,27 @@ from .path_access import canonical_path, internal_path, retry_sharing_violation
# Recovery retains owned native handles after failed cleanup. This registry is # Recovery retains owned native handles after failed cleanup. This registry is
# never an implicit execution context and never contains COM application objects. # never an implicit execution context and never contains COM application objects.
LIVE_RESOURCES = {} LIVE_RESOURCES = {}
RESOURCE_RELEASE_BACKOFF_SECONDS = (0.5, 1, 2)
def _observe_release(observe, record):
"""Check once immediately, then at most three times after backoff."""
record['release_rechecks'] = []
for attempt, delay in enumerate((0, *RESOURCE_RELEASE_BACKOFF_SECONDS)):
if delay:
time.sleep(delay)
try:
confirmed = observe()
except (OSError, TaskCenterError) as error:
confirmed, detail = False, str(error)
else:
detail = ''
if attempt:
record['release_rechecks'].append({'attempt': attempt, 'delay_seconds': delay,
'confirmed': confirmed, 'error': detail})
if confirmed:
return True
return False
class BatchResourceCleanupError(TaskCenterError): class BatchResourceCleanupError(TaskCenterError):
@@ -237,6 +258,31 @@ def _process_gone(identity):
handle.Close() handle.Close()
def _historical_writer_trees_closed(record, path):
cleanup = record.get('cleanup') or {}
if cleanup.get('owned_cleanup_complete') is True:
return True
if not record.get('processes'):
return record.get('cad_pid') is None and record.get('cad_start_requested') is not True
if not record.get('cad_process') or record['processes'] != [record['cad_process']]:
return False # Older Job snapshots only bind the CAD root's process creation time.
# Older blocked records can miss the latest desktop cleanup while already
# retaining a complete per-CAD Job accounting record.
marker = path.parent / f"generation-{record['generation']}" / 'private-desktop.json'
native = json.loads(internal_path(marker).read_text(encoding='utf-8'))
if ((native.get('token'), native.get('guid'), native.get('desktop'), native.get('cad_process'))
!= (record.get('cad_token'), record.get('cad_guid'), record.get('desktop'), record.get('cad_process'))
or not record.get('cad_token') or not record.get('cad_guid') or not record.get('cad_process')):
return False
observations = (native.get('desktop_cleanup') or {}).get('processes', ())
return sum(observation.get('pid') == record['cad_pid']
and observation.get('job_membership_verified') is True
and observation.get('job_active_processes') == 0
and observation.get('job_handle_closed') is True
and observation.get('unconfirmed_descendant_handles') == 0
for observation in observations) == 1
def cleanup_pending_resources(root, *, logging_context=None, retry_failed=False): def cleanup_pending_resources(root, *, logging_context=None, retry_failed=False):
from .isolated_desktop import _Win32Api from .isolated_desktop import _Win32Api
from .batch_release_log import write_release_event from .batch_release_log import write_release_event
@@ -269,6 +315,8 @@ def cleanup_pending_resources(root, *, logging_context=None, retry_failed=False)
continue continue
live = LIVE_RESOURCES.get(str(path)) live = LIVE_RESOURCES.get(str(path))
if live is not None: if live is not None:
if live.record.get('state') != 'blocked':
continue # An active generation has not asked for release.
try: try:
live.close(reason='manual_retry' if retry_failed else 'resource_recheck') live.close(reason='manual_retry' if retry_failed else 'resource_recheck')
except Exception: except Exception:
@@ -305,30 +353,47 @@ def cleanup_pending_resources(root, *, logging_context=None, retry_failed=False)
if not all(_process_gone(item) for item in identities): if not all(_process_gone(item) for item in identities):
log('failed', '记录中的进程仍未确认退出') log('failed', '记录中的进程仍未确认退出')
continue continue
if not _historical_writer_trees_closed(record, path):
log('failed', '缺少历史写入进程树退出证明')
continue
desktop = record.get('desktop') desktop = record.get('desktop')
if (record.get('cleanup') or {}).get('desktop_lease'): if (record.get('cleanup') or {}).get('desktop_lease'):
# A return belongs to this past lease, even while the same name # A return belongs to this past lease, even while the same name
# is now serving another batch. Never open or stop its new owner. # is now serving another batch. Never open or stop its new owner.
proof = isolation_proof(record) proof = isolation_proof(record)
from .desktop_slot import managed_desktop_disappeared from .desktop_slot import managed_desktop_disappeared
if not managed_desktop_disappeared(record['cleanup']['desktop_lease']): receipt = record['cleanup']['desktop_lease']
absent = _observe_release(lambda: managed_desktop_disappeared(receipt), record)
if not absent:
record.pop('record_path', None) record.pop('record_path', None)
record.update(state='isolated', blocking=False, isolation_proof=proof) record.update(state='isolated', blocking=False, isolation_proof=proof)
write_record(path, record) write_record(path, record)
log('isolated') log('isolated')
continue continue
elif desktop: elif desktop:
try: from .desktop_slot import observe_current_desktop_name
_Win32Api().confirm_desktop_released(desktop) api = None
except Exception as error:
def observe():
nonlocal api
managed = observe_current_desktop_name(desktop) if os.name == 'nt' else None
if managed is not None:
return managed
if api is None:
api = _Win32Api()
api.confirm_desktop_released(desktop)
return True
if not _observe_release(observe, record):
# A residual desktop name is only a warning after owned # A residual desktop name is only a warning after owned
# handle closure and independently revalidated writer exit. # handle closure and independently revalidated writer exit.
proof = isolation_proof(record) proof = isolation_proof(record)
record.pop('record_path', None) record.pop('record_path', None)
warning = '桌面仍在或同名桌面正在使用,未取得桌面消失证明'
record.update(state='isolated', blocking=False, isolation_proof=proof, record.update(state='isolated', blocking=False, isolation_proof=proof,
isolation_warning=str(error)) isolation_warning=warning)
write_record(path, record) write_record(path, record)
log('isolated', str(error)) log('isolated', warning)
continue continue
# After restart only confirm disappearance. Never attach to COM, # After restart only confirm disappearance. Never attach to COM,
# close a project, or terminate a PID whose handles we no longer own. # close a project, or terminate a PID whose handles we no longer own.
@@ -12,7 +12,7 @@ from uuid import UUID, uuid4
from .batch_resources import (BatchResourceCleanupError, LIVE_RESOURCES, cleanup_pending_resources, from .batch_resources import (BatchResourceCleanupError, LIVE_RESOURCES, cleanup_pending_resources,
guard_pending_resources, pending_resources, process_identity, project_checkpoint_released, write_record, guard_pending_resources, pending_resources, process_identity, project_checkpoint_released, write_record,
isolation_proof) isolation_proof, RESOURCE_RELEASE_BACKOFF_SECONDS)
from .errors import TaskCenterError from .errors import TaskCenterError
from .path_access import canonical_path, internal_path, legacy_path from .path_access import canonical_path, internal_path, legacy_path
from .isolated_desktop import PrivateDesktop, ProcessNotStartedError from .isolated_desktop import PrivateDesktop, ProcessNotStartedError
@@ -222,6 +222,7 @@ class BatchCadRuntime:
blocking=True, isolation_proof=None, blocking=True, isolation_proof=None,
stopping_reason='', wait_reason='', primary_error=None, stopping_reason='', wait_reason='', primary_error=None,
cad_process=None, cad_token=None, cad_shutdown=None, cad_start_requested=False, cleanup=None, cad_process=None, cad_token=None, cad_shutdown=None, cad_start_requested=False, cleanup=None,
release_rechecks=[],
release_state={'mentor': 'not_started', 'desktop': 'pending'}) release_state={'mentor': 'not_started', 'desktop': 'pending'})
self.generation = generation self.generation = generation
self.desktop = desktop self.desktop = desktop
@@ -949,11 +950,42 @@ class BatchCadRuntime:
def close(self, *, rebuilding=False, reason=None): def close(self, *, rebuilding=False, reason=None):
if not self._release_lock.acquire(blocking=False): if not self._release_lock.acquire(blocking=False):
raise BatchResourceCleanupError('资源释放正在进行,请等待当前释放结果。') raise BatchResourceCleanupError('资源释放正在进行,请等待当前释放结果。')
try:
try: try:
return self._close_once(rebuilding=rebuilding, reason=reason) return self._close_once(rebuilding=rebuilding, reason=reason)
except BatchResourceCleanupError as initial:
shutdown = self.record.get('cad_shutdown') or {}
if (reason in {'resource_recheck', 'automatic_recheck'}
or not shutdown.get('forced_termination')
or self.record['state'] not in {'blocked', 'released'}):
raise
self.record['shutdown_warning'] = str(initial)
for attempt, delay in enumerate(RESOURCE_RELEASE_BACKOFF_SECONDS, start=1):
time.sleep(delay)
self.record.setdefault('release_rechecks', []).append({'attempt': attempt, 'delay_seconds': delay})
try:
self._close_once(rebuilding=rebuilding, reason='automatic_recheck')
except BatchResourceCleanupError:
continue
self._save()
if self._completed_project_after_shutdown():
return
break
self._save()
raise
finally: finally:
self._release_lock.release() self._release_lock.release()
def _completed_project_after_shutdown(self):
shutdown = self.record.get('cad_shutdown') or {}
proof = self.record.get('release_proof') or {}
return (self.result is not None and getattr(self, '_cad_close_error', None) is None
and self._active_evidence is not None and not self._active_attempts
and shutdown.get('project_close_policy') == 'saved_only'
and proof.get('method') == 'owned_cleanup'
and not internal_path(self._active_evidence / 'uncertain.flag').exists()
and project_checkpoint_released(self._active_evidence))
def _close_once(self, *, rebuilding=False, reason=None): def _close_once(self, *, rebuilding=False, reason=None):
if self.desktop is None and not self.generation: if self.desktop is None and not self.generation:
return # A cache-only batch never acquired resources. return # A cache-only batch never acquired resources.
@@ -967,7 +999,7 @@ class BatchCadRuntime:
for event in cleanup.get('desktop_handle_history', ()))): for event in cleanup.get('desktop_handle_history', ()))):
raise BatchResourceCleanupError(str(self._close_failure), raise BatchResourceCleanupError(str(self._close_failure),
completed_result=self.result, cleanup_error=self._close_failure) completed_result=self.result, cleanup_error=self._close_failure)
if (reason == 'resource_recheck' if (reason in {'resource_recheck', 'automatic_recheck'}
and self.record.get('release_results', {}).get('desktop_released') is not True and self.record.get('release_results', {}).get('desktop_released') is not True
and cleanup.get('desktop_handle_closed') is True and cleanup.get('desktop_handle_closed') is True
and not getattr(self.desktop, '_processes', getattr(self.desktop, 'processes', ())) and not getattr(self.desktop, '_processes', getattr(self.desktop, 'processes', ()))
@@ -1124,6 +1156,10 @@ class BatchCadRuntime:
'cad_pid': self.record['cad_pid'], 'cad_guid': self.record['cad_guid'], 'cad_pid': self.record['cad_pid'], 'cad_guid': self.record['cad_guid'],
'cleanup': self.record['cleanup'], 'released_at': released_at} 'cleanup': self.record['cleanup'], 'released_at': released_at}
releases = [*self.record.get('generation_releases', ()), release] releases = [*self.record.get('generation_releases', ()), release]
shutdown = self.record.get('cad_shutdown') or {}
if shutdown.get('forced_termination') and (release['cleanup'] or {}).get('owned_cleanup_complete') is True:
proof = isolation_proof(self.record)
self.record['release_proof'] = dict(proof, desktop_released=True, method='owned_cleanup')
self._save(state='released', blocking=False, released_at=released_at, processes=[], generation_releases=releases, self._save(state='released', blocking=False, released_at=released_at, processes=[], generation_releases=releases,
wait_reason='') wait_reason='')
LIVE_RESOURCES.pop(str(self.path), None) LIVE_RESOURCES.pop(str(self.path), None)
@@ -219,7 +219,7 @@ def run(request_path):
def phase(value, message): def phase(value, message):
emit('phase', encode((value, str(message)))) emit('phase', encode((value, str(message))))
if operation == 'cleanup_batch_resources': if operation == 'cleanup_batch_resources':
result = service.cleanup_batch_resources() result = service.cleanup_batch_resources(automatic=arguments.get('automatic') is True)
response.update(status='ok', business_succeeded=True, result=encode(result)) response.update(status='ok', business_succeeded=True, result=encode(result))
else: else:
with runtime: with runtime:
@@ -48,6 +48,7 @@ class BomImportReport:
source_map_path: Path | None = None source_map_path: Path | None = None
passed_preview: BomBatchPreview | None = None passed_preview: BomBatchPreview | None = None
deferred: bool = False deferred: bool = False
warnings: tuple[str, ...] = ()
@property @property
def total_rows(self): def total_rows(self):
@@ -77,7 +77,9 @@ def resolution_binding(store, task_id):
def import_drafts(service, task_id, sources, *, stop_event=None, on_progress=None, on_phase=None, allow_partial=False): def import_drafts(service, task_id, sources, *, stop_event=None, on_progress=None, on_phase=None, allow_partial=False):
"""Persist routed spreadsheet requests without opening CAD or resolving parts.""" """Persist routed spreadsheet requests without opening CAD or resolving parts."""
rows = load_sources(sources, stop_event=stop_event, on_progress=on_progress, allow_partial=allow_partial) warnings = []
rows = load_sources(sources, stop_event=stop_event, on_progress=on_progress,
allow_partial=allow_partial, warnings=warnings)
scope = _scope(service._store, task_id) scope = _scope(service._store, task_id)
paths = tuple(project.path for _, project in scope) paths = tuple(project.path for _, project in scope)
names = {project.path: task.name for task, project in scope} names = {project.path: task.name for task, project in scope}
@@ -93,7 +95,8 @@ def import_drafts(service, task_id, sources, *, stop_event=None, on_progress=Non
write_routed_bom(normalized, rows, routes, project_names=names) write_routed_bom(normalized, rows, routes, project_names=names)
append_task_event(service._logging, level='INFO', task_id=task_id, append_task_event(service._logging, level='INFO', task_id=task_id,
operation='import_bom_drafts', message='BOM 表格来源记录已保存,工程位号待核验', operation='import_bom_drafts', message='BOM 表格来源记录已保存,工程位号待核验',
details={'source_map_path': str(mapping), 'source_count': len({row.source for row in rows})}) details={'source_map_path': str(mapping), 'source_count': len({row.source for row in rows}),
'warnings': warnings})
try: try:
report = inspect_batch(service, task_id, normalized, stop_event=stop_event, on_progress=on_progress, report = inspect_batch(service, task_id, normalized, stop_event=stop_event, on_progress=on_progress,
on_phase=on_phase, spreadsheet_only=True, allow_partial=allow_partial) on_phase=on_phase, spreadsheet_only=True, allow_partial=allow_partial)
@@ -110,7 +113,7 @@ def import_drafts(service, task_id, sources, *, stop_event=None, on_progress=Non
if report.deferred and result.project_path not in failed_paths: if report.deferred and result.project_path not in failed_paths:
reason = '表格已保存,执行前核验工程位号' reason = '表格已保存,执行前核验工程位号'
annotated.append(replace(result, source_file=str(source.source), source_row=source.excel_row, reason=reason)) annotated.append(replace(result, source_file=str(source.source), source_row=source.excel_row, reason=reason))
report = replace(report, rows=tuple(annotated), source_map_path=mapping) report = replace(report, rows=tuple(annotated), source_map_path=mapping, warnings=tuple(warnings))
if report.deferred: if report.deferred:
accepted_sources = tuple(source for result, source in zip(report.rows, rows, strict=True) accepted_sources = tuple(source for result, source in zip(report.rows, rows, strict=True)
if result.project_path not in failed_paths) if result.project_path not in failed_paths)
@@ -135,6 +135,14 @@ def managed_desktop_disappeared(receipt):
backend.unlock(mutex) backend.unlock(mutex)
def observe_current_desktop_name(name):
"""Observe a historical name in this logon without opening a desktop handle."""
slot = DesktopSlot()
if slot.name != name:
return None
return managed_desktop_disappeared({'scope': slot.scope, 'name': slot.name})
class DesktopSlot: class DesktopSlot:
def __init__(self, *, root=None, context=None, backend=None): def __init__(self, *, root=None, context=None, backend=None):
self.context = _context() if context is None else context self.context = _context() if context is None else context
@@ -27,3 +27,7 @@ class TaskCenterError(ValueError):
def _new_error_id() -> str: def _new_error_id() -> str:
date = datetime.now(timezone.utc).strftime("%Y%m%d") date = datetime.now(timezone.utc).strftime("%Y%m%d")
return f"DXT-{date}-{secrets.token_hex(4).upper()}" return f"DXT-{date}-{secrets.token_hex(4).upper()}"
class ProjectPathError(TaskCenterError):
"""An expected filesystem failure while reading or selecting projects."""
@@ -258,7 +258,9 @@ def _stop_and_wait(process):
running = process.poll() is None running = process.poll() is None
except Exception as error: except Exception as error:
errors.append(error) errors.append(error)
if running: termination_requested = (isinstance(process, _Win32Process)
and process.cleanup_record.get('forced_root_termination'))
if running and not termination_requested:
try: try:
if isinstance(process, _Win32Process): if isinstance(process, _Win32Process):
process.terminate(reason='root_process_active') process.terminate(reason='root_process_active')
@@ -17,7 +17,7 @@ import time
import traceback import traceback
from typing import Any, Mapping from typing import Any, Mapping
from .errors import TaskCenterError from .errors import ProjectPathError, TaskCenterError
from .path_access import internal_path from .path_access import internal_path
from .retention import rotate_text_log from .retention import rotate_text_log
@@ -62,15 +62,18 @@ class LoggingContext:
reported = error reported = error
else: else:
reported = TaskCenterError("unhandled_exception", "发生未处理异常") reported = TaskCenterError("unhandled_exception", "发生未处理异常")
message = reported.message
if not isinstance(error, ProjectPathError):
detail = "".join( detail = "".join(
traceback.format_exception(type(error), error, traceback_object or error.__traceback__) traceback.format_exception(type(error), error, traceback_object or error.__traceback__)
) )
message += "\n" + detail.rstrip()
self.logger.error( self.logger.error(
"error_id=%s operation=%s message=%s\n%s", "error_id=%s operation=%s code=%s message=%s",
reported.error_id, reported.error_id,
operation, operation,
reported.message, reported.code,
detail.rstrip(), message,
) )
_flush_handlers(self.logger) _flush_handlers(self.logger)
return reported return reported
@@ -292,7 +292,8 @@ def wait_for(callback, description, timeout=15):
raise TimeoutError(description) 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=30, stable_for=0.45, poll_interval=0.15,
scope=lambda: None):
deadline = time.monotonic() + timeout deadline = time.monotonic() + timeout
previous = None previous = None
stable_since = None stable_since = None
@@ -309,7 +310,7 @@ def wait_for_library_rows(callback, target, timeout=30, stable_for=0.45, poll_in
previous = stable_since = None previous = stable_since = None
time.sleep(poll_interval) time.sleep(poll_interval)
continue continue
signature = tuple(tuple(str(value) for value in columns) for _, columns in latest) signature = (scope(), tuple(tuple(str(value) for value in columns) for _, columns in latest))
now = time.monotonic() now = time.monotonic()
if signature != previous: if signature != previous:
previous = signature previous = signature
@@ -321,6 +322,106 @@ def wait_for_library_rows(callback, target, timeout=30, stable_for=0.45, poll_in
raise TimeoutError(f"Native DxDataBook did not finish loading target part: {target}") raise TimeoutError(f"Native DxDataBook did not finish loading target part: {target}")
def load_databook_target(snapshot, report, target, *, controls, browse, filter_part,
list_rows, dialogs, close_dialog):
"""Load the target before the native submit boundary and retry a prepared batch once."""
from .batch_attempt import can_retry_attempt
diagnostic = report.setdefault('databook', {})
loads = diagnostic['loads'] = []
baseline = {row['hwnd'] for row in dialogs()}
initial = snapshot_attempt(snapshot)
warm = controls() is not None
for index in range(2):
timeout = 20 if warm else 45
started = time.monotonic()
load = {'mode': 'warm' if warm else 'cold', 'timeout_seconds': timeout,
'attempt_state_before_load': initial[1]['state'] if initial else None}
loads.append(load)
save_report(snapshot, report)
pair = None
def read():
nonlocal pair
current = controls()
if current is None:
pair = None
return []
try:
if current != pair:
filter_part(current[1])
pair = current
load.update(list_handle=pair[0], filter_handle=pair[1])
return list_rows(pair[0])
except Exception as error:
if (getattr(error, 'winerror', None) != 1400 # ERROR_INVALID_WINDOW_HANDLE
and getattr(error, 'hresult', None) != -2147220991): # UIA_E_ELEMENTNOTAVAILABLE
raise
pair = None
return []
try:
if index == 0 or controls() is None:
browse()
rows = wait_for_library_rows(read, target, timeout=timeout, scope=lambda: pair)
except TimeoutError as error:
load['error'] = str(error)
load['elapsed_seconds'] = round(time.monotonic() - started, 3)
load['dialogs'] = [row for row in dialogs() if row['hwnd'] not in baseline]
bound = snapshot_attempt(snapshot)
prepared = initial is not None and initial[1]['state'] == 'prepared' and can_retry_attempt(*initial)
load['attempt_state'] = bound[1]['state'] if bound else None
blockers = [row for row in load['dialogs'] if not row.get('browser')]
candidates = [row for row in blockers if row['dismissible']]
retry = index == 0 and prepared and bool(os.environ.get('DXPART_DESKTOP'))
# A different modal must get its normal operator handling.
retry = retry and (not blockers or len(blockers) == len(candidates) == 1)
load['retry'] = retry
save_report(snapshot, report)
if not retry:
raise
if candidates:
close_dialog(candidates[0])
load['closed_dialog'] = candidates[0]['hwnd']
warm = True
else:
load['elapsed_seconds'] = round(time.monotonic() - started, 3)
return pair[0], rows
def databook_dialogs(gui, process, pid, replacement, main_handle):
from .cad_dialogs import _text
replacement_thread, _ = process.GetWindowThreadProcessId(replacement)
rows = []
def dialog(handle, _):
if (handle in {replacement, main_handle} or not gui.IsWindowVisible(handle)
or process.GetWindowThreadProcessId(handle)[1] != pid
or gui.GetClassName(handle) != '#32770'):
return
owner = gui.GetWindow(handle, 4) # GW_OWNER
row = {'hwnd': handle, 'owner': owner, 'pid': pid, 'title': '', 'children': [],
'browser': False, 'dismissible': False}
rows.append(row)
children = []
try:
row['title'] = _text(handle)
gui.EnumChildWindows(handle, lambda child, _: children.append(child), None)
row['children'] = [{'hwnd': child, 'parent': gui.GetParent(child), 'class': gui.GetClassName(child),
'id': gui.GetDlgCtrlID(child)} for child in children[:64]]
row['browser'] = {('SysListView32', 4000), ('Edit', 4006)} <= {
(child['class'], child['id']) for child in row['children']}
row['dismissible'] = (not row['title'].strip() and not children and owner == replacement
and process.GetWindowThreadProcessId(handle)[0] == replacement_thread
and not gui.IsWindowEnabled(replacement))
except (OSError, gui.error) as error:
row['read_error'] = str(error)
gui.EnumWindows(dialog, None)
return rows
def target_symbol_matches(displayed, library_symbol, slot_count): def target_symbol_matches(displayed, library_symbol, slot_count):
actual = str(displayed).casefold() actual = str(displayed).casefold()
expected = str(library_symbol).casefold() expected = str(library_symbol).casefold()
@@ -848,8 +949,8 @@ def run_native(snapshot, report):
raise ValueError("Multiple replacement dialogs") raise ValueError("Multiple replacement dialogs")
return matches[0] if matches else None return matches[0] if matches else None
def message(handle, code, wparam=0, lparam=0): def message(handle, code, wparam=0, lparam=0, *, timeout=15000):
return win32gui.SendMessageTimeout(handle, code, wparam, lparam, win32con.SMTO_ABORTIFHUNG, 15000) return win32gui.SendMessageTimeout(handle, code, wparam, lparam, win32con.SMTO_ABORTIFHUNG, timeout)
def control_text(control): def control_text(control):
buffer = ctypes.create_unicode_buffer(2048) buffer = ctypes.create_unicode_buffer(2048)
@@ -865,9 +966,9 @@ def run_native(snapshot, report):
control = dlg_item(dialog, identifier) control = dlg_item(dialog, identifier)
if not control: if not control:
raise ValueError(f"Required native option {identifier} is unavailable") raise ValueError(f"Required native option {identifier} is unavailable")
if win32gui.SendMessage(control, 0x00F0, 0, 0) != 1: if message(control, 0x00F0)[1] != 1:
click(control) click(control)
if win32gui.SendMessage(control, 0x00F0, 0, 0) != 1: if message(control, 0x00F0)[1] != 1:
raise ValueError(f"Native option {identifier} was not enabled") raise ValueError(f"Native option {identifier} was not enabled")
report.setdefault("native_options", {})[str(identifier)] = { report.setdefault("native_options", {})[str(identifier)] = {
"text": control_text(control), "text": control_text(control),
@@ -896,31 +997,68 @@ def run_native(snapshot, report):
"main_visible_before_browse": bool(win32gui.IsWindowVisible(main_handle)), "main_visible_before_browse": bool(win32gui.IsWindowVisible(main_handle)),
"browse_button": int(dlg_item(dialog, 1366)), "browse_button": int(dlg_item(dialog, 1366)),
} }
click(dlg_item(dialog, 1366))
def part_list(): def query_message(handle, code, wparam=0, lparam=0):
report["databook"]["main_visible_during_wait"] = bool( try:
win32gui.IsWindowVisible(main_handle) message(handle, code, wparam, lparam, timeout=5000)
) except win32gui.error as error:
if error.winerror == 1460:
raise TimeoutError('Native DxDataBook browse or filter did not respond') from error
raise
def browse():
button = dlg_item(dialog, 1366)
if button and win32gui.IsWindowEnabled(dialog) and win32gui.IsWindowEnabled(button):
query_message(button, 0x00F5) # BM_CLICK
def controls():
lists, filters = {}, {}
for handle in owned_windows(include_hidden=True): for handle in owned_windows(include_hidden=True):
if win32gui.GetClassName(handle) == "SysListView32" and win32gui.GetDlgCtrlID(handle) == 4000: try:
return handle kind = (win32gui.GetClassName(handle), win32gui.GetDlgCtrlID(handle))
return None if kind == ('SysListView32', 4000):
list_handle = wait_for(part_list, "Native DxDataBook part list did not open", timeout=30) lists[handle] = win32gui.GetAncestor(handle, 2)
elif kind == ('Edit', 4006):
filters[handle] = win32gui.GetAncestor(handle, 2)
except win32gui.error:
if win32gui.IsWindow(handle):
raise
pairs = [(part_list, part_filter) for part_list, list_root in lists.items()
for part_filter, filter_root in filters.items() if list_root == filter_root]
visible = [pair for pair in pairs if all(win32gui.IsWindowVisible(handle) for handle in pair)]
pairs = visible or pairs
return pairs[0] if len(pairs) == 1 else None
def filter_part(handle):
query_message(handle, win32con.WM_SETTEXT, 0, metadata[3])
def current_library_rows(list_handle):
try:
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")]
except Exception:
if win32gui.IsWindow(list_handle):
raise
return []
def dialogs():
return databook_dialogs(win32gui, win32process, process_id, dialog, main_handle)
def close_dialog(expected):
if expected not in dialogs():
raise OSError('DxDataBook dialog changed before close')
win32gui.PostMessage(expected['hwnd'], win32con.WM_CLOSE, 0, 0)
wait_for(lambda: not win32gui.IsWindowVisible(expected['hwnd']),
'Native DxDataBook dialog did not close', timeout=3)
list_handle, rows = load_databook_target(snapshot, report, metadata[3], controls=controls,
browse=browse, filter_part=filter_part, list_rows=current_library_rows,
dialogs=dialogs, close_dialog=close_dialog)
report["databook"].update( report["databook"].update(
list_handle=int(list_handle), list_handle=int(list_handle),
list_visible=bool(win32gui.IsWindowVisible(list_handle)), list_visible=bool(win32gui.IsWindowVisible(list_handle)),
main_visible_after_load=bool(win32gui.IsWindowVisible(main_handle)), main_visible_after_load=bool(win32gui.IsWindowVisible(main_handle)),
) )
filter_handles = [handle for handle in owned_windows(include_hidden=True)
if win32gui.GetDlgCtrlID(handle) == 4006 and win32gui.GetClassName(handle) == "Edit"]
if len(filter_handles) != 1:
raise ValueError("Cannot uniquely identify native Part Number filter")
message(filter_handles[0], win32con.WM_SETTEXT, 0, metadata[3])
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])
row, columns = exact_target(rows, metadata[3]) row, columns = exact_target(rows, metadata[3])
report["library_row"] = columns report["library_row"] = columns
symbol_parts = columns[2].split(":", 1) symbol_parts = columns[2].split(":", 1)
@@ -930,6 +1068,9 @@ def run_native(snapshot, report):
report["slot_count"] = slot_count report["slot_count"] = slot_count
if slot_count < 1: if slot_count < 1:
raise ValueError("Library target has no valid slots") raise ValueError("Library target has no valid slots")
current_pair = controls()
if current_pair is None or current_pair[0] != list_handle:
raise ValueError("DxDataBook controls changed after target selection")
rectangle = row.rectangle() rectangle = row.rectangle()
list_rectangle = win32gui.GetWindowRect(list_handle) list_rectangle = win32gui.GetWindowRect(list_handle)
if rectangle.height() <= 0 or rectangle.top < list_rectangle[1] or rectangle.bottom > list_rectangle[3]: if rectangle.height() <= 0 or rectangle.top < list_rectangle[1] or rectangle.bottom > list_rectangle[3]:
@@ -6,12 +6,19 @@ import re
from .path_access import canonical_path, internal_path from .path_access import canonical_path, internal_path
def write_sources(project): def write_sources(project, *, strict=False):
project = canonical_path(project) project = canonical_path(project)
sources = {str(project).casefold()} sources = {str(project).casefold()}
try: try:
from .native_inventory_protocol import read_native_text from .native_inventory_protocol import read_native_text
text = read_native_text(internal_path(project)) text = read_native_text(internal_path(project))
if strict:
definitions = re.findall(r'^[ \t]*KEY[ \t]+iCDBDir\b([^\r\n]*)', text,
re.MULTILINE | re.IGNORECASE)
match = re.fullmatch(r'[ \t]+"([^"\r\n]+)"[ \t]*', definitions[0]) if len(definitions) == 1 else None
if not match:
raise ValueError('The iCDBDir write source must be declared once')
else:
match = re.search(r'^\s*KEY\s+iCDBDir\s+"([^"\r\n]+)"', text, re.MULTILINE | re.IGNORECASE) match = re.search(r'^\s*KEY\s+iCDBDir\s+"([^"\r\n]+)"', text, re.MULTILINE | re.IGNORECASE)
if match: if match:
directory = Path(match[1]) directory = Path(match[1])
@@ -19,7 +26,8 @@ def write_sources(project):
directory = project.parent / directory directory = project.parent / directory
sources.add(str(canonical_path(directory / 'icdb.dat')).casefold()) sources.add(str(canonical_path(directory / 'icdb.dat')).casefold())
except (OSError, UnicodeError, ValueError): except (OSError, UnicodeError, ValueError):
pass if strict:
raise
return sources return sources
@@ -3,6 +3,7 @@
from __future__ import annotations from __future__ import annotations
from collections.abc import Callable from collections.abc import Callable
from contextlib import contextmanager
from threading import Event from threading import Event
import os import os
@@ -10,20 +11,44 @@ from pathlib import Path
import stat import stat
from uuid import uuid4 from uuid import uuid4
from .errors import TaskCenterError from .errors import ProjectPathError, TaskCenterError
from .path_access import canonical_path, internal_path, strip_extended_prefix from .path_access import canonical_path, internal_path, strip_extended_prefix
from .models import TaskRecord, TaskStatus from .models import TaskRecord, TaskStatus
from .scanner import _is_schematic_project, _reject_reparse from .scanner import _is_schematic_project, _reject_reparse
from .store import TaskStore from .store import TaskStore
@contextmanager
def _path_errors(path: Path):
try:
yield
except FileNotFoundError as error:
raise ProjectPathError(
"path_missing", f"找不到路径「{path}」。请确认目录或工程是否已移动或删除,然后重新选择并读取。"
) from error
except PermissionError as error:
raise ProjectPathError(
"path_denied", f"无法读取路径「{path}」。请检查当前用户的读取权限,然后重试。"
) from error
except NotADirectoryError as error:
raise _not_directory(path) from error
def _not_directory(path: Path) -> ProjectPathError:
return ProjectPathError(
"path_not_directory", f"路径「{path}」中有一项不是目录。请选择工程目录后重试。"
)
def _validated_root(root: Path, excluded_roots: tuple[Path, ...]) -> tuple[Path, tuple[Path, ...]]: def _validated_root(root: Path, excluded_roots: tuple[Path, ...]) -> tuple[Path, tuple[Path, ...]]:
root = Path(os.path.abspath(strip_extended_prefix(root))) root = Path(os.path.abspath(strip_extended_prefix(root)))
with _path_errors(root):
for ancestor in (*reversed(root.parents), root): for ancestor in (*reversed(root.parents), root):
_reject_reparse(internal_path(ancestor).lstat(), ancestor) details = internal_path(ancestor).lstat()
_reject_reparse(details, ancestor)
if not stat.S_ISDIR(details.st_mode):
raise _not_directory(root)
root = canonical_path(root, strict=True) root = canonical_path(root, strict=True)
if not internal_path(root).is_dir():
raise TaskCenterError("discovery_root", "project root is not a directory")
excluded = tuple(canonical_path(path) for path in excluded_roots) excluded = tuple(canonical_path(path) for path in excluded_roots)
if any(root.is_relative_to(blocked) for blocked in excluded): if any(root.is_relative_to(blocked) for blocked in excluded):
raise TaskCenterError("discovery_root", "project root is inside an excluded directory") raise TaskCenterError("discovery_root", "project root is inside an excluded directory")
@@ -50,8 +75,9 @@ def scan_project_directory(root: Path, *, excluded_roots: tuple[Path, ...] = (),
while pending: while pending:
check_cancelled() check_cancelled()
directory = pending.pop() directory = pending.pop()
_reject_reparse(internal_path(directory).lstat(), directory)
children = [] children = []
with _path_errors(directory):
_reject_reparse(internal_path(directory).lstat(), directory)
with os.scandir(internal_path(directory)) as entries: with os.scandir(internal_path(directory)) as entries:
for entry in entries: for entry in entries:
check_cancelled() check_cancelled()
@@ -63,6 +89,7 @@ def scan_project_directory(root: Path, *, excluded_roots: tuple[Path, ...] = (),
path = Path(strip_extended_prefix(entry.path)) path = Path(strip_extended_prefix(entry.path))
if any(path.is_relative_to(blocked) for blocked in excluded): if any(path.is_relative_to(blocked) for blocked in excluded):
continue continue
with _path_errors(path):
details = entry.stat(follow_symlinks=False) details = entry.stat(follow_symlinks=False)
_reject_reparse(details, path) _reject_reparse(details, path)
if stat.S_ISDIR(details.st_mode): if stat.S_ISDIR(details.st_mode):
@@ -84,14 +111,18 @@ def _validate_selected(root: Path, selected_paths: tuple[Path, ...], excluded: t
ancestor_projects: dict[Path, bool] = {} ancestor_projects: dict[Path, bool] = {}
for candidate in selected_paths: for candidate in selected_paths:
path = Path(os.path.abspath(strip_extended_prefix(candidate))) path = Path(os.path.abspath(strip_extended_prefix(candidate)))
if not path.is_relative_to(root) or any(path.is_relative_to(blocked) for blocked in excluded): if path == root or not path.is_relative_to(root) or any(path.is_relative_to(blocked) for blocked in excluded):
raise TaskCenterError("project_selection", "selected project is outside discovery results") raise TaskCenterError("project_selection", "selected project is outside discovery results")
relative = path.relative_to(root) relative = path.relative_to(root)
cursor = root cursor = root
with _path_errors(path):
for part in relative.parts: for part in relative.parts:
cursor /= part cursor /= part
_reject_reparse(internal_path(cursor).lstat(), cursor) details = internal_path(cursor).lstat()
if not internal_path(path).is_file() or path.suffix.casefold() != ".prj" or not _is_schematic_project(path): _reject_reparse(details, cursor)
if cursor != path and not stat.S_ISDIR(details.st_mode):
raise _not_directory(path)
if not stat.S_ISREG(details.st_mode) or path.suffix.casefold() != ".prj" or not _is_schematic_project(path):
raise TaskCenterError("project_selection", "selected file is not a schematic project") raise TaskCenterError("project_selection", "selected file is not a schematic project")
# A project in any ancestor directory stops discovery below that directory. # A project in any ancestor directory stops discovery below that directory.
directory = path.parent directory = path.parent
@@ -99,11 +130,12 @@ def _validate_selected(root: Path, selected_paths: tuple[Path, ...], excluded: t
directory = directory.parent directory = directory.parent
if directory not in ancestor_projects: if directory not in ancestor_projects:
has_project = False has_project = False
with os.scandir(internal_path(directory)) as entries: with _path_errors(directory), os.scandir(internal_path(directory)) as entries:
for entry in entries: for entry in entries:
sibling = Path(strip_extended_prefix(entry.path)) sibling = Path(strip_extended_prefix(entry.path))
if sibling.suffix.casefold() != ".prj" or any(sibling.is_relative_to(b) for b in excluded): if sibling.suffix.casefold() != ".prj" or any(sibling.is_relative_to(b) for b in excluded):
continue continue
with _path_errors(sibling):
details = entry.stat(follow_symlinks=False) details = entry.stat(follow_symlinks=False)
_reject_reparse(details, sibling) _reject_reparse(details, sibling)
if stat.S_ISREG(details.st_mode) and _is_schematic_project(sibling): if stat.S_ISREG(details.st_mode) and _is_schematic_project(sibling):
@@ -112,6 +144,7 @@ def _validate_selected(root: Path, selected_paths: tuple[Path, ...], excluded: t
ancestor_projects[directory] = has_project ancestor_projects[directory] = has_project
if ancestor_projects[directory]: if ancestor_projects[directory]:
raise TaskCenterError("project_selection", "selected project is hidden by an ancestor project") raise TaskCenterError("project_selection", "selected project is hidden by an ancestor project")
with _path_errors(path):
selected.add(canonical_path(path, strict=True)) selected.add(canonical_path(path, strict=True))
return tuple(sorted(selected, key=lambda path: str(path).casefold())) return tuple(sorted(selected, key=lambda path: str(path).casefold()))
@@ -245,7 +245,8 @@ class TaskCenterService:
on_phase(BomImportPhase.READING, message) on_phase(BomImportPhase.READING, message)
if on_progress is not None: if on_progress is not None:
on_progress(message) on_progress(message)
rows = load_sources(sources, stop_event=stop_event, on_progress=on_progress, warnings = []
rows = load_sources(sources, stop_event=stop_event, on_progress=on_progress, warnings=warnings,
**({'allow_partial': True} if allow_partial else {})) **({'allow_partial': True} if allow_partial else {}))
scope = _scope(self._store, task_id) scope = _scope(self._store, task_id)
paths = tuple(project.path for _, project in scope) paths = tuple(project.path for _, project in scope)
@@ -278,7 +279,7 @@ class TaskCenterService:
reason = '位号在 BOM 中重复(' + ';'.join(locations) + ')' reason = '位号在 BOM 中重复(' + ';'.join(locations) + ')'
annotated.append(replace(row, source_file=str(source.source), source_row=source.excel_row, annotated.append(replace(row, source_file=str(source.source), source_row=source.excel_row,
reason=reason + f';来源:{source.source} 第 {source.excel_row} 行')) reason=reason + f';来源:{source.source} 第 {source.excel_row} 行'))
annotated_report = replace(report, rows=tuple(annotated), source_map_path=mapping) annotated_report = replace(report, rows=tuple(annotated), source_map_path=mapping, warnings=tuple(warnings))
return bind_source_report(annotated_report, return bind_source_report(annotated_report,
tuple(dict.fromkeys((str(row.source), row.source_sha256) for row in rows)), mapping) tuple(dict.fromkeys((str(row.source), row.source_sha256) for row in rows)), mapping)
@@ -290,7 +291,8 @@ class TaskCenterService:
write_routed_bom(normalized, rows, routes, project_names=names) write_routed_bom(normalized, rows, routes, project_names=names)
append_task_event(self._logging, level='INFO', task_id=task_id, append_task_event(self._logging, level='INFO', task_id=task_id,
operation='preview_bom_sources', message='BOM 导入来源记录已保存', operation='preview_bom_sources', message='BOM 导入来源记录已保存',
details={'source_map_path': str(mapping), 'source_count': len({row.source for row in rows})}) details={'source_map_path': str(mapping), 'source_count': len({row.source for row in rows}),
'warnings': warnings})
report = inspect_batch(self, task_id, normalized, stop_event=stop_event, report = inspect_batch(self, task_id, normalized, stop_event=stop_event,
on_progress=on_progress, on_phase=inspection_phase, runtime=runtime, on_progress=on_progress, on_phase=inspection_phase, runtime=runtime,
**({'allow_partial': True} if allow_partial else {})) **({'allow_partial': True} if allow_partial else {}))
@@ -1078,10 +1080,10 @@ class TaskCenterService:
return self._operation('force_pending_owned_resources', None, return self._operation('force_pending_owned_resources', None,
lambda: force_pending_owned_resources(self._logging.root, confirmed=confirmed)) lambda: force_pending_owned_resources(self._logging.root, confirmed=confirmed))
def cleanup_batch_resources(self): def cleanup_batch_resources(self, *, automatic=False):
"""Retry owned-resource release without opening or changing any project.""" """Retry owned-resource release without opening or changing any project."""
if self._supervised: if self._supervised:
result = self._supervise('cleanup_batch_resources', {}) self._supervise('cleanup_batch_resources', {'automatic': True} if automatic else {})
from .batch_supervisor import reconcile_supervisors from .batch_supervisor import reconcile_supervisors
reconcile_supervisors(self._logging.root) reconcile_supervisors(self._logging.root)
return self.pending_batch_resources() return self.pending_batch_resources()
@@ -1090,7 +1092,7 @@ class TaskCenterService:
assert_task_queue_idle(self._logging.root) assert_task_queue_idle(self._logging.root)
with _quick_run_lease(self._logging.root): with _quick_run_lease(self._logging.root):
return self._operation('cleanup_batch_resources', None, return self._operation('cleanup_batch_resources', None,
lambda: cleanup_pending_resources(self._logging.root, logging_context=self._logging, retry_failed=True)) lambda: cleanup_pending_resources(self._logging.root, logging_context=self._logging, retry_failed=not automatic))
def inspect_bom_batch(self, task_id: str, path: Path, *, stop_event=None, on_progress=None, on_phase=None, runtime=None): def inspect_bom_batch(self, task_id: str, path: Path, *, stop_event=None, on_progress=None, on_phase=None, runtime=None):
if runtime is None and self._supervised: if runtime is None and self._supervised:
@@ -0,0 +1,86 @@
"""Hold a data-root lock while the GUI owns its database and layout."""
from contextlib import contextmanager
import errno
import os
import time
from PySide6.QtNetwork import QLocalServer, QLocalSocket
from .path_access import internal_path
from .task_queue import _os_lock
class InstanceUnavailable(RuntimeError):
pass
@contextmanager
def gui_instance(data_root):
root = internal_path(data_root)
root.mkdir(parents=True, exist_ok=True)
# OS locks release on process death. Keep the file so every contender locks the same inode.
with (root / '.gui-instance.lock').open('a+b') as handle:
identity = os.fstat(handle.fileno())
endpoint = f'DxPartReplace-{identity.st_dev:x}-{identity.st_ino:x}'
deadline = time.monotonic() + 30
while True:
try:
_os_lock(handle, True)
break
except OSError as error:
if error.errno not in (errno.EACCES, errno.EAGAIN, errno.EDEADLK):
raise
if _activate(endpoint):
yield None
return
if time.monotonic() >= deadline:
raise InstanceUnavailable('此数据目录已在使用,现有窗口暂未响应。')
time.sleep(.05)
yield endpoint
def _activate(endpoint):
socket = QLocalSocket()
socket.connectToServer(endpoint)
if not socket.waitForConnected(100):
return False
if os.name == 'nt':
import ctypes
from ctypes import wintypes
pid = wintypes.DWORD()
get_pipe_pid = ctypes.windll.kernel32.GetNamedPipeServerProcessId
get_pipe_pid.argtypes = (wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD))
if get_pipe_pid(int(socket.socketDescriptor()), ctypes.byref(pid)):
ctypes.windll.user32.AllowSetForegroundWindow(pid.value)
socket.write(b'activate\n')
socket.flush()
return (socket.bytesAvailable() > 0 or socket.waitForReadyRead(1000)) and socket.readAll() == b'1'
def listen_for_activation(endpoint, activate):
server = QLocalServer()
server.setSocketOptions(QLocalServer.SocketOption.UserAccessOption)
if os.name != 'nt':
QLocalServer.removeServer(endpoint) # The lock owner can remove a crashed owner's socket.
if not server.listen(endpoint):
raise RuntimeError(server.errorString())
def accept():
while server.hasPendingConnections():
socket = server.nextPendingConnection()
def respond(socket=socket):
if socket.canReadLine() and socket.readLine() == b'activate\n':
activate()
socket.write(b'1')
socket.flush()
socket.disconnectFromServer()
socket.disconnected.connect(socket.deleteLater)
socket.readyRead.connect(respond)
respond()
server.newConnection.connect(accept)
return server
@@ -183,9 +183,76 @@ def reconcile_interrupted_queue(root, journal):
_save(path, state) _save(path, state)
def resource_pause_admitted(root, batch_id, task_ids, plan_hashes, result=None, *, require_released=True):
"""Bind a completed supervisor's resource pause to the frozen queue."""
from .batch_resources import _process_gone, blocking_resources
from .batch_supervisor import pending_supervisors
from .path_access import canonical_path, internal_path
from .supervisor_protocol import MessageGate, decode, valid_journal
def token(value):
return isinstance(value, str) and len(value) == 32 and all(c in '0123456789abcdef' for c in value)
if not token(batch_id) or not plan_hashes:
return False
root = canonical_path(root)
directory = internal_path(root / 'batch-resources' / batch_id)
try:
journal = json.loads((directory / 'supervisor.json').read_bytes())
if (not valid_journal(journal, batch_id) or journal['state'] not in {'blocked', 'finished'}
or journal['operation'] != 'execute_task_queue' or journal['task_ids'] != list(task_ids)
or not journal['process'] or 'stop_requested_at' in journal
or journal.get('stop_mode') in {'safe', 'forced'} or (directory / 'cancel.json').exists()):
return False
raw_request = (directory / 'request.json').read_bytes()
request = json.loads(raw_request)
arguments = decode(request['arguments'])
if (hashlib.sha256(raw_request).hexdigest() != journal['request_sha256']
or request['batch_id'] != batch_id or request['attempt_id'] != journal['attempt_id']
or request['operation'] != journal['operation'] or canonical_path(request['root']) != root
or list(arguments['task_ids']) != list(task_ids) or arguments['expected_plan_hashes'] != plan_hashes):
return False
message = json.loads((directory / 'result.json').read_bytes())
if not MessageGate(batch_id, journal['attempt_id']).accept(message) or message['type'] != 'result':
return False
payload = message['payload']
recorded = decode(payload['result'])
if (payload['business_succeeded'] is not True or not isinstance(recorded, TaskQueueResult)
or result is not None and recorded != result or not recorded.paused
or not token(recorded.queue_id) or recorded.current_task_id not in task_ids
or (arguments['queue_id'] or arguments['checkpoint_id']) != recorded.queue_id):
return False
result = recorded
checkpoint = internal_path(root / 'task-queues' / (result.queue_id + '.json'))
state = json.loads(checkpoint.read_bytes())
current = result.current_task_id
if (state['version'] != 1 or state['task_ids'] != list(task_ids) or state['plan_hashes'] != plan_hashes
or state['phase'] != 'primary' or set(state['entries']) != set(task_ids)
or list(entry.task_id for entry in result.entries) != list(task_ids)
or any(state['entries'][entry.task_id]['state'] != entry.state for entry in result.entries)
or state['entries'][current]['state'] != 'blocked'
or any(entry.state in {'paused', 'running'} for entry in result.entries)
or not any(state['entries'][item]['state'] == 'pending' for item in task_ids[task_ids.index(current) + 1:])):
return False
if batch_id in state.get('consumed_resource_pauses', {}):
return False
warning = payload.get('resource_warning') or {}
pause = state.get('resource_pause') or {}
intended = ((pause.get('task_id'), pause.get('batch_id')) == (current, batch_id)
and isinstance(pause.get('sources'), dict)
and set(pause['sources']) == set(task_ids)
or not pause and warning.get('state') == 'isolated' and warning.get('owned_writers_exited') is True)
if intended and (not require_released or (journal['state'] == 'finished'
and _process_gone(journal['process']) and not blocking_resources(root) and not pending_supervisors(root))):
return result
return False
except (OSError, ValueError, TypeError, KeyError, AttributeError):
return False
def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event, def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
queue_id: str | None = None, runtime=None, expected_plan_hashes=None, checkpoint_id=None, queue_id: str | None = None, runtime=None, expected_plan_hashes=None, checkpoint_id=None,
defer_problem_pass=False) -> TaskQueueResult: defer_problem_pass=False, resource_batch_id=None) -> TaskQueueResult:
"""Execute the frozen order; uncertain state stops before the next project.""" """Execute the frozen order; uncertain state stops before the next project."""
if runtime is None and getattr(service, '_supervised', False): if runtime is None and getattr(service, '_supervised', False):
# Existing per-project checkpoints keep their original resume owner. # Existing per-project checkpoints keep their original resume owner.
@@ -196,9 +263,30 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
return execute_workspace_projects(service, task_ids, queue_id=queue_id, stop_event=stop_event, return execute_workspace_projects(service, task_ids, queue_id=queue_id, stop_event=stop_event,
expected_plan_hashes=expected_plan_hashes, checkpoint_id=checkpoint_id, expected_plan_hashes=expected_plan_hashes, checkpoint_id=checkpoint_id,
defer_problem_pass=defer_problem_pass) defer_problem_pass=defer_problem_pass)
return service._supervise('execute_task_queue', {'task_ids': tuple(task_ids), arguments = {'task_ids': tuple(task_ids),
'queue_id': queue_id, 'expected_plan_hashes': expected_plan_hashes, 'queue_id': queue_id, 'expected_plan_hashes': expected_plan_hashes,
'checkpoint_id': checkpoint_id, 'defer_problem_pass': defer_problem_pass}, stop_event=stop_event) 'checkpoint_id': checkpoint_id, 'defer_problem_pass': defer_problem_pass}
if resource_batch_id:
arguments['resource_batch_id'] = resource_batch_id
recovered = set()
while True:
try:
result = service._supervise('execute_task_queue', arguments, stop_event=stop_event)
except TaskCenterError as error:
result = getattr(error, 'completed_result', None)
batch_id = getattr(service, '_last_supervisor_batch_id', None)
if (error.code not in {'batch_resources_pending', 'application_shutdown_failed'}
or stop_event.is_set() or not isinstance(result, TaskQueueResult)
or not resource_pause_admitted(service._logging.root, batch_id, tuple(task_ids),
expected_plan_hashes, result, require_released=False)):
raise
if (not result.paused or stop_event.is_set() or result.current_task_id in recovered
or not resource_pause_admitted(service._logging.root,
batch_id := getattr(service, '_last_supervisor_batch_id', None), tuple(task_ids),
expected_plan_hashes, result)):
return result
recovered.add(result.current_task_id)
arguments = dict(arguments, queue_id=result.queue_id, checkpoint_id=None, resource_batch_id=batch_id)
if runtime is None: if runtime is None:
from .batch_runtime import BatchCadRuntime from .batch_runtime import BatchCadRuntime
with BatchCadRuntime(service._logging.root, 'task_queue', stop_event) as owned_runtime: with BatchCadRuntime(service._logging.root, 'task_queue', stop_event) as owned_runtime:
@@ -213,7 +301,7 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
root = service._logging.root root = service._logging.root
with _queue_lease(root): with _queue_lease(root):
children = {task_id: service.for_project_task(task_id) for task_id in ids} children = {task_id: service.for_project_task(task_id) for task_id in ids}
project_paths = [] project_paths, projects_by_task = [], {}
sources = {} sources = {}
for task_id, child in children.items(): for task_id, child in children.items():
task = child.get_task(task_id) task = child.get_task(task_id)
@@ -221,9 +309,14 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
if not getattr(task, 'primary_project_id', None) or len(projects) != 1: if not getattr(task, 'primary_project_id', None) or len(projects) != 1:
raise TaskCenterError('project_binding', '顺序执行仅支持绑定单个工程的任务。') raise TaskCenterError('project_binding', '顺序执行仅支持绑定单个工程的任务。')
project_paths.append(str(projects[0].path.resolve(strict=False)).casefold()) project_paths.append(str(projects[0].path.resolve(strict=False)).casefold())
projects_by_task[task_id] = projects[0].path
sources[task_id] = write_sources(projects[0].path) sources[task_id] = write_sources(projects[0].path)
if len(set(project_paths)) != len(ids): if len(set(project_paths)) != len(ids):
raise TaskCenterError('task_queue_selection', '不能在同一队列重复处理同一个工程。') raise TaskCenterError('task_queue_selection', '不能在同一队列重复处理同一个工程。')
try:
frozen_sources = {item: sorted(write_sources(projects_by_task[item], strict=True)) for item in ids}
except (OSError, UnicodeError, ValueError):
frozen_sources = None
runtime.bind_logs(service._logging, ids) runtime.bind_logs(service._logging, ids)
hashes = {task_id: _plan_hash(child, task_id) for task_id, child in children.items()} hashes = {task_id: _plan_hash(child, task_id) for task_id, child in children.items()}
if expected_plan_hashes is not None and hashes != expected_plan_hashes: if expected_plan_hashes is not None and hashes != expected_plan_hashes:
@@ -260,6 +353,29 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
isolated_tasks = state.setdefault('isolated_tasks', {}) isolated_tasks = state.setdefault('isolated_tasks', {})
isolated_sources = state.setdefault('isolated_sources', {}) isolated_sources = state.setdefault('isolated_sources', {})
dependency_tasks = state.setdefault('dependency_tasks', {}) dependency_tasks = state.setdefault('dependency_tasks', {})
if resource_batch_id:
evidence = resource_pause_admitted(root, resource_batch_id, ids, hashes)
if not evidence or evidence.queue_id != queue_id:
raise TaskCenterError('task_queue_state', '原队列的资源释放或阻断回执无法核验。')
item = evidence.current_task_id
if not children[item].has_interrupted_quick_run(item):
raise TaskCenterError('task_queue_state', '阻断工程缺少原待核验证据。')
pause = state.get('resource_pause')
if pause:
known_sources = pause['sources']
else:
before = (state.get('netlist_verification', {}).get(item, {}).get('before') or {})
known = [str(Path(name).resolve()).casefold() for name in before.get('source_hashes', {})
if Path(name).suffix.casefold() == '.prj' or Path(name).name.casefold() == 'icdb.dat']
known_sources = {item: sorted(known)}
if not frozen_sources or any(frozen_sources.get(task) != values for task, values in known_sources.items()):
raise TaskCenterError('task_queue_state', '工程写入源已变化或无法核验,须重新确认。')
sources = {task: set(values) for task, values in frozen_sources.items()}
isolated_tasks[item] = state['entries'][item]['message']
isolated_sources.update((source, item) for source in sources[item])
state.setdefault('consumed_resource_pauses', {})[resource_batch_id] = item
state.pop('resource_pause', None)
_save(path, state)
from .netlist_verification import NetlistVerification from .netlist_verification import NetlistVerification
checks = NetlistVerification(root, token, stop_event) checks = NetlistVerification(root, token, stop_event)
try: try:
@@ -289,6 +405,7 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
continue continue
if state['entries'][task_id]['state'] in _TERMINAL: if state['entries'][task_id]['state'] in _TERMINAL:
if state['entries'][task_id]['state'] == 'completed': if state['entries'][task_id]['state'] == 'completed':
if not resource_batch_id or task_id not in state.get('netlist_verification', {}):
checks.before_task(children[task_id], task_id, existing_only=True) checks.before_task(children[task_id], task_id, existing_only=True)
continue continue
if stop_event.is_set(): if stop_event.is_set():
@@ -409,6 +526,11 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
execution_summary={key: getattr(progress, key, None) execution_summary={key: getattr(progress, key, None)
for key in ('saved_items', 'failed_items', 'no_match_items')}) for key in ('saved_items', 'failed_items', 'no_match_items')})
if paused: if paused:
if (entry['state'] == 'blocked' and not stop_event.is_set()
and frozen_sources and hasattr(runtime, 'session_id')):
state['resource_pause'] = {'task_id': task_id, 'batch_id': runtime.session_id,
'sources': frozen_sources}
_save(path, state)
break break
if (not paused and stop_event.is_set() and state.get('phase') != 'finished' if (not paused and stop_event.is_set() and state.get('phase') != 'finished'
and any(entry['state'] == 'failed' for entry in state['entries'].values())): and any(entry['state'] == 'failed' for entry in state['entries'].values())):
@@ -4,7 +4,7 @@ from threading import Event
from ..stop_control import StopControl from ..stop_control import StopControl
from shiboken6 import isValid from shiboken6 import isValid
import time import time
from PySide6.QtCore import QElapsedTimer, QSettings, QSignalBlocker, QThreadPool, QTimer, Qt from PySide6.QtCore import QByteArray, QElapsedTimer, QRect, QSettings, QSignalBlocker, QThreadPool, QTimer, Qt
from PySide6.QtGui import QAction, QActionGroup from PySide6.QtGui import QAction, QActionGroup
from PySide6.QtWidgets import (QApplication, QCheckBox, QDialog, QFileDialog, QHBoxLayout, QMessageBox, from PySide6.QtWidgets import (QApplication, QCheckBox, QDialog, QFileDialog, QHBoxLayout, QMessageBox,
QPushButton, QLabel, QSizePolicy, QSplitter, QStackedWidget, QTabWidget, QToolButton, QVBoxLayout, QWidget) QPushButton, QLabel, QSizePolicy, QSplitter, QStackedWidget, QTabWidget, QToolButton, QVBoxLayout, QWidget)
@@ -122,6 +122,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self._batch_stop = None self._batch_stop = None
self._active_quick_run_task_id = None self._active_quick_run_task_id = None
self._project_queues = {} self._project_queues = {}
self._resource_queue_resume = None
self._execution_after_save = None self._execution_after_save = None
self._generation = 0 self._generation = 0
self._message = '' self._message = ''
@@ -184,6 +185,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self.archive_on_close_check.setToolTip('默认关闭。仅归档安全任务,保留计划、日志和文件;待核验或资源未释放的任务保留在当前列表。') self.archive_on_close_check.setToolTip('默认关闭。仅归档安全任务,保留计划、日志和文件;待核验或资源未释放的任务保留在当前列表。')
self._build_layout() self._build_layout()
self._layout_settings = QSettings(str(service.layout_settings_path), QSettings.Format.IniFormat) self._layout_settings = QSettings(str(service.layout_settings_path), QSettings.Format.IniFormat)
self._restore_window_geometry()
self.auto_intervention_check.setChecked(self._layout_settings.value( self.auto_intervention_check.setChecked(self._layout_settings.value(
'dsh/auto_intervention', True, type=bool)) 'dsh/auto_intervention', True, type=bool))
self.auto_intervention_check.toggled.connect(self._set_auto_intervention) self.auto_intervention_check.toggled.connect(self._set_auto_intervention)
@@ -214,6 +216,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self._dsh_stall_timer.start() self._dsh_stall_timer.start()
self._resource_status.changed.connect(self._update_gates) self._resource_status.changed.connect(self._update_gates)
self._resource_status.changed.connect(self._observe_dsh_resource_blockers) self._resource_status.changed.connect(self._observe_dsh_resource_blockers)
self._resource_status.changed.connect(self._resume_resource_queue)
self._resource_status.refresh() self._resource_status.refresh()
self._refresh_task_list() self._refresh_task_list()
self._update_gates() self._update_gates()
@@ -319,6 +322,34 @@ class TrialTaskCenterWindow(MaterialMainWindow):
return {'workspace': self.workspace_splitter, 'detail': self.detail_splitter, return {'workspace': self.workspace_splitter, 'detail': self.detail_splitter,
'rules': self.mapping_table.horizontalHeader(), 'targets': self.plan_panel.table.horizontalHeader()} 'rules': self.mapping_table.horizontalHeader(), 'targets': self.plan_panel.table.horizontalHeader()}
def _restore_window_geometry(self):
saved = self._layout_settings.value('main_window/geometry')
if saved is None:
return
default = self.geometry()
restored = isinstance(saved, QByteArray) and self.restoreGeometry(saved)
normal = self.normalGeometry() if restored else default
screen = QApplication.screenAt(normal.center()) if restored else None
screen = screen or QApplication.primaryScreen()
if screen is None:
return
available = screen.availableGeometry()
if restored and available.contains(normal) and normal.size().expandedTo(self.minimumSize()) == normal.size():
return
# Qt may reject a saved geometry after a DPI change. Keep the normal
# window reachable on the current display, even when its minimum exceeds it.
available = available.adjusted(8, 36, -8, -8)
state = self.windowState()
self.setWindowState(Qt.WindowState.WindowNoState)
size = normal.size().boundedTo(available.size()).expandedTo(self.minimumSize())
fallback = QRect(available.topLeft(), size)
fallback.moveCenter(available.center())
fallback.moveLeft(max(fallback.left(), available.left()))
fallback.moveTop(max(fallback.top(), available.top()))
self.setGeometry(fallback)
self.setWindowState(state)
def _reset_layout(self): def _reset_layout(self):
self.workspace_splitter.setSizes((240, 1040)) self.workspace_splitter.setSizes((240, 1040))
self.detail_splitter.setSizes((650, 110)) self.detail_splitter.setSizes((650, 110))
@@ -416,9 +447,11 @@ class TrialTaskCenterWindow(MaterialMainWindow):
QTimer.singleShot(100, self.close) QTimer.singleShot(100, self.close)
return return
self._cancel_dsh_diagnosis() self._cancel_dsh_diagnosis()
self._layout_settings.setValue('main_window/geometry', self.saveGeometry())
for name, widget in self._layout_widgets().items(): for name, widget in self._layout_widgets().items():
self._layout_settings.setValue(f'single_project/{name}', widget.saveState()) self._layout_settings.setValue(f'single_project/{name}', widget.saveState())
self._layout_settings.setValue('tasks/sort', self.task_list.sort.currentData()) self._layout_settings.setValue('tasks/sort', self.task_list.sort.currentData())
self._layout_settings.sync()
self._closed = True self._closed = True
self._dsh_status.close() self._dsh_status.close()
self._dsh_stall_timer.stop() self._dsh_stall_timer.stop()
@@ -869,7 +902,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self._bind_dsh_context() self._bind_dsh_context()
self._run_async(execute, done, self.run_panel.quick_run_button, expected_task_id=task_id) self._run_async(execute, done, self.run_panel.quick_run_button, expected_task_id=task_id)
def _execute_project_tasks(self): def _execute_project_tasks(self, *, resource_resume=False):
if not self.task_list.queue_button.isEnabled(): if not self.task_list.queue_button.isEnabled():
return return
owner_task_id = self._context.task.task_id owner_task_id = self._context.task.task_id
@@ -885,7 +918,10 @@ class TrialTaskCenterWindow(MaterialMainWindow):
try: try:
if token: if token:
from ...dsh.run_journal import resume_preflight from ...dsh.run_journal import resume_preflight
report = resume_preflight(self.service, self._dsh_operations.runs.inspect(self.service, token)) inspected = self._dsh_operations.runs.inspect(self.service, token)
if resource_resume and not inspected.get('resource_batch_id'):
return
report = resume_preflight(self.service, inspected)
else: else:
report = lifecycle.preflight(self.service, list(ids), allow_completed=True) report = lifecycle.preflight(self.service, list(ids), allow_completed=True)
except Exception as error: except Exception as error:
@@ -895,7 +931,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
return return
self._dsh_confirmation_impact = report.get('impact', {}) self._dsh_confirmation_impact = report.get('impact', {})
enabled = report.get('impact', {}).get('enabled_scope', 0) enabled = report.get('impact', {}).get('enabled_scope', 0)
if not self._quick_run_confirmer('batch', len(ids), enabled): if not resource_resume and not self._quick_run_confirmer('batch', len(ids), enabled):
return return
if not self._confirmed_execution_allowed(owner_task_id, ids, self.task_list.queue_button): if not self._confirmed_execution_allowed(owner_task_id, ids, self.task_list.queue_button):
return return
@@ -941,9 +977,30 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self._show_receipt_verification(receipt) self._show_receipt_verification(receipt)
self._dsh_last_execution = receipt self._dsh_last_execution = receipt
self._bind_dsh_context() self._bind_dsh_context()
if (result.paused and receipt.get('resource_batch_id') and not stop.is_set()
and not self._close_pending and not self._closed):
self._resource_queue_resume = (group, result.queue_id, ids)
else: else:
done(value) done(value)
self._run_async(execute, completed, self.task_list.queue_button) self._run_async(execute, completed, self.task_list.queue_button, on_finished=self._check_resource_queue)
def _check_resource_queue(self):
if self._resource_queue_resume and self._resource_status.blocked and not self._workers:
self._cleanup_batch_resources(automatic=True)
else:
self._resume_resource_queue()
def _resume_resource_queue(self):
pending = self._resource_queue_resume
if (not pending or self._closed or self._close_pending or self._workers or self._loading
or self._resource_status.busy or not self._resource_status.known or self._resource_status.blocked):
return
group, token, ids = pending
if (self._context is None or self._context.task.group_id != group
or self._project_queues.get(group) != (token, ids) or self.plan_panel.has_unsaved_plan(ids)):
return
self._resource_queue_resume = None
self._execute_project_tasks(resource_resume=True)
def _begin_run(self, task_id): def _begin_run(self, task_id):
from uuid import uuid4 from uuid import uuid4
@@ -1032,11 +1089,13 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self._close_pending = False self._close_pending = False
self._set_operator_message(self.run_panel.operator_band.text() + '\n' + details, 'warning') self._set_operator_message(self.run_panel.operator_band.text() + '\n' + details, 'warning')
def _cleanup_batch_resources(self): def _cleanup_batch_resources(self, *, automatic=False):
if not self.run_panel.cleanup_resources_button.isEnabled(): if not automatic and not self.run_panel.cleanup_resources_button.isEnabled():
return return
state = getattr(self.service, '_supervisor_dialog_state', None) or {} state = getattr(self.service, '_supervisor_dialog_state', None) or {}
if (state.get('supervision') or {}).get('blocked'): if (state.get('supervision') or {}).get('blocked'):
if automatic:
return
from .cad_dialog_operations import show_cad_dialogs from .cad_dialog_operations import show_cad_dialogs
show_cad_dialogs(self) show_cad_dialogs(self)
self._update_gates() self._update_gates()
@@ -1054,6 +1113,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
nonlocal cleanup_finished nonlocal cleanup_finished
cleanup_finished = True cleanup_finished = True
start_force_if_ready() start_force_if_ready()
self._resume_resource_queue()
def forced(remaining): def forced(remaining):
from ..batch_resources import resource_blockers from ..batch_resources import resource_blockers
self._resource_status.refresh() self._resource_status.refresh()
@@ -1077,7 +1137,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
else: else:
self._dsh_blockers.clear('resource-release') self._dsh_blockers.clear('resource-release')
self._update_gates() self._update_gates()
if pending and not any(row.get('force_available', True) for row in pending): if automatic or pending and not any(row.get('force_available', True) for row in pending):
return return
if pending and QMessageBox.question(self, '强制结束自有残留进程', if pending and QMessageBox.question(self, '强制结束自有残留进程',
'安全释放尚未完成。是否强制结束本程序仍持有且能证明归属的残留进程?\n\n' '安全释放尚未完成。是否强制结束本程序仍持有且能证明归属的残留进程?\n\n'
@@ -1087,7 +1147,8 @@ class TrialTaskCenterWindow(MaterialMainWindow):
force_confirmed = True force_confirmed = True
# A modal question can deliver finished before returning Yes. # A modal question can deliver finished before returning Yes.
start_force_if_ready() start_force_if_ready()
self._run_async(self.service.cleanup_batch_resources, done, cleanup = (lambda: self.service.cleanup_batch_resources(automatic=True)) if automatic else self.service.cleanup_batch_resources
self._run_async(cleanup, done,
self.run_panel.cleanup_resources_button, operation_area='resources', on_finished=after_cleanup) self.run_panel.cleanup_resources_button, operation_area='resources', on_finished=after_cleanup)
def _startup_resource_recheck(self): def _startup_resource_recheck(self):
@@ -1096,9 +1157,9 @@ class TrialTaskCenterWindow(MaterialMainWindow):
if self._workers or self._loading or not self._resource_status.known or self._resource_status.busy: if self._workers or self._loading or not self._resource_status.known or self._resource_status.busy:
QTimer.singleShot(250, self._startup_resource_recheck) QTimer.singleShot(250, self._startup_resource_recheck)
return return
if self._resource_status.blocked: if self._resource_status.records:
self._update_gates() self._update_gates()
self._cleanup_batch_resources() # Resource-only; never resumes a queue. self._cleanup_batch_resources(automatic=True)
def _export_diagnostics(self): def _export_diagnostics(self):
from pathlib import Path from pathlib import Path
@@ -3,6 +3,8 @@ from datetime import datetime
import json import json
import re import re
from ..errors import ProjectPathError
ERROR_TEXT = { ERROR_TEXT = {
"dsh_startup": "DSH助手启动失败,请检查发布包中的运行时和 Node.js。", "dsh_startup": "DSH助手启动失败,请检查发布包中的运行时和 Node.js。",
'user_forced_stop': '操作已强制中断,结果待核验。', 'user_forced_stop': '操作已强制中断,结果待核验。',
@@ -57,6 +59,8 @@ ERROR_TEXT = {
def format_operation_error(error): def format_operation_error(error):
if isinstance(error, ProjectPathError):
return f'{error.message}\n错误代码:{error.code} · 错误编号:{error.error_id}'
title = ERROR_TEXT.get(error.code, '操作未完成') title = ERROR_TEXT.get(error.code, '操作未完成')
report = getattr(error, 'bom_report', None) report = getattr(error, 'bom_report', None)
if report is not None: if report is not None:
@@ -19,6 +19,8 @@ from .workers import ServiceWorker
from .operation_state import OperationPhase from .operation_state import OperationPhase
from .command_menu import CommandMenu from .command_menu import CommandMenu
from .icons import icon from .icons import icon
from .messages import format_operation_error
from ..errors import ProjectPathError
from ..bom_import_state import BomImportMachine, BomImportPhase, BomImportState from ..bom_import_state import BomImportMachine, BomImportPhase, BomImportState
from ..bom_pending import retained_bom_rows from ..bom_pending import retained_bom_rows
@@ -44,6 +46,9 @@ class DirectoryTaskDialog(QDialog):
self.scan = QPushButton('读取工程', objectName='readTaskProjects') self.scan = QPushButton('读取工程', objectName='readTaskProjects')
self.projects = QListWidget(objectName='taskProjectCandidates') self.projects = QListWidget(objectName='taskProjectCandidates')
self.summary = QLabel('先读取工程,再勾选需要创建任务的项目。') self.summary = QLabel('先读取工程,再勾选需要创建任务的项目。')
self.summary.setWordWrap(True)
self.summary.setTextFormat(Qt.TextFormat.PlainText)
self.summary.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
self.buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) self.buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
self.buttons.button(QDialogButtonBox.StandardButton.Ok).setText('创建任务') self.buttons.button(QDialogButtonBox.StandardButton.Ok).setText('创建任务')
self.buttons.button(QDialogButtonBox.StandardButton.Ok).setEnabled(False) self.buttons.button(QDialogButtonBox.StandardButton.Ok).setEnabled(False)
@@ -137,6 +142,9 @@ class DirectoryTaskDialog(QDialog):
if self._closed: if self._closed:
return return
self._scanned_root = None self._scanned_root = None
if isinstance(error, ProjectPathError):
self.summary.setText(format_operation_error(error))
else:
self.summary.setText(getattr(error, 'message', str(error))) self.summary.setText(getattr(error, 'message', str(error)))
def _finished(self): def _finished(self):
@@ -779,21 +787,22 @@ class ProjectPlanPanel(QWidget):
report = state.report report = state.report
if report is None: if report is None:
return '', '', '' return '', '', ''
warning_summary = f' · 警告 {len(report.warnings)} 项' if report.warnings else ''
if report.deferred: if report.deferred:
failed_paths = {row.project_path for row in report.rows if row.status == 'failed'} failed_paths = {row.project_path for row in report.rows if row.status == 'failed'}
accepted = tuple(row for row in report.rows if row.project_path not in failed_paths) accepted = tuple(row for row in report.rows if row.project_path not in failed_paths)
summary = (f'BOM 表格已保存,工程位号待核验:{len(accepted)} 行、' summary = (f'BOM 表格已保存,工程位号待核验:{len(accepted)} 行、'
f'{len({row.project_path for row in accepted})} 个工程;失败 {report.failed_rows} 行。') f'{len({row.project_path for row in accepted})} 个工程;失败 {report.failed_rows} 行{warning_summary}。')
details = [summary, '确认执行后仅核验当前工程;本次导入未读取工程位号。'] details = [summary, *report.warnings, '确认执行后仅核验当前工程;本次导入未读取工程位号。']
details.extend(f'{row.project_name} · {Path(row.source_file).name} 第 {row.source_row} 行:{row.reason}' details.extend(f'{row.project_name} · {Path(row.source_file).name} 第 {row.source_row} 行:{row.reason}'
for row in report.rows) for row in report.rows)
return summary, '\n'.join(details), 'BOM 已保存 · 待核验 · 详情' return summary, '\n'.join(details), f'BOM 已保存 · 待核验{warning_summary} · 详情'
outcome = '校验通过' if state.phase is BomImportPhase.PREVIEW_READY else '校验未通过' outcome = '校验通过' if state.phase is BomImportPhase.PREVIEW_READY else '校验未通过'
summary = (f'BOM {outcome}:共 {report.total_rows} 行,通过 {report.passed_rows} 行、' summary = (f'BOM {outcome}:共 {report.total_rows} 行,通过 {report.passed_rows} 行、'
f'失败 {report.failed_rows} 行、未检查 {report.unchecked_rows} 行;' f'失败 {report.failed_rows} 行、未检查 {report.unchecked_rows} 行;'
f'共 {report.total_projects} 个工程,通过 {report.passed_projects} 个、' f'共 {report.total_projects} 个工程,通过 {report.passed_projects} 个、'
f'失败 {report.failed_projects} 个、未检查 {report.unchecked_projects} 个。') f'失败 {report.failed_projects} 个、未检查 {report.unchecked_projects} 个{warning_summary}。')
details = [summary, *report.errors] details = [summary, *report.errors, *report.warnings]
if report.source_map_path is not None: if report.source_map_path is not None:
details.append(f'导入来源记录:{report.source_map_path}') details.append(f'导入来源记录:{report.source_map_path}')
details.extend(f'{Path(row.source_file).name + " · " if row.source_file else ""}' details.extend(f'{Path(row.source_file).name + " · " if row.source_file else ""}'
@@ -79,6 +79,10 @@ class TaskList(QWidget):
self.recycle_button = QPushButton('回收站', objectName='taskRecycleBin') self.recycle_button = QPushButton('回收站', objectName='taskRecycleBin')
self.recycle_button.setCheckable(True) self.recycle_button.setCheckable(True)
self.count = QLabel(objectName='taskCount') self.count = QLabel(objectName='taskCount')
self.empty_hint = QLabel(objectName='taskEmptyHint')
self.empty_hint.setTextFormat(Qt.TextFormat.PlainText)
self.empty_hint.setWordWrap(True)
self.empty_hint.hide()
self.filter = QComboBox(objectName="taskFilter") self.filter = QComboBox(objectName="taskFilter")
for label, key, picture in (('全部任务', 'all', 'grid'), ('未完成', 'unfinished', 'clock'), for label, key, picture in (('全部任务', 'all', 'grid'), ('未完成', 'unfinished', 'clock'),
('待开始', 'pending', 'clock'), ('执行中', 'running', 'clock'), ('待开始', 'pending', 'clock'), ('执行中', 'running', 'clock'),
@@ -146,6 +150,7 @@ class TaskList(QWidget):
layout.addWidget(self.filter) layout.addWidget(self.filter)
layout.addLayout(batch) layout.addLayout(batch)
layout.addLayout(selection) layout.addLayout(selection)
layout.addWidget(self.empty_hint)
layout.addWidget(self.list, 1) layout.addWidget(self.list, 1)
layout.addWidget(self.queue_button) layout.addWidget(self.queue_button)
layout.addLayout(footer) layout.addLayout(footer)
@@ -254,6 +259,17 @@ class TaskList(QWidget):
if getattr(task, "task_id") == selected: if getattr(task, "task_id") == selected:
self.list.setCurrentItem(item) self.list.setCurrentItem(item)
hidden = selected and self.current_task_id() is None hidden = selected and self.current_task_id() is None
self.count.setText(f'{len(tasks)} / {len(self._tasks)} 个任务' + (' · 当前任务已隐藏' if hidden else '')) if not tasks:
category_text = self.filter.currentText() if category != 'all' and not self.recycle_button.isChecked() else ''
if not self._tasks:
hint = '回收站为空。' if self.recycle_button.isChecked() else '暂无任务,点击“新建任务”导入工程。'
elif query:
scope = f'“{category_text}”中' if category_text else ''
hint = f'{scope}未找到与“{self.search.text().strip()}”匹配的任务。'
else:
hint = f'暂无“{category_text}”任务。'
self.empty_hint.setText(hint)
self.empty_hint.setVisible(not tasks)
self.count.setText(f'匹配 {len(tasks)} / 共 {len(self._tasks)} 个任务' + (' · 当前任务已隐藏' if hidden else ''))
self._update_selection_state() self._update_selection_state()
self.view_changed.emit() self.view_changed.emit()
@@ -1 +1 @@
VERSION = "1.3.1" VERSION = "1.3.3-beta.1"
@@ -1,11 +1,13 @@
"""Safe multi-file BOM loading and project routing for workspace imports.""" """Safe multi-file BOM loading and project routing for workspace imports."""
from dataclasses import dataclass from dataclasses import dataclass
from difflib import get_close_matches
import hashlib import hashlib
from pathlib import Path, PureWindowsPath from pathlib import Path, PureWindowsPath
from openpyxl import load_workbook from openpyxl import load_workbook
from .bom_import_report import BomImportReport, BomInspectionError
from .bom_plan import BOM_HEADERS, _normal_headers, _part_number_text, write_bom_template from .bom_plan import BOM_HEADERS, _normal_headers, _part_number_text, write_bom_template
from .errors import TaskCenterError from .errors import TaskCenterError
@@ -55,7 +57,37 @@ def _selected_xlsx(sources):
return tuple(sorted(paths, key=lambda path: str(path).casefold())) return tuple(sorted(paths, key=lambda path: str(path).casefold()))
def load_sources(sources, *, stop_event=None, on_progress=None, allow_partial=False): _REQUIRED_HEADERS = (
('old_part_number', '旧料号'), ('new_part_number', '新料号'), ('refdes', '位号'),
)
def _source_headers(path, cells):
headers = _normal_headers(tuple(cell.value for cell in cells))
names = tuple(name for name in headers if name)
unknown = tuple(str(cell.value).strip() for cell, name in zip(cells, headers, strict=True)
if not name and cell.value is not None and str(cell.value).strip())
if any(cell.data_type == 'f' for cell in cells):
reason = 'BOM 表头不接受公式'
elif len(names) != len(set(names)):
reason = 'BOM 列名重复'
else:
missing = [(name, label) for name, label in _REQUIRED_HEADERS if name not in names]
if not missing:
return {name: index for index, name in enumerate(headers) if name}, unknown
labels = '、'.join(label for _, label in missing)
hints = []
for name, label in missing:
matches = (get_close_matches(label, unknown, n=1, cutoff=.7)
or get_close_matches(name, unknown, n=1, cutoff=.8))
if matches:
hints.append(f'请将「{matches[0]}」改为「{label}」')
reason = '。'.join([f'BOM 缺少必需列「{labels}」', *hints])
message = f'{path.name} 第 1 行:{reason}'
raise BomInspectionError(TaskCenterError('bom_import', message), BomImportReport((), (), errors=(message,)))
def load_sources(sources, *, stop_event=None, on_progress=None, allow_partial=False, warnings=None):
"""Read every selected workbook before any CAD operation starts.""" """Read every selected workbook before any CAD operation starts."""
from .operation_control import check_cancelled from .operation_control import check_cancelled
@@ -74,17 +106,7 @@ def load_sources(sources, *, stop_event=None, on_progress=None, allow_partial=Fa
if len(workbook.worksheets) != 1: if len(workbook.worksheets) != 1:
raise ValueError('BOM 只能包含一个工作表') raise ValueError('BOM 只能包含一个工作表')
rows = iter(workbook.active.iter_rows()) rows = iter(workbook.active.iter_rows())
header_cells = next(rows, ()) positions, unknown = _source_headers(path, next(rows, ()))
headers = _normal_headers(tuple(cell.value for cell in header_cells))
names = tuple(name for name in headers if name)
if len(names) != len(set(names)):
raise ValueError('BOM 列名重复')
required = {'old_part_number', 'new_part_number', 'refdes'}
if not required <= set(names):
raise ValueError('BOM 必须包含旧料号、新料号和位号列')
if any(cell.data_type == 'f' for cell in header_cells):
raise ValueError('BOM 表头不接受公式')
positions = {name: index for index, name in enumerate(headers) if name}
for excel_row, cells in enumerate(rows, 2): for excel_row, cells in enumerate(rows, 2):
check_cancelled(stop_event) check_cancelled(stop_event)
formula = any(cell.data_type == 'f' for cell in cells) formula = any(cell.data_type == 'f' for cell in cells)
@@ -116,6 +138,8 @@ def load_sources(sources, *, stop_event=None, on_progress=None, allow_partial=Fa
result.append(SourceRow(path, excel_row, values, value_mode, source_sha256)) result.append(SourceRow(path, excel_row, values, value_mode, source_sha256))
if hashlib.sha256(path.read_bytes()).hexdigest() != source_sha256: if hashlib.sha256(path.read_bytes()).hexdigest() != source_sha256:
raise ValueError('BOM 来源在读取期间已改变,请重新导入') raise ValueError('BOM 来源在读取期间已改变,请重新导入')
if warnings is not None:
warnings.extend(f'{path.name}:已忽略未知列「{name}」' for name in unknown)
except TaskCenterError: except TaskCenterError:
raise raise
except Exception as error: except Exception as error:
+24
View File
@@ -96,6 +96,30 @@ def test_inspect_accepts_frozen_workspace_checkpoint(project_service):
assert result['remaining_task_ids'] == ids assert result['remaining_task_ids'] == ids
def test_inspect_restores_a_legacy_resource_pause_only_from_its_original_batch(project_service, monkeypatch):
from dx_productivity.trial_task_center import task_queue
service, _, data, ids, hashes = project_service
journal = RunJournal(data)
token, batch_id = 'a' * 32, 'b' * 32
journal.begin(token, ids, hashes)
checkpoint(data, token, ids, hashes, {ids[0]: 'blocked'})
path = data / 'task-queues' / (token + '.json')
state = json.loads(path.read_bytes())
path.write_text(json.dumps(dict(state, phase='primary')), encoding='utf-8')
journal.finish(token, {'status': 'blocked', 'paused': True, 'user_pause_requested': False})
archive = data / 'batch-resources' / batch_id / 'result.json'
archive.parent.mkdir(parents=True)
archive.touch()
monkeypatch.setattr(task_queue, 'resource_pause_admitted', lambda root, owner, tasks, plan:
TaskQueueResult(token, (), True, ids[0]) if owner == batch_id and tuple(ids) == tasks and hashes == plan else False)
result = journal.inspect(service, token)
assert result['resource_batch_id'] == batch_id
assert result['isolated_task_ids'] == ids[:1]
assert result['remaining_task_ids'] == ids[1:]
journal.finish(token, {'status': 'blocked', 'paused': True, 'user_pause_requested': True})
assert journal.inspect(service, token)['resource_batch_id'] is None
@pytest.mark.parametrize('interrupted', [False, True]) @pytest.mark.parametrize('interrupted', [False, True])
def test_shared_safe_primary_failure_can_hold_remaining_commands_on_resume(project_service, monkeypatch, interrupted): def test_shared_safe_primary_failure_can_hold_remaining_commands_on_resume(project_service, monkeypatch, interrupted):
from dataclasses import replace from dataclasses import replace
+20
View File
@@ -27,6 +27,26 @@ def visible_ids(panel):
return [panel.list.item(index).data(Qt.ItemDataRole.UserRole) for index in range(panel.list.count())] return [panel.list.item(index).data(Qt.ItemDataRole.UserRole) for index in range(panel.list.count())]
def test_empty_list_explains_search_filter_and_initial_state(navigation, qtbot):
panel, tasks, opened = navigation
panel.populate(tasks[:1])
qtbot.keyClicks(panel.search, 'zzzz_no_match')
assert panel.empty_hint.isVisible()
assert 'zzzz_no_match' in panel.empty_hint.text()
assert '匹配 0 / 共 1 个任务' in panel.count.text()
panel.filter.setCurrentIndex(panel.filter.findData('completed'))
assert '已完成' in panel.empty_hint.text() and 'zzzz_no_match' in panel.empty_hint.text()
panel.search.clear()
assert '已完成' in panel.empty_hint.text()
panel.filter.setCurrentIndex(panel.filter.findData('all'))
assert not panel.empty_hint.isVisible() and len(visible_ids(panel)) == 1
panel.populate(())
assert '新建任务' in panel.empty_hint.text()
panel.recycle_button.setChecked(True)
panel.populate(())
assert '回收站' in panel.empty_hint.text()
@pytest.mark.parametrize(('category','expected'),[ @pytest.mark.parametrize(('category','expected'),[
('all',['draft','ready','running','paused','completed','failed','blocked']), ('all',['draft','ready','running','paused','completed','failed','blocked']),
('unfinished',['draft','ready','running','paused','failed','blocked']), ('unfinished',['draft','ready','running','paused','failed','blocked']),
+39
View File
@@ -4,6 +4,8 @@ import os
from pathlib import Path from pathlib import Path
import subprocess import subprocess
import sys import sys
from threading import Timer
from types import SimpleNamespace
import pytest import pytest
@@ -14,6 +16,43 @@ from dx_productivity.trial_task_center.isolated_desktop import _Win32Api, build_
from dx_productivity.trial_task_center.logging_setup import configure_logging from dx_productivity.trial_task_center.logging_setup import configure_logging
@pytest.mark.skipif(os.name != 'nt', reason='Windows desktop object lifetime')
def test_a_late_owned_job_exit_releases_the_live_lease_without_second_quit(tmp_path):
runtime = BatchCadRuntime(tmp_path, 'execution')
desktop = runtime._ensure_desktop()
exit_file = tmp_path / 'exit'
process = desktop.start_process((sys.executable, '-u', '-c',
'import pathlib,sys,time; marker=pathlib.Path(sys.argv[1]); print("ready",flush=True); '
'exec("while not marker.exists(): time.sleep(.02)")', str(exit_file)),
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
runtime._track(process)
quit_attempts = []
signal = Timer(.8, exit_file.touch)
def interrupted_quit(*args):
quit_attempts.append(process.pid)
signal.start()
raise OSError('injected delayed root exit')
try:
assert process.stdout.readline() == b'ready\r\n'
runtime.cad = SimpleNamespace(cad=process, record={'forced_termination': True}, __exit__=interrupted_quit)
with pytest.raises(BatchResourceCleanupError, match='injected delayed root exit'):
runtime.close()
assert len(quit_attempts) == 1
assert runtime.record['state'] == 'released'
assert runtime.record['release_proof']['method'] == 'owned_cleanup'
assert runtime.record['release_proof']['processes_exited'] is True
assert desktop.cleanup_record['desktop_lease']['returned'] is True
assert runtime.record['cad_shutdown']['forced_termination'] is True
assert len(runtime.record['release_rechecks']) in {2, 3}
guard_pending_resources(tmp_path)
finally:
exit_file.touch()
signal.cancel()
desktop.close()
@pytest.mark.skipif(os.name != 'nt', reason='Windows desktop object lifetime') @pytest.mark.skipif(os.name != 'nt', reason='Windows desktop object lifetime')
def test_external_reference_preserves_completed_result_until_resource_only_cleanup(tmp_path): def test_external_reference_preserves_completed_result_until_resource_only_cleanup(tmp_path):
before = current_desktop_name() before = current_desktop_name()
+99
View File
@@ -0,0 +1,99 @@
import json
import os
from pathlib import Path
import pytest
from openpyxl import load_workbook
from PySide6.QtWidgets import QFileDialog
from test_bom_batch import batch, records_for
from dx_productivity.trial_task_center.bom_plan import write_bom_template
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
@pytest.mark.parametrize('case', ['extra', 'near', 'missing', 'header_formula', 'row_formula', 'original'])
def test_bom_header_feedback_through_workspace(case, batch, tmp_path, qtbot, monkeypatch):
service, _, tasks, targets, inventory_calls = batch
task = tasks[0]
record = records_for(tasks, targets)[0]
source = write_bom_template(tmp_path / f'{case}.xlsx', [record])
workbook = load_workbook(source)
sheet = workbook.active
if case == 'extra':
sheet['L1'], sheet['L2'] = '供应商', 'Example supplier'
sheet['M1'], sheet['M2'] = '备注', 'Example note'
elif case == 'near':
sheet['D1'] = '新料号编码'
elif case == 'missing':
sheet['D1'] = None
elif case == 'header_formula':
sheet['L1'] = '=1+1'
elif case == 'row_formula':
sheet['L1'], sheet['L2'] = '备注', '=1+1'
workbook.save(source)
workbook.close()
assert_workspace_import(case, source, task, service, inventory_calls, qtbot, monkeypatch)
def test_field_extra_column_through_workspace(batch, tmp_path, qtbot, monkeypatch):
field = os.environ.get('DX_ISSUE33_D5_FIELD')
if not field:
pytest.skip('set DX_ISSUE33_D5_FIELD to replay the field attachment')
service, _, tasks, targets, inventory_calls = batch
source = tmp_path / Path(field).name
workbook = load_workbook(field)
sheet = workbook.active
# Rebind to the local fixture project. Keep the original Excel header and BOM cells.
sheet['A2'] = tasks[0].name
sheet['B2'] = str(targets[tasks[0].task_id][0].project_path)
workbook.save(source)
workbook.close()
assert_workspace_import('field', source, tasks[0], service, inventory_calls, qtbot, monkeypatch)
def assert_workspace_import(case, source, task, service, inventory_calls, qtbot, monkeypatch):
window = TrialTaskCenterWindow(service)
window.auto_intervention_check.setChecked(False)
qtbot.addWidget(window)
window.open_task(task.task_id)
panel = window.plan_panel
qtbot.waitUntil(panel.import_bom_button.isEnabled, timeout=5000)
monkeypatch.setattr(QFileDialog, 'getOpenFileNames', lambda *args: ([str(source)], 'Excel (*.xlsx)'))
panel.import_bom_button.click()
qtbot.waitUntil(lambda: not window._workers, timeout=8000)
status = window.run_panel.operator_band.text()
print(status)
pending = service.pending_bom(task.task_id)
assert not inventory_calls
if case in {'extra', 'field', 'original', 'near', 'missing', 'header_formula'}:
panel.report_toggle.setChecked(True)
assert panel.report_dialog is not None
details = panel.report_dialog.view.toPlainText()
print(details)
if case in {'extra', 'field', 'original'}:
assert len(pending) == 1
assert panel.last_bom_report.failed_rows == 0 and panel.last_bom_report.deferred
if case == 'extra':
assert '失败 0 行' in status and '警告 2 项' in status
assert all(text in details for text in ('已忽略', '供应商', '备注', source.name))
assert pending[0].record.new == 'NEW-0'
events = (service._logging.root / 'tasks' / task.task_id / 'events.jsonl').read_text(encoding='utf-8')
entries = [json.loads(line) for line in events.splitlines()]
entry = next(event for event in entries if event['operation'] == 'import_bom_drafts')
assert tuple(entry['details']['warnings']) == panel.last_bom_report.warnings
elif case == 'field':
assert '警告 1 项' in status and 'extra_column' in details
else:
assert '警告' not in status and '已忽略' not in details
else:
assert not pending
if case == 'near':
assert '缺少必需列「新料号」' in status
assert '「新料号编码」' in details and '改为「新料号」' in details
elif case == 'missing':
assert '缺少必需列「新料号」' in status and '新料号' in details
elif case == 'header_formula':
assert 'BOM 表头不接受公式' in status and 'BOM 表头不接受公式' in details
else:
assert '第 2 行不接受公式' in status
window.close()
@@ -9,6 +9,8 @@ from test_bom_batch import batch
def test_real_supervised_sources_roundtrip_origin_metadata_and_preview(batch, tmp_path): def test_real_supervised_sources_roundtrip_origin_metadata_and_preview(batch, tmp_path):
from openpyxl import load_workbook
from dx_productivity.trial_task_center.bom_plan import write_bom_template from dx_productivity.trial_task_center.bom_plan import write_bom_template
service, store, tasks, targets, calls = batch service, store, tasks, targets, calls = batch
for task in tasks: for task in tasks:
@@ -17,9 +19,14 @@ def test_real_supervised_sources_roundtrip_origin_metadata_and_preview(batch, tm
'project_name': task.name, 'project_path': str(targets[task.task_id][0].project_path), 'project_name': task.name, 'project_path': str(targets[task.task_id][0].project_path),
'old_part_number': 'OLD', 'new_part_number': 'NEW', 'refdes': 'R1', 'value_mode': 'part_number', 'old_part_number': 'OLD', 'new_part_number': 'NEW', 'refdes': 'R1', 'value_mode': 'part_number',
},)) for index, task in enumerate(tasks)) },)) for index, task in enumerate(tasks))
workbook = load_workbook(sources[0])
workbook.active['M1'] = '备注'
workbook.save(sources[0])
workbook.close()
service._supervised = True service._supervised = True
report = service.preview_bom_sources(tasks[0].task_id, sources) report = service.preview_bom_sources(tasks[0].task_id, sources)
assert report.passed_rows == 2 and report.preview is not None assert report.passed_rows == 2 and report.preview is not None
assert report.warnings == ('source-0.xlsx:已忽略未知列「备注」',)
assert tuple(row.source_file for row in report.rows) == tuple(str(path.resolve()) for path in sources) assert tuple(row.source_file for row in report.rows) == tuple(str(path.resolve()) for path in sources)
assert all(row.source_row == 2 for row in report.rows) assert all(row.source_row == 2 for row in report.rows)
assert report.source_map_path.is_file() assert report.source_map_path.is_file()
+175
View File
@@ -0,0 +1,175 @@
from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center import native_helper as native
from dx_productivity.trial_task_center.batch_attempt import prepare_attempt, read_attempt
@pytest.fixture
def attempt(tmp_path, monkeypatch):
job = 'job'
project = tmp_path / 'board.prj'
record_path = tmp_path / 'attempt.json'
snapshot = tmp_path / f'snapshot-{job}.tsv'
snapshot.write_text(f'M\t{project}\tOLD\tNEW\tMAIN:1\nC\tuid\tR1\t0\t0\t0\t1\t\n', encoding='utf-8')
(tmp_path / 'command.tsv').write_text(
f'job_id\ttask_id\tproject_path\n{job}\ttask\t{project}\n', encoding='utf-8')
record = prepare_attempt(record_path, session_id='session', generation=1,
job_id=job, task_id='task', project_path=project)
for name, value in {
'DXPART_DESKTOP': 'dx-test',
'DXPART_ATTEMPT_FILE': record_path,
'DXPART_ATTEMPT_ID': record['attempt_id'],
'DXPART_BATCH_GENERATION': record['generation'],
'DXPART_BATCH_SESSION_ID': record['session_id'],
}.items():
monkeypatch.setenv(name, str(value))
return snapshot, record_path
@pytest.fixture
def clock(monkeypatch):
now = [0.]
monkeypatch.setattr(native, 'time', SimpleNamespace(
monotonic=lambda: now[0], sleep=lambda seconds: now.__setitem__(0, now[0] + seconds)))
return now
def test_cold_list_recreation_reapplies_filter_and_uses_the_new_handle(attempt, clock):
snapshot, record = attempt
report, filtered = {}, []
browsing = False
def browse():
nonlocal browsing
browsing = True
def controls():
if browsing:
return (10, 11) if clock[0] < .3 else (20, 21)
return None
list_handle, rows = native.load_databook_target(snapshot, report, 'NEW',
controls=controls, browse=browse, filter_part=lambda handle: filtered.append(handle),
list_rows=lambda handle: [(handle, ['GATE', 'NEW', 'lib:SYM'])],
dialogs=lambda: (), close_dialog=lambda handle: pytest.fail('unexpected close'))
assert (list_handle, rows[0][0], filtered) == (20, 20, [11, 21])
assert report['databook']['loads'][0]['mode'] == 'cold'
assert read_attempt(record)['state'] == 'prepared'
@pytest.mark.parametrize('during', ['filter', 'rows'])
def test_control_destroyed_between_discovery_and_access_is_reacquired(attempt, clock, during):
snapshot, record = attempt
state = {'controls': (10, 11)}
visited = []
def destroyed():
state['controls'] = (20, 21)
error = OSError('stale DxDataBook control')
if during == 'filter':
error.winerror = 1400
else:
error.hresult = -2147220991
raise error
def filter_part(handle):
visited.append(handle)
if during == 'filter' and handle == 11:
destroyed()
def rows(handle):
if during == 'rows' and handle == 10:
destroyed()
return [(handle, ['GATE', 'NEW', 'lib:SYM'])]
report = {}
handle, _ = native.load_databook_target(snapshot, report, 'NEW',
controls=lambda: state['controls'], browse=lambda: None, filter_part=filter_part,
list_rows=rows, dialogs=lambda: (), close_dialog=lambda _: pytest.fail('unexpected close'))
assert handle == 20 and visited == [11, 21]
assert len(report['databook']['loads']) == 1
assert read_attempt(record)['state'] == 'prepared'
@pytest.mark.parametrize('already_written', [False, True])
def test_timeout_reissues_filter_once_only_with_bound_prepared_attempt(attempt, clock, already_written):
snapshot, record = attempt
if already_written:
native.mark_snapshot_mutation(snapshot)
report, filters = {}, []
def run():
return native.load_databook_target(snapshot, report, 'NEW',
controls=lambda: (10, 11), browse=lambda: None,
filter_part=lambda handle: filters.append(handle), list_rows=lambda handle: [],
dialogs=lambda: (), close_dialog=lambda handle: pytest.fail('unexpected close'))
with pytest.raises(TimeoutError, match='DxDataBook'):
run()
loads = report['databook']['loads']
assert [load['mode'] for load in loads] == ['warm'] * (1 if already_written else 2)
assert len(filters) == len(loads)
assert read_attempt(record)['state'] == ('mutation_possible' if already_written else 'prepared')
def test_retry_closes_only_new_owned_empty_dialog_and_persists_evidence_first(attempt, clock):
snapshot, record = attempt
report, closed = {}, []
blank = {'hwnd': 19, 'owner': 7, 'title': '', 'children': [], 'dismissible': True}
previous = dict(blank, hwnd=18)
named = dict(blank, hwnd=20, title='Save', dismissible=False)
def dialogs():
return [previous, named] if clock[0] == 0 else [previous, blank, named]
def close(row):
import json
evidence = json.loads(snapshot.with_suffix('.tsv.native.json').read_bytes())
assert evidence['databook']['loads'][0]['dialogs'][0]['hwnd'] == 19
assert evidence['databook']['loads'][0]['attempt_state'] == 'prepared'
closed.append(row['hwnd'])
native.load_databook_target(snapshot, report, 'NEW',
controls=lambda: (10, 11), browse=lambda: None, filter_part=lambda handle: None,
list_rows=lambda handle: [(handle, ['GATE', 'NEW', 'lib:SYM'])] if closed else [],
dialogs=dialogs, close_dialog=close)
assert closed == [19]
assert len(report['databook']['loads']) == 2
assert read_attempt(record)['state'] == 'prepared'
def test_named_or_unowned_prompt_keeps_operator_handling(attempt, clock):
snapshot, _ = attempt
report = {}
with pytest.raises(TimeoutError, match='DxDataBook'):
native.load_databook_target(snapshot, report, 'NEW',
controls=lambda: (10, 11), browse=lambda: None, filter_part=lambda handle: None,
list_rows=lambda handle: [],
dialogs=lambda: [{'hwnd': 20, 'dismissible': False}] if clock[0] else [],
close_dialog=lambda row: pytest.fail('unrecognized prompt was closed'))
assert len(report['databook']['loads']) == 1
def test_dialog_fingerprint_requires_same_owner_pid_thread_and_empty_controls(monkeypatch):
from dx_productivity.trial_task_center import cad_dialogs
owner, pid = 7, 8
windows = {10: (1, pid, owner), 11: (1, pid, 99), 12: (2, pid, owner),
13: (1, 99, owner), 14: (1, pid, owner), owner: (1, pid, 99)}
monkeypatch.setattr(cad_dialogs, '_text', lambda hwnd: '')
gui = SimpleNamespace(
error=RuntimeError, IsWindowVisible=lambda hwnd: True, IsWindowEnabled=lambda hwnd: False,
EnumWindows=lambda callback, _: [callback(hwnd, None) for hwnd in windows],
GetWindow=lambda hwnd, _: windows[hwnd][2],
EnumChildWindows=lambda hwnd, callback, _: callback(20, None) if hwnd == 14 else None,
GetClassName=lambda hwnd: 'Button' if hwnd == 20 else '#32770',
GetDlgCtrlID=lambda hwnd: 1, GetParent=lambda hwnd: 14,
)
process = SimpleNamespace(GetWindowThreadProcessId=lambda hwnd: windows[hwnd][:2])
rows = native.databook_dialogs(gui, process, pid, owner, 99)
assert [row['hwnd'] for row in rows] == [10, 11, 12, 14]
assert [row['hwnd'] for row in rows if row['dismissible']] == [10]
assert rows[-1]['children'] == [{'hwnd': 20, 'parent': 14, 'class': 'Button', 'id': 1}]
+6 -3
View File
@@ -3,7 +3,8 @@ import test_accuracy_vbs_guards as guards
@pytest.mark.parametrize('fault', ['', 'snapshot', 'identity', 'transaction', 'native', @pytest.mark.parametrize('fault', ['', 'snapshot', 'identity', 'transaction', 'native',
'save_requested', 'save_committed', 'close']) 'native_unresolved', 'prior_staged_write', 'save_requested',
'save_committed', 'close'])
def test_safe_pause_cannot_interrupt_verified_failure_cleanup(tmp_path, fault): def test_safe_pause_cannot_interrupt_verified_failure_cleanup(tmp_path, fault):
output = guards.run_vbs(tmp_path, ['QPProgress', 'QPDiscardFailedBatchProject', output = guards.run_vbs(tmp_path, ['QPProgress', 'QPDiscardFailedBatchProject',
'QPCloseBatchProject', 'QPReadUtf8'], ''' 'QPCloseBatchProject', 'QPReadUtf8'], '''
@@ -33,6 +34,8 @@ Set QP_Fso=CreateObject("Scripting.FileSystemObject")
QP_Root="''' + str(tmp_path) + '''":QP_AttemptToken="token":QP_ProgressSequence=0 QP_Root="''' + str(tmp_path) + '''":QP_AttemptToken="token":QP_ProgressSequence=0
QP_BatchMode=True:QP_OwnedProject=True:QP_OwnedProjectPath="board.prj" QP_BatchMode=True:QP_OwnedProject=True:QP_OwnedProjectPath="board.prj"
QP_NativeMutationPossible=''' + str(fault == 'native') + ''' QP_NativeMutationPossible=''' + str(fault == 'native') + '''
QP_NativeCallActive=''' + str(fault == 'native_unresolved') + '''
If ''' + str(fault == 'prior_staged_write') + ''' Then QP_SessionItems.Add "previous-job", "restored_ok"
QP_BatchSaveRequested=''' + str(fault == 'save_requested') + ''' QP_BatchSaveRequested=''' + str(fault == 'save_requested') + '''
QP_BatchSaveCommitted=''' + str(fault == 'save_committed') + ''' QP_BatchSaveCommitted=''' + str(fault == 'save_committed') + '''
Class FakeApp Class FakeApp
@@ -85,8 +88,8 @@ End Sub
Sub QPLog(ByVal Root,ByVal Level,ByVal Message) Sub QPLog(ByVal Root,ByVal Level,ByVal Message)
End Sub End Sub
''') ''')
paused_before = fault != 'native' paused_before = fault not in {'native', 'native_unresolved'}
paused_after = fault not in {'native', 'transaction'} paused_after = fault not in {'native', 'native_unresolved', 'transaction'}
assert output.splitlines()[-1] == f'result:{paused_before}:{not fault}:{bool(fault)}:{paused_after}' assert output.splitlines()[-1] == f'result:{paused_before}:{not fault}:{bool(fault)}:{paused_after}'
+134
View File
@@ -0,0 +1,134 @@
from contextlib import closing
import os
from pathlib import Path
import pytest
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QDialogButtonBox
from dx_productivity.trial_task_center import project_tasks
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.ui.messages import format_operation_error
from dx_productivity.trial_task_center.ui.project_plan import DirectoryTaskDialog
@pytest.fixture
def service(tmp_path):
log = configure_logging(tmp_path / 'data')
with closing(TaskStore(tmp_path / 'tasks.db')) as store:
yield TaskCenterService(store, log), store, log.application_log_path
def deny_directory_listing(folder, request):
if os.name != 'nt':
pytest.skip('requires a Windows filesystem ACL')
import ntsecuritycon
import win32api
import win32con
import win32security
flag = win32security.DACL_SECURITY_INFORMATION
path = str(folder)
original = win32security.GetFileSecurity(path, flag)
token = win32security.OpenProcessToken(win32api.GetCurrentProcess(), win32con.TOKEN_QUERY)
try:
sid = win32security.GetTokenInformation(token, win32security.TokenUser)[0]
finally:
token.Close()
dacl = win32security.ACL()
dacl.AddAccessDeniedAce(win32security.ACL_REVISION, ntsecuritycon.FILE_LIST_DIRECTORY, sid)
dacl.AddAccessAllowedAce(win32security.ACL_REVISION, ntsecuritycon.FILE_ALL_ACCESS, sid)
descriptor = win32security.SECURITY_DESCRIPTOR()
descriptor.SetSecurityDescriptorDacl(True, dacl, False)
request.addfinalizer(lambda: win32security.SetFileSecurity(path, flag, original))
win32security.SetFileSecurity(path, flag, descriptor)
with pytest.raises(PermissionError) as failure, os.scandir(folder):
pytest.fail('directory ACL did not deny enumeration')
assert failure.value.winerror == 5
print('Windows ACL produced WinError 5')
def assert_operator_error(text, path, code, advice):
print(text)
assert str(path) in text
assert code in text and 'DXT-' in text
assert advice in text
assert 'Traceback' not in text
assert '发生未处理异常' not in text
@pytest.mark.parametrize(('case', 'code', 'advice'), [
('missing', 'path_missing', '移动或删除'),
('file', 'path_not_directory', '请选择工程目录'),
('file_parent', 'path_not_directory', '请选择工程目录'),
('denied', 'path_denied', '读取权限'),
])
def test_directory_dialog_shows_actionable_path_error(qtbot, tmp_path, request, service, case, code, advice):
api, store, log = service
folder = tmp_path / case
requested = folder
if case in {'file', 'file_parent'}:
folder.touch()
if case == 'file_parent':
requested = folder / 'subfolder'
if case == 'denied':
folder.mkdir()
deny_directory_listing(folder, request)
dialog = DirectoryTaskDialog(api)
qtbot.addWidget(dialog)
dialog.directory.setText(str(requested))
dialog.show()
qtbot.mouseClick(dialog.scan, Qt.MouseButton.LeftButton)
qtbot.waitUntil(lambda: dialog._worker is None, timeout=5000)
assert dialog.directory.isEnabled()
assert not dialog.buttons.button(QDialogButtonBox.StandardButton.Ok).isEnabled()
assert_operator_error(dialog.summary.text(), requested, code, advice)
assert store.list_tasks() == ()
contents = log.read_text(encoding='utf-8')
assert f'operation=scan_project_directory code={code}' in contents
assert 'Traceback' not in contents
def test_moved_project_fails_after_scan_without_creating_partial_tasks(qtbot, tmp_path, service):
api, store, log = service
root = tmp_path / 'projects'
root.mkdir()
for name in ('one.prj', 'two.prj'):
(root / name).write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
dialog = DirectoryTaskDialog(api)
qtbot.addWidget(dialog)
dialog.directory.setText(str(root))
dialog.show()
qtbot.mouseClick(dialog.scan, Qt.MouseButton.LeftButton)
create = dialog.buttons.button(QDialogButtonBox.StandardButton.Ok)
qtbot.waitUntil(create.isEnabled, timeout=5000)
moved = root / 'two.prj'
moved.rename(root / 'relocated.prj')
qtbot.mouseClick(create, Qt.MouseButton.LeftButton)
with pytest.raises(TaskCenterError) as failure:
api.create_project_tasks(dialog.values()[0], selected_paths=dialog.values()[1])
assert_operator_error(format_operation_error(failure.value), moved, 'path_missing', '移动或删除')
assert store.list_tasks() == ()
contents = log.read_text(encoding='utf-8')
assert 'operation=create_project_tasks code=path_missing' in contents
assert 'Traceback' not in contents
def test_unexpected_scan_fault_remains_traceable_in_application_log(tmp_path, monkeypatch, service):
api, _, log = service
def fail(*args, **kwargs):
raise RuntimeError('injected non-filesystem failure')
monkeypatch.setattr(project_tasks, '_validated_root', fail)
with pytest.raises(TaskCenterError) as failure:
api.scan_project_directory(tmp_path)
assert failure.value.code == 'unhandled_exception'
contents = log.read_text(encoding='utf-8')
assert 'operation=scan_project_directory code=unhandled_exception' in contents
assert 'Traceback' in contents and failure.value.error_id in contents
+96
View File
@@ -10,6 +10,102 @@ from dx_productivity.trial_task_center.batch_resources import LIVE_RESOURCES, cl
from dx_productivity.trial_task_center.errors import TaskCenterError from dx_productivity.trial_task_center.errors import TaskCenterError
@pytest.mark.parametrize('exits_after_retry', [True, False])
def test_batch_close_rechecks_owned_exit_three_times_without_repeating_quit(tmp_path, monkeypatch, exits_after_retry):
from dx_productivity.trial_task_center import batch_runtime
calls, delays = [], []
runtime = BatchCadRuntime(tmp_path, 'execution', desktop_factory=Desktop)
runtime._ensure_desktop()
process = SimpleNamespace(returncode=None, poll=lambda: process.returncode)
def close_mentor(*args):
calls.append('quit')
raise OSError('root exit still pending after forced job stop')
def advance(seconds):
delays.append(seconds)
if exits_after_retry and len(delays) == 2:
process.returncode = 1
monkeypatch.setattr(batch_runtime.time, 'sleep', advance)
runtime.cad = SimpleNamespace(cad=process, record={'forced_termination': True}, __exit__=close_mentor)
runtime.result = 'saved and independently verified'
try:
with pytest.raises(TaskCenterError, match='root exit still pending'):
runtime.close()
if exits_after_retry:
assert runtime.record['state'] == 'released'
assert runtime.record['cad_shutdown']['forced_termination'] is True
assert delays == [0.5, 1]
else:
assert runtime.record['state'] == 'blocked'
assert not runtime.desktop.released
assert delays == [0.5, 1, 2]
assert calls == ['quit']
assert runtime.result == 'saved and independently verified'
finally:
LIVE_RESOURCES.pop(str(runtime.path), None)
def test_restart_rechecks_physical_disappearance_without_replaying_owned_actions(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import batch_resources, isolated_desktop
runtime = BatchCadRuntime(tmp_path, 'execution', desktop_factory=Desktop)
runtime._ensure_desktop()
LIVE_RESOURCES.pop(str(runtime.path), None)
runtime._save(state='blocked')
observed, delays = [], []
work = tmp_path / 'uncertain.flag'
work.write_bytes(b'original business protection')
def confirm(name):
observed.append(name)
if len(observed) < 3:
raise OSError('desktop still exists')
monkeypatch.setattr(isolated_desktop, '_Win32Api', lambda: SimpleNamespace(confirm_desktop_released=confirm))
monkeypatch.setattr(batch_resources.time, 'sleep', delays.append)
assert cleanup_pending_resources(tmp_path) == ()
assert observed == [runtime.desktop.name] * 3
assert delays == [0.5, 1]
assert work.read_bytes() == b'original business protection'
def test_resource_only_observation_never_closes_a_ready_live_owner(tmp_path):
runtime = BatchCadRuntime(tmp_path, 'execution', desktop_factory=Desktop)
runtime._ensure_desktop()
try:
assert cleanup_pending_resources(tmp_path)[0]['state'] == 'ready'
assert not runtime.desktop.released
finally:
runtime.close()
def test_missing_historical_job_exit_blocks_even_when_the_desktop_is_gone(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import batch_resources, isolated_desktop
runtime = BatchCadRuntime(tmp_path, 'execution', desktop_factory=Desktop)
runtime._ensure_desktop()
LIVE_RESOURCES.pop(str(runtime.path), None)
identity = {'pid': 1400, 'creation_time': 'exact'}
runtime._save(state='blocked', cad_pid=1400, cad_process=identity, processes=[identity])
monkeypatch.setattr(batch_resources, '_process_gone', lambda _: True)
monkeypatch.setattr(isolated_desktop, '_Win32Api', lambda: pytest.fail('insufficient Job proof'))
assert cleanup_pending_resources(tmp_path)[0]['state'] == 'blocked'
def test_supervised_cleanup_carries_automatic_mode_to_worker(tmp_path):
from dx_productivity.trial_task_center.service import TaskCenterService
service = TaskCenterService.__new__(TaskCenterService)
service._supervised = True
service._logging = SimpleNamespace(root=tmp_path)
calls = []
service._supervise = lambda operation, arguments: calls.append((operation, arguments))
service.pending_batch_resources = lambda: ()
assert service.cleanup_batch_resources(automatic=True) == ()
assert calls == [('cleanup_batch_resources', {'automatic': True})]
def test_closed_desktop_rechecks_only_observe_until_external_reference_disappears(tmp_path, monkeypatch): def test_closed_desktop_rechecks_only_observe_until_external_reference_disappears(tmp_path, monkeypatch):
from dx_productivity.trial_task_center.isolated_desktop import PrivateDesktop from dx_productivity.trial_task_center.isolated_desktop import PrivateDesktop
from dx_productivity.trial_task_center import isolated_desktop, batch_resources from dx_productivity.trial_task_center import isolated_desktop, batch_resources
+86
View File
@@ -0,0 +1,86 @@
import hashlib
import json
from threading import Event
from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center import task_queue
from dx_productivity.trial_task_center.supervisor_protocol import encode
from dx_productivity.trial_task_center.task_queue import TaskQueueEntry, TaskQueueResult
@pytest.mark.parametrize('release', [True, False])
@pytest.mark.parametrize('user_pause', [False, True])
def test_normal_supervised_queue_reuses_original_queue_after_resource_pause(tmp_path, monkeypatch, release, user_pause):
ids = ('A', 'B', 'C')
token = 'a' * 32
hashes = dict.fromkeys(ids, 'f' * 64)
result = TaskQueueResult(token, (TaskQueueEntry('A', 'completed'), TaskQueueEntry('B', 'blocked'),
TaskQueueEntry('C', 'pending')), True, 'B')
done = TaskQueueResult(token, (result.entries[0], result.entries[1], TaskQueueEntry('C', 'completed')), False)
calls = []
service = SimpleNamespace(_supervised=True, _logging=SimpleNamespace(root=tmp_path))
stop = Event()
def supervise(operation, arguments, **kwargs):
calls.append(arguments)
if user_pause:
stop.set()
return result if len(calls) == 1 else done
service._supervise = supervise
service._last_supervisor_batch_id = 'b' * 32
service.pending_batch_resources = lambda: ()
monkeypatch.setattr(task_queue, 'resource_pause_admitted', lambda *args: release, raising=False)
resumed = release and not user_pause
assert task_queue.execute_task_queue(service, ids, stop_event=stop, checkpoint_id=token,
expected_plan_hashes=hashes) == (done if resumed else result)
assert [call['checkpoint_id'] for call in calls] == ([token, None] if resumed else [token])
if resumed:
assert calls[-1]['queue_id'] == token
assert calls[-1]['expected_plan_hashes'] == hashes
@pytest.mark.parametrize('reason', [None, 'unknown_writer', 'cancel', 'consumed', 'unknown_pause'])
def test_original_receipt_must_prove_resource_pause_and_cannot_be_consumed_again(tmp_path, monkeypatch, reason):
from dx_productivity.trial_task_center import batch_resources
batch_id, attempt, queue = 'b' * 32, 'c' * 32, 'a' * 32
ids, hashes = ('A', 'B'), {'A': '01', 'B': '02'}
entries = (TaskQueueEntry('A', 'blocked'), TaskQueueEntry('B', 'pending'))
result = TaskQueueResult(queue, entries, True, 'A')
folder = tmp_path / 'batch-resources' / batch_id
request = {'batch_id': batch_id, 'attempt_id': attempt, 'operation': 'execute_task_queue', 'root': str(tmp_path),
'arguments': encode({'task_ids': ids, 'queue_id': None, 'checkpoint_id': queue,
'expected_plan_hashes': hashes})}
batch_resources.write_record(folder / 'request.json', request)
digest = hashlib.sha256((folder / 'request.json').read_bytes()).hexdigest()
process = {'pid': 17, 'creation_time': 'worker'}
batch_resources.write_record(folder / 'supervisor.json', {'version': 1, 'batch_id': batch_id, 'attempt_id': attempt,
'operation': 'execute_task_queue', 'task_ids': list(ids), 'parent_process': process,
'process': process, 'state': 'finished', 'request_sha256': digest})
payload = {'business_succeeded': True, 'status': 'ok', 'result': encode(result)}
if reason != 'unknown_pause':
payload['resource_warning'] = {'state': 'isolated', 'owned_writers_exited': True}
batch_resources.write_record(folder / 'result.json', {'version': 1, 'batch_id': batch_id, 'attempt_id': attempt,
'generation': 1, 'sequence': 1, 'type': 'result', 'payload': payload})
state = {'version': 1, 'task_ids': list(ids), 'plan_hashes': hashes, 'phase': 'primary',
'entries': {entry.task_id: {'state': entry.state, 'message': entry.message} for entry in entries}}
if reason == 'consumed':
state['consumed_resource_pauses'] = {batch_id: 'A'}
if reason == 'cancel':
(folder / 'cancel.json').write_text(json.dumps({'batch_id': batch_id}))
batch_resources.write_record(tmp_path / 'task-queues' / (queue + '.json'), state)
monkeypatch.setattr(batch_resources, '_process_gone', lambda _: reason != 'unknown_writer')
assert task_queue.resource_pause_admitted(tmp_path, batch_id, ids, hashes) == (False if reason else result)
@pytest.mark.parametrize('text', ['', 'KEY iCDBDir database', 'KEY iCDBDir "database"\nKEY iCDBDir "../other"'])
def test_ambiguous_or_missing_write_sources_cannot_be_used_to_resume(tmp_path, text):
from dx_productivity.trial_task_center.project_isolation import write_sources
project = tmp_path / 'board.prj'
project.write_text(text)
with pytest.raises(ValueError, match='iCDBDir'):
write_sources(project, strict=True)
@@ -7,6 +7,23 @@ import pytest
from test_ui_remediation import window from test_ui_remediation import window
def test_startup_rechecks_isolation_without_using_the_manual_button(window, qtbot, monkeypatch):
qtbot.waitUntil(lambda: not window._workers and not window._resource_status.busy)
pending = ({'state': 'isolated', 'blocking': False},)
monkeypatch.setattr(window.service, 'pending_batch_resources', lambda: pending)
modes = []
monkeypatch.setattr(window.service, 'cleanup_batch_resources',
lambda *, automatic=False: (modes.append(automatic) or ()))
monkeypatch.setattr(QMessageBox, 'question', lambda *args, **kwargs: pytest.fail('automatic force prompt'))
window._resource_status.records = pending
window._resource_status.known = True
window._update_gates()
assert not window.run_panel.cleanup_resources_button.isEnabled()
window._startup_resource_recheck()
qtbot.waitUntil(lambda: len(modes) == 1 and not window._workers)
assert modes == [True]
@pytest.mark.parametrize('finish_order', ['normal', 'after_confirmation', 'during_confirmation']) @pytest.mark.parametrize('finish_order', ['normal', 'after_confirmation', 'during_confirmation'])
@pytest.mark.parametrize('confirmed', [False, True]) @pytest.mark.parametrize('confirmed', [False, True])
def test_confirmed_force_runs_after_cleanup_worker_finishes(window, qtbot, monkeypatch, finish_order, confirmed): def test_confirmed_force_runs_after_cleanup_worker_finishes(window, qtbot, monkeypatch, finish_order, confirmed):
+84
View File
@@ -0,0 +1,84 @@
from __future__ import annotations
import os
from pathlib import Path
import subprocess
import sys
import time
from dx_productivity.trial_task_center.store import TaskStore
_SOURCE = Path(__file__).resolve().parents[2] / 'src'
_APP = 'dx_productivity.trial_task_center.application'
def _wait_for(predicate, description):
deadline = time.monotonic() + 90
while time.monotonic() < deadline:
if predicate():
return
time.sleep(.05)
raise AssertionError(description)
def test_concurrent_gui_launches_activate_one_owner_and_recover_after_kill(tmp_path):
root = tmp_path / 'Shared Root'
independent = tmp_path / 'Independent Root'
root.mkdir()
store = TaskStore(root / 'task-center.db')
try:
task = store.create_task('Existing task')
finally:
store.close()
processes = []
env = os.environ | {'PYTHONPATH': str(_SOURCE), 'QT_QPA_PLATFORM': 'offscreen'}
def launch(path, *arguments):
process = subprocess.Popen(
[sys.executable, '-m', _APP, '--data-root', str(path), *arguments],
env=env,
)
processes.append(process)
return process
def log(path):
logfile = path / 'logs/application.log'
return logfile.read_text(encoding='utf-8') if logfile.exists() else ''
try:
alias = root.with_name(root.name.upper()) if os.name == 'nt' else root
contenders = [launch(root), launch(alias), launch(root), launch(alias)]
_wait_for(lambda: sum(p.poll() is not None for p in contenders) >= 3,
'Three concurrent launches should exit after handing off to one GUI')
owners = [p for p in contenders if p.poll() is None]
assert len(owners) == 1
assert [p.returncode for p in contenders if p not in owners] == [0, 0, 0]
_wait_for(lambda: log(root).count('instance_conflict') == 3,
'The GUI should handle and log all three activation requests')
assert log(root).count('application_start ') == 1
other = launch(independent)
_wait_for(lambda: 'application_start ' in log(independent), 'Different root should start independently')
assert other.poll() is None and owners[0].poll() is None
helper = launch(root, '--native-helper')
assert helper.wait(timeout=60) == 2 # The helper validates its own required snapshot.
assert log(root).count('instance_conflict') == 3
owners[0].kill()
owners[0].wait(timeout=10)
assert launch(root, '--smoke-test').wait(timeout=60) == 0
assert log(root).count('application_start ') == 2
assert log(root).count('application_clean_shutdown') == 1
assert other.poll() is None
store = TaskStore(root / 'task-center.db')
try:
assert [record.task_id for record in store.list_tasks()] == [task.task_id]
finally:
store.close()
finally:
for process in processes:
if process.poll() is None:
process.kill()
process.wait(timeout=10)
+2 -1
View File
@@ -152,6 +152,7 @@ def test_native_catalog_checks_cannot_cold_read_or_submit_on_miss(tmp_path, monk
elif code == 0xF5 and handle == 1695: elif code == 0xF5 and handle == 1695:
submits.append(handle) submits.append(handle)
raise RuntimeError('native submit reached') raise RuntimeError('native submit reached')
return 1, 1
gui = SimpleNamespace(error=RuntimeError, GetAncestor=lambda *args: 1, EnumWindows=enum_windows, gui = SimpleNamespace(error=RuntimeError, GetAncestor=lambda *args: 1, EnumWindows=enum_windows,
EnumChildWindows=lambda *args: None, IsWindowVisible=lambda handle: True, EnumChildWindows=lambda *args: None, IsWindowVisible=lambda handle: True,
GetClassName=lambda handle: {2: '#32770', 3: 'SysListView32', 4: 'Edit'}.get(handle, 'Main'), GetClassName=lambda handle: {2: '#32770', 3: 'SysListView32', 4: 'Edit'}.get(handle, 'Main'),
@@ -179,7 +180,7 @@ def test_native_catalog_checks_cannot_cold_read_or_submit_on_miss(tmp_path, monk
monkeypatch.setattr(native_helper, 'selection', lambda *args: None) monkeypatch.setattr(native_helper, 'selection', lambda *args: None)
monkeypatch.setattr(native_helper, 'replacement_command_from_resources', lambda *args: 33977) monkeypatch.setattr(native_helper, 'replacement_command_from_resources', lambda *args: 33977)
monkeypatch.setattr(native_helper, 'wait_for', lambda callback, *args, **kwargs: callback()) monkeypatch.setattr(native_helper, 'wait_for', lambda callback, *args, **kwargs: callback())
monkeypatch.setattr(native_helper, 'wait_for_library_rows', lambda callback, *args: callback()) monkeypatch.setattr(native_helper, 'wait_for_library_rows', lambda callback, *args, **kwargs: callback())
monkeypatch.setattr(native_helper, 'wait_for_native_target', lambda callback, *args: callback()) monkeypatch.setattr(native_helper, 'wait_for_native_target', lambda callback, *args: callback())
report = {} report = {}
with pytest.raises(ValueError if fail_at else RuntimeError, match='重新读取目标封装' if fail_at else 'native submit reached'): with pytest.raises(ValueError if fail_at else RuntimeError, match='重新读取目标封装' if fail_at else 'native submit reached'):
+89
View File
@@ -0,0 +1,89 @@
import json
import os
from pathlib import Path
import subprocess
import sys
import pytest
from PySide6.QtCore import QByteArray
from test_ui_remediation import window
_GEOMETRY = 'main_window/geometry'
def test_geometry_persists_across_application_processes(tmp_path):
source = Path(__file__).resolve().parents[2] / 'src'
env = os.environ | {'PYTHONPATH': str(source)}
script = """
import json
import sys
from PySide6.QtCore import QTimer
from dx_productivity.trial_task_center import application
mode, root = sys.argv[1:]
window_type = application._load_window()
def open_window(service):
window = window_type(service)
def capture():
normal = window.normalGeometry()
area = window.screen().availableGeometry()
print(json.dumps({'normal': normal.getRect(), 'maximized': window.isMaximized(),
'reachable': area.contains(normal.topLeft()), 'fits': area.contains(normal)}),
flush=True)
window.close()
def arrange():
if mode == 'save':
window.setGeometry(45, 55, 1200, 760)
window.showMaximized()
QTimer.singleShot(200, capture)
QTimer.singleShot(0, arrange)
return window
application._load_window = lambda: open_window
raise SystemExit(application.main(['--data-root', root]))
"""
env.setdefault('QT_QPA_PLATFORM', 'offscreen')
def launch(mode, **overrides):
result = subprocess.run([sys.executable, '-c', script, mode, str(tmp_path)], env=env | overrides,
timeout=90, capture_output=True, text=True)
assert result.returncode == 0, result.stderr
return json.loads(result.stdout)
saved = launch('save')
reopened = launch('restore')
rescaled = launch('restore', QT_SCALE_FACTOR='1.5')
print(f'window geometry saved={saved}, reopened={reopened}')
print(f'window geometry at changed DPI={rescaled}')
assert saved['maximized'] and reopened['maximized']
assert saved['normal'][2:] == [1200, 760]
assert reopened['reachable'] and rescaled['reachable']
if saved['fits']:
assert reopened['normal'] == saved['normal']
@pytest.mark.parametrize('saved', ['broken', QByteArray(b'bad'), 'offscreen'])
def test_invalid_or_offscreen_settings_leave_window_visible(window, qtbot, saved):
if saved == 'offscreen':
window.setGeometry(50000, 50000, 1200, 760)
saved = window.saveGeometry()
window._layout_settings.setValue(_GEOMETRY, saved)
window._layout_settings.sync()
reopened = type(window)(window.service)
qtbot.addWidget(reopened)
try:
reopened.show()
rect = reopened.geometry()
area = reopened.screen().availableGeometry()
assert area.contains(rect.topLeft())
assert rect.intersects(area)
assert not reopened.isMaximized()
finally:
reopened.close()
+244
View File
@@ -0,0 +1,244 @@
"""Run issue #33 D8 through real service/SQLite queues with an injected CAD runner."""
from argparse import ArgumentParser
from collections import Counter
import csv
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
from uuid import uuid4
from dx_productivity.trial_task_center import supervisor_protocol
from dx_productivity.trial_task_center.batch_resources import _process_gone, process_identity, write_record
from dx_productivity.trial_task_center.inventory import HEADER
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer, _decode_vbs_field
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.stop_control import StopControl
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.target_plan import TargetPlanRow
from dx_productivity.trial_task_center.task_queue import _plan_hash, execute_task_queue
class SimulatedRuntime:
cad = desktop = None
stop_event = None
def __init__(self, root, release):
self.root = root
self.release = release
self.session_id = uuid4().hex
def bind_logs(self, *_):
pass
def release_failed_project(self, *args):
return self.release(*args)
def run(root, projects, *, expect_baseline, resume_short=False):
resource_failure = projects == 100
data = root / 'data'
source = root / 'projects'
shared = source / 'shared-db'
prior, blocked, dependent = (10, 11, 12) if resource_failure else (0, 0, 0)
if not resume_short:
root.mkdir(parents=True)
shared.mkdir(parents=True)
(shared / 'icdb.dat').write_bytes(b'simulated shared design source')
for ordinal in range(1, projects + 1):
path = source / f'board-{ordinal:03}' / 'board.prj'
path.parent.mkdir()
databank = shared if ordinal in (blocked, dependent) else 'database'
path.write_text(f'KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "{databank}"\n', encoding='utf-8')
data.mkdir()
stop = StopControl()
calls = []
release_checks = []
supervisor_calls = []
pre_cleanup = None
live_writer = None
identity = None
def worker(command, _timeout):
evidence = Path(command[3])
command_path = evidence / 'current-command.tsv'
if not command_path.exists():
command_path = evidence / 'command.tsv'
with command_path.open(encoding='utf-8-sig') as stream:
item = next(csv.DictReader(stream, delimiter='\t'))
path = Path(item['project_path'])
ordinal = int(path.parent.name.split('-')[-1])
if (evidence / 'sheet-discovery.request').exists():
(evidence / 'sheets.tsv').write_text(f'project_path\tschematic_name\tsheet_number\n{path}\tMAIN\t1\n')
(evidence / 'inventory.tsv').write_text(f'project_path\tschematic_name\tsheet_number\told_part\n{path}\tMAIN\t1\tOLD\n')
(evidence / 'components.tsv').write_text('\t'.join(HEADER) + f'\n{path}\tMAIN\t1\tuid\tR1\tOLD\t10K\n')
return subprocess.CompletedProcess(command, 0, '', '')
job = command[-1]
assert item['job_id'] == job
assert _decode_vbs_field(item['target_selectors']) == 'uid\x1fR1\x1f10K'
assert all(call['project'] != ordinal and call['job_id'] != job for call in calls)
state = 'batch_saved_unverified' if ordinal in (prior, blocked) else 'saved_ok'
calls.append({'project': ordinal, 'job_id': job, 'result': state})
message = ('Native replacement and parameter readback passed on current sheet. Replacements: '
'R1 OLD -> NEW Display verified: attributes=2. Saved, reopened for readback, and closed.')
if state != 'saved_ok':
message = 'Injected lookup timeout after an earlier possible CAD write.'
with (evidence / 'status.tsv').open('a', encoding='utf-8') as stream:
stream.write(f'{job}\tawaiting_native_replace\t\tcaptured\n')
stream.write(f'{job}\t{state}\tbatch_closed\t{message}\n')
if not resource_failure and ordinal == 3:
stop.set()
return subprocess.CompletedProcess(command, 0, '', '')
store = None
def open_service():
nonlocal store
store = TaskStore(data / 'task-center.db')
service = TaskCenterService(store, configure_logging(data), quick_run_preparer=QuickRunPreparer(
data, process_runner=worker, cscript_resolver=lambda: Path('simulated-cscript'),
sheet_discoverer=lambda _: (('MAIN', '1'),)))
service._supervised = True
def supervise(operation, arguments, *, stop_event):
nonlocal pre_cleanup
assert operation == 'execute_task_queue'
runtime = SimulatedRuntime(data, release)
supervisor_calls.append(dict(batch_id=runtime.session_id, queue_id=arguments.get('queue_id'),
resource_batch_id=arguments.get('resource_batch_id')))
result = execute_task_queue(service, stop_event=stop_event, runtime=runtime, **arguments)
if resource_failure and live_writer is not None and live_writer.poll() is None:
assert result.paused and result.current_task_id == ids[blocked - 1]
assert [entry['project'] for entry in calls] == list(range(1, blocked + 1))
assert not _process_gone(identity)
pre_cleanup = Counter(row.state for row in result.entries)
batch_id = runtime.session_id
attempt_id = uuid4().hex
directory = data / 'batch-resources' / batch_id
common = dict(version=supervisor_protocol.VERSION, batch_id=batch_id, attempt_id=attempt_id)
write_record(directory / 'request.json', dict(common, operation=operation,
root=str(data), arguments=supervisor_protocol.encode(arguments)))
request_digest = hashlib.sha256((directory / 'request.json').read_bytes()).hexdigest()
write_record(directory / 'result.json', dict(common, sequence=1, generation=1, type='result',
payload=dict(business_succeeded=True, result=supervisor_protocol.encode(result))))
journal = dict(common, operation=operation, task_ids=list(ids), state='finished',
process=identity, parent_process=identity, request_sha256=request_digest)
assert supervisor_protocol.valid_journal(journal, batch_id)
write_record(directory / 'supervisor.json', journal)
service._last_supervisor_batch_id = batch_id
from dx_productivity.trial_task_center import task_queue
admitted = getattr(task_queue, 'resource_pause_admitted', None)
if admitted is not None:
assert not admitted(data, batch_id, ids, hashes, result)
live_writer.terminate()
live_writer.wait(timeout=10)
assert _process_gone(identity)
return result
def release(error, evidence):
nonlocal live_writer, identity
ordinal = calls[-1]['project']
release_checks.append(ordinal)
if resource_failure and ordinal == blocked and live_writer is None:
live_writer = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(300)'],
creationflags=subprocess.CREATE_NO_WINDOW)
identity = process_identity(live_writer)
return live_writer is None or live_writer.poll() is not None
service._supervise = supervise
return service
service = open_service()
try:
if resume_short:
recorded = json.loads((root / 'pause.json').read_text(encoding='utf-8'))
ids = tuple(recorded['checkpoint']['task_ids'])
hashes = recorded['checkpoint']['plan_hashes']
calls.extend(recorded['calls'])
result = execute_task_queue(service, ids, stop_event=stop,
queue_id=recorded['queue_id'], expected_plan_hashes=hashes)
assert result.queue_id == recorded['queue_id']
final = json.loads((data / 'task-queues' / (result.queue_id + '.json')).read_text(encoding='utf-8'))
assert final['task_ids'] == list(ids) and final['plan_hashes'] == hashes
assert final['phase'] == 'finished' and not result.paused
assert Counter(row.state for row in result.entries) == {'completed': projects}
assert [call['project'] for call in calls] == list(range(1, projects + 1))
assert recorded['paused_in_pid'] != os.getpid()
return dict(projects=projects, first_return=recorded['first_return'],
final={'completed': projects}, queue_id=result.queue_id, calls=calls,
paused_in_pid=recorded['paused_in_pid'], resumed_in_pid=os.getpid())
tasks = service.create_project_tasks(source)
ids = tuple(task.task_id for task in tasks)
assert len(ids) == projects
assert [service.projects(task_id)[0].path.parent.name for task_id in ids] == [
f'board-{number:03}' for number in range(1, projects + 1)]
service.add_rule(ids[0], 'OLD', 'NEW')
for task_id in ids:
targets = service.collect_target_inventory(task_id, runtime=SimulatedRuntime(data, lambda *_: True))
service.replace_target_plan(task_id, [TargetPlanRow(targets[0].target, enabled=True, new_part_number='NEW')])
hashes = {task_id: _plan_hash(service.for_project_task(task_id), task_id) for task_id in ids}
first = execute_task_queue(service, ids, stop_event=stop, expected_plan_hashes=hashes,
checkpoint_id=uuid4().hex)
path = data / 'task-queues' / (first.queue_id + '.json')
checkpoint = json.loads(path.read_text(encoding='utf-8'))
initial = Counter(row.state for row in first.entries)
print(f'{projects} projects first return {dict(initial)}', flush=True)
if resource_failure:
assert pre_cleanup == {'completed': 9, 'blocked': 2, 'pending': projects - 11}
if expect_baseline:
assert first.paused and initial == pre_cleanup
return dict(projects=projects, first_return=initial, before_release=pre_cleanup,
queue_id=first.queue_id, writer_pid=identity['pid'],
writer_gone=_process_gone(identity), calls=calls, supervisor_calls=supervisor_calls)
assert not first.paused and initial == {'completed': 97, 'blocked': 3}
assert len(supervisor_calls) == 2
assert supervisor_calls[-1]['queue_id'] == first.queue_id
assert supervisor_calls[-1]['resource_batch_id'] == supervisor_calls[0]['batch_id']
else:
assert first.paused and [entry['project'] for entry in calls] == [1, 2, 3]
write_record(root / 'pause.json', dict(queue_id=first.queue_id, checkpoint=checkpoint,
calls=calls, first_return=initial, paused_in_pid=os.getpid()))
store.close()
subprocess.run([sys.executable, __file__, '--projects', str(projects), '--output', str(root),
'--resume-short'], check=True, creationflags=subprocess.CREATE_NO_WINDOW)
return json.loads((root / 'report.json').read_text(encoding='utf-8'))
store.close()
service = open_service()
stop = StopControl()
result = execute_task_queue(service, ids, stop_event=stop, queue_id=first.queue_id, expected_plan_hashes=hashes)
final = json.loads(path.read_text(encoding='utf-8'))
assert final['task_ids'] == checkpoint['task_ids']
assert final['plan_hashes'] == checkpoint['plan_hashes']
assert final['phase'] == 'finished' and not result.paused
if resource_failure:
assert final['dependency_tasks'] == {ids[dependent - 1]: ids[blocked - 1]}
assert [entry.state for entry in result.entries[prior - 1:dependent]] == ['blocked'] * 3
assert [call['project'] for call in calls] == [ordinal for ordinal in range(1, projects + 1) if ordinal != dependent]
assert execute_task_queue(service, ids, stop_event=stop, queue_id=result.queue_id) == result
return dict(projects=projects, first_return=initial, before_release=pre_cleanup,
final=Counter(row.state for row in result.entries), supervisor_calls=supervisor_calls,
queue_id=result.queue_id, shared_source_blocked=dependent or None,
writer_pid=(identity or {}).get('pid'), release_checks=release_checks, calls=calls)
finally:
if live_writer is not None and live_writer.poll() is None:
live_writer.terminate()
live_writer.wait(timeout=10)
store.close()
if __name__ == '__main__':
parser = ArgumentParser(description=__doc__)
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--projects', type=int, choices=(8, 100), required=True)
parser.add_argument('--expect-baseline', action='store_true')
parser.add_argument('--resume-short', action='store_true', help='Internal pause handoff to a new Python process')
args = parser.parse_args()
result = run(args.output.resolve(), args.projects, expect_baseline=args.expect_baseline,
resume_short=args.resume_short)
(args.output / 'report.json').write_text(json.dumps(result, indent=2), encoding='utf-8')
print({key: result.get(key) for key in ('projects', 'first_return', 'final', 'queue_id')}, flush=True)