Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4fb715507e | ||
|
|
c114db9f31 | ||
|
|
7d4f6bde0b | ||
|
|
ad3ee4151c | ||
|
|
8ccc9716de | ||
|
|
3187b304c6 | ||
|
|
29b40a5370 | ||
|
|
315d2e85b3 |
No files matched your search
@@ -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,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,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
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
|||||||
@@ -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:
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -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')
|
||||||
|
|||||||
@@ -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]:
|
||||||
|
|||||||
@@ -1078,10 +1078,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 +1090,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
|
||||||
@@ -1032,11 +1032,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()
|
||||||
@@ -1077,7 +1079,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 +1089,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 +1099,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
|
||||||
|
|||||||
@@ -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()
|
||||||
|
|||||||
@@ -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}]
|
||||||
@@ -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}'
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -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):
|
||||||
|
|||||||
@@ -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)
|
||||||
@@ -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'):
|
||||||
|
|||||||
Reference in new issue
Block a user