Compare commits
55
Commits
v1.0.0-r21
...
v1.1.1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fc67d403cb | ||
|
|
7610a0fd86 | ||
|
|
980198a987 | ||
|
|
579ecc38c4 | ||
|
|
48ad7b3592 | ||
|
|
fee1aff557 | ||
|
|
f26e868bfc | ||
|
|
5c0f6a3fd3 | ||
|
|
2a4e793d70 | ||
|
|
7d1574e748 | ||
|
|
dfe1f80f90 | ||
|
|
5817522ac0 | ||
|
|
2172d8faee | ||
|
|
4194c011e3 | ||
|
|
260e270be8 | ||
|
|
80f1cfd799 | ||
|
|
e265ca515d | ||
|
|
e3b0f8940c | ||
|
|
c0bf96f49d | ||
|
|
1df3f0cf30 | ||
|
|
42e5736ec6 | ||
|
|
bc6b726675 | ||
|
|
87ec3acc20 | ||
|
|
78f3b0c32a | ||
|
|
3e45040def | ||
|
|
44b4f5be48 | ||
|
|
1719683fc3 | ||
|
|
83ed50452b | ||
|
|
d79250b699 | ||
|
|
0225787084 | ||
|
|
20d8b81a34 | ||
|
|
10581df3e2 | ||
|
|
ae7e0e6a1b | ||
|
|
6c817de359 | ||
|
|
cffa845b11 | ||
|
|
f5d91e6216 | ||
|
|
6b52aa534e | ||
|
|
a18d4dbee6 | ||
|
|
b1a72bef29 | ||
|
|
fbc7ddd037 | ||
|
|
855af0bd12 | ||
|
|
4f457b1e88 | ||
|
|
a93e40ed2a | ||
|
|
62e7114211 | ||
|
|
dd6ab99a31 | ||
|
|
de2d48fbe0 | ||
|
|
157b99851a | ||
|
|
730c76081f | ||
|
|
f3d0d7a93d | ||
|
|
235a1005e9 | ||
|
|
a7e1b9bd33 | ||
|
|
210fae575d | ||
|
|
c9b38f15c0 | ||
|
|
5051a3b9d6 | ||
|
|
7dd7bc8d12 |
No files matched your search
@@ -16,3 +16,4 @@ __pycache__/
|
||||
*.rar
|
||||
.coverage
|
||||
coverage.xml
|
||||
/.worktrees/
|
||||
@@ -0,0 +1,209 @@
|
||||
# DxDesigner Part Replacement
|
||||
|
||||
面向 Windows 和 DxDesigner/Expedition Enterprise 7.9.5 的器件批量替换工具。工具通过 DxDesigner 原生 `Replace Part` 完成替换,并在写入前后保存快照、检查受保护字段、记录操作证据,支持桌面连续队列和可恢复的批处理流程。
|
||||
|
||||
**当前版本 V1.1.1**:[下载便携包](https://git.simgreek.com/simgreek/dxdesigner-part-replacement/releases/tag/v1.1.1) · [版本说明](docs/releases/v1.1.1.md)。目录读取后一个工程对应一个任务,可采集位号并直接选择部分器件替换,逐行设置新料号、Value 和 NC;Excel 为可选编辑方式,同批任务顺序执行。见 [使用说明](docs/user/v1.1.0-project-tasks.md) 和 [快速测试入口](docs/testing/v1.1.0-test-entrypoints.md)。
|
||||
|
||||
**V1.1.1 后台执行**:任务中心的自动采集、替换和恢复默认在独立 Windows 桌面启动自有 CAD;完成或暂停后退出 CAD、等待进程结束并确认桌面释放。用户可继续在主桌面查看其他文件,工具不接管主桌面的 CAD。目标工程仍须保存并关闭,避免同时访问同一工程。实测及限制见 [私有桌面执行验证](docs/testing/2026-10-15-private-desktop-execution.md)。
|
||||
|
||||
> **当前发布级别:evaluation-only(仅评估)。** 在目标现场完成 7.9.5 验收并取得可追溯证据之前,只能对完整、可丢弃的工程副本和对应中央库进行操作。不要用于唯一工程副本、生产库或未经认证的料号映射。
|
||||
|
||||
## 能做什么
|
||||
|
||||
| 使用路径 | 适合场景 | 结果含义 |
|
||||
| --- | --- | --- |
|
||||
| `DxPartReplace.exe` 桌面连续队列 | 选择工程目录和映射后,按“工程 → 图页 → 规则”串行执行 | 命中项经过替换、保存、关闭和重新打开核验;未命中项记录并跳过;“队列完成”不等于通过 Packager、ERC 或网表检查 |
|
||||
| 桌面人工证据流程 | 由操作员在 DxDesigner 中完成替换,工具采集 Before/After 证据 | 只表示证据比较通过,不自动替换、保存或关闭工程 |
|
||||
| `Start-PartReplacement.ps1` + `dx_productivity` CLI | 需要完整库存、认证、备份、恢复和外部检查门禁的评估批次 | 只有项目进入 `verified_saved` 且外部检查通过,批次才可报告为成功 |
|
||||
|
||||
三条路径的任务、日志和通过条件不同,不能互相替代。详细边界见 [`docs/user/trial-task-center.md`](docs/user/trial-task-center.md)。
|
||||
|
||||
## 运行前提
|
||||
|
||||
- Windows;真实替换基线为 **DxDesigner/Expedition Enterprise 7.9.5**。
|
||||
- 源码运行和批处理 CLI 使用 **Python 3.12(必须是 3.12)**。
|
||||
- 目标机器需要可用的 DxDesigner 安装、许可证和中央库;没有中央库时只能运行测试、构建和界面冒烟检查。
|
||||
- 自动替换每次处理一个工程。开始前保存并关闭本次目标工程;V1.1.1 使用自有后台 CAD,用户打开的其他工程不会被接管。更早发布包仍按原版本要求关闭已打开工程。
|
||||
- 每次现场试验使用完整工程副本,并保留备份、快照、状态、事件日志和报告。
|
||||
|
||||
## 发布包:最快上手
|
||||
|
||||
1. 解压与目标 DxDesigner 版本匹配的发布包,保留 `DxPartReplace.exe`、`_internal` 和 `data` 目录结构。
|
||||
2. 双击 `DxPartReplace.exe`。
|
||||
3. 新建任务,读取包含 `.prj` 文件的根目录;勾选工程后批量创建任务,一个工程一个任务。
|
||||
4. 添加“旧 Part Number → 新 Part Number”映射,按需要设置 Value 和 `/NC` 选项。
|
||||
5. 需要只替换部分位号时,在“位号计划”采集、勾选并保存;先确认工程已经保存并关闭,再点击 **连续执行队列** 或 **顺序执行本批任务**。
|
||||
6. 执行过程中不要在 DxDesigner 中切页、编辑或关闭当前工程。遇到“结果无法确认”、保护锁或恢复提示时,先保留现场文件并按恢复文档处理,不要重复点击。
|
||||
|
||||
发布版默认把可变数据放在 EXE 同目录的 `data` 下:
|
||||
|
||||
~~~text
|
||||
data/task-center.db 任务数据库
|
||||
data/logs/application.log 应用日志
|
||||
data/tasks/<task-id>/ 任务事件与证据
|
||||
data/quick-run/ 连续队列交接文件、备份和运行日志
|
||||
~~~
|
||||
|
||||
更新程序时只替换 EXE 和 `_internal`,不要删除 `data`。分发新包时使用未运行过的干净目录,不要把包含工程备份的本机 `data` 一起外发。
|
||||
|
||||
## 从源码运行
|
||||
|
||||
在仓库根目录使用 PowerShell:
|
||||
|
||||
~~~powershell
|
||||
py -3.12 -m venv .venv
|
||||
.\.venv\Scripts\python.exe -m pip install --upgrade pip
|
||||
.\.venv\Scripts\python.exe -m pip install -e ".[dev]"
|
||||
~~~
|
||||
|
||||
启动桌面程序:
|
||||
|
||||
~~~powershell
|
||||
.\.venv\Scripts\python.exe -m dx_productivity.trial_task_center.application
|
||||
# 或
|
||||
.\.venv\Scripts\dx-part-replace-gui.exe
|
||||
~~~
|
||||
|
||||
启动 CLI:
|
||||
|
||||
~~~powershell
|
||||
.\.venv\Scripts\python.exe -m dx_productivity --help
|
||||
# 或
|
||||
.\.venv\Scripts\dx-part-replace.exe --help
|
||||
~~~
|
||||
|
||||
源码运行时,任务中心默认使用 `%LOCALAPPDATA%\DxProductivity\trial-task-center`。可以用 `DX_TASK_CENTER_HOME` 指定独立数据目录;发布版则默认使用 EXE 旁边的 `data`。
|
||||
|
||||
## CLI 快速参考
|
||||
|
||||
CLI 的输出默认是便于阅读的文本;添加 `--json` 可获得脚本可消费的稳定 JSON。下面的命令只负责发现和创建作业,真实 DxDesigner 操作仍需要已验收的配置、中央库和现场操作流程。
|
||||
|
||||
发现候选项目后必须逐行审阅:
|
||||
|
||||
~~~powershell
|
||||
.\.venv\Scripts\python.exe -m dx_productivity --json discover "D:\Disposable\Projects" --output "D:\Qualification\projects-candidates.txt"
|
||||
~~~
|
||||
|
||||
创建作业需要 UTF-8 映射、项目列表和认证文件:
|
||||
|
||||
~~~powershell
|
||||
.\.venv\Scripts\python.exe -m dx_productivity --json create "C:\DxProductivity\runs\part-replace-<GUID>" --mapping "D:\Qualification\replacement.csv" --projects "D:\Qualification\projects.txt" --certifications "D:\Qualification\certifications.json"
|
||||
~~~
|
||||
|
||||
常用作业查询和恢复命令:
|
||||
|
||||
~~~powershell
|
||||
.\.venv\Scripts\python.exe -m dx_productivity --json status "C:\DxProductivity\runs\part-replace-<GUID>"
|
||||
.\.venv\Scripts\python.exe -m dx_productivity --json restore "C:\DxProductivity\runs\part-replace-<GUID>" "<project_id>"
|
||||
~~~
|
||||
|
||||
不要编辑 `manifest`、`mailbox`、状态文件或事件文件来推进任务;恢复必须使用原作业目录,不能用相同输入重新创建一个“看起来一样”的新作业。完整命令循环、状态和恢复前提见 [`docs/user/part-replacement.md`](docs/user/part-replacement.md)。
|
||||
|
||||
## 原生批处理集成
|
||||
|
||||
这条路径用于需要兼容性配置、项目库存、认证映射、备份、恢复和 Packager/ERC/网表检查门禁的评估批次。
|
||||
|
||||
### 1. 安装运行目录
|
||||
|
||||
`Install.ps1` 会验证 Python 3.12 和 `dx_productivity` 导入,将现场 probe 产生的兼容性配置原子部署到 `runs\compatibility-profile.json`,并写入当前用户的设置。先用 `-WhatIf` 预览路径:
|
||||
|
||||
~~~powershell
|
||||
& "C:\DxProductivity\integration\dxdesigner795\Install.ps1" -InstallRoot "C:\DxProductivity" -PythonExecutable "C:\Python312\python.exe" -CompatibilityProfile "C:\Qualification\compatibility-profile.json" -WhatIf
|
||||
~~~
|
||||
|
||||
确认输出后再去掉 `-WhatIf`。然后在 DxDesigner 中导入 `integration\dxdesigner795\MenuAdd.vbs`,使 `Dx Productivity` 菜单出现。
|
||||
|
||||
兼容性配置必须来自实际 probe 和现场验收。不能手工把 `live_acceptance.checked` 改成 `true`;未完成验收时,发布分类仍为 `evaluation-only`。
|
||||
|
||||
### 2. 准备输入
|
||||
|
||||
映射文件 `replacement.csv` 只有两个列名:
|
||||
|
||||
~~~csv
|
||||
old_part_number,new_part_number
|
||||
OLD-001,NEW-001
|
||||
OLD-002,NEW-002
|
||||
~~~
|
||||
|
||||
工具会拒绝空值、重复旧值、旧新相同、链式映射和循环映射。目标只能通过中央库 `Part Number` 指定,不能用元件名、符号名或引脚名代替。
|
||||
|
||||
项目列表 `projects.txt` 每行一个绝对 `.prj` 路径:
|
||||
|
||||
~~~text
|
||||
D:\Disposable\Board-A\Board-A.prj
|
||||
D:\Disposable\Board-B\Board-B.prj
|
||||
~~~
|
||||
|
||||
每个 old/new 映射都必须先在代表性、关闭的可丢弃副本上完成认证,并绑定中央库身份或目标指纹。当前交付没有公开的“生成认证”命令,不要伪造 `certifications.json`。
|
||||
|
||||
### 3. 启动作业
|
||||
|
||||
~~~powershell
|
||||
& "C:\DxProductivity\integration\dxdesigner795\Start-PartReplacement.ps1" -Mapping "D:\Qualification\replacement.csv" -Projects "D:\Qualification\projects.txt" -Certifications "D:\Qualification\certifications.json"
|
||||
~~~
|
||||
|
||||
暂停时保留控制台打印的绝对作业路径,用 `-ResumeJob` 恢复;恢复时不要再次传入 Mapping、Projects、Certifications 或 DiscoveryRoot:
|
||||
|
||||
~~~powershell
|
||||
& "C:\DxProductivity\integration\dxdesigner795\Start-PartReplacement.ps1" -ResumeJob "C:\DxProductivity\runs\part-replace-<GUID>"
|
||||
~~~
|
||||
|
||||
完整操作顺序和人工菜单动作见 [`docs/user/part-replacement.md`](docs/user/part-replacement.md)。
|
||||
|
||||
## 安全边界与恢复
|
||||
|
||||
- 写入前先固定图页清单、检查工程身份,并为实际命中的工程创建原理图精简备份;备份包含文件清单和 SHA-256。
|
||||
- 原生替换后检查 Part Number、RefDes、层级、放置单元、位置、旋转、镜像、门/槽、引脚集合、引脚坐标和网络身份。硬字段或连接无法证明未变时必须阻断。
|
||||
- 连续队列按“工程 → 图页 → 规则”串行执行,同一时间不打开多个工程;图页新增、删除或重命名会在下一次写入前停止。
|
||||
- 零命中会记录为 `no_match` 并跳过替换,不等于替换成功,也不代表其他图页没有该料号。
|
||||
- 保存、关闭、回读或监控结果不确定时保留保护锁、快照和证据,不要删除锁文件或强制重试。
|
||||
- 恢复只能针对原作业、原工程和绑定证据执行;恢复失败时保留失败树、备份和隔离证据,交给现场负责人调查。
|
||||
|
||||
Value 内容、样式继承和 `/NC` 同步规则见 [`docs/user/value-copy-and-layout.md`](docs/user/value-copy-and-layout.md);连续队列和长期证据保留见 [`docs/user/continuous-queue.md`](docs/user/continuous-queue.md)。
|
||||
|
||||
## 日志、报告与支持交接
|
||||
|
||||
排查问题时保留目标工程副本和整个数据目录,至少包括:
|
||||
|
||||
- `logs/application.log`;
|
||||
- 对应任务的 `events.jsonl`;
|
||||
- `quick-run/quick-part-replace.log`、`command.tsv`、`status.tsv`;
|
||||
- 替换前后快照、原生 helper 报告、`uncertain.flag`(如存在);
|
||||
- CLI 作业中的 `reports/impact.csv`、`reports/differences.json`、`reports/summary.html`。
|
||||
|
||||
交接记录还应包含 DxDesigner build、Windows 版本、工程规范路径、中央库身份/指纹、映射、操作员、日期及每份证据的 SHA-256。自动化回归和 mock 测试不能替代现场验收。
|
||||
|
||||
## 开发、测试与构建
|
||||
|
||||
运行完整测试:
|
||||
|
||||
~~~powershell
|
||||
.\.venv\Scripts\python.exe -m pytest -q
|
||||
~~~
|
||||
|
||||
构建 Windows 发布目录:
|
||||
|
||||
~~~powershell
|
||||
.\packaging\Build-DxPartReplace.ps1 -PythonExecutable ".\.venv\Scripts\python.exe"
|
||||
~~~
|
||||
|
||||
构建脚本会运行打包相关测试、调用 PyInstaller、检查 `QuickPartReplace.vbs` 是否完整复制,并启动 `--smoke-test` 验证 EXE 能创建和关闭日志。打包需要本机已注册的 DxDesigner EE 7.9.5 类型库;输出位于 `dist\DxPartReplace`。
|
||||
|
||||
## 文档索引
|
||||
|
||||
- [桌面任务中心与连续队列](docs/user/trial-task-center.md)
|
||||
- [DxDesigner 7.9.5 批处理操作指南](docs/user/part-replacement.md)
|
||||
- [连续队列细节与长期保留](docs/user/continuous-queue.md)
|
||||
- [Value、布局和 `/NC` 规则](docs/user/value-copy-and-layout.md)
|
||||
- [中断恢复](docs/user/interrupted-recovery.md)
|
||||
- [进度监控与超时](docs/user/progress-timeout.md)
|
||||
- [自动启动 DxDesigner](docs/user/automatic-designer-startup.md)
|
||||
- [现场验收清单](docs/testing/dxdesigner-795-part-replacement-live.md)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
{
|
||||
"artifacts": {
|
||||
"version": "1.1.1",
|
||||
"code_commit": "7610a0fd86b98733b6e92234ba744ca5bcfc88d4",
|
||||
"build_checks": {
|
||||
"passed": 219,
|
||||
"seconds": 34.87
|
||||
},
|
||||
"exe_sha256": "f029d60fe808c7b5eb47adf9795d4733faa66f33c3f6e9f779fc2541268d1c70",
|
||||
"vbs_sha256": "212857251e3f42347720b21520836035fa467635ef47f4ca3f330f04cc5a2480",
|
||||
"private_cad_helper_probe": {
|
||||
"passed": true,
|
||||
"project_opened": false,
|
||||
"clean_released": true
|
||||
},
|
||||
"zip_sha256": "f42f656974cb5170dc4ed80a3e9eaabdedae45ecee229da46a57a178d867e532",
|
||||
"zip_bytes": 52514265,
|
||||
"file_count": 235,
|
||||
"unpacked_bytes": 128586142
|
||||
},
|
||||
"packaged_helpers": {
|
||||
"passed": true,
|
||||
"commands": [
|
||||
{
|
||||
"action": "probe",
|
||||
"executable": "F:\\Sync Tool Skyworth\\Work Maps\\dxdesigner-part-replacement\\dist\\DxPartReplace\\DxPartReplace.exe"
|
||||
},
|
||||
{
|
||||
"action": "quit",
|
||||
"executable": "F:\\Sync Tool Skyworth\\Work Maps\\dxdesigner-part-replacement\\dist\\DxPartReplace\\DxPartReplace.exe"
|
||||
}
|
||||
],
|
||||
"session": {
|
||||
"desktop": "dx-258535e794ca41598c912ae87fcdf92b",
|
||||
"token": "258535e794ca41598c912ae87fcdf92b",
|
||||
"state": "released",
|
||||
"cad_pid": 52248,
|
||||
"guid": "{449B3896xE3A2x469Ax9AEExE68DD21C4B67}",
|
||||
"startup_seconds": 31.484000000025844,
|
||||
"clean": true,
|
||||
"shutdown_seconds": 4.60999999998603
|
||||
},
|
||||
"source_path_removed_from_child": true,
|
||||
"project_opened": false
|
||||
},
|
||||
"desktop_observation": {
|
||||
"samples": 166,
|
||||
"file_read_samples": 166,
|
||||
"input_desktop_before": "Default",
|
||||
"input_desktop_after": "Default",
|
||||
"foreground_pids": [
|
||||
10104,
|
||||
13256
|
||||
],
|
||||
"owned_cad_became_foreground": false,
|
||||
"owned_cad_on_input_desktop": false,
|
||||
"baseline_default_cad_pids": [
|
||||
18732
|
||||
],
|
||||
"observed_default_cad_pids": [
|
||||
18732
|
||||
],
|
||||
"cad_exit_confirmed": {
|
||||
"52248": true
|
||||
},
|
||||
"desktop_absent": {
|
||||
"dx-258535e794ca41598c912ae87fcdf92b": true
|
||||
},
|
||||
"sessions": {
|
||||
"dx-258535e794ca41598c912ae87fcdf92b": {
|
||||
"desktop": "dx-258535e794ca41598c912ae87fcdf92b",
|
||||
"token": "258535e794ca41598c912ae87fcdf92b",
|
||||
"state": "released",
|
||||
"cad_pid": 52248,
|
||||
"guid": "{449B3896xE3A2x469Ax9AEExE68DD21C4B67}",
|
||||
"startup_seconds": 31.484000000025844,
|
||||
"clean": true,
|
||||
"shutdown_seconds": 4.60999999998603,
|
||||
"evidence_path": "data\\tasks\\packaged\\quick-run\\private-desktop.json"
|
||||
}
|
||||
},
|
||||
"observer_errors": []
|
||||
},
|
||||
"extracted_zip_smoke": {
|
||||
"extracted_zip_smoke": true,
|
||||
"version": "1.1.1",
|
||||
"exit_code": 0,
|
||||
"missing_helper_arguments_exit_code": 2,
|
||||
"data_directory_excluded_from_archive": true,
|
||||
"log": "2026-10-15T05:34:36Z INFO dx_productivity.trial_task_center.f2619d17fd50a1f1 logging configured root=F:\\Sync Tool Skyworth\\Work Maps\\dxdesigner-part-replacement\\build\\release-1.1.1-smoke-data application_log=F:\\Sync Tool Skyworth\\Work Maps\\dxdesigner-part-replacement\\build\\release-1.1.1-smoke-data\\logs\\application.log\n2026-10-15T05:34:36Z INFO dx_productivity.trial_task_center.f2619d17fd50a1f1 application_start version=1.1.1 executable=F:\\Sync Tool Skyworth\\Work Maps\\dxdesigner-part-replacement\\build\\release-1.1.1-extracted\\DxPartReplace\\DxPartReplace.exe os=Windows-11-10.0.26200-SP0 data_root=F:\\Sync Tool Skyworth\\Work Maps\\dxdesigner-part-replacement\\build\\release-1.1.1-smoke-data database=F:\\Sync Tool Skyworth\\Work Maps\\dxdesigner-part-replacement\\build\\release-1.1.1-smoke-data\\task-center.db application_log=F:\\Sync Tool Skyworth\\Work Maps\\dxdesigner-part-replacement\\build\\release-1.1.1-smoke-data\\logs\\application.log\n2026-10-15T05:34:36Z INFO dx_productivity.trial_task_center.f2619d17fd50a1f1 recovered_interrupted_projects=none\n2026-10-15T05:34:37Z INFO dx_productivity.trial_task_center.f2619d17fd50a1f1 operation_start=list_tasks task_id= at=2026-10-15T13:34:37.043664\n2026-10-15T05:34:37Z INFO dx_productivity.trial_task_center.f2619d17fd50a1f1 operation_complete=list_tasks task_id= at=2026-10-15T13:34:37.047016\n2026-10-15T05:34:37Z INFO dx_productivity.trial_task_center.f2619d17fd50a1f1 application_clean_shutdown exit_code=0\n"
|
||||
},
|
||||
"pre_release_fixes": [
|
||||
"Absolute package import for an application executed as the frozen entry script; regression reproduced before the fix.",
|
||||
"Bounded atomic state publication retry for Windows readers denying delete access; native transient and persistent sharing tests added."
|
||||
],
|
||||
"validation_boundary": "Real packaged EXE probe/quit helpers launched by the source supervisor; no project opened in this package smoke. Previous real replacement evidence is linked in the release notes. No new Packager/ERC qualification."
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
# 1.1.1 发布构建记录
|
||||
|
||||
日期:2026-10-15。程序源码提交:`7610a0fd86b98733b6e92234ba744ca5bcfc88d4`;后续发布文档及探针提交不改变成品程序代码。
|
||||
|
||||
- 标准构建脚本发布检查:219 passed,34.87 秒;没有跳过或放宽构建门槛。
|
||||
- PyInstaller 6.22.3 / Python 3.12.10 构建成功;构建自带的独立启动退出检查通过。
|
||||
- ZIP 解压到全新目录后,EXE 启动日志为 version=1.1.1,正常退出码 0;helper 缺少必要参数时退出码 2。
|
||||
- 成品 EXE 的真实后台 CAD probe/quit 通过,子进程移除源码 PYTHONPATH,没有打开工程;CAD 与桌面确认释放,主桌面没有被切换或抢占。
|
||||
- 本次私有 CAD 启动 31.484 秒,退出 4.610 秒;166 次主桌面采样和普通文件读取均完成。
|
||||
- ZIP CRC、文件清单、EXE 哈希及包内 VBS 与源码哈希一致性检查通过;包内不含 data、任务数据库、日志或工程备份。
|
||||
|
||||
产物:`dist/DxPartReplace-1.1.1.zip`,52,514,265 字节(50.08 MiB),235 个文件。
|
||||
|
||||
| 文件 | SHA-256 |
|
||||
| --- | --- |
|
||||
| ZIP | `f42f656974cb5170dc4ed80a3e9eaabdedae45ecee229da46a57a178d867e532` |
|
||||
| EXE | `f029d60fe808c7b5eb47adf9795d4733faa66f33c3f6e9f779fc2541268d1c70` |
|
||||
| QuickPartReplace.vbs | `212857251e3f42347720b21520836035fa467635ef47f4ca3f330f04cc5a2480` |
|
||||
|
||||
源码、验证探针和记录推送至 `codex/execution-responsiveness`,版本标签 `v1.1.1`。发行附件为 ZIP 与 `SHA256SUMS-1.1.1.txt`,发布页:[DxPartReplace 1.1.1](https://git.simgreek.com/simgreek/dxdesigner-part-replacement/releases/tag/v1.1.1)。附件上传后另行下载验证 SHA-256。
|
||||
|
||||
本次发版过程中复现并修复了两项:冻结脚本入口的相对导入失败,以及状态读者短暂占用导致 Windows 原子替换失败。第一轮成品 helper 实际已退出 CAD、释放桌面,但最终状态记录因占用失败;修复后重新运行标准构建与成品探针通过。
|
||||
|
||||
详细证据见 [JSON](v1.1.1-build.json)。本轮成品验证由源码监督器调用实际 EXE 的 probe/quit 入口,不代表又执行了成品整批替换。此前真实替换、恢复及异常清理证据见 [后端验证记录](../testing/2026-10-15-private-desktop-execution.md),没有新增 Packager/ERC 认证。
|
||||
@@ -0,0 +1,31 @@
|
||||
# DxPartReplace 1.1.1
|
||||
|
||||
发布日期:2026-10-15。
|
||||
|
||||
本版包含按工程创建任务、位号计划、可选 BOM/Excel 导入、任务顺序执行,以及后台 CAD 执行与完整退出清理。
|
||||
|
||||
## 更新内容
|
||||
|
||||
- 自动采集、替换和中断恢复默认使用私有桌面中的自有 CAD,主桌面可继续查看其他文件。
|
||||
- 完成、暂停和异常退出均检查自有进程及桌面释放;记录每次后台会话证据。
|
||||
- 单步替换同样执行备份、保存、关闭与重开核验;恢复成功后无需另行手动保存。
|
||||
- 界面显示后台 CAD 启动及退出阶段,保留位号、旧新物料号、执行阶段耗时和速率记录。
|
||||
- 保留同一工程的连续步骤会话复用、异步查询及取消、工程发现缓存等优化。
|
||||
- 修复冻结程序后台 helper 的脚本入口导入错误,版本号更新为 1.1.1。
|
||||
- 后台状态文件遇到短暂的 Windows 读取占用时进行有限重试,持续权限错误仍会明确报告。
|
||||
|
||||
## 下载与使用
|
||||
|
||||
下载 `DxPartReplace-1.1.1.zip` 并完整解压,运行 `DxPartReplace/DxPartReplace.exe`。保留同目录的 `_internal`,不能只复制 EXE。无需另外安装 Python,仍需本机可用的 DxDesigner EE 7.9.5、许可证和中央库。
|
||||
|
||||
升级前关闭旧工具并备份原 `data`;更新 EXE 和 `_internal`,保留原有 `data`。新包不含本机任务、日志或工程备份,不同版本不要同时使用同一数据目录。
|
||||
|
||||
目标工程开始前须保存关闭,运行时不要同时打开或修改它。其他工程不会被接管。后台 CAD 启动实测约 22~35 秒,许可证和系统资源仍共享。
|
||||
|
||||
`SHA256SUMS-1.1.1.txt` 提供 ZIP 的 SHA-256。便携目录同时包含使用说明和版本清单。
|
||||
|
||||
## 验证范围
|
||||
|
||||
发布构建运行功能和执行保护检查,再执行 PyInstaller 构建及独立 EXE 启动退出检查。成品另执行实际私有 CAD probe/quit 验证,不依赖源码 PYTHONPATH;确认主桌面不切换、自有 CAD 退出、私有桌面释放。发布记录保存测试结果、ZIP/EXE/脚本哈希及验证证据。
|
||||
|
||||
原生替换、保存回读、恢复、暂停和超时证据见 [私有桌面执行验证](../testing/2026-10-15-private-desktop-execution.md)。本次成品验证没有重新进行整批替换或 Packager/ERC 验收;现有现场验收边界不变。
|
||||
@@ -0,0 +1,89 @@
|
||||
# CBB Verify 与后台原生后端借鉴调研
|
||||
|
||||
调研日期:2026-10-14。读取 `cbb-refresh-verify-795`、`mentor_PDF_output` 源码、已有离线证据和本机 EE7.9.5 安装目录静态文件;没有启动 Mentor、没有附着 COM、没有修改工程或中心库。
|
||||
|
||||
## CBB Verify 的真正原理
|
||||
|
||||
CBB Verify 当前代码使用有界的原生进程监督器:
|
||||
|
||||
```text
|
||||
单个 CBB
|
||||
-> 固定目标 LMC/CBB/PCB 身份
|
||||
-> 创建独立 Windows desktop
|
||||
-> CreateProcess + Job Object 管理 worker 和子进程
|
||||
-> 启动 common\\win32\\bin\\ExpeditionPCB.exe <PCB> -ReusableCircuit
|
||||
-> 通过 PID、命令行和父子关系绑定本次 wg PCB worker
|
||||
-> COM 获取 MGCPCB.Application / ActiveDocument
|
||||
-> ProjectIntegration 状态机逐项执行并重新读取状态
|
||||
-> 保存、关闭、退出证据
|
||||
-> x86 状态桥调用 IsVerifiedReuseBlock
|
||||
-> 只有本次执行后的 READY/raw=1 才算成功
|
||||
```
|
||||
|
||||
其中 `Library Manager` 的原生 Verify 菜单路线只是兼容/诊断路线。已有现场记录表明,在 7.9.5 上它依赖物理光标命中树节点;私有 desktop 中光标位置不可用,消息投递会落到停靠面板菜单。真实输入可以成功,但会切换用户输入桌面,因此没有作为默认后台路径。
|
||||
|
||||
`reusable_circuit_direct` 路线的价值在于:窗口可以存在于私有桌面,用户前台不被切走;进程树可被 Job Object 收回;COM 操作不靠屏幕坐标;成功判定依赖执行后的权威状态,而不是“窗口关闭”或某个中间灯变绿。
|
||||
|
||||
本轮核对的源码依据:
|
||||
|
||||
- `cbb-refresh-verify-795/src/cbb_refresh_verify/desktop_worker.py:26-45`:CreateDesktop、STARTUPINFO.lpDesktop、CreateProcess、Job Object。
|
||||
- `src/cbb_refresh_verify/mentor_adapter.py:178-192,651-706`:优先 common 启动器、生产 direct 路线、实际 PCB worker 绑定和 COM 文档身份检查。
|
||||
- `src/cbb_refresh_verify/integration.py:10-15,57-96`:ForwardAnnotate/SynchCES/LoadCES/BackAnnotate 状态机,每次执行后重读状态;初始四绿时只做一次 ForwardAnnotate,再按实际 Required 修复。
|
||||
- `tools/status_bridge/CbbStatusBridge32.cpp:19,187-205`:x86/MFC 桥动态读取 LMCDLL70.dll 的 IsVerifiedReuseBlock 导出。它是 CBB 状态读取接口,不能作为替换执行接口。
|
||||
- `docs/diagnostics/2026-09-29-r4-field-log-review.md:9-27`:已有现场报告记载 direct 路线、9 个本次 READY/raw=1 成功项和 8 个失败项。本轮未重新运行这些工程。
|
||||
|
||||
旧 README、API-FINDINGS 和研究计划中存在不同历史路线,不能只按其中一句话判断当前实现。上述结论优先依据当前 mentor_adapter 的实际分支以及有日期的现场记录。
|
||||
|
||||
## 可借鉴到 Part Replace 的部分
|
||||
|
||||
可以直接借鉴以下架构:
|
||||
|
||||
1. 把一个工程任务封装成独立 native worker,会话绑定工程路径、任务 ID、目标 UID 集合、旧料号、新料号和计划哈希。
|
||||
2. 用 `CreateProcess`、私有 desktop 和 Job Object 管理 DxDesigner 及其脚本/辅助进程。超时只终止本次创建的进程树。
|
||||
3. 通过进程 PID、命令行和父子关系绑定本次 DxDesigner/worker,禁止附着到用户已有的同名进程。
|
||||
4. 将“打开工程、选中 UID、调用 Replace Part、Library Wins、保存、关闭、重新打开”拆成状态机,每个阶段写结构化事件和快照。
|
||||
5. 把最终判断改成后置不变量:目标 UID 已变成新料号、RefDes/网络/引脚/受保护属性保持、未选中同旧料号器件未变、保存后重开仍成立。任一状态不确定就阻断后续任务。
|
||||
6. 沿用 CBB 的单项证据目录、串行队列、失败后继续/不确定后停止、最终报告和可恢复检查点。
|
||||
|
||||
不能直接照搬 CBB 的内容检查接口。CBB 的 `ProjectIntegration`、ReusableCircuit 保存和 `IsVerifiedReuseBlock` 是 CBB 中心库认证语义,与原理图器件替换不是同一对象。
|
||||
|
||||
## “像 MentorPDF 一样”的原生接口调查
|
||||
|
||||
MentorPDF 使用的是官方命令行:
|
||||
|
||||
```text
|
||||
sch2pdf.exe -project <project.prj> -a <output.pdf> -c <color> ...
|
||||
```
|
||||
|
||||
它没有 UID、RefDes、旧料号、新料号或 Library Wins 参数,所以只能借鉴其进程管理、串行队列、Job Object、前后指纹、日志目录和原子提交,不能作为替换后端。
|
||||
|
||||
本机安装目录静态检索到的候选如下:
|
||||
|
||||
| 候选 | 证据 | 判断 |
|
||||
| --- | --- | --- |
|
||||
| `sch2pdf.exe` | 官方 CLI;输入工程,输出 PDF | PDF 导出,可能更新 iCDB/日志;没有已证明的替换合同 |
|
||||
| `DxPDF.exe` | PDF GUI 前端字符串 | 不含替换合同 |
|
||||
| `icdbPartsLister.exe` | 字符串包含 `Part Number`、`REFDES`、`cComp`、`Component` | 只能作为只读库存候选,尚无输出协议或写入证据 |
|
||||
| `IVdApp.ExecuteCommand` / `ccomp` | TypeLib 有 ExecuteCommand;安装样例只证明 `component 74ls01` 放置元件 | `ccomp` 语法、范围、Library Wins 均未证实 |
|
||||
| `IVdBlock.ChangeComponentPreserveRefdes` | 当前 7.9.5 TypeLib 确有 DISPID 42 | 没有 Library Wins 参数,未证明选中范围、网络/引脚和中心库语义 |
|
||||
| `IVdApp.ReplacePart` | 只在工作区保存的 119.0 wrapper 中出现 | 当前安装版 TypeLib 1.0 不含,不能盲调 |
|
||||
| `CLibServer::VerifyRCCells(int)` | CBB 研究计划中的内部 ABI 候选 | 只与 CBB Verify 相关,ABI 尚未验证,不能用于 Part Replace |
|
||||
|
||||
补充搜索范围:四个相关安装 bin 目录中的 91 个 PE 文件导出表,只找到两个 iCDB::String::Replace 字符串处理符号,没有发现设计替换导出。这个结果不能排除未导出内部函数、资源命令或其他版本能力。详细路径、符号和边界见 `2026-10-14-mentorpdf-native-interface-followup.md`。
|
||||
|
||||
另外,本轮用 7-Zip 成功解开本机 `automate.chm`、`viewdraw.chm`、`dxdesigner.chm`。`viewdraw/command/ccomp.htm`、`getst/Replacing_Components_.htm` 和 `refer2/HID_COMP_REPLACE.htm` 实际为跳转至 InfoHub 的占位页面,没有命令参数说明。安装 `docs` 只包含系统管理手册,没有找到对应的完整原理图命令参考。提取内容仅保存在忽略目录 `build/native-help-20261014`,没有提交厂商帮助内容。
|
||||
|
||||
## 建议的下一步
|
||||
|
||||
建议新增一个 **research-only `private_desktop_backend`**,不改变当前生产后端:
|
||||
|
||||
1. 先用可丢弃工程副本验证 `viewdraw.exe`/Viewdraw COM 是否能在私有 desktop 启动、打开单工程并通过 UID 选中;只读确认 COM 身份,不执行替换。
|
||||
2. 再验证原生 Replace Part 对话框能否通过窗口消息在私有 desktop 完成一次单 UID 替换。若依赖物理光标或真实输入,立即判定该路线不适合后台。
|
||||
3. 只有在目标选择、Library Wins、保存回读、未选中件保护和进程清理全部有证据后,才把它提升为可选后端。
|
||||
4. `icdbPartsLister.exe` 先做命令行 `--help`/版本和只读输出探针;如果没有稳定输入输出合同,就不接入库存采集。
|
||||
|
||||
当前推荐:保留 V1.1.0 的原生对话框后端作为现行写入路径;借鉴 CBB Verify 的私有 desktop、Job Object、PID 绑定和权威后置验证,先做独立探针,不把未证实候选接口接入正式替换流程。任务、位号计划和 Excel 继续由现有架构管理,后台适配只改变执行器。
|
||||
|
||||
已有串行调度、任务证据、输入冻结和保存回读不需要再重写。新增工作的重点是桌面隔离、自己启动的 CAD 进程身份、跨进程 COM 绑定以及对话框是否依赖真实输入。Job Object 强制回收也不能照搬为所有阶段的取消策略:在 CAD/iCDB 写入或保存期间,应先完成收尾或标记不确定,再决定清理,避免中断数据库写回。
|
||||
|
||||
证据等级:源码调用链为 A;安装文件名和 PE 字符串为 B;`icdbPartsLister`、`ccomp`、`ChangeComponentPreserveRefdes` 的实际语义和私有 desktop Replace Part 行为为 C,必须现场验证。
|
||||
@@ -0,0 +1,98 @@
|
||||
# MentorPDF 原生接口链路补充调研
|
||||
|
||||
调研日期:2026-10-14。此次只读取 `mentor_PDF_output` 源码、本机 EE7.9.5 安装目录文件名/PE 字符串和已存在的 Viewdraw 脚本样例;没有启动 `sch2pdf`、`DxPDF`、DxDesigner,也没有附着 COM 或写入工程。
|
||||
|
||||
## MentorPDF 的实际原生链路
|
||||
|
||||
MentorPDF 不是 COM 自动化器,也没有向 Viewdraw 发送替换命令。它是一个 Python UI/CLI 外壳,发现并串行启动 Mentor 安装提供的独立 `sch2pdf.exe`:
|
||||
|
||||
- `src/mentor_pdf_export/engine.py:6-23` 从 `SDD_HOME` 或有限的 `CDEFG:\Mentor*` 路径寻找 `wv/win32/bin/sch2pdf.exe`。
|
||||
- `src/mentor_pdf_export/profiles.py:56-74` 只组装 `sch2pdf.exe -project <project> -a <pdf> -c <color>` 以及 `-p/-e/-i2s/-uAll/-udx/-l/-schematic` 选项;没有组件 UID、RefDes、料号或替换参数。
|
||||
- `src/mentor_pdf_export/engine.py:82-120,148-205` 用 Windows `CreateProcess`/Job Object 启动子进程,捕获 stdout/stderr,支持取消、超时和后台 iCDB 写回等待。Linux/非 Windows 才退回 `subprocess.Popen`。
|
||||
- `src/mentor_pdf_export/exporter.py:72-124,144-170` 在启动前保存源指纹和 `command.json`,原生输出先写 staging PDF,验证 PDF 和源工程指纹后再原子发布。
|
||||
- `src/mentor_pdf_export/workers.py:28-100` 用一个 `BatchWorker` 串行执行多个工程,禁止同一 `Exporter` 并行运行;每个项目有独立结果和可重试运行目录。
|
||||
- `src/mentor_pdf_export/scanner.py:34-65` 扫描 `.prj`,只读工程头部中的 `FrontEndSnapshot`、`iCDBDir`、`RootBlock`,拒绝链接和受保护目录。
|
||||
|
||||
因此可借鉴的是**原生进程适配器、批次队列、证据目录、源指纹与原子提交**,不能借鉴为替换 API。PDF 工具输入的是工程路径和打印参数,实际设计读取/数据库行为留给 `sch2pdf` 内部,源码没有提供“按位号选择组件”的可复用协议。
|
||||
|
||||
## 本机官方工具和候选
|
||||
|
||||
在 `D:\Mentor\7.9.5EE\SDD_HOME\wv\win32\bin` 中,受限检索得到三个相关可执行文件:
|
||||
|
||||
| 文件 | SHA-256 | 静态线索 | 判断 |
|
||||
| --- | --- | --- | --- |
|
||||
| `sch2pdf.exe` | `EF246E3AA2F1CD46BF41F1C89393EED362E8DC8540ADD49F489D9BDEED5A51A6` | PE 字符串含 `-project`、`Schematic`、`Component`、`RefDes`、`Part Number` | 原生 PDF 导出器;没有证据表明它接受替换/写入参数。 |
|
||||
| `DxPDF.exe` | `F9F7F63FE1C1C85004F020118775728CE6D407352CCA8008D25110504595F112` | PE 字符串含 `DxPDF (Version 4.00)`、`-project`、`CDxPdfMainDialog::setProjectFile`,依赖 `dxpdfgui70.dll` | GUI PDF 前端;没有发现替换接口。 |
|
||||
| `icdbPartsLister.exe` | `B227796564C59AAAF6DF19939A559DF1FF180C0E3D26173F043CC44B5919DA8D` | PE 字符串含 `Part Number`、`REFDES`、`cComp`、`Component`、`refdes` | 可能是只读部品/数据库列表器;静态字符串不能证明筛选、导出格式或写入能力,不能当替换后端。 |
|
||||
|
||||
安装目录的 Viewdraw 样例只有 `D:\Mentor\7.9.5EE\SDD_HOME\wv\samples\viewdraw\scripting\ToolbarButton.vbs`、`menu.vbs` 和 `readme.txt`。`ToolbarButton.vbs:30-34` 示例为 `Application.ExecuteCommand "component 74ls01"` 或 `ActiveView.ActiveBlock.AddComponentMoveMode`,语义是放置新元件,不是替换现有元件,也没有 `Library Wins` 或目标 RefDes 参数。安装样例没有 `ccomp`、`ReplacePart` 或 `Library Wins` 示例。
|
||||
|
||||
现有安装版 TypeLib 的真实成员仍以 `docs/research/v1.1.0-native-typelib-evidence.json` 为准:有 `ExecuteCommand`、`SelectComponent`、`Selected` 和 `ChangeComponentPreserveRefdes`,没有直接 `ReplacePart`。因此 MentorPDF 的独立进程模式不能绕过这一接口事实。
|
||||
|
||||
## 对 V1.1.0 的借鉴
|
||||
|
||||
可以把替换工具的单工程任务执行器做成类似 MentorPDF 的独立 backend runner:
|
||||
|
||||
```text
|
||||
task -> preflight/inventory -> frozen target UID set
|
||||
-> backend process/COM bridge
|
||||
-> before/after snapshot -> verify
|
||||
-> saved/reopened readback -> atomic evidence/result
|
||||
```
|
||||
|
||||
可直接借鉴的设计点:
|
||||
|
||||
1. 用 `request.json`、`command.json`、`stdout/stderr`、前后快照和 `result.json` 建立每任务证据目录(MentorPDF `exporter.py:120-165`)。
|
||||
2. 任务按工程串行执行,禁止同一原生工具并行(`exporter.py:72-78`、`workers.py:28-100`)。
|
||||
3. 子进程必须创建后立即纳入 Job Object,超时只终止本工具创建的进程树(`engine.py:82-120`)。
|
||||
4. 执行前后保存工程指纹;外部原生程序可能写 iCDB/log,即使可接受也必须单独标为 warning,不能伪称源工程字节不变(`exporter.py:120-152`、`docs/testing/2026-10-10-v032-native-policy.md:5-7,30-41`)。
|
||||
5. 输出/报告写到独立运行目录,成功结果才原子提交,失败/不确定保留证据(`exporter.py:122-170,186-213`)。
|
||||
|
||||
替换工具的差异是:替换会写设计,必须先做备份/冻结 UID,再验证未选中的同旧料号位号没有变化;不能照搬 MentorPDF “直接读取原工程”的策略。MentorPDF 的 `sch2pdf` 子进程也不适合作为替换代理,因为它的 CLI 合同没有组件选择或新料号字段,且其内部可能更新 iCDB。
|
||||
|
||||
## 建议的接口代理边界
|
||||
|
||||
为 V1.1.0 保留三个明确后端类别:
|
||||
|
||||
- `native_dialog_backend`:当前已实现的精确选中 + 原生 Replace Part 操作,仍需现场验证控件/完成观察;
|
||||
- `viewdraw_component_backend`:仅研究 `SelectComponent`、`ChangeComponentPreserveRefdes`,必须标记 `research_only`,不宣称 Library Wins;
|
||||
- `native_process_backend`:未来若发现带明确输入合同的官方替换 CLI,可借鉴 MentorPDF 的 Job Object/日志/证据框架接入。当前安装目录未发现该工具。
|
||||
|
||||
任何代理都必须接收 `project_path + sheet + target_uids + expected_old_part + new_part + evidence_dir`,在写入前核对工程指纹和选中集合;接口没有目标 UID、范围和库策略时不得自动扩大范围。`icdbPartsLister.exe` 只有在单独验证输出字段、只读性质和与当前工程身份绑定后,才可作为 inventory 辅助,不可直接成为 replacement backend。
|
||||
|
||||
## 证据等级
|
||||
|
||||
- **A:源码直接证据**:MentorPDF 的 `engine.py`、`profiles.py`、`exporter.py`、`workers.py`、`scanner.py` 调用链和行号。
|
||||
- **B:安装文件静态证据**:可执行文件名、哈希、PE 字符串、Viewdraw 样例脚本。只能证明存在和字符串/示例,不证明完整运行语义。
|
||||
- **C:待现场验证**:`icdbPartsLister.exe` 的实际输出协议、任何 `ccomp` 命令行为、`ChangeComponentPreserveRefdes` 的写入结果,以及未来版本可能存在的直接 `ReplacePart` API。
|
||||
|
||||
本报告没有运行任何官方工具,也没有把 PE 字符串或 MentorPDF 的导出命令解释成“支持按位号替换”的证据。
|
||||
|
||||
## 有界 PE 导出检索补充
|
||||
|
||||
为检查是否存在类似 `sch2pdf.exe` 的原生替换进程,我对以下已安装目录做了静态 PE 导出扫描,没有加载 DLL 或执行 EXE:
|
||||
|
||||
```text
|
||||
D:\Mentor\7.9.5EE\SDD_HOME\wv\win32\bin
|
||||
D:\Mentor\7.9.5EE\SDD_HOME\dx\win32\bin
|
||||
D:\Mentor\7.9.5EE\SDD_HOME\iCDB\win32\bin
|
||||
D:\Mentor\7.9.5EE\SDD_HOME\lm\win32\bin
|
||||
```
|
||||
|
||||
扫描了上述目录中 91 个 PE 文件(`.dll`/`.exe`),按导出名称筛选 `replace`、`ccomp`、`ChangeComponent`、`LibraryWins`、`Library_Wins`,结果只有两条内部 C++ 修饰导出:
|
||||
|
||||
```text
|
||||
iCDBNetLauncher.exe
|
||||
?Replace@String@iCDB@@QAE?AV12@ABV12@0ABV?$BitContainerT@W4ESearchParams@iCDB@@$00@2@@Z
|
||||
ordinal 4101, RVA 0x486e0
|
||||
|
||||
iCDBRSCMConfigurator.exe
|
||||
?Replace@String@iCDB@@QAE?AV12@ABV12@0ABV?$BitContainerT@W4ESearchParams@iCDB@@$00@2@@Z
|
||||
ordinal 4101, RVA 0x15ccc0
|
||||
```
|
||||
|
||||
这两个符号是 `iCDB::String::Replace` 风格的字符串/搜索参数函数,不是设计元件替换;导出对象是 EXE 而非稳定 SDK DLL,名称包含编译器修饰、C++ 类 ABI、内部类型和固定 ordinal,不能从外部安全调用。没有发现名称含 `ccomp`、`ChangeComponent`、`LibraryWins` 或设计 `ReplacePart` 的导出。这个阴性结果只覆盖上述四个目录的 PE 导出表,不能证明所有资源、未导出内部函数、脚本命令或其他安装版本不存在相关能力。
|
||||
|
||||
官方启动脚本也没有隐藏替换参数:`D:\Mentor\7.9.5EE\SDD_HOME\common\win32\bin\viewdraw.bat:1-14` 只收集 `%*` 并执行 `%SDD_START% ...\\viewdraw.exe %epdarglist%`;`icdbPartsLister.bat:1-14` 以同样方式执行 `icdbPartsLister.exe`。这些脚本提供进程环境/参数转发,不定义 `ccomp`、料号、位号或 Library Wins 合同。
|
||||
|
||||
因此,当前安装中没有静态证据显示存在可像 `sch2pdf` 一样、以独立 CLI/导出函数实现精确库料号替换的官方原生进程。后端仍应使用已知的 Viewdraw COM 选择能力加原生替换交互;任何内部 C++ 导出都应标为 `unsupported`,不应作为 V1.1.0 代理。
|
||||
@@ -0,0 +1,69 @@
|
||||
# V1.1.0 DxDesigner 7.9.5 原生替换接口调研
|
||||
|
||||
调研日期:2026-10-14。范围为现有工作区源码、已有测试、本机注册的 7.9.5 COM TypeLib 与安装帮助;本次没有附着、启动或修改任何 CAD 工程,也没有做写入式 live probe。
|
||||
|
||||
**安装版 TypeLib 复核更正:** 本机实际注册的 `viewdraw.tlb` 是版本 `1.0`,不含 `ReplacePart`、`OpenReplacePartDialog`、`ReplacePartCompleted` 或 `SelectExactSet`。工作区保存的一份同名 `designer_ifc.py` 是声明版本 `119.0` 的 makepy wrapper,虽然含 `IVdApp.ReplacePart(SourcePart, Scope, DestinationPart, PinMapping, PropertyMapping)`、`SRP_Selection=5` 和 `PropMT_LibraryWins=3`,但**不能用于证明本机 7.9.5 有这些成员**。下文旧桥中的这些名称应按候选/模拟接口理解。本机真实接口结果以 [离线 TypeLib 证据](v1.1.0-native-typelib-evidence.json) 为准。
|
||||
|
||||
## 结论
|
||||
|
||||
现有的 `Viewdraw.Application` COM 接口足以读取工程/图页/器件,按 UID 精确选中指定器件,并在替换前后核对选中集合。V1.1.0 的“一个旧料号只替换部分位号”可沿用这条选择链路。**写入路径仍应调用原生 Replace Symbol / Replace Part 并明确核验 Library Wins**。目前没有证据表明 `Block.ChangeComponentPreserveRefdes` 或 `ExecuteCommand("ccomp ...")` 能完整实现中央库选件、Library Wins、引脚及网络保持、Undo 和 Packager 通过。两者只适合作为可丢弃工程上的隔离探针,不能注册为默认执行后端。
|
||||
|
||||
这里的“原生接口”需要分清层次:现行自动执行使用 COM 读写选中状态,再从 `viewdraw.exe` 菜单资源识别 Replace Symbol 命令并发送 `WM_COMMAND`,随后通过 DxDesigner 原生对话框选择库行及选项。这是**原生 UI 工作流的自动化**,不是已证明存在的“传入旧件、新料号、Library Wins 参数的一次性 COM API”。
|
||||
|
||||
## 现有证据
|
||||
|
||||
| 路线 | 已有证据 | 当前判断 |
|
||||
| --- | --- | --- |
|
||||
| `Viewdraw.Application` | `QuickPartReplace.vbs:184,402,416` 附着/创建对象;`native_helper.py:196-204` 从活动对象取得 `IVdApp`;一叶知秋 `integration/dxdesigner795/CompatibilityProbe.vbs:122-132` 使用 `GetProjectData` 和 `DesignComponents` 枚举全工程。 | 可用作工程上下文、清单和选中控制;实际环境、精确 build 和 32/64 位组合仍需现场验收。 |
|
||||
| 按器件精确选择 | `native_helper.py:214-249` 以 UID 设置 `Selected` 并重新读取选中 UID;本机 TypeLib 有 `IVdComp.Selected/_SetSelected` 和 `IVdApp.SelectComponent`;旧桥 `PartReplaceBridge.vbs:2097-2150` 所用的 `SelectExactSet` 不在安装版 TypeLib。一叶知秋 `core/Mailbox.vbs:365-375` 已用 `SelectByName` 定位单件。 | 位号应在扫描阶段绑定项目、图页、UID、旧料号;执行前重查完整身份和选中集合。仅用 RefDes 文本不能跨图页唯一定位。 |
|
||||
| 原生 Replace Part + Library Wins | `native_helper.py:165-193,437-445` 从 Viewdraw 菜单资源识别 Replace Symbol;`:450-517` 打开原生对话框、选择精确库行、检查目标 Part Number/符号、确认原生选项,再执行;`:519-553` 验证结果及未选中件未变。`QuickPartReplace.vbs:780-815` 调用 helper;`:837-865` 对未保存失败做原生 Undo 和快照验证。 | 是已有的自动写入路线;需在现场 build/中央库上回归,并以证据确认每个控件 ID 对应的选项,不能只依赖 ID。 |
|
||||
| `Application.OpenReplacePartDialog` | 旧桥 `PartReplaceBridge.vbs:2260-2261,2341-2384` 调用该名称并读 `ReplacePartCompleted`;旧 probe `PartReplaceProbe.vbs:951-985` 将其列为候选,`ccomp_research` 明确 `production_enabled=false`。本机 7.9.5 `IVdApp` TypeLib 没有这两个成员。 | 旧桥属于未证实候选/模拟路径;不能注册为本机可调用 COM 接口。 |
|
||||
| `Block.ChangeComponentPreserveRefdes` | 本机 7.9.5 TypeLib 的 `IVdBlock` 确有 DISPID `42`,参数 `OldComp, NewComp`,返回 `VARIANT_BOOL`;保存的 wrapper `designer_ifc.py:5005,9943` 也有相同名称。现有设计 `docs/superpowers/specs/2026-09-01-dxdesigner-795-part-replacement-design.md:50-61` 记录符号原点及 Packager 失败的社区线索。 | 存在方法不等于可用于库料号替换;签名没有 Library Wins 参数,也未说明只作用于选中位号、如何选库及连接语义。 |
|
||||
| `ExecuteCommand("ccomp ...")` | 类型库包装 `designer_ifc.py:1385,2974,3926` 暴露 `ExecuteCommand(CommandString)`;现有脚本只在 `QuickPartReplace.vbs:845,1143` 对 `undo` 使用它。旧设计 `...part-replacement-design.md:50-60` 仅记载 `ccomp :component_name` 候选,旧 probe 将 `Application.CComp` 标为研究项。全工作区未找到执行 `ExecuteCommand("ccomp ...")` 的生产调用或成功报告。 | 命令存在性、准确语法、选择范围及 Library Wins 行为均未证实。不能用 `undo` 可执行推断 `ccomp` 可执行。 |
|
||||
|
||||
已有文档 `docs/user/part-replacement.md:5,129-142` 对生产边界、精确选择与硬不变量作了明确约束。旧设计 `...part-replacement-design.md:37` 曾写“Python 不直接附着 COM”,但当前 `native_helper.py:196-204` 已直接附着。V1.1.0 文档应以当前实现和 live 证据为准,修正这处历史差异;不要把旧设计中的未验证候选当作生产能力。模拟测试 `tests/integration/test_part_replace_probe.py:498-562` 与 `test_part_replace_bridge.py:336-355` 只能证明协议和错误处理,不构成真实 7.9.5 行为证据。
|
||||
|
||||
## 本机安装版 TypeLib 细查
|
||||
|
||||
注册表 `HKLM\SOFTWARE\Classes\TypeLib\{4ADEF4E1-690A-11CE-9261-0020C5E26659}\1.0\0\win32` 指向 `D:\Mentor\7.9.5EE\SDD_HOME\wv\win32\bin\viewdraw.tlb`,SHA-256 为 `09323c8940f1acf3f469d887dcfdf7bcd114164a29b01ebeb9a7f978fa1a0df7`,共 223 个 TypeInfo。离线脚本 `tools/research/probe-native-capabilities.py` 直接调用 `pythoncom.LoadTypeLib(path)` 读这个文件,并与保存的 wrapper 比较;它不调用 `GetActiveObject` 或 `CreateObject`。输出 `docs/research/v1.1.0-native-typelib-evidence.json` 的 `wrapper_matches_installed_version=false`。
|
||||
|
||||
安装版真实可见成员包括 `IVdApp.ExecuteCommand(CommandString)` DISPID 29、`SelectComponent(sSchName, sSheetName, sCompUID)` DISPID 266、`QueryPages` DISPID 46、`DesignComponents` DISPID 59、`GetProjectData` DISPID 228;`IVdComp.Selected` 和 `_SetSelected`;`IVdBlock.DeSelectAll`、`ChangeComponent` DISPID 24、`ChangeComponentPreserveRefdes` DISPID 42。**没有任何名称含 Replace 的 TypeLib 函数**。旧桥引用的 `SelectExactSet`、`OpenReplacePartDialog`、`ReplacePartCompleted` 在安装版各接口中均未出现;目前测试里的同名 mock 不能当作原生接口。
|
||||
|
||||
外部 wrapper 的 `IVdApp.ReplacePart` 确有 DISPID 300、两个 BSTR、三个 32 位整数/枚举、布尔返回,以及 `SRP_Selection=5`、`PinMT_ByPinNumber=2`、`PropMT_LibraryWins=3`。它的声明版本是 `119.0`,与安装版 `1.0` 不同。因此可作为**未来版本接口线索**,但本机 V1.1.0 后端 capability 必须返回 `unavailable`,不能尝试按 DISPID 300 盲调。只有安装的 TypeLib 与运行时真实包含该方法,且 Selection + 精确 UID 选中 + Library Wins 的现场语义全部验证,才能为对应 build 启用直接 API 后端。
|
||||
|
||||
安装版 `automate.chm` 尝试用系统 `hh.exe -decompile` 提取,但没有得到可读文件;工作区的 `designer_auto_ref.pdf` 为较新 Xpedition Designer Automation Reference,页 696-697 解释 PinMapping/PropertyMapping 枚举,却不能代表本机 7.9.5 的接口集。故本结论优先依据安装版二进制 TypeLib,帮助材料只用于理解候选语义。
|
||||
|
||||
## 建议的 live probe
|
||||
|
||||
1. 准备已关闭、可丢弃的完整工程副本,记录 DxDesigner 版本/build、中央库身份、工程树哈希;选择同一旧料号的两个以上器件,其中仅一个目标位号需要替换。另选一个多单元或引脚较多的代表件。
|
||||
2. 先只读探测 `ProjectPath`、`QueryPages`、`DesignComponents`、每个器件的 UID/RefDes/层级/图页/旧料号/Value/引脚/网络;在不同图页和同页重复位号场景验证身份是否唯一。记录 COM 调用返回值与错误号。
|
||||
3. 在副本上单独验证 `IVdComp.Selected` 与 `IVdApp.SelectComponent`:只选目标 UID,重新枚举选中集合。若集合不一致则停止。记录目标与同旧料号未选中器件的完整前快照。`SelectExactSet` 不作为本机 7.9.5 探针调用。
|
||||
4. 建立基准:使用现行原生对话框路线对目标位号执行一次 Replace Part + Library Wins,记录库行、目标符号、控件文本/状态、替换后全图页快照、Undo、保存关闭再打开回读、Packager/ERC/网表结果。
|
||||
5. 对 `ChangeComponentPreserveRefdes` 和 `ccomp` **分别使用新的副本**做最小写入探针。先只读确认签名和命令语法;确认可恢复后仅改一个目标件。记录实际作用范围、库控制字段、RefDes/位置/方向、引脚号与网络、非目标件、Undo、保存回读和 Packager。任一步不确定就关闭副本且不保存,并留证;不能把属性值或 Part Number 单字段变化视为通过。
|
||||
6. 只有候选路线在多类器件、多图页、现场中央库上满足与基准相同的硬不变量,且有可重复证据和精确 build 绑定,才考虑提升为可选后端。选择一组目标位号后,必须证明未选中的同料号位号保持原样。
|
||||
|
||||
现行代码核验目标及未选中件料号(`native_helper.py:519-547`),但后端晋级标准还要使用 `docs/user/part-replacement.md:140` 的完整保护字段,并核对 NC/Value 策略、保存回读和独立 Packager/ERC/网表结果。现场报告应保存命令、参数、返回值/错误、前后快照、差异及文件 SHA-256,而不是只保存“成功”布尔值。
|
||||
|
||||
## V1.1.0 后端边界建议
|
||||
|
||||
将**计划和身份验证**留在任务层;替换后端只负责一组已冻结的目标 UID。在单工程任务内按图页、旧料号、新料号及 Value/NC 策略分组,后端逐组处理。最小契约可表达为:
|
||||
|
||||
```text
|
||||
ReplacementRequest:
|
||||
project_path, project_fingerprint, sheet_identity
|
||||
targets: [{uid, refdes, old_part_number, baseline_fingerprint}]
|
||||
new_part_number, library_identity, policy, command_id
|
||||
|
||||
ReplacementBackend:
|
||||
capability(build, library_identity) -> supported / research_only / unavailable
|
||||
inspect(request) -> current target identities and full-sheet baseline
|
||||
replace(request, evidence_dir) -> result with attempted/committed/uncertain status
|
||||
verify(request, result) -> selected and unselected differences
|
||||
recover(request, result) -> verified undo or close_without_save evidence
|
||||
```
|
||||
|
||||
生产后端先封装当前 native dialog/helper 路线。`ChangeComponentPreserveRefdes` 与 `ccomp` 应放入独立研究适配器,并强制 `research_only`、可丢弃副本和显式试验入口。后端不能自行扩大目标集合;命令中无 UID、旧料号或工程指纹匹配失败时,必须在写入前失败。结果须区分“未开始”“已变更但未确认”“已验证”和“已恢复”,使批次调度器遇到不确定状态时停下。
|
||||
|
||||
## 外部资料与证据等级
|
||||
|
||||
现有设计在 `...part-replacement-design.md:69` 引用了 Siemens 社区关于 `ChangeComponentPreserveRefdes` 导致封装失败的讨论。此次网络可访问 Siemens 支持门户首页(HTTP 200),但未取得公开的 7.9.5 API 正文或可复核的 `ccomp`/Library Wins 参数说明;搜索请求超时。因此报告中对这两条路线的判断以本机类型库、工作区源码与设计记录为依据,**没有宣称公开资料证明其替换语义**。下一轮应优先取得站点安装包里的 Automation Reference、命令手册和现场 build 录屏/日志,再做写入试验。
|
||||
@@ -0,0 +1,629 @@
|
||||
{
|
||||
"format_version": 1,
|
||||
"mode": "offline_installed_typelib_and_wrapper_comparison",
|
||||
"attached_to_viewdraw": false,
|
||||
"mutation_attempted": false,
|
||||
"wrapper": {
|
||||
"path": "F:\\Sync Tool Skyworth\\Work Maps\\AppTraceRecorder\\reference\\SiemensEDA_Python_Interface\\xpedition_designer\\designer_ifc.py",
|
||||
"sha256": "4f6c341091b3b55ed579df6747b2cf261f49533cdbafaa9db306b06ff751c95a"
|
||||
},
|
||||
"typelib": {
|
||||
"path": "D:\\Mentor\\7.9.5EE\\SDD_HOME\\wv\\win32\\bin\\viewdraw.tlb",
|
||||
"exists": true,
|
||||
"sha256": "09323c8940f1acf3f469d887dcfdf7bcd114164a29b01ebeb9a7f978fa1a0df7",
|
||||
"size": 188040
|
||||
},
|
||||
"saved_wrapper_candidates": {
|
||||
"declared_version": {
|
||||
"major": 119,
|
||||
"minor": 0
|
||||
},
|
||||
"constants": {
|
||||
"SRP_Project": 1,
|
||||
"SRP_Board": 2,
|
||||
"SRP_Schematic": 3,
|
||||
"SRP_Sheet": 4,
|
||||
"SRP_Selection": 5,
|
||||
"PinMT_ByName": 1,
|
||||
"PinMT_ByPinNumber": 2,
|
||||
"PropMT_LibraryOnly": 1,
|
||||
"PropMT_SchematicWins": 2,
|
||||
"PropMT_LibraryWins": 3
|
||||
},
|
||||
"methods": [
|
||||
{
|
||||
"interface": "IVdApp",
|
||||
"name": "ReplacePart",
|
||||
"dispid": 300,
|
||||
"arguments": [
|
||||
"SourcePart",
|
||||
"Scope",
|
||||
"DestinationPart",
|
||||
"PinMapping",
|
||||
"PropertyMapping"
|
||||
],
|
||||
"makepy_return_type": [
|
||||
11,
|
||||
0
|
||||
],
|
||||
"makepy_argument_types": [
|
||||
[
|
||||
8,
|
||||
1
|
||||
],
|
||||
[
|
||||
3,
|
||||
1
|
||||
],
|
||||
[
|
||||
8,
|
||||
1
|
||||
],
|
||||
[
|
||||
3,
|
||||
1
|
||||
],
|
||||
[
|
||||
3,
|
||||
1
|
||||
]
|
||||
],
|
||||
"wrapper_line": 3347,
|
||||
"status": "typelib_candidate"
|
||||
},
|
||||
{
|
||||
"interface": "IVdAppProtectionProxy",
|
||||
"name": "ReplacePart",
|
||||
"dispid": 300,
|
||||
"arguments": [
|
||||
"SourcePart",
|
||||
"Scope",
|
||||
"DestinationPart",
|
||||
"PinMapping",
|
||||
"PropertyMapping"
|
||||
],
|
||||
"makepy_return_type": [
|
||||
11,
|
||||
0
|
||||
],
|
||||
"makepy_argument_types": [
|
||||
[
|
||||
8,
|
||||
1
|
||||
],
|
||||
[
|
||||
3,
|
||||
1
|
||||
],
|
||||
[
|
||||
8,
|
||||
1
|
||||
],
|
||||
[
|
||||
3,
|
||||
1
|
||||
],
|
||||
[
|
||||
3,
|
||||
1
|
||||
]
|
||||
],
|
||||
"wrapper_line": 4277,
|
||||
"status": "typelib_candidate"
|
||||
},
|
||||
{
|
||||
"interface": "IVdApplicationAtTest",
|
||||
"name": "ReplaceConnector",
|
||||
"dispid": 2,
|
||||
"arguments": [
|
||||
"SourceConnector",
|
||||
"Scope",
|
||||
"DestinationConnector",
|
||||
"PinMapping",
|
||||
"PropertyMapping"
|
||||
],
|
||||
"makepy_return_type": [
|
||||
11,
|
||||
0
|
||||
],
|
||||
"makepy_argument_types": [
|
||||
[
|
||||
8,
|
||||
1
|
||||
],
|
||||
[
|
||||
3,
|
||||
1
|
||||
],
|
||||
[
|
||||
8,
|
||||
1
|
||||
],
|
||||
[
|
||||
3,
|
||||
1
|
||||
],
|
||||
[
|
||||
3,
|
||||
1
|
||||
]
|
||||
],
|
||||
"wrapper_line": 4549,
|
||||
"status": "typelib_candidate"
|
||||
},
|
||||
{
|
||||
"interface": "IVdApplicationAtTest",
|
||||
"name": "ReplaceSymbol",
|
||||
"dispid": 3,
|
||||
"arguments": [
|
||||
"SourceSymbol",
|
||||
"Scope",
|
||||
"DestinationSymbol",
|
||||
"PinMapping",
|
||||
"PropertyMapping"
|
||||
],
|
||||
"makepy_return_type": [
|
||||
11,
|
||||
0
|
||||
],
|
||||
"makepy_argument_types": [
|
||||
[
|
||||
8,
|
||||
1
|
||||
],
|
||||
[
|
||||
3,
|
||||
1
|
||||
],
|
||||
[
|
||||
8,
|
||||
1
|
||||
],
|
||||
[
|
||||
3,
|
||||
1
|
||||
],
|
||||
[
|
||||
3,
|
||||
1
|
||||
]
|
||||
],
|
||||
"wrapper_line": 4554,
|
||||
"status": "typelib_candidate"
|
||||
}
|
||||
]
|
||||
},
|
||||
"installed_typelib": {
|
||||
"guid": "{4ADEF4E1-690A-11CE-9261-0020C5E26659}",
|
||||
"major_version": 1,
|
||||
"minor_version": 0,
|
||||
"type_count": 223,
|
||||
"interfaces": {
|
||||
"IVdApp": [
|
||||
{
|
||||
"name": "ExecuteCommand",
|
||||
"dispid": 29,
|
||||
"parameters": [
|
||||
"CommandString"
|
||||
],
|
||||
"argument_types": [
|
||||
[
|
||||
8,
|
||||
1
|
||||
]
|
||||
],
|
||||
"return_type": [
|
||||
11,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "QueryPages",
|
||||
"dispid": 46,
|
||||
"parameters": [
|
||||
"Name"
|
||||
],
|
||||
"argument_types": [
|
||||
[
|
||||
8,
|
||||
1
|
||||
]
|
||||
],
|
||||
"return_type": [
|
||||
[
|
||||
26,
|
||||
[
|
||||
29,
|
||||
50338560
|
||||
]
|
||||
],
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "DesignComponents",
|
||||
"dispid": 59,
|
||||
"parameters": [
|
||||
"Library",
|
||||
"Name",
|
||||
"EndSheet",
|
||||
"LevelString",
|
||||
"RecurseDown"
|
||||
],
|
||||
"argument_types": [
|
||||
[
|
||||
8,
|
||||
1
|
||||
],
|
||||
[
|
||||
8,
|
||||
1
|
||||
],
|
||||
[
|
||||
8,
|
||||
49
|
||||
],
|
||||
[
|
||||
8,
|
||||
49
|
||||
],
|
||||
[
|
||||
11,
|
||||
49
|
||||
]
|
||||
],
|
||||
"return_type": [
|
||||
[
|
||||
26,
|
||||
[
|
||||
29,
|
||||
50338560
|
||||
]
|
||||
],
|
||||
32
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "GetProjectData",
|
||||
"dispid": 228,
|
||||
"parameters": [],
|
||||
"argument_types": [],
|
||||
"return_type": [
|
||||
[
|
||||
26,
|
||||
[
|
||||
29,
|
||||
50343040
|
||||
]
|
||||
],
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "SelectComponent",
|
||||
"dispid": 266,
|
||||
"parameters": [
|
||||
"sSchName",
|
||||
"sSheetName",
|
||||
"sCompUID"
|
||||
],
|
||||
"argument_types": [
|
||||
[
|
||||
8,
|
||||
1
|
||||
],
|
||||
[
|
||||
8,
|
||||
1
|
||||
],
|
||||
[
|
||||
8,
|
||||
1
|
||||
]
|
||||
],
|
||||
"return_type": [
|
||||
11,
|
||||
0
|
||||
]
|
||||
}
|
||||
],
|
||||
"IVdView": [
|
||||
{
|
||||
"name": "SelectByName",
|
||||
"dispid": 1,
|
||||
"parameters": [
|
||||
"Name"
|
||||
],
|
||||
"argument_types": [
|
||||
[
|
||||
8,
|
||||
1
|
||||
]
|
||||
],
|
||||
"return_type": [
|
||||
11,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "SelectObject",
|
||||
"dispid": 12,
|
||||
"parameters": [
|
||||
"ObjectType",
|
||||
"Expression",
|
||||
"SelectOwner",
|
||||
"RegExp",
|
||||
"AddSelect"
|
||||
],
|
||||
"argument_types": [
|
||||
[
|
||||
[
|
||||
29,
|
||||
50334848
|
||||
],
|
||||
1
|
||||
],
|
||||
[
|
||||
8,
|
||||
1
|
||||
],
|
||||
[
|
||||
11,
|
||||
1
|
||||
],
|
||||
[
|
||||
11,
|
||||
1
|
||||
],
|
||||
[
|
||||
11,
|
||||
1
|
||||
]
|
||||
],
|
||||
"return_type": [
|
||||
22,
|
||||
0
|
||||
]
|
||||
}
|
||||
],
|
||||
"IVdBlock": [
|
||||
{
|
||||
"name": "DeSelectAll",
|
||||
"dispid": 14,
|
||||
"parameters": [],
|
||||
"argument_types": [],
|
||||
"return_type": [
|
||||
24,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "ChangeComponent",
|
||||
"dispid": 24,
|
||||
"parameters": [
|
||||
"OldComp",
|
||||
"NewComp"
|
||||
],
|
||||
"argument_types": [
|
||||
[
|
||||
8,
|
||||
1
|
||||
],
|
||||
[
|
||||
8,
|
||||
1
|
||||
]
|
||||
],
|
||||
"return_type": [
|
||||
11,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "ChangeComponentPreserveRefdes",
|
||||
"dispid": 42,
|
||||
"parameters": [
|
||||
"OldComp",
|
||||
"NewComp"
|
||||
],
|
||||
"argument_types": [
|
||||
[
|
||||
8,
|
||||
1
|
||||
],
|
||||
[
|
||||
8,
|
||||
1
|
||||
]
|
||||
],
|
||||
"return_type": [
|
||||
11,
|
||||
0
|
||||
]
|
||||
}
|
||||
],
|
||||
"IVdComp": [
|
||||
{
|
||||
"name": "Selected",
|
||||
"dispid": 26,
|
||||
"parameters": [],
|
||||
"argument_types": [
|
||||
[
|
||||
11,
|
||||
1
|
||||
]
|
||||
],
|
||||
"return_type": [
|
||||
24,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "_SetSelected",
|
||||
"dispid": 12,
|
||||
"parameters": [
|
||||
"Flag"
|
||||
],
|
||||
"argument_types": [
|
||||
[
|
||||
22,
|
||||
1
|
||||
]
|
||||
],
|
||||
"return_type": [
|
||||
24,
|
||||
0
|
||||
]
|
||||
}
|
||||
],
|
||||
"ICommandsManager": [
|
||||
{
|
||||
"name": "ExecuteCommand",
|
||||
"dispid": 307,
|
||||
"parameters": [
|
||||
"CommandString"
|
||||
],
|
||||
"argument_types": [
|
||||
[
|
||||
8,
|
||||
1
|
||||
]
|
||||
],
|
||||
"return_type": [
|
||||
11,
|
||||
0
|
||||
]
|
||||
}
|
||||
],
|
||||
"IVdAppProtectionProxy": [
|
||||
{
|
||||
"name": "ExecuteCommand",
|
||||
"dispid": 29,
|
||||
"parameters": [
|
||||
"CommandString"
|
||||
],
|
||||
"argument_types": [
|
||||
[
|
||||
8,
|
||||
1
|
||||
]
|
||||
],
|
||||
"return_type": [
|
||||
11,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "QueryPages",
|
||||
"dispid": 46,
|
||||
"parameters": [
|
||||
"Name"
|
||||
],
|
||||
"argument_types": [
|
||||
[
|
||||
8,
|
||||
1
|
||||
]
|
||||
],
|
||||
"return_type": [
|
||||
[
|
||||
26,
|
||||
[
|
||||
29,
|
||||
50338560
|
||||
]
|
||||
],
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "DesignComponents",
|
||||
"dispid": 59,
|
||||
"parameters": [
|
||||
"Library",
|
||||
"Name",
|
||||
"EndSheet",
|
||||
"LevelString",
|
||||
"RecurseDown"
|
||||
],
|
||||
"argument_types": [
|
||||
[
|
||||
8,
|
||||
1
|
||||
],
|
||||
[
|
||||
8,
|
||||
1
|
||||
],
|
||||
[
|
||||
8,
|
||||
49
|
||||
],
|
||||
[
|
||||
8,
|
||||
49
|
||||
],
|
||||
[
|
||||
11,
|
||||
49
|
||||
]
|
||||
],
|
||||
"return_type": [
|
||||
[
|
||||
26,
|
||||
[
|
||||
29,
|
||||
50338560
|
||||
]
|
||||
],
|
||||
32
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "GetProjectData",
|
||||
"dispid": 228,
|
||||
"parameters": [],
|
||||
"argument_types": [],
|
||||
"return_type": [
|
||||
[
|
||||
26,
|
||||
[
|
||||
29,
|
||||
50343040
|
||||
]
|
||||
],
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "SelectComponent",
|
||||
"dispid": 266,
|
||||
"parameters": [
|
||||
"sSchName",
|
||||
"sSheetName",
|
||||
"sCompUID"
|
||||
],
|
||||
"argument_types": [
|
||||
[
|
||||
8,
|
||||
1
|
||||
],
|
||||
[
|
||||
8,
|
||||
1
|
||||
],
|
||||
[
|
||||
8,
|
||||
1
|
||||
]
|
||||
],
|
||||
"return_type": [
|
||||
11,
|
||||
0
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"wrapper_matches_installed_version": false
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
# Task 1 report: single-project context and isolated worker
|
||||
|
||||
Implemented the backend portion of the single-project workflow without starting
|
||||
CAD, packaging, or modifying project files.
|
||||
|
||||
## Public API
|
||||
|
||||
`TaskCenterService.task_context(task_id: str) -> ProjectTaskContext` returns a
|
||||
fresh immutable context for UI refreshes; only the per-task service facade is
|
||||
cached. `TaskCenterService.refresh_bound_project(task_id:
|
||||
str) -> ProjectTaskContext` rereads the task and its bound project from SQLite,
|
||||
without scanning a directory or attaching COM. A bound task must have one
|
||||
`primary_project_id` and exactly one project. Historical tasks without that
|
||||
binding remain available through `task_context` with `legacy=True` and
|
||||
`project=None`; `refresh_bound_project` rejects them so new execution cannot
|
||||
accidentally mutate a multi-project record.
|
||||
|
||||
`ProjectTaskContext` fields are:
|
||||
|
||||
```python
|
||||
ProjectTaskContext(
|
||||
task, project, rules, targets, progress, phase,
|
||||
has_evidence, interrupted, legacy
|
||||
)
|
||||
```
|
||||
|
||||
The target plan is authoritative for target-plan tasks. An empty or fully
|
||||
disabled plan produces zero queued items and never falls back to broad mapping
|
||||
rules.
|
||||
|
||||
`IsolatedDesktopWorker` is an opt-in research boundary. Its request contract is
|
||||
`IsolatedWorkerRequest(protocol_version, task_id, project_path, target_uids,
|
||||
plan_hash, allow_writes=False)`. `run()` rejects the default disabled mode,
|
||||
rejects unrelated existing CAD identity, rejects write enablement, and emits
|
||||
versioned `request.json`/`evidence.json` files when an evidence root is given.
|
||||
It does not attach COM or launch CAD.
|
||||
|
||||
`PrivateDesktop` owns the Windows desktop handle and processes started with
|
||||
`STARTUPINFO.lpDesktop="winsta0\\<private>"`; launch uses pywin32
|
||||
`CreateProcess`, a Job Object with kill-on-close, and fails when no private
|
||||
desktop was created, so there is no input-desktop fallback. Cleanup terminates
|
||||
only processes created by the worker and closes the owned desktop handle.
|
||||
|
||||
`IsolatedDesktopWorker.read_only_probe(request, cad_probe, evidence_root=...)`
|
||||
is the usable native boundary: it runs the injected native reader inside the
|
||||
owned private desktop, then checks its `CadIdentity(pid, project_path)` against
|
||||
the request before `read_only_verified` evidence is published. The worker
|
||||
refuses unrelated CAD identity and write enablement. It remains opt-in and does
|
||||
not mutate CAD.
|
||||
|
||||
## Verification
|
||||
|
||||
- `tests/v1_1/test_project_context.py` and `test_isolated_desktop.py`: **11 passed**.
|
||||
- Existing target/quick-run checks (`test_service_target_integration.py`,
|
||||
`test_target_execution.py`): **8 passed**.
|
||||
- Python bytecode compilation passed for all changed backend modules.
|
||||
|
||||
The private desktop path remains research-only until a native DxDesigner build
|
||||
is validated on a disposable project; no production write claims are made.
|
||||
@@ -0,0 +1,44 @@
|
||||
# Single-project UI and background worker implementation plan
|
||||
|
||||
> For agentic workers: use subagent-driven-development for the backend task and inline implementation for the UI; review the combined branch before integration.
|
||||
|
||||
Goal: implement the approved single-project workflow and research desktop backend without packaging.
|
||||
|
||||
Architecture: one context read replaces repeated multi-project UI queries; independent process supervision contains CAD automation. Existing persistence and execution safeguards remain authoritative.
|
||||
|
||||
Tech stack: Python 3.12, PySide6, SQLite, Win32/COM, ASCII VBS.
|
||||
|
||||
Spec: docs/superpowers/specs/2026-10-14-single-project-ui-background-design.md
|
||||
|
||||
## Global constraints
|
||||
|
||||
- Keep V1.1.0, do not package; commit each verified feature block.
|
||||
- One immutable bound project per new task; preserve historical data.
|
||||
- Default tests remain fast; no full legacy suite or production CAD writes.
|
||||
- No background claim without native validation; private desktop stays opt-in research.
|
||||
- No empty target fallback, unsaved-plan execution, unrelated CAD attachment or unsafe write interruption.
|
||||
|
||||
## Task 1 — single-project context and isolated worker
|
||||
|
||||
Owned by backend implementer: service.py; new project_context.py, isolated_desktop.py, isolated_worker.py; necessary quick_run/native_helper/VBS boundary edits; tests/v1_1/test_project_context.py and test_isolated_desktop.py. No UI files.
|
||||
|
||||
- [ ] Prove bound context returns one project and cached task facade; reject mutable project membership on bound tasks. Include empty/disabled target plans and legacy read-only context cases.
|
||||
- [ ] Produce service.task_context(task_id), service.refresh_bound_project(task_id), and immutable ProjectTaskContext(task, project, rules, targets, progress, phase, has_evidence, interrupted, legacy).
|
||||
- [ ] Build opt-in private desktop worker using CreateDesktop, STARTUPINFO.lpDesktop, owned process tree and versioned request/evidence. Reject existing unrelated CAD, verify CAD PID/project before COM use and retain safe write-boundary pause semantics. Give root exact API for UI context and backend integration.
|
||||
- [ ] Run focused context/worker safety tests, write task report, commit only owned files.
|
||||
|
||||
## Task 2 — UI cleanup and search
|
||||
|
||||
Owned by root: ui/main_window.py, run_panel.py, project_plan.py, target_table.py, task_list.py; new project_summary.py and execution_state.py if useful; UI tests and docs.
|
||||
|
||||
- [ ] Add behavior checks for no multi-project controls, current-task scope, Find/Next/Clear preserving hidden plan rows and hidden drafts blocking group execution.
|
||||
- [ ] Replace task-details project table with immutable summary and refresh; remove manual-run/project-select code and use ProjectTaskContext for local gates.
|
||||
- [ ] Keep task creation modal; add cached plan search, clear/next, correct visible-row bulk operations and ordered task list.
|
||||
- [ ] Wire execution/retry/recovery/pause controls with consistent labels and one confirmation summary; prevent conflicting edits while workers run.
|
||||
- [ ] Run focused UI tests, inspect offscreen screenshot, document workflow and commit.
|
||||
|
||||
## Task 3 — review and integration
|
||||
|
||||
- [ ] Review combined diffs for target scope, stale UI callbacks, locks, legacy handling and isolated desktop lifecycle. Fix material findings with focused checks.
|
||||
- [ ] Run default behavior suite plus only impacted safety modules; record counts/times and limitations. No packaging.
|
||||
- [ ] Commit review fixes and integrate verified changes locally without overwriting user edits.
|
||||
@@ -0,0 +1,62 @@
|
||||
# V1.1.0 Project Tasks Implementation Plan
|
||||
|
||||
> **For agentic workers:** Use superpowers:subagent-driven-development task-by-task. Steps use checkbox syntax.
|
||||
|
||||
**Goal:** Iterate the existing replacement application with single-project tasks, editable per-component plans, optional Excel imports and serial task execution.
|
||||
|
||||
**Architecture:** Reuse the existing desktop service/store and native replacement helper. Add focused plan/inventory/queue modules with stable target identities and transactional persistence. Keep historic jobs and an explicit legacy test entry point.
|
||||
|
||||
**Tech Stack:** Python 3.12, SQLite, PySide6, ASCII VBScript; openpyxl for XLSX files.
|
||||
|
||||
**Spec:** docs/superpowers/specs/2026-10-14-v1.1.0-project-tasks-design.md
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- Version 1.1.0; retain existing task view and direct editing.
|
||||
- Each directory-created task owns exactly one .prj; historical tasks are preserved.
|
||||
- Explicit empty targets never mean all matches.
|
||||
- UID + schematic + sheet + expected RefDes + old Part Number identify targets.
|
||||
- Default NC synchronization remains on and is editable in UI/import; independent /NC only.
|
||||
- Existing Replace Part + Library Wins, backup and saved readback remain required.
|
||||
- No production CAD writes for interface research or tests.
|
||||
- Default tests are fast behavior tests; historic regressions are explicit and preserved.
|
||||
|
||||
---
|
||||
|
||||
## Task 1: Persistence, inventory, plans and target execution
|
||||
|
||||
Files: models.py, store.py, service.py, quick_run.py, recovery.py, QuickPartReplace.vbs; create target_plan.py, inventory.py, spreadsheet_plan.py and project_tasks.py as focused modules; tests/v1_1/test_project_tasks.py, test_target_plan.py, test_inventory.py, test_spreadsheet_plan.py, test_target_execution.py.
|
||||
|
||||
Interfaces consumed: TaskStore transaction(), create_task(), sync_projects(); QuickRunPreparer and existing sheet discovery. Produced: directory task creation, task inventory, target plan edit/import/export APIs and versioned target-aware queue preparation. Define exact signatures in the implementation report for UI/task queue integration.
|
||||
|
||||
- [x] Write failing behavior tests for two .prj files creating two single-project tasks, duplicate scanning not duplicating active tasks, same names differentiated by relative path; run these tests and observe missing APIs.
|
||||
- [x] Implement transaction-backed group/order/project binding and migrations; maintain legacy constructor defaults. Test transaction rollback and reopen.
|
||||
- [x] Write failing tests using injected inventory rows for same old part on R1/R2/R3: selecting R1/R3 yields only those UIDs; R2 stays excluded; missing target errors, empty target errors, conflicting imports and equal/chain/cycle rules error.
|
||||
- [x] Implement component inventory read mode on existing discovery route, collecting effective Value and all stable identifiers without pin/attribute full snapshots; do not save while scanning.
|
||||
- [x] Implement target rule grouping and target-aware command/snapshot/recovery freeze validation in both Python and VBS. Run isolated VBS contract tests and native_helper mocks; tests must prove selectors survive recovery and stale targets do not become no_match.
|
||||
- [x] Add openpyxl reader/writer using explicit columns and literal values; parse whole workbook, validate identity and duplicates, then commit atomically. Test roundtrip editing new part, Value and NC plus forged UID and duplicate row rejection.
|
||||
- [x] Run V1.1 behavior tests and relevant existing inputs/value/recovery tests; commit this task only after covering tests pass and report API signatures and validation limits.
|
||||
|
||||
## Task 2: Cross-task scheduler and existing UI integration
|
||||
|
||||
Files: task_queue.py; ui/main_window.py, task_list.py, mapping_table.py; tests/v1_1/test_task_queue.py, test_project_task_ui.py.
|
||||
|
||||
Consumed APIs: Task 1 report; existing service.execute_quick_run_queue/quick_run_progress and safe pause. Produced APIs: fixed ordered task queue runner and UI directory wizard/inventory target table/Excel optional entry points.
|
||||
|
||||
- [x] Write failing scheduler test with fake runner logging starts/ends: A completes before B starts; pause leaves B unstarted; uncertain A prevents B; safe ordinary A failure allows B and summary records both.
|
||||
- [x] Implement scheduler with per-task evidence paths and fixed IDs/plan fingerprints; reject same-project concurrent tasks, preserve active task evidence on resume.
|
||||
- [x] Add directory scanner/create dialog to existing New action with project checkboxes and async scan; existing edit/name notes and historical view survive. Show counts and execution order, support ordering and group start/pause.
|
||||
- [x] Add Collect Targets action and editable target table: per row enabled/new part/custom Value/NC controls; preserve existing rule dialog/full-match path. Excel import/export optional actions use same plan validation; blank typed target lists rejected rather than matching all.
|
||||
- [x] Verify Qt widgets with offscreen smoke interactions and scheduler failure/lock tests. Commit after tests pass.
|
||||
|
||||
## Task 3: Test entry points, version and deliverable verification
|
||||
|
||||
Files: pyproject.toml, version.py, packaging/Build-DxPartReplace.ps1, docs/user/v1.1.0-project-tasks.md, tests/conftest.py or tests/legacy/conftest.py, tools/test_v1_1.ps1 and tools/test_legacy.ps1.
|
||||
|
||||
- [x] Default testpaths becomes tests/v1_1. Keep existing directories reachable with explicit paths; scripts set local src PYTHONPATH to prevent unrelated installed dx_productivity package collisions.
|
||||
- [x] Version pyproject and desktop to 1.1.0. Add openpyxl dependency and ensure packaging discovers it; update build QA commands to run V1.1 and meaningful safety regressions rather than reintroducing full slow suite implicitly.
|
||||
- [x] Document new task/inventory/Excel/NC workflows, previous data migration and real CAD validation limits; include native research report.
|
||||
- [x] Run default behavior suite, selected safety/Qt/VBS tests, compileall and build/frozen smoke if toolchain available. Review diff for selector fallback, evidence overwrites, migration loss and UI async locks; fix findings.
|
||||
- [x] Bring verified commits into the main workspace without rewriting user work; supply V1.1.0 ZIP/EXE if build succeeds and distinguish code test results from live CAD acceptance.
|
||||
|
||||
Verification and implementation details: v1.1.0-task-1-report.md and v1.1.0-task-2-report.md. Live CAD acceptance remains outside offline verification.
|
||||
@@ -0,0 +1,28 @@
|
||||
# 执行响应与模块边界优化
|
||||
|
||||
用户已确认上一轮审查提出的优化方向。本计划在现有 V1.1.0 上增量实施,不打包、不推送。
|
||||
|
||||
## 设计和约束
|
||||
|
||||
- CAD 仍串行执行,保存、关闭、重开回读及不确定状态阻断继续保留。
|
||||
- 查询与修改分开:任务和日志查询独立后台执行,过期结果不覆盖当前选择;执行过程中允许只读浏览其他任务。
|
||||
- 日志默认加载最近一页,历史分页加载,实时更新按游标追加;轮转、截断、未完成行和任务切换不能丢失或串日志。
|
||||
- 目录扫描可取消并显示进度;创建任务复用已选结果,重新校验路径、工程类型和扫描边界,避免重复递归。
|
||||
- 采集生成的图页发现结果只在工程内容指纹仍一致且料号范围满足时复用;执行前的身份校验保持。
|
||||
- 按职责提取查询控制器、日志读取、发现缓存及执行反馈接口,避免为了缩短文件破坏事务边界。
|
||||
- 同工程跨步骤保持 CAD 打开的优化需要改变当前“一步一份持久结果”的恢复协议。本轮先通过发现缓存减少重复打开;不直接合并尚未验证的保存事务。
|
||||
|
||||
## 实施
|
||||
|
||||
- [x] 目录扫描取消、进度与创建阶段定向复核;验证取消不创建部分任务、边界和排除目录保护。
|
||||
- [x] 发现缓存和公开执行器接口;验证命中、工程文件变化失效、料号范围及任务隔离。最终使用元数据加 SHA256 内容摘要,覆盖保留时间戳的等长修改。
|
||||
- [x] 后台任务快照、后台增量分页日志、运行时只读导航及可靠完成回调;验证慢查询下事件循环仍响应、旧请求被丢弃、暂停可用。
|
||||
- [x] 针对性回归、独立审查与响应计时报告;按功能及时提交 Git。
|
||||
|
||||
备份状态及预备份策略独立为 BatchBackupCoordinator,主执行函数约 304 行缩为 170 行。执行反馈使用独立只读快照接口;关闭窗口先废弃查询回调,进程退出前等待查询结束再关闭 SQLite。任务完成强制刷新最终日志,执行 A、查看 B 时明确标注 A 的结果。
|
||||
|
||||
审查记录:初审发现慢日志请求饿死和跨任务完成提示归属问题,均补测试修复;终审复现元数据指纹复用负结果漏洞,已改内容摘要并通过复审。完整记录见 `docs/testing/2026-10-15-execution-responsiveness.md`。
|
||||
|
||||
## 验证
|
||||
|
||||
真实 SQLite 和临时工程目录验证扫描及持久化;模拟外部 CAD 验证发现调用次数和缓存失效;Qt offscreen 用受控慢 I/O 验证事件循环、导航、关闭及回调归属。复用既有队列安全测试,不重复运行整套压力测试或更改原始工程。
|
||||
@@ -0,0 +1,16 @@
|
||||
# 私有桌面正式执行实施计划
|
||||
|
||||
**目标:** 完成用户已授权的私有桌面替换与释放闭环,不打包,及时提交并推送现有开发分支。
|
||||
|
||||
**设计:** `docs/superpowers/specs/2026-10-15-private-desktop-execution-design.md`。
|
||||
|
||||
- [x] 原生只读探针确认显式 CAD 启动、COM/窗口 PID 和桌面身份;用户现有 CAD 保持不动。
|
||||
- [x] 加固 `isolated_desktop.py`:先绑定 Job 再恢复进程;等待退出;异常时逐项清理;验证自有进程及桌面释放。
|
||||
- [x] 独立隔离执行模块接入 `worker_monitor.py`、`project_session.py` 和只读枚举;补齐 VBS、native helper 身份核验与正常退出。
|
||||
- [x] 默认正式入口走隔离执行;继续兼容注入模拟执行器;打包入口支持所有必要 worker 参数。
|
||||
- [x] 独立真实副本验证选中/未选中位号、NC 开关、逐步保存回读、暂停和异常清理,记录前台窗口/输入桌面及资源释放证据。
|
||||
- [x] 定向回归与审查,记录限制并推送远端;不重复无关基础测试、不放宽既有门槛。
|
||||
|
||||
验证范围:私有桌面生命周期、PID 绑定、执行监督器和批量会话回归;原生操作由主代理串行执行。低层 Win32 资源模块可委派独立实现,其余集成由主代理负责,避免共享文件覆盖。
|
||||
|
||||
验证详情及未覆盖边界见 `docs/testing/2026-10-15-private-desktop-execution.md`。无活动图页时 ActiveViewHandle 可能陈旧;启动和退出使用显式自有 CAD、私有 ROT 与 GUID,活动图页读写才强制验证 HWND/PID。NC 开/关参与本次真实步骤,但样本没有独立 `/NC` 标记,不声称重新验收了 NC 转换效果。
|
||||
@@ -0,0 +1,30 @@
|
||||
# 工程会话、统一快照与可取消查询实施计划
|
||||
|
||||
用户已明确授权四项优化,在 `codex/execution-responsiveness` 上继续迭代,基线 `bc6b726`;完成后推送同名远端分支,不打包。
|
||||
|
||||
## 约束与设计
|
||||
|
||||
- 一个工程一个任务,CAD 串行,不能接管用户已打开的工程。
|
||||
- 会话复用保留每步保存和重开回读检查点;同工程下一步复用上一步回读后仍由工具持有的工程及 worker。结束、暂停、换工程或失败时关闭自有会话,状态不确定则阻断。
|
||||
- 持久 worker 使用带随机令牌的命令/应答,下一步仍复核冻结命令、图页及状态文件;复用不能绕过目标 UID/位号/旧料号、属性和连接核验。
|
||||
- 原单步执行器兼容,测试注入的 worker 不强制采用原生持久会话。新 transport 与监控、状态读取独立。
|
||||
- 一次任务读取使用同一数据库只读快照及同一次证据解析,得出进度、证据位置、中断状态,不能在查询中写入恢复状态。
|
||||
- 慢查询使用协作取消 token、分段 checkpoint 与有界调度;旧请求失效后尽快退出,单次无法中断的系统 I/O 不冒充已取消。
|
||||
- 数据库拆分迁移、位号计划等职责,继续共享同一个连接、锁和嵌套事务;协议模型/编解码与快照从 quick_run 分离,保留兼容导出。
|
||||
|
||||
## 任务
|
||||
|
||||
- [x] 统一文件执行快照与协议模块,改服务为一次读取,保留未知/损坏证据的保护;增加读取次数和一致性回归。
|
||||
- [x] 可取消查询、分段读取及有界旧请求处理,验证快速切换、关闭、慢 I/O、旧回调隔离。
|
||||
- [x] 拆分存储职责并新增一致的任务数据读取接口,验证迁移、回滚、目标计划与执行状态事务。
|
||||
- [x] 持久工程 worker 与 VBS 循环,接入批量调度,验证每步检查点、同页/换页、暂停/失败/超时/外部修改保护。
|
||||
- [x] 在独立真实工程副本测量单步与复用方式,独立回读选中和未选中位号;记录逐步耗时、启动和打开次数。
|
||||
- [x] 针对性回归、独立审查、及时提交并推送远端,记录尚存的现场限制。
|
||||
|
||||
## 责任边界
|
||||
|
||||
快照/协议修改与执行 transport 仅在 quick_run 的导入及各自方法连接,避免覆盖彼此代码。查询 token 是跨 UI、服务和文件读取的公共依赖。存储拆分提供 `read_task_bundle(task_id, read_control=None)`,一次锁/事务返回 task、projects、rules、targets。真实 CAD 验证由主代理串行进行,其他代理只使用临时数据和模拟器。
|
||||
|
||||
## 核验记录
|
||||
|
||||
集成、快照/存储/监督器、会话及旧单步执行器兼容性去重合计 301 项通过。独立副本的两步实际替换从 113.175 秒降至 100.641 秒,2 个选中及 11 个保留位号均独立回读一致;原生三页未命中及中途关闭、外部编辑/外部工程保护通过。千步用例功能和内存通过,当前 41.516 秒、原基线同环境 42.453 秒,均未达到原 30 秒门槛,不放宽阈值。PON 原单步替换基线存在失败,未作为成功替换性能对照。详见 `docs/testing/2026-10-15-project-session-and-read-model.md`。
|
||||
@@ -0,0 +1,39 @@
|
||||
# V1.1.0 Project Tasks Implementation Plan
|
||||
|
||||
> **For agentic workers:** Use superpowers:subagent-driven-development task-by-task. Steps use checkbox syntax.
|
||||
|
||||
**Goal:** Iterate the existing replacement application with single-project tasks, editable per-component plans, optional Excel imports and serial task execution.
|
||||
|
||||
**Architecture:** Reuse the existing desktop service/store and native replacement helper. Add focused plan/inventory/queue modules with stable target identities and transactional persistence. Keep historic jobs and an explicit legacy test entry point.
|
||||
|
||||
**Tech Stack:** Python 3.12, SQLite, PySide6, ASCII VBScript; openpyxl for XLSX files.
|
||||
|
||||
**Spec:** docs/superpowers/specs/2026-10-14-v1.1.0-project-tasks-design.md
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- Version 1.1.0; retain existing task view and direct editing.
|
||||
- Each directory-created task owns exactly one .prj; historical tasks are preserved.
|
||||
- Explicit empty targets never mean all matches.
|
||||
- UID + schematic + sheet + expected RefDes + old Part Number identify targets.
|
||||
- Default NC synchronization remains on and is editable in UI/import; independent /NC only.
|
||||
- Existing Replace Part + Library Wins, backup and saved readback remain required.
|
||||
- No production CAD writes for interface research or tests.
|
||||
- Default tests are fast behavior tests; historic regressions are explicit and preserved.
|
||||
|
||||
---
|
||||
|
||||
## Task 1: Persistence, inventory, plans and target execution
|
||||
|
||||
Files: models.py, store.py, service.py, quick_run.py, recovery.py, QuickPartReplace.vbs; create target_plan.py, inventory.py, spreadsheet_plan.py and project_tasks.py as focused modules; tests/v1_1/test_project_tasks.py, test_target_plan.py, test_inventory.py, test_spreadsheet_plan.py, test_target_execution.py.
|
||||
|
||||
Interfaces consumed: TaskStore transaction(), create_task(), sync_projects(); QuickRunPreparer and existing sheet discovery. Produced: directory task creation, task inventory, target plan edit/import/export APIs and versioned target-aware queue preparation. Define exact signatures in the implementation report for UI/task queue integration.
|
||||
|
||||
- [ ] Write failing behavior tests for two .prj files creating two single-project tasks, duplicate scanning not duplicating active tasks, same names differentiated by relative path; run these tests and observe missing APIs.
|
||||
- [ ] Implement transaction-backed group/order/project binding and migrations; maintain legacy constructor defaults. Test transaction rollback and reopen.
|
||||
- [ ] Write failing tests using injected inventory rows for same old part on R1/R2/R3: selecting R1/R3 yields only those UIDs; R2 stays excluded; missing target errors, empty target errors, conflicting imports and equal/chain/cycle rules error.
|
||||
- [ ] Implement component inventory read mode on existing discovery route, collecting effective Value and all stable identifiers without pin/attribute full snapshots; do not save while scanning.
|
||||
- [ ] Implement target rule grouping and target-aware command/snapshot/recovery freeze validation in both Python and VBS. Run isolated VBS contract tests and native_helper mocks; tests must prove selectors survive recovery and stale targets do not become no_match.
|
||||
- [ ] Add openpyxl reader/writer using explicit columns and literal values; parse whole workbook, validate identity and duplicates, then commit atomically. Test roundtrip editing new part, Value and NC plus forged UID and duplicate row rejection.
|
||||
- [ ] Run V1.1 behavior tests and relevant existing inputs/value/recovery tests; commit this task only after covering tests pass and report API signatures and validation limits.
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
# V1.1.0 Task 1 Backend Report
|
||||
|
||||
Task 1 implements single-project persistence, target inventory/plans, Excel interchange, target-aware queue preparation, native selector checks, and recovery bindings.
|
||||
|
||||
## APIs for UI and scheduler
|
||||
|
||||
- `TaskCenterService.create_project_tasks(root: Path, selected_paths: tuple[Path, ...] | None = None) -> tuple[TaskRecord, ...]`: scans a directory and creates one task per selected `.prj`; each task owns exactly one project. Active unfinished paths are deduplicated. Completed tasks may be recreated with a readable suffix.
|
||||
- `TaskCenterService.scan_project_directory(root: Path) -> tuple[Path, ...]`: read-only directory scan.
|
||||
- `TaskCenterService.collect_target_inventory(task_id: str, old_part_numbers: tuple[str, ...] | None = None) -> tuple[TargetPlanRow, ...]`: runs existing owned-project discovery in read mode and records stable `ComponentTarget` baselines. No save is requested from the CAD process.
|
||||
- `TaskCenterService.target_plan(task_id: str) -> tuple[TargetPlanRow, ...]` and `replace_target_plan(task_id, rows)`: read/edit the plan. `store.record_target_inventory(task_id, targets)` is the trusted initial baseline operation. A plan edit cannot alter project/schematic/sheet/UID/RefDes/old-part/old-Value identity.
|
||||
- `TaskCenterService.preview_target_plan(task_id, path)` validates an Excel workbook without writing; `import_target_plan(task_id, path)` validates then commits atomically; `export_target_plan(task_id, path)` writes explicit columns.
|
||||
- `TaskCenterService.for_project_task(task_id) -> TaskCenterService`: returns a facade whose queue evidence root is `storage/tasks/<task_id>/quick-run`; the facade shares the store and logging context. Parent quick-run entry points delegate automatically for bound single-project tasks.
|
||||
- `TaskCenterService.move_project_task(task_id, offset)` changes group ordering while the group is idle.
|
||||
- `ComponentTarget(project_path, schematic_name, sheet_number, uid, refdes, old_part_number, old_value)` is immutable identity. `TargetPlanRow(target, enabled=False, new_part_number='', custom_value_enabled=False, custom_value='', sync_nc=True)` contains editable fields. NC defaults to enabled.
|
||||
|
||||
## Execution behavior
|
||||
|
||||
`TaskRecord.target_plan_mode` is set when inventory is recorded, including an explicitly empty inventory. Execution compiles only enabled target rows into `TargetRule` groups. An empty or all-disabled target plan raises `enabled_rule_required`; it never falls back to old-part full matching. Mixing target and full-match rules is rejected. Target queue rows carry `target_scope=targets` and encoded UID/RefDes/old-Value selectors.
|
||||
|
||||
The VBS helper validates selectors against the active project/sheet before capture and native replacement. Python native checks do the same and compare the unselected component baseline (UID, RefDes, Part Number, Value, Part Name, Part Label) before and after mutation. Recovery binds the selector set and snapshot hash to the transaction evidence. Native CAD operations remain uncalled by tests.
|
||||
|
||||
## Validation
|
||||
|
||||
Commands run from the worktree:
|
||||
|
||||
```text
|
||||
PYTHONPATH=src python -m pytest tests/v1_1 -q
|
||||
36 passed in 5.06s
|
||||
|
||||
PYTHONPATH=src python -m pytest tests/integration/test_quick_part_replace_contract.py tests/trial_task_center/test_recovery.py tests/trial_task_center/test_value_options.py -q
|
||||
45 passed in 7.57s
|
||||
```
|
||||
|
||||
The V1.1 suite covers transaction rollback/reopen, schema 5 to 6 migration, project deduplication and recreation, target subset isolation, empty target safety, forged identity rejection, Excel roundtrip/atomic validation, per-task evidence roots, native selector checks, unselected-change detection, and purge cleanup.
|
||||
|
||||
## Limits
|
||||
|
||||
Component inventory depends on the existing `QuickPartReplace.vbs` read-only discovery route and therefore requires a Windows DxDesigner installation for live collection. The test suite uses injected inventory rows and never performs production CAD writes. The native helper cannot prove arbitrary attributes that are not included in the recorded baseline; it checks the documented identity/value fields above.
|
||||
@@ -0,0 +1,37 @@
|
||||
# V1.1.0 Project Tasks Implementation Plan
|
||||
|
||||
> **For agentic workers:** Use superpowers:subagent-driven-development task-by-task. Steps use checkbox syntax.
|
||||
|
||||
**Goal:** Iterate the existing replacement application with single-project tasks, editable per-component plans, optional Excel imports and serial task execution.
|
||||
|
||||
**Architecture:** Reuse the existing desktop service/store and native replacement helper. Add focused plan/inventory/queue modules with stable target identities and transactional persistence. Keep historic jobs and an explicit legacy test entry point.
|
||||
|
||||
**Tech Stack:** Python 3.12, SQLite, PySide6, ASCII VBScript; openpyxl for XLSX files.
|
||||
|
||||
**Spec:** docs/superpowers/specs/2026-10-14-v1.1.0-project-tasks-design.md
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- Version 1.1.0; retain existing task view and direct editing.
|
||||
- Each directory-created task owns exactly one .prj; historical tasks are preserved.
|
||||
- Explicit empty targets never mean all matches.
|
||||
- UID + schematic + sheet + expected RefDes + old Part Number identify targets.
|
||||
- Default NC synchronization remains on and is editable in UI/import; independent /NC only.
|
||||
- Existing Replace Part + Library Wins, backup and saved readback remain required.
|
||||
- No production CAD writes for interface research or tests.
|
||||
- Default tests are fast behavior tests; historic regressions are explicit and preserved.
|
||||
|
||||
---
|
||||
|
||||
## Task 2: Cross-task scheduler and existing UI integration
|
||||
|
||||
Files: task_queue.py; ui/main_window.py, task_list.py, mapping_table.py; tests/v1_1/test_task_queue.py, test_project_task_ui.py.
|
||||
|
||||
Consumed APIs: Task 1 report; existing service.execute_quick_run_queue/quick_run_progress and safe pause. Produced APIs: fixed ordered task queue runner and UI directory wizard/inventory target table/Excel optional entry points.
|
||||
|
||||
- [ ] Write failing scheduler test with fake runner logging starts/ends: A completes before B starts; pause leaves B unstarted; uncertain A prevents B; safe ordinary A failure allows B and summary records both.
|
||||
- [ ] Implement scheduler with per-task evidence paths and fixed IDs/plan fingerprints; reject same-project concurrent tasks, preserve active task evidence on resume.
|
||||
- [ ] Add directory scanner/create dialog to existing New action with project checkboxes and async scan; existing edit/name notes and historical view survive. Show counts and execution order, support ordering and group start/pause.
|
||||
- [ ] Add Collect Targets action and editable target table: per row enabled/new part/custom Value/NC controls; preserve existing rule dialog/full-match path. Excel import/export optional actions use same plan validation; blank typed target lists rejected rather than matching all.
|
||||
- [ ] Verify Qt widgets with offscreen smoke interactions and scheduler failure/lock tests. Commit after tests pass.
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
# V1.1.0 UI, scheduler and delivery report
|
||||
|
||||
The existing task view now creates one task per selected project from a directory preview. The original mapping editor remains available beside the new target plan tab. The plan supports direct editing of selected targets, new Part Number, custom Value and NC; Excel import is a draft preview requiring Save. Unsaved drafts survive task switching and block group execution. NC is editable and defaults on, as confirmed by the user.
|
||||
|
||||
The task scheduler freezes task order and plan fingerprints, uses isolated per-task evidence, persists checkpoints and holds process/thread execution locks. Safe preflight failures are recorded; uncertainty stops before the next task. A paused UI queue retains the same task IDs including completed entries, allowing durable resume without replaying successful tasks. Target-mode and project-selection state are included in fingerprints.
|
||||
|
||||
Independent review identified raw-rule batch fallback, evidence routing differences, disappearing target pages, saved-unverified resume, mutation guards, purge foreign keys and subset rollback comparisons. These were fixed in the backend commits and checked against their focused tests. No live CAD write was performed.
|
||||
|
||||
## Verification and artifacts
|
||||
|
||||
- Default behavior suite: 36 passed in 5.43 seconds via `tools/Test-V1.1.ps1`.
|
||||
- Selected existing safety suite: 38 passed in 5.12 seconds.
|
||||
- Release build QA: combined 74 passed in 8.42 seconds.
|
||||
- Focused backend VBS/recovery/Value checks: 45 passed in 7.57 seconds; final VBS contract check: 10 passed in 0.14 seconds.
|
||||
- Python compileall and Git whitespace check passed.
|
||||
- Offscreen UI screenshot inspected with a Windows Chinese font loaded for the offscreen renderer. It shows selected R1/R3, retained R2/R4/R5/R6 and editable NC. Default splitter proportions give the plan more space.
|
||||
- PyInstaller 6.22.3 / Python 3.12.10 build succeeded. The frozen application started and shut down cleanly using an isolated temporary data root.
|
||||
- After the final VBS component-count guard, the release runtime script was refreshed from source, its SHA-256 checked, and the frozen smoke repeated successfully. Final bridge SHA-256: `3BDEC7476762C28D6606825183DAC98505541EE2808B2F4C240577A7E304C72D`.
|
||||
|
||||
The historical suite remains explicitly available; it is not part of default development or release checks. Actual central-library replacement, saves/readback and external CAD validation still require a disposable project acceptance run. The included native interface report confirms the installed 7.9.5 typelib lacks a direct ReplacePart method.
|
||||
@@ -0,0 +1,13 @@
|
||||
# Single-project task UI and isolated execution
|
||||
|
||||
User approved this direction on 2026-10-14. This is continued V1.1.0 source development; do not build or package. Commit verified functional increments promptly.
|
||||
|
||||
- New-task dialog scans a root and selects projects; every resulting task owns one immutable project. Task details contain a project summary, refresh action, rules, targets and execution controls, with no project list/select-all/filter/skip/manual-run controls.
|
||||
- Existing data is preserved. Multi-project historical tasks remain inspectable but are read-only in the new single-project UI; create project tasks through the dialog for further execution.
|
||||
- Read task context once per refresh, then compute gates locally. UI changes and table search must not reread SQLite/CAD or regenerate log content unnecessarily. A per-task service facade must be reused without mixing evidence roots.
|
||||
- Target search matches RefDes, UID, old/new part, sheet/schematic and Values case-insensitively; explicit Find filters cached table data, Enter runs Find, Next locates another match, Clear restores all. Filters never remove rows from saved plans. Bulk/select actions operate visible rows while preserving hidden rows.
|
||||
- Execution commands are Execute current task, Execute batch in order, Pause at safe boundary, Retry failed items and Reconcile interruption. Scope, pending unsaved plans, lifecycle and active worker guards must be coherent. No backup-failure bypass control in the streamlined UI.
|
||||
- Desktop isolation is an explicit research backend, not automatically enabled. It creates and owns a private desktop/process tree, validates CAD PID/project identity and reuses the existing UID/Library Wins/backup/save/readback safeguards. Never attach an unrelated CAD instance or fall back to the input desktop. No production CAD writes for validation.
|
||||
- Normal workflows retain direct mapping/target edits, custom Value and default-on editable NC, plus optional spreadsheet import draft followed by explicit save.
|
||||
|
||||
Architecture: service produces a frozen ProjectTaskContext; task bindings remain store-compatible. UI is separated into project summary, plan/search table and execution state presentation. Native isolated worker is an independent backend boundary with evidence and cleanup. Safety checks remain at services and native code as well as UI gates.
|
||||
@@ -0,0 +1,31 @@
|
||||
# DxPartReplace V1.1.0 单工程任务与位号计划
|
||||
|
||||
已获用户授权开始迭代;本设计记录当前对话决定,不新增审批步骤。
|
||||
|
||||
## 产品流程
|
||||
|
||||
保留现有任务列表与规则编辑体验。新建入口支持选择目录、扫描 .prj、勾选工程、一次创建多个任务;每个新任务绑定且只绑定一个工程。同名工程使用相对路径区分。任务组只是目录创建与排序的组织单位。历史多工程任务保留,不能在迁移中重写执行证据。
|
||||
|
||||
用户在任务内填写旧料号、新料号,点击采集位号。使用已有只读图页发现链路读取真实器件的图页、UID、RefDes、Part Number、有效 Value。采集不调用替换、不保存。图页不同、层级不同或同名位号不能只靠 RefDes 合并。采集只读进程必须有界结束并关闭其拥有的工程。
|
||||
|
||||
用户可在原界面直接编辑/选择目标位号,不必导出。Excel 导入是可选入口;可导出同样的计划用于 Excel 编辑,但不会要求导出后才能执行。一行代表一个真实器件,保留工程、原理图、图页、UID、位号、旧料号、旧 Value,用户可编辑启用、新料号、自定义 Value、NC 同步。基线身份列不可重新解释;导入必须完整校验后原子提交,不得部分写入。
|
||||
|
||||
## 规则与执行
|
||||
|
||||
规则支持明确的全匹配范围与显式目标范围。旧规则迁移为全匹配;新目标规则使用已采集的 UID 与图页/位号作为预期状态。空目标集合不能退化为全匹配。同一旧料号允许不同位号子集和不同目标料号;重叠目标、全匹配与目标子集混用、链式/循环映射拒绝。一个目标可写独立自定义 Value;按图页/旧料号/新料号/Value/NC 策略编译分组再执行。
|
||||
|
||||
NC 保留现有可选语义并补齐任务视图编辑及 Excel 导入,默认开启;仅独立 /NC 段识别,禁止重复追加,写入和保存后回读均检验。保留模式的真实含义沿用现有原生库 Value 语义,不凭名为 preserve 推断会恢复旧文字。自定义模式明确写入用户给出的新值。
|
||||
|
||||
保持已有原生 Replace Part + Library Wins 写入路径与备份/连接/位置/保存回读/不确定保护。Python 计划携带 UID 清单,VBScript 在选取前校验 UID、RefDes、源料号、图页;目标缺失/状态变化必须失败而不是 no_match。未选器件的变化必须检测。目标绑定加入命令、快照、恢复与输入冻结校验。
|
||||
|
||||
跨任务执行采用已确认的任务 ID 顺序并固定计划。一个任务完成收尾/关闭后才进入下一个;普通失败在工程已安全关闭时可继续,未确定结果、恢复保护、关闭失败停止。各任务持有独立队列、备份、日志,不能用共享目录覆盖上一任务的未完成状态。规则、选择和任务操作在活动执行期间锁定,暂停在安全项边界。
|
||||
|
||||
## 结构与迁移
|
||||
|
||||
添加聚焦的 project_tasks、target_plan、inventory、spreadsheet_plan、task_queue 模块;复用 TaskStore/TaskCenterService 与 Qt 视图;不得复制旧多工程控制器或实现另一套 CAD 写入引擎。数据库使用事务迁移,新增字段有兼容默认值。版本从 1.1.0 起,EXE 标题、构建清单、依赖版本同步。
|
||||
|
||||
原生接口调研代理独立只读:检查当地官方类型库与帮助、已有探针以及公开资料,报告已证实能力/待验证能力;不对当前 CAD 会话或生产工程发起写操作。实验接口不自动成为默认后端。
|
||||
|
||||
## 验证
|
||||
|
||||
重建测试入口:默认只运行 V1.1.0 的行为级快速核心测试和必要的现有安全回归。旧测试保留为显式 legacy 回归入口,不删掉证据、不把过长模拟睡眠放入默认测试。无需 CAD、真实 COM 或网络即可测试导入原子性、目标隔离、顺序、重启/暂停、NC 和协议绑定。VBS 契约验证、Qt 交互和冻结 EXE 冒烟单独报告。现场原生替换与单元测试结论必须区分。
|
||||
@@ -0,0 +1,11 @@
|
||||
# 私有桌面正式执行闭环
|
||||
|
||||
用户在说明研究框架未接入后明确要求“那就把这一套执行好”。本轮在 `codex/execution-responsiveness` 上完成原执行器的私有桌面接入,不再停留于准备协议或回调探针。
|
||||
|
||||
生产入口的工程枚举和批量替换都必须在独立 Windows desktop 启动本工具持有的 CAD/worker。冻结任务、UID 选择、Library Wins、NC/Value 策略、连接保护、逐步保存重开回读和串行任务语义继续沿用。CAD 的 COM 对象必须验证窗口 PID、私有桌面与本次创建的进程身份;不能使用用户的其他 CAD 或静默回退普通桌面。保留模拟执行器注入用于自动化回归。
|
||||
|
||||
生命周期为:创建随机命名 desktop/job → 显式启动并绑定自有 CAD → 私有 desktop 中运行监督脚本及 helper → 保存并独立回读 → 正常退出 CAD → 等待进程退出 → 回收残余自有子进程 → 关闭 job、进程和 desktop 句柄。暂停仅在安全检查点收尾。异常、超时、身份冲突和释放失败保留证据并明确阻断;不得误报成功。主桌面不调用 SwitchDesktop、不注入键鼠,用户其他 CAD 进程和文件保持不动。
|
||||
|
||||
实施前首先用独立进程只读验证当前 EE7.9.5 的显式启动、私有桌面和 COM 绑定;真实替换只使用独立副本。验证至少包括成功、暂停、异常、进程退出、桌面消失以及主桌面前台窗口不被切换。不能用创建 desktop 的单元测试代替原生实际执行证明。
|
||||
|
||||
实现核实:普通显式启动 CAD 可提供私有 ROT,`-Embedding` 不可用。活动工程严格验证活动图页 HWND/PID;没有活动工程时 ActiveViewHandle 可能陈旧,启动和 Quit 改用显式自有 CAD 启动、私有 ROT/GUID 绑定。生产模块为 `isolated_cad.py`,原研究用 `isolated_worker.py` 不作为正式执行后端。实际结果及边界见 `docs/testing/2026-10-15-private-desktop-execution.md`。
|
||||
@@ -0,0 +1,52 @@
|
||||
# 2026-10-15 执行响应与模块优化验证
|
||||
|
||||
在原 V1.1.0 工具上迭代,开发分支 `codex/execution-responsiveness`,基线 `d79250b`。本轮不打包、不推送,也不修改真实原理图工程。
|
||||
|
||||
## 最终行为
|
||||
|
||||
- 任务列表、任务详情、日志和执行反馈通过独立后台查询读取;同一通道最多一个活动查询和一个最新待处理请求,旧结果不能覆盖当前选择。
|
||||
- CAD 执行仍串行;执行过程中可以切换任务只读查看、选择和查找位号,修改和重复启动继续禁用,暂停作用于实际执行队列。
|
||||
- 完成/失败提示明确任务归属,查看 B 时不会把 A 的结果当成 B 的完成记录。完成后强制读取最终日志,避免被执行前尚未返回的旧快照覆盖。
|
||||
- 日志初次加载最近 200 条事件,历史向前分页;实时增量读取并追加,保留 UTF-8 未完成行的读取位置。实时累计到 400 条事件后,下一次刷新重取最近一页以限制显示规模。所有保留历史仍可分页访问;文件轮转、截断或重建时更新游标。旧的完整日志 API 保持兼容。
|
||||
- 目录扫描显示已扫描目录和发现工程数量,可取消和关闭;取消不返回部分候选。任务创建只复核已选工程、路径边界、排除目录、重解析点和祖先工程的扫描规则,不重复递归无关目录。
|
||||
- 只读采集和执行准备可复用图页发现结果,缓存仅限当前任务执行器。工程树内容摘要或元数据变化、扩大料号范围、缺少组件信息会重新发现;执行修改前主动失效。
|
||||
- 新的 `BatchBackupCoordinator` 管理备份状态、失败策略和单工程预备份,`execute_batch` 从约 304 行降至 170 行。保留原生执行、保存关闭重开回读、失败/中断保护及既有事务边界。
|
||||
- 查询回调在窗口关闭时失效;退出应用时等待后台读取结束后再释放共享 SQLite 连接。
|
||||
|
||||
## 响应计时
|
||||
|
||||
在本机一次运行的 **模拟数据 / Qt offscreen** 测量,不是 CAD 性能数据。生成 5000 条事件、40000 条位号修改明细,日志 2,122,783 字节;完整显示采用此前的 QTextEdit,全量读取并格式化。新显示采用 QPlainTextEdit 和分页;单次测量受磁盘缓存等因素影响,不作为通用提速比例。
|
||||
|
||||
| 场景 | 本次耗时 |
|
||||
| --- | ---: |
|
||||
| 原方式:全量读取、格式化、显示 | 851.482 ms |
|
||||
| 最近 200 条:读取、格式化、显示 | 42.178 ms |
|
||||
| 未变化日志的增量轮询(后台) | 27.748 ms |
|
||||
| 新界面异步显示最近日志的端到端时间 | 28.263 ms |
|
||||
| 注入 400 ms 慢读取后,open_task 返回 | 1.362 ms |
|
||||
| 注入慢读取后,任务实际加载完成 | 444.039 ms |
|
||||
| 慢读取期间 20 ms 心跳计时器触发次数 | 22 |
|
||||
| 心跳最大间隔 | 21.601 ms |
|
||||
|
||||
分页遍历独立核对恢复了全部 5000 条事件。原始测量:`build/ui-response/report.json`。
|
||||
|
||||
复现:`python -X utf8 tools/measure_responsiveness.py --output build/ui-response/report.json`。脚本只创建独立临时数据,不连接 CAD。
|
||||
|
||||
缓存采用内容摘要有额外读取成本。独立临时目录 65 个文件、总计 32 MiB 的五次指纹测量约 149~203 ms,中位数约 169 ms;缓存命中需要读取包含文件一次,发现缓存未命中会在发现前后各读取一次。大工程和慢盘需以现场数据判断收益。本轮未重新测量 CAD 实际替换耗时,不能把界面数据或缓存命中次数等同于原生替换提速。
|
||||
|
||||
## 回归与审查
|
||||
|
||||
- `build/responsiveness-final.xml`:219 passed、1 deselected,103.09 秒。覆盖 V1.1、队列、备份、暂停/恢复、执行安全、监控、应用启动退出和日志;单独排除 1000 步压力用例。
|
||||
- `build/responsiveness-stress.xml`:压力用例单独运行通过,测试总耗时 24.32 秒;执行段 22.376 秒,1000 步、44.69 步/秒,内存峰值 1,995,169 字节(约 1.90 MiB)。91 步保存成功、909 步正常未命中,无重复调度。使用模拟 CAD、备份桩和 tracemalloc,不代表 CAD 速度。
|
||||
- 两部分合计 **220 个不同用例通过**,未放宽原 `<30 秒`、`<128 MiB` 门槛。
|
||||
- 开发期间在并行运行其他任务时,压力用例曾测得 36.32 秒并失败;保留这一事实,最终单独运行通过,不把负载影响说成稳定提速。
|
||||
- 独立审查发现:慢初始日志反复刷新可能饿死;执行与查看任务不同导致提示归属错误;仅元数据缓存无法识别 Windows 保留时间戳的等长修改。这些问题均补充行为回归并修复。内容摘要修复及最终反馈/退出路径复审通过,无剩余必须修复项。
|
||||
|
||||
~~~powershell
|
||||
python -m pytest tests/v1_1 tests/trial_task_center/test_batch.py tests/trial_task_center/test_execution_safety.py tests/trial_task_center/test_recovery.py tests/trial_task_center/test_worker_monitor.py tests/trial_task_center/test_application.py tests/trial_task_center/test_logging_setup.py -q -k 'not thousand_item_multisheet_mixed_queue' --junitxml=build/responsiveness-final.xml
|
||||
python -m pytest tests/trial_task_center/test_batch.py::test_thousand_item_multisheet_mixed_queue_has_bounded_runtime_and_memory -q --junitxml=build/responsiveness-stress.xml
|
||||
~~~
|
||||
|
||||
## 后续边界
|
||||
|
||||
同工程跨步骤持续持有 CAD 会话尚未实施:当前每步以保存、关闭、重开回读后的持久结果作为恢复边界。合并会话需要升级该协议,并用真实多图页、多规则工程验证中断和保存失败行为。本轮通过安全复用发现结果先减少重复枚举,保留既有保存核验保证。历史 controller、store 和 VBS 的完整拆分也未在本轮完成。
|
||||
@@ -0,0 +1,112 @@
|
||||
# 2026-10-15 多工程执行与速率回归
|
||||
|
||||
本次在 DxDesigner 7.9.5 上使用 3 个不同真实工程的独立副本,实际执行了原生 Replace Part、保存关闭和重开回读;另以模拟 CAD 执行器检验多工程、多图页、多规则队列及压力场景。两类速率分开报告。
|
||||
|
||||
代码提交:`0225787`。真实 CAD 数据在短路径修复和计时接入后测得;此后继续优化了 Python 队列开销,并用自动回归验证。没有再次替换这 3 个已验证副本,不能把软件压力测试的改善比例当作 CAD 实际速度改善比例。
|
||||
|
||||
真实工程来自 `Skyworth_CBB_Lib/CBB`,测试副本仅将失效的 `S:\mentor_lib.lmc` 改为本机现有中央库的绝对路径。未用历史 CAF 或人工构造 UID 充当真实替换证据。下述为本机一次实测,部分测量与自动回归同时进行,不是重复采样的硬件基准。
|
||||
|
||||
## 真实多工程队列
|
||||
|
||||
| 顺序 | 工程 | 实际修改位号 | 旧料号 | 新料号 | 回读结果 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 1 | 1GPHY_8211 | RL02 | 4100-CA3300-T7 | 4100-CA3300-2200 | saved_ok / batch_closed |
|
||||
| 2 | Audio_D2128 | RV05 | 4100-CA0000-T7 | 4100-CA0000-T0 | saved_ok / batch_closed |
|
||||
| 3 | Audio_T605A | RV05 | 4100-CA0000-T7 | 4100-CA0000-T0 | saved_ok / batch_closed |
|
||||
|
||||
3 个任务顺序结束,无暂停、失败或未确认状态。队列耗时 **187.174 秒**,即 **0.962 个工程/分钟**;包含前置库存采集与准备的运行总耗时 221.145 秒。每个工程本次只有一个启用的图页/规则步骤,不能据此推断所有工程规模的平均速度。
|
||||
|
||||
### 每一步耗时(秒)
|
||||
|
||||
| 工程 | 只读采集 | 图页枚举及队列准备 | 备份 | 替换步骤(含保存回读) | 进度同步 | 本次任务执行合计 |
|
||||
| --- | ---: | ---: | ---: | ---: | ---: | ---: |
|
||||
| 1GPHY_8211 | 10.191 | 12.851 | 1.211 | 62.814 | 0.012 | 77.059 |
|
||||
| Audio_D2128 | 12.586 | 8.851 | 0.981 | 42.971 | 0.011 | 52.910 |
|
||||
| Audio_T605A | 10.222 | 11.012 | 0.958 | 44.812 | 0.012 | 56.894 |
|
||||
|
||||
任务合计包含枚举、备份、替换、进度和日志开销,不包含先前的只读采集;它与子步骤不能重复相加。整批队列另外包含任务切换和检查点开销。
|
||||
|
||||
### 保存后独立回读
|
||||
|
||||
| 工程 | 已验证的计划位号 | 实际改变 | 其余保留原料号 | 独立回读耗时(秒) |
|
||||
| --- | ---: | ---: | ---: | ---: |
|
||||
| 1GPHY_8211 | 13 | 1 | 12 | 10.530 |
|
||||
| Audio_D2128 | 2 | 1 | 1 | 9.993 |
|
||||
| Audio_T605A | 2 | 1 | 1 | 11.254 |
|
||||
|
||||
所有比对均通过:按工程、图页、UID、位号和料号逐个核对,3 个目标变更,14 个未勾选匹配位号保留。两个 Audio 工程都含 RV05,结果分别归属于各自任务。上述独立回读在队列结束后另行执行,不包含在队列耗时中。
|
||||
|
||||
### 执行器内部阶段(秒)
|
||||
|
||||
进度监控按阶段切换计时,同名阶段多次出现时累计;这是互斥时间段,不是每个同名函数的完整调用时长。例如保存回读内再次打开工程的时间会累计到 open_project。非常短的阶段可显示为 0.000。
|
||||
|
||||
| 阶段 | 1GPHY_8211 | Audio_D2128 | Audio_T605A |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| starting | 0.297 | 0.390 | 0.235 |
|
||||
| session_startup | 1.109 | 0.985 | 0.843 |
|
||||
| check_project | 0.032 | 0.015 | 0.047 |
|
||||
| open_project | 15.374 | 12.719 | 13.563 |
|
||||
| open_sheet | 2.438 | 2.876 | 2.359 |
|
||||
| session_ready | 0.016 | 0.046 | 0.047 |
|
||||
| query_components | 0.297 | 0.454 | 0.469 |
|
||||
| index_components | 3.249 | 1.406 | 1.562 |
|
||||
| find_components | 0.937 | 0.406 | 0.766 |
|
||||
| index_pins | 2.906 | 1.859 | 1.704 |
|
||||
| snapshot_attributes | 0.189 | 0.219 | 0.407 |
|
||||
| capture | 2.515 | 1.500 | 1.390 |
|
||||
| before_native | 0.079 | 0.062 | 0.063 |
|
||||
| native_replace | 24.000 | 12.672 | 13.547 |
|
||||
| restore_preflight | 2.624 | 1.406 | 1.608 |
|
||||
| before_restore_transaction | 0.219 | 0.219 | 0.235 |
|
||||
| restore_attribute_fields | 0.625 | 0.625 | 0.640 |
|
||||
| restore_attributes | 0.031 | 0.000 | 0.000 |
|
||||
| verify_restoration | 0.063 | 0.094 | 0.172 |
|
||||
| verify_attribute_fields | 0.140 | 0.141 | 0.156 |
|
||||
| finished | 1.750 | 1.077 | 1.218 |
|
||||
| save_and_close | 3.891 | 3.751 | 3.720 |
|
||||
| verify_saved_project | 0.000 | 0.015 | 0.031 |
|
||||
|
||||
## 软件队列回归与压力测试
|
||||
|
||||
模拟 CAD 场景仍使用真实 SQLite、XLSX、计划编译、命令/状态文件、备份及任务日志,模拟执行器只按收到的真实 UID 选择器修改内存器件模型并返回协议结果。其速率不能代表 DxDesigner 替换速度。
|
||||
|
||||
| 场景 | 工程数 | 实际执行步骤 | 修改模型器件数 | 保留的未选器件数 | 总流程耗时(秒) |
|
||||
| --- | ---: | ---: | ---: | ---: | ---: |
|
||||
| failure_continue (case-failure_continue) | 3 | 12 | 22 | 12 | 4.017 |
|
||||
| pause_resume (case-pause_resume) | 3 | 12 | 24 | 12 | 3.275 |
|
||||
| success (case-success) | 3 | 12 | 24 | 12 | 4.556 |
|
||||
| uncertain_stop (case-uncertain_stop) | 3 | 1 | 0 | 12 | 1.730 |
|
||||
| success (scale-10-final) | 10 | 120 | 240 | 120 | 38.722 |
|
||||
|
||||
3 工程场景覆盖:串行顺序、失败继续下一工程、未确认结果阻断后续工程、暂停续跑不重复、同名位号按工程/图页隔离、BOM 一行多个位号以及日志完整归属。10 工程场景为每工程 3 张图页、每图页 4 条规则,共 120 步;240 个选中模型器件改变、120 个未选模型器件保留。
|
||||
|
||||
1000 步兼容性压力场景使用历史单任务多工程队列(20 工程 × 5 图页 × 10 规则),开启 tracemalloc,真实备份由桩替代。它单独检查队列开销与内存,不是新版多任务调度或 CAD 吞吐量。最终全部 1000 步完成:91 步模拟保存成功、909 步未命中正常跳过,无重复调度;耗时 **27.764 秒**,速率 **36.02 步/秒**,tracemalloc 峰值 **1.865 MiB**。原有 `<30 秒` 和 `<128 MiB` 检查均通过,未放宽阈值。
|
||||
|
||||
## 本次发现和修复
|
||||
|
||||
1. 监控握手路径长 264 字符时,Python 可见文件而 VBS FileSystemObject.FileExists 返回 False,造成约 20 秒后报 supervisor did not authorize startup。改用系统短路径后,真实项目枚举和替换均可执行;没有可用短路径的系统会在 CAD 启动前给出短目录提示。原有证据目录保持不变。
|
||||
2. 每步重复解析整份命令与状态文件,40 步检测到 41 次命令读取,1000 步耗时 228.154 秒。改为每会话缓存命令、按追加量读取状态;在每次启动 worker 前检查状态文件身份、大小及修改时间,外部插入状态会在下一次写入前阻断。
|
||||
3. 缓存工程备份根目录和项目 ID,避免在后续备份查找中重复解析文件路径;没有后续备份候选后不再反复扫描。每步计时合并到原执行结果事件中,避免重复刷写日志。
|
||||
|
||||
## 原始证据和复现
|
||||
|
||||
本机证据目录:`F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\build\multitask-regression-20261015`。
|
||||
|
||||
- `native-live-results.json`:3 个真实任务及队列状态。
|
||||
- `native-timings.csv` / `native-timings.json`:18 条真实阶段计时。
|
||||
- `native-worker-stages.csv`:69 条真实执行器阶段计时。
|
||||
- `native-post-verification.json`:17 个计划位号的独立回读比较。
|
||||
- `native-data-live/tasks/<task-id>/quick-run/`:每个真实任务的命令、状态、备份、快照及原生报告。
|
||||
- `scale-10-final/timings.csv`:10 工程、120 步及流程/任务统计;layer 标明流程计时和执行计时,二者不能重复相加。
|
||||
- `case-*/report.json`:故障、阻断、暂停续跑及成功场景的断言与每次调度。
|
||||
- `stress-timings.csv` / `stress-final.json`:1000 步逐项统计和内存峰值。
|
||||
- `regression-before-queue-cache.xml`:首次回归中的两个性能失败,保留用于回溯。
|
||||
|
||||
最终验证覆盖 **188 个不同用例,全部通过**:`regression.xml` 记录 187 项通过(单独排除已执行的压力项),`performance-final.xml` 记录压力项及 7 项相关检查通过;两个文件有 7 项重叠,去重为 188 项。包含串行调度、BOM、结果日志、长路径真实 VBS、监控超时清理、状态外部改动保护、失败/暂停/恢复及连接保护。
|
||||
|
||||
~~~powershell
|
||||
python -m pytest tests/v1_1 tests/trial_task_center/test_worker_monitor.py tests/trial_task_center/test_batch.py tests/trial_task_center/test_execution_safety.py tests/trial_task_center/test_recovery.py tests/part_replace/test_verification.py -q -k 'not thousand_item_multisheet_mixed_queue'
|
||||
python -m pytest tests/trial_task_center/test_batch.py::test_thousand_item_multisheet_mixed_queue_has_bounded_runtime_and_memory tests/v1_1/test_execution_metrics.py tests/v1_1/test_replacement_logs.py -q
|
||||
~~~
|
||||
|
||||
源码计时记录保存在任务事件中;真实数据 CSV 已逐项展开,模拟 120 步的 CSV 保留了每个 job_id、工程、图页、料号、结果、耗时及速率。测试期间未重新打包。真实中央库替换依赖现场库;本次未进行 Packager、ERC 或网表验收。
|
||||
@@ -0,0 +1,50 @@
|
||||
# 2026-10-15 私有桌面正式执行验证
|
||||
|
||||
> 本文记录源码接入阶段的验证;后续 1.1.1 成品已完成打包,见 [1.1.1 版本说明](../releases/v1.1.1.md)。下文“本轮没有打包”保留该阶段的实际边界。
|
||||
|
||||
任务中心源码已把私有桌面接入自动采集、单步替换、批量工程会话及中断恢复,完成成功、暂停和异常退出的资源清理。本轮没有打包;此前 EXE 不包含这些更新。
|
||||
|
||||
实现提交:`5c0f6a3`、`f26e868`、`fee1aff`、`48ad7b3`。原始工程未修改,原生测试仅操作 `build/private-desktop-native` 下独立副本。环境为 Windows、Python 3.12、DxDesigner EE 7.9.5;中央库使用本机已安装库。压缩证据及原始文件 SHA-256 见 [JSON 数据](data/2026-10-15-private-desktop-execution.json)。不提交工程、中央库或大型供应商文件。
|
||||
|
||||
## 实际接入与资源边界
|
||||
|
||||
显式普通启动 `viewdraw.exe`,通过随机私有 desktop 中的 ROT 连接自有实例,再绑定会话 GUID。`-Embedding` 启动没有提供可用 ROT,`DispatchEx` 也不能作为本机可靠的私有启动方式,正式执行没有沿用这两条路径。
|
||||
|
||||
活动工程读写校验 desktop、GUID 和活动图页 HWND 所属 PID。关闭最后工程后,CAD 的 ActiveViewHandle 可能保留已销毁或已复用的窗口值;无活动图页的启动与退出使用显式自有 CAD 启动、私有 ROT 和 GUID,不声称此时也有可靠的活动图页 PID 校验。身份不符立即停止,不回退主桌面或创建未受控的 COM 实例。
|
||||
|
||||
进程以挂起状态创建,先加入本工具持有的 Job,再恢复运行。正常收尾先要求工程关闭,再请求 CAD Quit 并等待退出;随后清理自有进程树、关闭句柄,枚举 window station 确认私有桌面消失。保留每次会话证据,避免恢复或重试覆盖前一次释放记录。释放失败会留下不确定状态,不能作为正常任务成功。
|
||||
|
||||
单步入口现在也先备份,再保存、重开回读及关闭,避免后台退出丢弃尚未保存的修改。恢复入口可以重新打开绑定工程,完成属性核验、保存与回读后关闭,不需要用户去隐藏桌面手动保存。
|
||||
|
||||
## 原生实测
|
||||
|
||||
| 用例 | 实际结果 | 耗时 |
|
||||
| --- | --- | ---: |
|
||||
| 同一工程两步替换 | RL02、RL05 分别替换;NC 开、关各一步;均 saved_ok;1 个持久 worker | 任务合计 284.208 秒 |
|
||||
| 保存后的独立枚举 | 按 UID、位号、料号检查 13 项:2 项变更,11 项保留 | 独立运行,不计入任务合计 |
|
||||
| 公开单步入口 | 仅 RL06 修改,备份、保存、重开核验、关闭及 CAD 释放通过 | 168.765 秒 |
|
||||
| 模拟保存后中断并恢复 | 仅在副本任务状态中注入中断;恢复 restored_ok,清除保护锁,无重复原生替换 | 104.998 秒 |
|
||||
| 恢复后独立枚举 | 13 项全部匹配:RL06 已变更,其余 12 项保留原料号 | 另开独立后台 CAD 读取 |
|
||||
| 多页队列暂停 | PON 的 block、01_POWER、02_ZX279133L 三页 no_match 后在 3/18 暂停;1 个 worker,退出并释放 | 83.992 秒 |
|
||||
| 启动取消 | 0.8 秒发取消,尚未运行工程 worker,退出自有进程并释放桌面 | 含实际 CAD 启动尝试 |
|
||||
| watchdog 超时 | 模拟卡住的 worker 及其子进程被自有 Job 清理;CAD 退出、桌面释放,保护状态保留 | 含实际 CAD 启动与退出 |
|
||||
|
||||
两步替换各耗时 157.410、121.297 秒,原生 Replace Part 阶段分别为 32.797、33.953 秒。任务准备 0.037 秒,备份 0.352 秒,两次进度同步为 0.013、0.009 秒。子步骤、内部阶段和任务合计存在包含关系,不应重复相加;JSON 保留每一步的内部阶段耗时。
|
||||
|
||||
本机成功启动私有 CAD 约 22~35 秒,正常退出约 1.8~2.7 秒。私有桌面解决前台隔离和所有权问题,不承诺提升原生 CAD 吞吐量,也不能把此前主桌面的多工程测量直接当作当前后端的速率。
|
||||
|
||||
## 主桌面与释放观测
|
||||
|
||||
暂停、单步/恢复/独立读回、取消/超时三个观测组共 **1997 次采样、6 次 CAD 会话**。每次采样都成功读取普通文件;输入桌面前后均为 Default,自有 CAD 没有成为主桌面前台,也未出现在输入桌面窗口清单。原来主桌面的 CAD PID 18732 保持原样。6 个自有 CAD 均确认退出,6 个私有桌面均确认消失。
|
||||
|
||||
这证明本次测试中没有抢占主桌面,普通文件可读取;不是所有系统负载和第三方 CAD 插件场景的性能保证。目标工程仍须保存关闭,不允许主桌面和后台同时编辑同一工程;许可证、CPU、磁盘和中央库仍共享。
|
||||
|
||||
## 自动回归、审查及测量问题
|
||||
|
||||
运行 `python -m pytest tests/v1_1 tests/trial_task_center/test_batch.py tests/trial_task_center/test_application.py tests/trial_task_center/test_quick_run.py tests/trial_task_center/test_recovery.py tests/trial_task_center/test_worker_monitor.py -q -x -k 'not thousand_item_multisheet_mixed_queue'`,结果 **310 passed、1 deselected,88.93 秒**。随后补充的会话证据留存及隐藏 helper 入口回归在 `test_isolated_cad.py` 中执行,**10 passed,4.47 秒**;与前述数量重叠,不相加。
|
||||
|
||||
桌面资源测试包含真实 Win32 进程树退出及另一个进程保留 desktop 句柄时不得报告释放成功。独立代理只读审查未发现新增可操作问题。未重复无关的千步模拟压力测试:此前本机基线和优化分支均超过原有时间门槛,门槛未修改;这条记录不能作为本轮全量压力测试通过的声明。
|
||||
|
||||
两步替换首次成功运行后,观测器在收尾时未识别 `pywintypes.error(2)`,因此没有写出 report.json。该用例结论由仍完整保留的 status、事件计时及独立 components.tsv 重建;不补造其前台采样记录。随后修正了原生错误捕获,完成暂停、单步/恢复和异常用例观测。异常观测第一轮另遇 Windows 替换状态文件时短暂拒绝读取;观测器加入短暂重试,重跑通过。测量脚本现在即使观测器失败也保留报告。
|
||||
|
||||
边界:本轮真实替换使用单工程两步及独立单步;此前三个不同工程的实测见 [旧后端多工程回归](2026-10-15-multi-project-regression.md),不混称当前私有后端多工程实测。多页暂停用例是 no_match,不是跨页替换。NC 开关传递已覆盖,但所选真实样本没有独立 `/NC` 标记,未重新验收该标记的转换效果。没有执行新的 Packager、ERC、网表验收,也没有生成发布包。
|
||||
@@ -0,0 +1,49 @@
|
||||
# 工程会话、统一快照与可取消查询验证
|
||||
|
||||
本轮在原 V1.1.0 上实施用户批准的四项优化,基线为 `bc6b726`,分支为 `codex/execution-responsiveness`。完成后推送同名远端分支,不打包。真实 CAD 操作全部针对 `build/session-live-20261015` 下的独立副本。
|
||||
|
||||
## 实现
|
||||
|
||||
1. 同工程多步骤保留一个受监督的 VBS worker。每次修改仍保存、关闭、重开并回读校验,下一步复用回读后的工程;暂停、完成和换工程时关闭自有会话。随机令牌、冻结命令和图页确认继续有效。注入的模拟执行器保留原单步协议。
|
||||
2. `TaskBundle` 用一个 SQLite 只读事务读取任务、工程、规则和位号计划;`QuickRunSnapshot` 复用一次证据文件解析,检查读取前后文件代次,最多重试三次,持续变化时禁止给出续跑坐标。创建任务 facade 复用已初始化 runner,避免查询触发启动恢复写入。
|
||||
3. UI 查询最多两个运行项、一个合并后的最新待办项。切换或关闭时取消旧 token;文件分块读取、逐行解析、数据库锁和日志锁等待均检查取消。底层单次系统调用仍需返回后才能退出,线程数量保持有界。
|
||||
4. 拆出协议、快照、只读工程枚举、会话 transport、数据库迁移、位号计划存储和任务读取模块。`quick_run.py` 从 2100 行降至 1866 行,`store.py` 从 1364 行降至 1083 行;剩余执行状态机继续保留在原模块。
|
||||
|
||||
工程首次打开可能规范化数据库。发现已知内容变化后丢弃该次枚举,只允许重试一次;仍不稳定则阻断。缓存仅精确排除 `database/cdbsvr/{log,plog,events}` 运行审计目录,权威数据库及图页仍校验内容哈希;初次无法取得指纹时允许一次全新、不缓存的枚举。
|
||||
|
||||
## 真实替换对照
|
||||
|
||||
工程为 CBB `1GPHY_8211.prj` 的两份独立副本;同页 `RL02` 与 `RL05` 分两步执行,分别测试 NC 同步开、关。旧料号 `4100-CA3300-T7`,新料号 `4100-CA3300-2200`。两种方式均独立重新枚举确认:2 个选中位号改为新料号,11 个未选中位号保持旧料号。
|
||||
|
||||
| 指标 | 原单步方式 | 会话复用 |
|
||||
| --- | ---: | ---: |
|
||||
| 整个队列 | 113.175 秒 | 100.641 秒 |
|
||||
| 第一步 | 64.371 秒 | 56.797 秒 |
|
||||
| 第二步 | 47.418 秒 | 41.168 秒 |
|
||||
| worker 启动次数 | 2 | 1 |
|
||||
| OpenProject 调用次数 | 4 | 3 |
|
||||
| 成功保存并重开验证 | 2 | 2 |
|
||||
| 独立回读核对 | 13/13 | 13/13 |
|
||||
|
||||
这一次本机样本总耗时减少 11.1%;有 CAD 缓存与机器负载差异,不能推广为所有项目的固定提升。统计含队列准备、备份和最终关闭;独立验证不计入队列耗时。逐步原生阶段耗时见 `build/session-live-20261015/{small-baseline,small-reuse}/report.json`。
|
||||
|
||||
## 图页、暂停与外部操作保护
|
||||
|
||||
PON 的 18 页清单中,连续验证 `block`、`01_POWER`、`02_ZX279133L` 三个图页,耗时分别为 16.364、4.627、10.181 秒;一个 worker,三个 `no_match` 检查点,完成 3/18 后退出会话并确认工程关闭。总计 34.737 秒,证据为 `build/session-live-20261015/multi-page/report.json`。此测试验证原生换页和中途关闭,不作为跨页实际替换成功的证据。
|
||||
|
||||
独立副本上的三项原生边界探针均通过:正常关闭自有工程;等待期间外部修改 Value 时中止并保留编辑;等待期间切换至其他工程时中止并保留其他工程。不能确认关闭时写入 `uncertain.flag`。证据为 `build/session-live-20261015/guards2/{clean,edit,foreign}/guard-report.json`。
|
||||
|
||||
PON 的原单步替换基线尝试耗时 166.381 秒,三步中一项成功、一项原生替换失败、一项保存后回读失败。失败原生报告停在 `pin_promotion_started`,尚不能证明 COM 崩溃等具体原因。本轮没有把它计作成功性能对照,也没有反复重跑状态不确定的副本。首次尝试还遇到测量脚本未传递 PYTHONPATH 的问题,修正测试脚本后才进行上述统计。
|
||||
|
||||
## 自动化回归
|
||||
|
||||
- 集成回归:224 passed,1 deselected,84.85 秒。范围为 V1.1 界面、日志、取消、工程发现,以及原 store、service、batch;单独排除千步性能用例。
|
||||
- 快照、数据库只读事务和监督器定向回归:42 passed,13.06 秒。
|
||||
- 后续增加 worker 失败后重建的回归,会话专用 6 项通过,4.90 秒;此前集成已覆盖其中 5 项。原单步执行器兼容性回归另有 34 项通过,4.52 秒;自动化去重合计 301 项通过。
|
||||
- 千步压力测试:20 个工程 × 5 页 × 10 条规则,共 1000 步,91 项保存、909 项未命中,全部任务唯一执行并正确完成,峰值 1.94 MiB。当前耗时 41.516 秒(24.09 步/秒),未通过 30 秒门槛。
|
||||
- 原基线 `bc6b726` 在同机、同一个用例、同样启用 tracemalloc 条件下的对照为 42.453 秒,也未通过 30 秒门槛。原子命令写入和事件日志在两版没有变化,快照解析不在逐步循环内;未发现新增热点导致退化。旧记录的 22.376 秒不能替代本次实测,不放宽阈值,不把耗时检查记为通过。
|
||||
- F 盘指定临时目录的一次压力尝试在第 139 步发布命令时遇到 WinError 5,安全停止,未形成完整性能数据。随后 C/F 盘各 120 次 fsync+replace 探针未复现,不能据此断言具体占用进程;保留该现场限制。
|
||||
|
||||
版本化的逐步阶段耗时、回读摘要及保护探针结果见 `docs/testing/data/2026-10-15-project-session.json`;完整原生执行证据保留在上述本机构建目录中。
|
||||
|
||||
可复用的原生测量脚本为 `tools/measure_project_session.py`,保护探针为 `tools/probe_project_session_guards.py`,多页探针为 `tools/probe_project_session_pages.py`。它们运行前要求当前 CAD 没有打开工程。
|
||||
@@ -0,0 +1,485 @@
|
||||
{
|
||||
"date": "2026-10-15",
|
||||
"implementation_commit": "48ad7b3",
|
||||
"platform": "Windows / DxDesigner EE 7.9.5 / Python 3.12",
|
||||
"batch": {
|
||||
"reconstructed_from_persistent_evidence": true,
|
||||
"observer_finalization_failed": "pywintypes.error(2) was not caught; report.json was not written. Business status, per-step events and independent inventory remain available. Fixed observer used by later cases.",
|
||||
"task_id": "5efd57e0-3de1-4f9a-850f-42a5593e301b",
|
||||
"task_total_seconds": 284.20772400000715,
|
||||
"worker_starts": 1,
|
||||
"steps": [
|
||||
{
|
||||
"refdes": "RL02",
|
||||
"sync_nc": true,
|
||||
"state": "saved_ok",
|
||||
"seconds": 157.4097580999951,
|
||||
"worker_stage_seconds": {
|
||||
"starting": 0.9370000000053551,
|
||||
"session_startup": 1.422000000020489,
|
||||
"check_project": 0.046999999962281436,
|
||||
"open_project": 14.14000000001397,
|
||||
"open_sheet": 12.548000000009779,
|
||||
"session_ready": 0.046000000002095476,
|
||||
"query_components": 2.125,
|
||||
"index_components": 13.01600000000326,
|
||||
"find_components": 2.8439999999827705,
|
||||
"index_pins": 11.437999999994645,
|
||||
"snapshot_attributes": 0.75,
|
||||
"capture": 7.60999999998603,
|
||||
"before_native": 0.26500000001396984,
|
||||
"native_replace": 32.796999999991385,
|
||||
"restore_preflight": 7.139999999984866,
|
||||
"before_restore_transaction": 1.1570000000065193,
|
||||
"restore_attribute_fields": 3.0460000000020955,
|
||||
"restore_attributes": 0.0,
|
||||
"verify_restoration": 0.4380000000237487,
|
||||
"verify_attribute_fields": 0.7810000000172295,
|
||||
"finished": 7.2339999999676365,
|
||||
"save_and_close": 2.0940000000118744,
|
||||
"verify_saved_project": 0.0,
|
||||
"session_wait": 0.0
|
||||
}
|
||||
},
|
||||
{
|
||||
"refdes": "RL05",
|
||||
"sync_nc": false,
|
||||
"state": "saved_ok",
|
||||
"seconds": 121.29693060001591,
|
||||
"worker_stage_seconds": {
|
||||
"check_project": 0.061999999976251274,
|
||||
"open_sheet": 10.09299999999348,
|
||||
"query_components": 1.1570000000065193,
|
||||
"index_components": 8.51600000000326,
|
||||
"find_components": 2.3589999999967404,
|
||||
"index_pins": 11.39100000000326,
|
||||
"snapshot_attributes": 0.7659999999741558,
|
||||
"capture": 12.437000000005355,
|
||||
"before_native": 0.34400000001187436,
|
||||
"native_replace": 33.95299999997951,
|
||||
"restore_preflight": 7.985000000015134,
|
||||
"before_restore_transaction": 1.0780000000086147,
|
||||
"restore_attribute_fields": 3.202999999979511,
|
||||
"restore_attributes": 0.0,
|
||||
"verify_restoration": 0.5000000000291038,
|
||||
"verify_attribute_fields": 0.6719999999913853,
|
||||
"finished": 16.264999999984866,
|
||||
"save_and_close": 4.219000000011874,
|
||||
"verify_saved_project": 0.01600000000325963,
|
||||
"open_project": 6.047000000020489,
|
||||
"session_wait": 0.0
|
||||
}
|
||||
}
|
||||
],
|
||||
"comparisons": [
|
||||
{
|
||||
"uid": "$1I362",
|
||||
"refdes": "RL02",
|
||||
"expected": "4100-CA3300-2200",
|
||||
"actual": "4100-CA3300-2200"
|
||||
},
|
||||
{
|
||||
"uid": "$1I551",
|
||||
"refdes": "RL05",
|
||||
"expected": "4100-CA3300-2200",
|
||||
"actual": "4100-CA3300-2200"
|
||||
},
|
||||
{
|
||||
"uid": "$1I559",
|
||||
"refdes": "RL06",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"uid": "$1I567",
|
||||
"refdes": "RL07",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"uid": "$1I575",
|
||||
"refdes": "RL08",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"uid": "$1I583",
|
||||
"refdes": "RL09",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"uid": "$1I584",
|
||||
"refdes": "RL10",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"uid": "$1I585",
|
||||
"refdes": "RL11",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"uid": "$1I586",
|
||||
"refdes": "RL12",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"uid": "$1I615",
|
||||
"refdes": "RL13",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"uid": "$1I616",
|
||||
"refdes": "RL14",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"uid": "$1I617",
|
||||
"refdes": "RL15",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"uid": "$1I618",
|
||||
"refdes": "RL16",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
}
|
||||
],
|
||||
"session": {
|
||||
"desktop": "dx-0e24d247e2bb44fc9d2cfb865751d03b",
|
||||
"token": "0e24d247e2bb44fc9d2cfb865751d03b",
|
||||
"state": "released",
|
||||
"cad_pid": 26884,
|
||||
"guid": "{AC2760DDx0ECCx4125x902Ax58D3762F7FD0}",
|
||||
"clean": true
|
||||
}
|
||||
},
|
||||
"single_and_recovery": {
|
||||
"single_step_seconds": 168.76488050000626,
|
||||
"single_step_state": "saved_ok",
|
||||
"recovery_seconds": 104.99790590000339,
|
||||
"recovery_state": "restored_ok",
|
||||
"single_step_session": {
|
||||
"desktop": "dx-ef24499c663e4059bb88ca4c5480428b",
|
||||
"token": "ef24499c663e4059bb88ca4c5480428b",
|
||||
"state": "released",
|
||||
"cad_pid": 5188,
|
||||
"guid": "{E07B201BxC81Dx4624xB0D2xE684F407C972}",
|
||||
"startup_seconds": 34.312999999994645,
|
||||
"clean": true,
|
||||
"shutdown_seconds": 1.8590000000258442
|
||||
},
|
||||
"recovery_session": {
|
||||
"desktop": "dx-b09cc37f113e48abbe4f1e8a6fbc493b",
|
||||
"token": "b09cc37f113e48abbe4f1e8a6fbc493b",
|
||||
"state": "released",
|
||||
"cad_pid": 51976,
|
||||
"guid": "{6418A6B6x512Bx434ExAC8Ax7C518FCFAA9E}",
|
||||
"startup_seconds": 21.98399999999674,
|
||||
"clean": true,
|
||||
"shutdown_seconds": 1.9689999999827705
|
||||
},
|
||||
"comparisons": [
|
||||
{
|
||||
"refdes": "RL02",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"refdes": "RL05",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"refdes": "RL06",
|
||||
"expected": "4100-CA3300-2200",
|
||||
"actual": "4100-CA3300-2200"
|
||||
},
|
||||
{
|
||||
"refdes": "RL07",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"refdes": "RL08",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"refdes": "RL09",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"refdes": "RL10",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"refdes": "RL11",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"refdes": "RL12",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"refdes": "RL13",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"refdes": "RL14",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"refdes": "RL15",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"refdes": "RL16",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
}
|
||||
],
|
||||
"verified": true
|
||||
},
|
||||
"pause": {
|
||||
"project": "F:\\Sync Tool Skyworth\\Work Maps\\dxdesigner-part-replacement\\build\\private-desktop-native\\pages-pause\\project\\PON.prj",
|
||||
"steps": [
|
||||
{
|
||||
"sheet": [
|
||||
"PON",
|
||||
"block"
|
||||
],
|
||||
"state": "no_match",
|
||||
"seconds": 46.64777720000711
|
||||
},
|
||||
{
|
||||
"sheet": [
|
||||
"PON",
|
||||
"01_POWER"
|
||||
],
|
||||
"state": "no_match",
|
||||
"seconds": 10.285367300006328
|
||||
},
|
||||
{
|
||||
"sheet": [
|
||||
"PON",
|
||||
"02_ZX279133L"
|
||||
],
|
||||
"state": "no_match",
|
||||
"seconds": 20.456011000002036
|
||||
}
|
||||
],
|
||||
"passed": true,
|
||||
"closed_between_steps": true,
|
||||
"worker_starts": 1,
|
||||
"paused": true,
|
||||
"completed_items": 3,
|
||||
"total_items": 18,
|
||||
"seconds": 83.99234019999858
|
||||
},
|
||||
"faults": {
|
||||
"startup_cancelled": true,
|
||||
"watchdog_timeout": true,
|
||||
"worker_exit_confirmed": {
|
||||
"parent": true,
|
||||
"child": true
|
||||
},
|
||||
"passed": true
|
||||
},
|
||||
"desktop_observations": {
|
||||
"single_and_recovery": {
|
||||
"samples": 1440,
|
||||
"file_read_samples": 1440,
|
||||
"input_desktop_before": "Default",
|
||||
"input_desktop_after": "Default",
|
||||
"foreground_pids": [
|
||||
10104
|
||||
],
|
||||
"owned_cad_became_foreground": false,
|
||||
"owned_cad_on_input_desktop": false,
|
||||
"baseline_default_cad_pids": [
|
||||
18732
|
||||
],
|
||||
"observed_default_cad_pids": [
|
||||
18732
|
||||
],
|
||||
"cad_exit_confirmed": {
|
||||
"5188": true,
|
||||
"51976": true,
|
||||
"55520": true
|
||||
},
|
||||
"desktop_absent": {
|
||||
"dx-ef24499c663e4059bb88ca4c5480428b": true,
|
||||
"dx-b09cc37f113e48abbe4f1e8a6fbc493b": true,
|
||||
"dx-ae937db569b34cb9827ba6ec481be55e": true
|
||||
},
|
||||
"sessions": {
|
||||
"dx-ef24499c663e4059bb88ca4c5480428b": {
|
||||
"desktop": "dx-ef24499c663e4059bb88ca4c5480428b",
|
||||
"token": "ef24499c663e4059bb88ca4c5480428b",
|
||||
"state": "released",
|
||||
"cad_pid": 5188,
|
||||
"guid": "{E07B201BxC81Dx4624xB0D2xE684F407C972}",
|
||||
"startup_seconds": 34.312999999994645,
|
||||
"clean": true,
|
||||
"shutdown_seconds": 1.8590000000258442,
|
||||
"evidence_path": "data\\tasks\\94da06ed-1f50-4396-9340-7df8f616e71c\\quick-run\\private-desktop.json"
|
||||
},
|
||||
"dx-b09cc37f113e48abbe4f1e8a6fbc493b": {
|
||||
"desktop": "dx-b09cc37f113e48abbe4f1e8a6fbc493b",
|
||||
"token": "b09cc37f113e48abbe4f1e8a6fbc493b",
|
||||
"state": "released",
|
||||
"cad_pid": 51976,
|
||||
"guid": "{6418A6B6x512Bx434ExAC8Ax7C518FCFAA9E}",
|
||||
"startup_seconds": 21.98399999999674,
|
||||
"clean": true,
|
||||
"shutdown_seconds": 1.9689999999827705,
|
||||
"evidence_path": "data\\tasks\\94da06ed-1f50-4396-9340-7df8f616e71c\\quick-run-history\\recovery-29865845abda42de8392273c2490efcf\\worker\\private-desktop.json"
|
||||
},
|
||||
"dx-ae937db569b34cb9827ba6ec481be55e": {
|
||||
"desktop": "dx-ae937db569b34cb9827ba6ec481be55e",
|
||||
"token": "ae937db569b34cb9827ba6ec481be55e",
|
||||
"state": "released",
|
||||
"cad_pid": 55520,
|
||||
"guid": "{71E521C8xD25Ex4028x9C35xAA7FB9D692F2}",
|
||||
"startup_seconds": 28.59399999998277,
|
||||
"clean": true,
|
||||
"shutdown_seconds": 1.7660000000032596,
|
||||
"evidence_path": "independent-read\\quick-run-history\\sheet-discovery-1103116427664f7a9db30fb37a5d2fa5\\private-desktop.json"
|
||||
}
|
||||
},
|
||||
"observer_errors": []
|
||||
},
|
||||
"pause": {
|
||||
"samples": 375,
|
||||
"file_read_samples": 375,
|
||||
"input_desktop_before": "Default",
|
||||
"input_desktop_after": "Default",
|
||||
"foreground_pids": [
|
||||
10104
|
||||
],
|
||||
"owned_cad_became_foreground": false,
|
||||
"owned_cad_on_input_desktop": false,
|
||||
"baseline_default_cad_pids": [
|
||||
18732
|
||||
],
|
||||
"observed_default_cad_pids": [
|
||||
18732
|
||||
],
|
||||
"cad_exit_confirmed": {
|
||||
"54972": true
|
||||
},
|
||||
"desktop_absent": {
|
||||
"dx-3284592a031c46c28d1c0ac187b9c6ed": true
|
||||
},
|
||||
"sessions": {
|
||||
"data\\tasks\\351d9922-f28c-429e-bce1-862e31b3aef4\\quick-run\\private-desktop.json": {
|
||||
"desktop": "dx-3284592a031c46c28d1c0ac187b9c6ed",
|
||||
"token": "3284592a031c46c28d1c0ac187b9c6ed",
|
||||
"state": "released",
|
||||
"cad_pid": 54972,
|
||||
"guid": "{32D71CB0xC1B6x4A8BxAF96x35B4051FC236}",
|
||||
"startup_seconds": 35.25,
|
||||
"clean": true,
|
||||
"shutdown_seconds": 2.687999999994645
|
||||
}
|
||||
},
|
||||
"observer_errors": []
|
||||
},
|
||||
"faults": {
|
||||
"samples": 182,
|
||||
"file_read_samples": 182,
|
||||
"input_desktop_before": "Default",
|
||||
"input_desktop_after": "Default",
|
||||
"foreground_pids": [
|
||||
10104
|
||||
],
|
||||
"owned_cad_became_foreground": false,
|
||||
"owned_cad_on_input_desktop": false,
|
||||
"baseline_default_cad_pids": [
|
||||
18732
|
||||
],
|
||||
"observed_default_cad_pids": [
|
||||
18732
|
||||
],
|
||||
"cad_exit_confirmed": {
|
||||
"56876": true,
|
||||
"53404": true
|
||||
},
|
||||
"desktop_absent": {
|
||||
"dx-96332c0efe8c40dcbd1e0fb98be3116e": true,
|
||||
"dx-c35da69cb8434bbebdb3af729be91516": true
|
||||
},
|
||||
"sessions": {
|
||||
"dx-96332c0efe8c40dcbd1e0fb98be3116e": {
|
||||
"desktop": "dx-96332c0efe8c40dcbd1e0fb98be3116e",
|
||||
"token": "96332c0efe8c40dcbd1e0fb98be3116e",
|
||||
"state": "released",
|
||||
"cad_pid": 56876,
|
||||
"clean": false,
|
||||
"startup_error": "private CAD startup was cancelled before execution",
|
||||
"evidence_path": "data\\tasks\\startup-cancel\\quick-run\\private-desktop.json"
|
||||
},
|
||||
"dx-c35da69cb8434bbebdb3af729be91516": {
|
||||
"desktop": "dx-c35da69cb8434bbebdb3af729be91516",
|
||||
"token": "c35da69cb8434bbebdb3af729be91516",
|
||||
"state": "released",
|
||||
"cad_pid": 53404,
|
||||
"guid": "{814B8CF2x0B4Fx486DxBD1ExBE0B1A5B29CD}",
|
||||
"startup_seconds": 32.84399999998277,
|
||||
"error": "Command '('C:\\\\Users\\\\ABS_Windows\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python312\\\\python.exe', '-u', 'F:\\\\Sync Tool Skyworth\\\\Work Maps\\\\dxdesigner-part-replacement\\\\build\\\\private-desktop-native\\\\failures-retry\\\\data\\\\tasks\\\\timeout\\\\quick-run\\\\stalled-worker.py', 'F:\\\\Sync Tool Skyworth\\\\Work Maps\\\\dxdesigner-part-replacement\\\\build\\\\private-desktop-native\\\\failures-retry\\\\data\\\\tasks\\\\timeout\\\\quick-run', 'C:\\\\Users\\\\ABS_Windows\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python312\\\\python.exe', '', 'timeout')' timed out after 3.0 seconds",
|
||||
"clean": false,
|
||||
"shutdown_seconds": 4.280999999988126,
|
||||
"evidence_path": "data\\tasks\\timeout\\quick-run\\private-desktop.json"
|
||||
}
|
||||
},
|
||||
"observer_errors": []
|
||||
}
|
||||
},
|
||||
"automated_regression": {
|
||||
"passed": 310,
|
||||
"deselected": 1,
|
||||
"seconds": 88.93,
|
||||
"deselected_test": "thousand_item_multisheet_mixed_queue",
|
||||
"reason": "Unchanged simulated stress test exceeds host timing gate on both baseline and earlier optimization checkout; threshold not changed.",
|
||||
"followup_isolated_cad_tests": {
|
||||
"passed": 10,
|
||||
"seconds": 4.47
|
||||
}
|
||||
},
|
||||
"limitations": [
|
||||
"No new package built.",
|
||||
"No Packager/ERC/netlist qualification performed.",
|
||||
"NC toggle on/off exercised; this real fixture contains no independent /NC marker.",
|
||||
"Private batch evidence uses one project, two real replacement steps. Prior three-project evidence used the previous backend.",
|
||||
"Pause covers actual multi-page no_match steps, not multi-page replacements.",
|
||||
"Startup/quit of empty CAD bind explicit PID-owned launch and private ROT/GUID; active view PID is verified only with an open project."
|
||||
],
|
||||
"raw_source_sha256": {
|
||||
"build\\private-desktop-native\\replacement3\\data\\tasks\\5efd57e0-3de1-4f9a-850f-42a5593e301b\\events.jsonl": "d5438645d0441b71e0b761bb570586c4b5a6debf86c8877203150646f7f00728",
|
||||
"build\\private-desktop-native\\replacement3\\data\\tasks\\5efd57e0-3de1-4f9a-850f-42a5593e301b\\quick-run\\command.tsv": "9586b5a449089da81b9517793900bda76c98be20a31644a788e60d59cc996643",
|
||||
"build\\private-desktop-native\\replacement3\\data\\tasks\\5efd57e0-3de1-4f9a-850f-42a5593e301b\\quick-run\\status.tsv": "7efec1a407ec23606fbdd4569a0b36d57db441fa9506850cbd91e125d3439f47",
|
||||
"build\\session-live-20261015\\small-inventory.json": "38783d947877e657a2c443496f95ab39f32182f84af1f25d444fffd7f9fe8159",
|
||||
"build\\private-desktop-native\\replacement3\\independent-read\\quick-run-history\\sheet-discovery-4159ca5ab5404a1f893247cf74b07ebf\\components.tsv": "788a2c87178edd2fab065d3cf405a4cabbec0f0f1b5f3f12f3da3145807f7b51",
|
||||
"build\\private-desktop-native\\single-recovery\\report.json": "c1a41f935d438e1bfe65a7d67dbafca41ce441aa0ce3a0cad0530c76ebf7d779",
|
||||
"build\\private-desktop-native\\pages-pause\\report.json": "d7e6a965d1accbdb8af402fa0ab370121fe7a062c5445cbac480e0d447f37e3c",
|
||||
"build\\private-desktop-native\\failures-retry\\report.json": "c6d2144f8a8593c5e0860ec4a9645411c55cffdd0de49e8c3f473068c102f0cd",
|
||||
"build\\private-desktop-native\\single-recovery\\desktop-observation.json": "73d2ec95e802044050ef26f020ae331ea336129493b5fe57a2f9f9fd6e3e133f",
|
||||
"build\\private-desktop-native\\pages-pause\\desktop-observation.json": "62406dfd60d66e2bb854d5ed62d9988afa200464a8a7a59df9867cb610241568",
|
||||
"build\\private-desktop-native\\failures-retry\\desktop-observation.json": "448ce3317928e6ae547e662b551afcfba61fe17f95b95b9d1120b31aa2cb36ba",
|
||||
"build\\private-desktop-native\\replacement3\\data\\tasks\\5efd57e0-3de1-4f9a-850f-42a5593e301b\\quick-run\\private-desktop.json": "d929b5a2d81b628866dc8a57af59356ce30e58f9be82933da531cae986d00918"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,518 @@
|
||||
{
|
||||
"baseline_commit": "bc6b726",
|
||||
"note": "Single paired native sample; copied projects only. Thousand-step time gate remains failed in both versions.",
|
||||
"native": {
|
||||
"small-baseline": {
|
||||
"queue_seconds": 113.17540310000186,
|
||||
"worker_starts": 2,
|
||||
"open_project_calls": 4,
|
||||
"verified": true,
|
||||
"readback_seconds": 9.846703400020488,
|
||||
"comparisons": [
|
||||
{
|
||||
"refdes": "RL02",
|
||||
"sheet": "8211_1GPHY_48PIN",
|
||||
"expected": "4100-CA3300-2200",
|
||||
"actual": "4100-CA3300-2200"
|
||||
},
|
||||
{
|
||||
"refdes": "RL05",
|
||||
"sheet": "8211_1GPHY_48PIN",
|
||||
"expected": "4100-CA3300-2200",
|
||||
"actual": "4100-CA3300-2200"
|
||||
},
|
||||
{
|
||||
"refdes": "RL06",
|
||||
"sheet": "8211_1GPHY_48PIN",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"refdes": "RL07",
|
||||
"sheet": "8211_1GPHY_48PIN",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"refdes": "RL08",
|
||||
"sheet": "8211_1GPHY_48PIN",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"refdes": "RL09",
|
||||
"sheet": "8211_1GPHY_48PIN",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"refdes": "RL10",
|
||||
"sheet": "8211_1GPHY_48PIN",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"refdes": "RL11",
|
||||
"sheet": "8211_1GPHY_48PIN",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"refdes": "RL12",
|
||||
"sheet": "8211_1GPHY_48PIN",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"refdes": "RL13",
|
||||
"sheet": "8211_1GPHY_48PIN",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"refdes": "RL14",
|
||||
"sheet": "8211_1GPHY_48PIN",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"refdes": "RL15",
|
||||
"sheet": "8211_1GPHY_48PIN",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"refdes": "RL16",
|
||||
"sheet": "8211_1GPHY_48PIN",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
}
|
||||
],
|
||||
"steps": [
|
||||
{
|
||||
"old_part_number": "4100-CA3300-T7",
|
||||
"new_part_number": "4100-CA3300-2200",
|
||||
"sheet": "8211_1GPHY_48PIN",
|
||||
"phase": "execute_step",
|
||||
"unit": "step",
|
||||
"completed_units": 1,
|
||||
"state": "saved_ok",
|
||||
"schematic_name": "1GPHY_8211",
|
||||
"sheet_number": "8211_1GPHY_48PIN",
|
||||
"job_id": "99f533d93c4a4dcabeb687b2311658af_0",
|
||||
"worker_stage_seconds": {
|
||||
"starting": 0.9839999999967404,
|
||||
"session_startup": 2.4690000000118744,
|
||||
"check_project": 0.0159999999741558,
|
||||
"open_project": 15.78100000001723,
|
||||
"open_sheet": 3.5310000000172295,
|
||||
"session_ready": 0.0629999999946449,
|
||||
"query_components": 0.75,
|
||||
"index_components": 5.203000000008615,
|
||||
"find_components": 0.7969999999913853,
|
||||
"index_pins": 4.514999999984866,
|
||||
"snapshot_attributes": 0.40700000000651926,
|
||||
"capture": 2.6559999999881256,
|
||||
"before_native": 0.07800000000861473,
|
||||
"native_replace": 17.01600000000326,
|
||||
"restore_preflight": 2.812000000005355,
|
||||
"before_restore_transaction": 0.25,
|
||||
"restore_attribute_fields": 0.6089999999967404,
|
||||
"restore_attributes": 0.0,
|
||||
"verify_restoration": 0.14199999999254942,
|
||||
"verify_attribute_fields": 0.1870000000053551,
|
||||
"finished": 1.9839999999967404,
|
||||
"save_and_close": 4.062999999994645,
|
||||
"verify_saved_project": 0.0
|
||||
},
|
||||
"elapsed_seconds": 64.37054100001114,
|
||||
"units_per_minute": 0.932103398043363
|
||||
},
|
||||
{
|
||||
"old_part_number": "4100-CA3300-T7",
|
||||
"new_part_number": "4100-CA3300-2200",
|
||||
"sheet": "8211_1GPHY_48PIN",
|
||||
"phase": "execute_step",
|
||||
"unit": "step",
|
||||
"completed_units": 1,
|
||||
"state": "saved_ok",
|
||||
"schematic_name": "1GPHY_8211",
|
||||
"sheet_number": "8211_1GPHY_48PIN",
|
||||
"job_id": "99f533d93c4a4dcabeb687b2311658af_1",
|
||||
"worker_stage_seconds": {
|
||||
"starting": 0.42199999999138527,
|
||||
"session_startup": 1.2810000000172295,
|
||||
"check_project": 0.03199999997741543,
|
||||
"open_project": 10.96799999999348,
|
||||
"open_sheet": 2.0789999999979045,
|
||||
"session_ready": 0.015000000013969839,
|
||||
"query_components": 0.3129999999946449,
|
||||
"index_components": 2.1559999999881256,
|
||||
"find_components": 1.0310000000172295,
|
||||
"index_pins": 3.6719999999913853,
|
||||
"snapshot_attributes": 0.25,
|
||||
"capture": 4.578000000008615,
|
||||
"before_native": 0.125,
|
||||
"native_replace": 14.51600000000326,
|
||||
"restore_preflight": 1.327999999979511,
|
||||
"before_restore_transaction": 0.21899999998277053,
|
||||
"restore_attribute_fields": 0.5940000000118744,
|
||||
"restore_attributes": 0.0,
|
||||
"verify_restoration": 0.061999999976251274,
|
||||
"verify_attribute_fields": 0.0940000000409782,
|
||||
"finished": 1.25,
|
||||
"save_and_close": 2.4060000000172295,
|
||||
"verify_saved_project": 0.0
|
||||
},
|
||||
"elapsed_seconds": 47.418164899980184,
|
||||
"units_per_minute": 1.2653378747692758
|
||||
}
|
||||
],
|
||||
"other_phases": [
|
||||
{
|
||||
"phase": "prepare_queue",
|
||||
"unit": "step",
|
||||
"completed_units": 2,
|
||||
"state": "completed",
|
||||
"elapsed_seconds": 0.07470610001473688,
|
||||
"units_per_minute": 1606.2945325258345
|
||||
},
|
||||
{
|
||||
"phase": "backup_project",
|
||||
"unit": "operation",
|
||||
"completed_units": 1,
|
||||
"state": "completed",
|
||||
"elapsed_seconds": 0.9657479999877978,
|
||||
"units_per_minute": 62.12800854959896
|
||||
},
|
||||
{
|
||||
"phase": "persist_progress",
|
||||
"unit": "operation",
|
||||
"completed_units": 1,
|
||||
"state": "completed",
|
||||
"job_id": "99f533d93c4a4dcabeb687b2311658af_0",
|
||||
"elapsed_seconds": 0.008863399998517707,
|
||||
"units_per_minute": 6769.411287997185
|
||||
},
|
||||
{
|
||||
"phase": "persist_progress",
|
||||
"unit": "operation",
|
||||
"completed_units": 1,
|
||||
"state": "completed",
|
||||
"job_id": "99f533d93c4a4dcabeb687b2311658af_1",
|
||||
"elapsed_seconds": 0.00932809998630546,
|
||||
"units_per_minute": 6432.178052131272
|
||||
},
|
||||
{
|
||||
"phase": "task_total",
|
||||
"unit": "task",
|
||||
"completed_units": 1,
|
||||
"state": "completed",
|
||||
"completed_steps": 2,
|
||||
"saved_steps": 2,
|
||||
"failed_steps": 0,
|
||||
"elapsed_seconds": 113.10993500001496,
|
||||
"units_per_minute": 0.5304573820150464
|
||||
}
|
||||
]
|
||||
},
|
||||
"small-reuse": {
|
||||
"queue_seconds": 100.6405139999988,
|
||||
"worker_starts": 1,
|
||||
"open_project_calls": 3,
|
||||
"verified": true,
|
||||
"readback_seconds": 10.346642499993322,
|
||||
"comparisons": [
|
||||
{
|
||||
"refdes": "RL02",
|
||||
"sheet": "8211_1GPHY_48PIN",
|
||||
"expected": "4100-CA3300-2200",
|
||||
"actual": "4100-CA3300-2200"
|
||||
},
|
||||
{
|
||||
"refdes": "RL05",
|
||||
"sheet": "8211_1GPHY_48PIN",
|
||||
"expected": "4100-CA3300-2200",
|
||||
"actual": "4100-CA3300-2200"
|
||||
},
|
||||
{
|
||||
"refdes": "RL06",
|
||||
"sheet": "8211_1GPHY_48PIN",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"refdes": "RL07",
|
||||
"sheet": "8211_1GPHY_48PIN",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"refdes": "RL08",
|
||||
"sheet": "8211_1GPHY_48PIN",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"refdes": "RL09",
|
||||
"sheet": "8211_1GPHY_48PIN",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"refdes": "RL10",
|
||||
"sheet": "8211_1GPHY_48PIN",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"refdes": "RL11",
|
||||
"sheet": "8211_1GPHY_48PIN",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"refdes": "RL12",
|
||||
"sheet": "8211_1GPHY_48PIN",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"refdes": "RL13",
|
||||
"sheet": "8211_1GPHY_48PIN",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"refdes": "RL14",
|
||||
"sheet": "8211_1GPHY_48PIN",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"refdes": "RL15",
|
||||
"sheet": "8211_1GPHY_48PIN",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
},
|
||||
{
|
||||
"refdes": "RL16",
|
||||
"sheet": "8211_1GPHY_48PIN",
|
||||
"expected": "4100-CA3300-T7",
|
||||
"actual": "4100-CA3300-T7"
|
||||
}
|
||||
],
|
||||
"steps": [
|
||||
{
|
||||
"old_part_number": "4100-CA3300-T7",
|
||||
"new_part_number": "4100-CA3300-2200",
|
||||
"sheet": "8211_1GPHY_48PIN",
|
||||
"phase": "execute_step",
|
||||
"unit": "step",
|
||||
"completed_units": 1,
|
||||
"state": "saved_ok",
|
||||
"schematic_name": "1GPHY_8211",
|
||||
"sheet_number": "8211_1GPHY_48PIN",
|
||||
"job_id": "246f84be443e4ae2a55a0df40dc4899f_0",
|
||||
"worker_stage_seconds": {
|
||||
"starting": 0.28099999998812564,
|
||||
"session_startup": 1.0,
|
||||
"check_project": 0.0,
|
||||
"open_project": 12.10999999998603,
|
||||
"open_sheet": 2.812000000034459,
|
||||
"session_ready": 0.01600000000325963,
|
||||
"query_components": 0.28099999998812564,
|
||||
"index_components": 2.702999999979511,
|
||||
"find_components": 0.875,
|
||||
"index_pins": 4.593000000022585,
|
||||
"snapshot_attributes": 0.42199999996228144,
|
||||
"capture": 4.094000000011874,
|
||||
"before_native": 0.125,
|
||||
"native_replace": 19.155999999988126,
|
||||
"restore_preflight": 2.109000000025844,
|
||||
"before_restore_transaction": 0.28200000000651926,
|
||||
"restore_attribute_fields": 0.75,
|
||||
"restore_attributes": 0.014999999984866008,
|
||||
"verify_restoration": 0.14100000003236346,
|
||||
"verify_attribute_fields": 0.1879999999946449,
|
||||
"finished": 3.2189999999827705,
|
||||
"save_and_close": 1.562000000005355,
|
||||
"verify_saved_project": 0.01600000000325963,
|
||||
"session_wait": 0.0
|
||||
},
|
||||
"elapsed_seconds": 56.79680049998569,
|
||||
"units_per_minute": 1.0563975342240468
|
||||
},
|
||||
{
|
||||
"old_part_number": "4100-CA3300-T7",
|
||||
"new_part_number": "4100-CA3300-2200",
|
||||
"sheet": "8211_1GPHY_48PIN",
|
||||
"phase": "execute_step",
|
||||
"unit": "step",
|
||||
"completed_units": 1,
|
||||
"state": "saved_ok",
|
||||
"schematic_name": "1GPHY_8211",
|
||||
"sheet_number": "8211_1GPHY_48PIN",
|
||||
"job_id": "246f84be443e4ae2a55a0df40dc4899f_1",
|
||||
"worker_stage_seconds": {
|
||||
"check_project": 0.015000000013969839,
|
||||
"open_sheet": 2.187999999965541,
|
||||
"query_components": 0.4220000000204891,
|
||||
"index_components": 2.9210000000020955,
|
||||
"find_components": 0.6089999999967404,
|
||||
"index_pins": 3.532999999995809,
|
||||
"snapshot_attributes": 0.24900000003981404,
|
||||
"capture": 2.85999999998603,
|
||||
"before_native": 0.07800000000861473,
|
||||
"native_replace": 16.264999999984866,
|
||||
"restore_preflight": 1.687999999994645,
|
||||
"before_restore_transaction": 0.2659999999741558,
|
||||
"restore_attribute_fields": 0.6870000000053551,
|
||||
"restore_attributes": 0.0,
|
||||
"verify_restoration": 0.12600000001839362,
|
||||
"verify_attribute_fields": 0.10899999999674037,
|
||||
"finished": 1.687000000005355,
|
||||
"save_and_close": 1.7039999999979045,
|
||||
"verify_saved_project": 0.015000000013969839,
|
||||
"open_project": 5.625,
|
||||
"session_wait": 0.0
|
||||
},
|
||||
"elapsed_seconds": 41.16839780000737,
|
||||
"units_per_minute": 1.4574285910147629
|
||||
}
|
||||
],
|
||||
"other_phases": [
|
||||
{
|
||||
"phase": "prepare_queue",
|
||||
"unit": "step",
|
||||
"completed_units": 2,
|
||||
"state": "completed",
|
||||
"elapsed_seconds": 0.025570099998731166,
|
||||
"units_per_minute": 4692.981255683576
|
||||
},
|
||||
{
|
||||
"phase": "backup_project",
|
||||
"unit": "operation",
|
||||
"completed_units": 1,
|
||||
"state": "completed",
|
||||
"elapsed_seconds": 0.32834000000730157,
|
||||
"units_per_minute": 182.73740634301555
|
||||
},
|
||||
{
|
||||
"phase": "persist_progress",
|
||||
"unit": "operation",
|
||||
"completed_units": 1,
|
||||
"state": "completed",
|
||||
"job_id": "246f84be443e4ae2a55a0df40dc4899f_0",
|
||||
"elapsed_seconds": 0.010178099997574463,
|
||||
"units_per_minute": 5895.009875546375
|
||||
},
|
||||
{
|
||||
"phase": "persist_progress",
|
||||
"unit": "operation",
|
||||
"completed_units": 1,
|
||||
"state": "completed",
|
||||
"job_id": "246f84be443e4ae2a55a0df40dc4899f_1",
|
||||
"elapsed_seconds": 0.009127400000579655,
|
||||
"units_per_minute": 6573.613514931916
|
||||
},
|
||||
{
|
||||
"phase": "task_total",
|
||||
"unit": "task",
|
||||
"completed_units": 1,
|
||||
"state": "completed",
|
||||
"completed_steps": 2,
|
||||
"saved_steps": 2,
|
||||
"failed_steps": 0,
|
||||
"elapsed_seconds": 100.6060615000024,
|
||||
"units_per_minute": 0.5963855368694516
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"multi_page": {
|
||||
"steps": [
|
||||
{
|
||||
"sheet": [
|
||||
"PON",
|
||||
"block"
|
||||
],
|
||||
"state": "no_match",
|
||||
"seconds": 16.36403070000233
|
||||
},
|
||||
{
|
||||
"sheet": [
|
||||
"PON",
|
||||
"01_POWER"
|
||||
],
|
||||
"state": "no_match",
|
||||
"seconds": 4.627093000017339
|
||||
},
|
||||
{
|
||||
"sheet": [
|
||||
"PON",
|
||||
"02_ZX279133L"
|
||||
],
|
||||
"state": "no_match",
|
||||
"seconds": 10.180998900003033
|
||||
}
|
||||
],
|
||||
"passed": true,
|
||||
"closed_between_steps": true,
|
||||
"worker_starts": 1,
|
||||
"completed_items": 3,
|
||||
"total_items": 18,
|
||||
"seconds": 34.73681229999056
|
||||
},
|
||||
"guards": {
|
||||
"clean": {
|
||||
"mode": "clean",
|
||||
"closed_cleanly": true,
|
||||
"passed": true
|
||||
},
|
||||
"edit": {
|
||||
"mode": "edit",
|
||||
"previous_value": "100NF/16V",
|
||||
"external_edit_written": true,
|
||||
"error_code": "quick_run_uncertain",
|
||||
"preserved_external_state": true,
|
||||
"passed": true
|
||||
},
|
||||
"foreign": {
|
||||
"mode": "foreign",
|
||||
"error_code": "quick_run_uncertain",
|
||||
"preserved_external_state": true,
|
||||
"passed": true
|
||||
}
|
||||
},
|
||||
"stress": {
|
||||
"current": {
|
||||
"mode": "simulated_worker_with_tracemalloc",
|
||||
"projects": 20,
|
||||
"sheets_per_project": 5,
|
||||
"rules_per_sheet": 10,
|
||||
"steps": 1000,
|
||||
"saved_steps": 91,
|
||||
"elapsed_seconds": 41.516500700003235,
|
||||
"peak_bytes": 2036758,
|
||||
"steps_per_second": 24.086808453004377,
|
||||
"functional_assertions_passed": true,
|
||||
"time_gate_seconds": 30,
|
||||
"time_gate_passed": false
|
||||
},
|
||||
"baseline": {
|
||||
"mode": "simulated_worker_with_tracemalloc",
|
||||
"projects": 20,
|
||||
"sheets_per_project": 5,
|
||||
"rules_per_sheet": 10,
|
||||
"steps": 1000,
|
||||
"saved_steps": 91,
|
||||
"elapsed_seconds": 42.45326560002286,
|
||||
"peak_bytes": 1992249,
|
||||
"steps_per_second": 23.555313963867636,
|
||||
"functional_assertions_passed": true,
|
||||
"time_gate_seconds": 30,
|
||||
"time_gate_passed": false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
# V1.1.0 测试入口
|
||||
|
||||
默认 `python -m pytest -q` 仅运行 `tests/v1_1` 的功能行为测试。pytest 固定使用本仓库 src,避免与同名 dx_productivity 安装包混淆。
|
||||
|
||||
`tools/Test-V1.1.ps1` 是日常入口;`-Safety` 增加连接/引脚/非目标修改校验、执行互斥及应用启动回归。发布构建必须执行新测试和安全子集,失败立即停止,不继续打包。
|
||||
|
||||
`tools/Test-Legacy.ps1` 保留历史测试入口,`-TestPath` 可以指定某个旧模块。全量历史回归包含 subprocess/VBS/旧 UI 等耗时路径,默认开发循环不调用它。历史测试未删除,也没有被替换成伪通过。
|
||||
|
||||
新测试使用真实 SQLite 迁移、真实 XLSX 往返及真实计划验证,CAD/原生进程边界使用注入数据与协议桩。默认不启动 Mentor、不访问生产工程、不等待模拟的真实 150 秒无进展预算。Qt 核验设置 QT_QPA_PLATFORM=offscreen。
|
||||
|
||||
打包后的 `--smoke-test --data-root <临时目录>` 单独验证启动、数据存储和退出。真实中央库器件替换、保存回读和外部 Packager/ERC 验收由独立副本现场探针完成。
|
||||
|
||||
多工程性能回归入口:`python tools/measure_task_queue.py --output build/queue-measure-001 --projects 10 --sheets 3 --rules 4`。输出目录须为新目录,结果为 `report.json` 和 UTF-8 BOM 编码的 `timings.csv`。默认覆盖任务创建、库存、BOM、计划保存、串行执行及未勾选位号保留;`--behavior` 可选 `failure_continue`、`uncertain_stop`、`pause_resume`。此入口使用真实 SQLite、XLSX、备份、队列和日志,仅 CAD 执行器为模拟,不能用其吞吐量代表现场 CAD 替换速率。
|
||||
|
||||
真实多工程测量与压力回归记录见 [2026-10-15 多工程回归](2026-10-15-multi-project-regression.md)。
|
||||
|
||||
私有桌面正式后端的原生替换、恢复、暂停及资源释放见 [2026-10-15 私有桌面执行验证](2026-10-15-private-desktop-execution.md)。`tools/probe_private_single_step.py` 验证独立副本单步保存及故障注入后的恢复,`tools/probe_private_failures.py` 验证启动取消和 watchdog 超时后的进程/桌面释放。两者会真实启动 CAD,须单独、串行运行;普通 pytest 不启动 CAD。
|
||||
@@ -1,5 +1,7 @@
|
||||
# 自动启动 DxDesigner(2026.09.06-R7)
|
||||
|
||||
> **V1.1.1 已更新后台执行**:当前任务中心自动执行改为显式启动私有桌面中的自有 CAD,采集、单步、批量和恢复均接入;不会复用主桌面 CAD。目标工程须关闭,其他文件可正常查看。完成与暂停会退出 CAD 并验证私有桌面释放。详见 [后台运行说明](v1.1.0-project-tasks.md)、[真实验证记录](../testing/2026-10-15-private-desktop-execution.md) 和 [1.1.1 版本说明](../releases/v1.1.1.md)。以下保留 R7 的历史启动行为,不能作为当前版本的操作说明。
|
||||
|
||||
> 连续队列会在原理图精简备份后自动枚举多图页工程,并逐页打开明确绑定的原理图名和页号。精简备份排除 PCB、CES、历史工程备份和运行日志。下文“只处理单页”的内容是 R7 历史边界,不再适用于当前连续队列;人工单步流程仍只操作当前活动页。
|
||||
|
||||
点击“开始自动替换”后,工具先从已确认的队列项读取工程路径,再执行以下准备流程:
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
# DxPartReplace V1.1 使用说明(当前版本 1.1.1)
|
||||
|
||||
V1.1.0 沿用原有任务视图和料号规则编辑,增加按工程拆分的任务、按位号选择的替换计划及可选 Excel 操作。
|
||||
|
||||
## 日常流程
|
||||
|
||||
1. 点击“新建”,填写或选择根目录,点击“读取工程”。勾选要处理的 `.prj` 后创建任务,每个工程对应一个任务。已存在未完成任务的工程不会重复创建。
|
||||
2. 在任务详情的“料号规则”页填写旧料号、新料号。新建任务只绑定一个工程;历史多工程任务仅供查看。
|
||||
3. 打开“位号计划”,点击“采集所有匹配位号”。采集读取工程中的器件 UID、位号、图页、旧料号和原 Value,不保存工程。
|
||||
4. 在表格中勾选需要替换的位号,其余行保持不勾选。查找框支持位号、UID、图页、料号和 Value,查找只过滤当前显示,不删除计划行。可逐行填写不同新料号、自定义 Value 和“同步 NC”,也可对可见行批量填写新料号。采集后的位号默认保留,避免误替换。
|
||||
5. 点击“保存位号计划”。有未保存的编辑时无法执行;切换任务会保留编辑草稿。重新采集会核对工程身份并保留已保存计划;有未保存编辑时会提示丢弃草稿。
|
||||
6. 点击“执行当前任务”只处理当前绑定工程,或点击“顺序执行本批任务”按任务顺序处理同批工程。上下移动按钮调整顺序。每次仅处理一个工程,暂停在当前步骤收尾后生效。
|
||||
|
||||
执行状态、失败重试和中断核验集中在底部操作区。界面不再维护当前任务的工程选择列表,避免工程范围和按钮范围混淆。
|
||||
|
||||
## 执行日志与修改明细
|
||||
|
||||
任务执行结束或暂停后,底部自动展开日志。每个完成步骤按位号列出旧、新物料号,例如:`图页 MAIN:1 · 已保存并核验 · 位号 R1:4100-CA0000-T7 → 4100-CA0000-T0`;识别到 NC 并同步时另列说明。未命中、失败和保存后待核验分别显示状态,不计为成功修改。
|
||||
|
||||
明细来自执行器实际回读结果,不以勾选计划代替执行结果。同一工程的不同图页、规则分别保留记录;重新打开已完成任务会自动显示其日志。运行时显示最近 100 条事件,结束后显示所有保留的事件(包括轮转日志)。历史版本未记录的中间步骤无法事后补全。
|
||||
|
||||
执行日志同时记录采集、图页枚举及队列准备、工程备份、每个“图页 × 规则”步骤、进度同步和任务合计的耗时及速率。一个步骤可能修改多个位号,步骤速率不等于器件替换速率;失败或暂停不会计为成功完成的任务。执行器的进度阶段耗时随该步骤证据保留,用于区分打开工程、原生替换、属性恢复、保存与回读的时间。任务合计包含子步骤,统计时不能重复相加。
|
||||
|
||||
## 可选 Excel 操作
|
||||
|
||||
无需导出也能完成全部编辑。需要在 Excel 中操作时,可导出完整位号计划,或点击“BOM 模板”生成更适合物料工程师编辑的 BOM 表。BOM 一行可以填写多个位号(逗号、分号、空格或顿号分隔),并填写旧料号、新料号、替换开关、Value 和同步 NC。
|
||||
|
||||
导入先显示到表格中预览,点击“保存位号计划”后才生效。工程、图页、UID、位号、旧料号及原 Value 是身份校验字段,应保持原样。无法添加未采集器件、重复器件或跨工程目标;不接受公式。布尔选项可使用 TRUE/FALSE 或 是/否。
|
||||
|
||||
BOM 导入会把未列出的采集位号保留为“不替换”,并要求每个填写的位号在当前工程清单中唯一匹配;同名位号跨图页时应填写图页或 UID。导入失败不会改变已保存计划。
|
||||
|
||||
“同步 NC”默认勾选,可以按行关闭;仅按原规则识别独立 `/NC` 标记。Value 复制选项和每行自定义 Value 延续原工具的处理方式。替换计划不允许旧、新料号相同,也不允许同批链式或循环替换。
|
||||
|
||||
## 保存、恢复及旧任务
|
||||
|
||||
执行前保留原工具的备份流程,替换后保存、关闭并重新打开核验。执行证据按任务存放。目标 UID、位号、原 Value 或旧料号变化时会停止校验,绝不会退回替换全部同料号器件。保存结果不确定时停止队列,先使用核验恢复入口处理。
|
||||
|
||||
旧数据库自动升级并保留任务、状态、规则。未采集位号计划的历史任务沿用旧流程;采集后,即使没有勾选位号,也不会触发全量替换。建议首次使用新版本前自行复制原工具的 data 文件夹;不同版本不要同时打开同一数据目录。
|
||||
|
||||
## 验证范围
|
||||
|
||||
快速测试覆盖任务拆分、SQLite 迁移、位号筛选、Excel 往返、串行调度和界面编辑;发布构建另检查执行保护及冻结程序启动。测试不会修改生产 CAD 工程。
|
||||
|
||||
本机 7.9.5 的真实 TypeLib 没有可直接调用的 ReplacePart 方法,生产替换仍沿用原生对话框及 Library Wins。详见 `docs/research/v1.1.0-native-interface-probe.md`。实际中央库、器件替换和保存回读仍需用工程副本现场验收。
|
||||
|
||||
## 后台运行与释放(1.1.1)
|
||||
|
||||
任务中心的自动采集、替换和中断核验恢复已默认接入私有 Windows 桌面。工具显式启动并持有自己的 CAD,通过私有桌面、会话 GUID 和活动图页窗口所属 PID 校验连接,不接管主桌面已有 CAD,也不自动退回主桌面执行。
|
||||
|
||||
主桌面可以继续查看其他文件。开始前仍须保存并关闭本次目标工程,运行中不要在其他软件内打开或修改同一工程;共享的许可证、CPU、磁盘和中央库资源仍会影响速度。当前本机实测私有 CAD 启动约 22~35 秒,不承诺启动更快。
|
||||
|
||||
同一工程连续步骤复用后台会话,任务仍顺序执行。界面显示“启动后台 CAD”和“关闭 CAD 并释放后台会话”。任务完成或在步骤检查点暂停后,工具关闭自有工程、正常退出 CAD,确认进程退出,再清理自有 Job 子进程及句柄,并确认私有桌面消失。每次会话的启动、退出和清理证据单独保留在 `private-desktop-sessions` 下。
|
||||
|
||||
单步入口也执行备份、保存、重开核验和关闭。恢复成功会显示属性已保存并重开回读,无需用户另开后台工程手动保存。启动阶段尚未进入工程执行且清理成功时可以重试;执行超时、状态不确定或清理失败仍保留保护状态,由核验恢复入口处理。
|
||||
|
||||
该后端已在独立真实副本上完成替换、保存回读、暂停、恢复、启动取消及超时退出验证,详见 [验证记录](../testing/2026-10-15-private-desktop-execution.md)。1.1.1 发布包已包含此更新,详见 [版本说明](../releases/v1.1.1.md)。
|
||||
@@ -32,6 +32,9 @@ Dim QP_BatchSaveCommitted
|
||||
Dim QP_DiscoveryMode, QP_TargetSchematic, QP_TargetSheet
|
||||
Dim QP_FailureNumber, QP_FailureSource, QP_FailureDescription
|
||||
Dim QP_NcSyncSummary
|
||||
Dim QP_SessionMode, QP_SessionToken, QP_SessionProject, QP_MonitorJobId
|
||||
Dim QP_OwnedProjectPath, QP_SessionWaiting, QP_SessionExternalChange
|
||||
Dim QP_CheckpointSchematic, QP_CheckpointSheet
|
||||
Dim FailureState, CloseError
|
||||
Set QP_Fso = CreateObject("Scripting.FileSystemObject")
|
||||
QP_RootTemplate = "%LOCALAPPDATA%\DxProductivity\trial-task-center\quick-run"
|
||||
@@ -67,6 +70,11 @@ QP_ComponentIndexContext = ""
|
||||
QP_CurrentJobId = ""
|
||||
QP_ExitCode = 0
|
||||
QP_Stage = "session_startup"
|
||||
QP_SessionMode = False
|
||||
QP_OwnedProjectPath = ""
|
||||
QP_SessionWaiting = False
|
||||
QP_SessionExternalChange = False
|
||||
QP_MonitorJobId = QP_ExpectedJobId
|
||||
Set QP_App = Nothing
|
||||
|
||||
On Error Resume Next
|
||||
@@ -86,8 +94,14 @@ Else
|
||||
If QP_DiscoveryMode Then
|
||||
QPDiscoverSheets
|
||||
Else
|
||||
QPMain
|
||||
If Err.Number = 0 And QP_BatchMode Then QPFinishBatchItem
|
||||
Do
|
||||
QPMain
|
||||
If Err.Number <> 0 Then Exit Do
|
||||
If QP_BatchMode Then QPFinishBatchItem
|
||||
If Err.Number <> 0 Or Not QP_SessionMode Then Exit Do
|
||||
QPSessionNext
|
||||
If Err.Number <> 0 Or Not QP_SessionMode Then Exit Do
|
||||
Loop
|
||||
End If
|
||||
If Err.Number <> 0 Then
|
||||
QP_FailureNumber = Err.Number
|
||||
@@ -96,7 +110,7 @@ Else
|
||||
If QP_DiscoveryMode Then QPCleanupDiscoveryFailure
|
||||
FailureState = "hard_failure"
|
||||
CloseError = ""
|
||||
If QP_BatchMode Then
|
||||
If QP_BatchMode Or QP_SessionMode Then
|
||||
QPDiscardFailedBatchProject CloseError
|
||||
If Len(CloseError) = 0 Then
|
||||
If QP_BatchSaveCommitted Then
|
||||
@@ -142,7 +156,15 @@ Sub QPMain()
|
||||
If QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root, "recovery.request")) Then
|
||||
If Trim(QPReadUtf8(QP_Fso.BuildPath(QP_Root, "recovery.request"))) <> QP_CurrentJobId Then _
|
||||
Err.Raise vbObjectError + 864, "QuickPartReplace.Recovery", "recovery job mismatch"
|
||||
If Len(CStr(CreateObject("WScript.Shell").Environment("PROCESS")("DXPART_DESKTOP"))) > 0 Then QP_BatchMode = True
|
||||
QPRecoverSavedJob Command, SnapshotPath
|
||||
If QP_BatchMode Then
|
||||
If QP_BatchState = "restored_ok" Then
|
||||
QPFinishBatchItem
|
||||
Else
|
||||
QP_BatchMode = False
|
||||
End If
|
||||
End If
|
||||
QPProgress "finished", 1, 1
|
||||
Exit Sub
|
||||
End If
|
||||
@@ -173,17 +195,20 @@ Sub QPBootstrapSession()
|
||||
Err.Raise vbObjectError + 872, "QuickPartReplace.Discovery", "sheet discovery authorization does not match this job"
|
||||
QP_DiscoveryMode = True
|
||||
End If
|
||||
QPReadSessionRequest
|
||||
QPProgress "session_startup", 0, 0
|
||||
TargetPath = QPConfirmedProjectPath()
|
||||
If QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root, "recovery.request")) Then
|
||||
If QPDesignerProcessCount() <> 0 Then _
|
||||
If Len(CStr(CreateObject("WScript.Shell").Environment("PROCESS")("DXPART_DESKTOP"))) = 0 And QPDesignerProcessCount() <> 0 Then _
|
||||
Err.Raise vbObjectError + 864, "QuickPartReplace.Recovery", _
|
||||
"recovery requires a fresh CAD session; close existing DxDesigner first without discarding wanted edits"
|
||||
If Len(CStr(CreateObject("WScript.Shell").Environment("PROCESS")("DXPART_DESKTOP"))) > 0 Then QP_BatchMode = True
|
||||
End If
|
||||
If Len(TargetPath) = 0 Then
|
||||
Set QP_App = GetObject(, "Viewdraw.Application")
|
||||
Set QP_App = QPAttachOrStart(QPDesignerProcessCount())
|
||||
Else
|
||||
Set QP_App = QPAttachOrStart(QPDesignerProcessCount())
|
||||
If QP_SessionMode Then WScript.ConnectObject QP_App, "QPEvent_"
|
||||
QPEnsureProject QP_App, TargetPath
|
||||
End If
|
||||
QP_Stage = "session_ready"
|
||||
@@ -193,7 +218,9 @@ End Sub
|
||||
|
||||
Sub QPCleanupDiscoveryFailure()
|
||||
On Error Resume Next
|
||||
If QP_OwnedProject And Not QP_App Is Nothing Then QP_App.CloseProject
|
||||
If QP_OwnedProject And Not QP_App Is Nothing Then
|
||||
If QPCanonicalPath(QPProjectPath()) = QPCanonicalPath(QP_OwnedProjectPath) Then QP_App.CloseProject
|
||||
End If
|
||||
QP_OwnedProject = False
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
@@ -220,15 +247,21 @@ Sub QPWaitForMonitor()
|
||||
End Sub
|
||||
|
||||
Sub QPProgress(ByVal Stage, ByVal Done, ByVal Total)
|
||||
Dim Safe, StopPath
|
||||
Dim Safe, StopPath, Job, Suffix
|
||||
If Len(CStr(QP_AttemptToken)) = 0 Then Exit Sub
|
||||
Safe = 0
|
||||
If Not CBool(QP_NativeMutationPossible) And Not CBool(QP_RestoreTransactionOpen) And _
|
||||
Not CBool(QP_NativeCallActive) Then Safe = 1
|
||||
QP_ProgressSequence = CLng(QP_ProgressSequence) + 1
|
||||
Job = QP_ExpectedJobId
|
||||
Suffix = ""
|
||||
If QP_SessionMode Then
|
||||
Job = QP_MonitorJobId
|
||||
Suffix = vbTab & QP_ExpectedJobId
|
||||
End If
|
||||
WScript.StdOut.WriteLine "DX_PROGRESS" & vbTab & QP_AttemptToken & vbTab & _
|
||||
QP_ExpectedJobId & vbTab & CStr(QP_ProgressSequence) & vbTab & Stage & _
|
||||
vbTab & CStr(Done) & vbTab & CStr(Total) & vbTab & CStr(Safe)
|
||||
Job & vbTab & CStr(QP_ProgressSequence) & vbTab & Stage & _
|
||||
vbTab & CStr(Done) & vbTab & CStr(Total) & vbTab & CStr(Safe) & Suffix
|
||||
If Safe = 1 And Stage <> "finished" Then
|
||||
StopPath = QP_Fso.BuildPath(QP_Root, "monitor-" & QP_AttemptToken & ".stop")
|
||||
If QP_Fso.FileExists(StopPath) Then
|
||||
@@ -239,6 +272,111 @@ Sub QPProgress(ByVal Stage, ByVal Done, ByVal Total)
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Sub QPReadSessionRequest()
|
||||
Dim Path, Fields, Index, Character
|
||||
Path = QP_Fso.BuildPath(QP_Root, "project-session.request")
|
||||
If Not QP_Fso.FileExists(Path) Then Exit Sub
|
||||
If Not QP_BatchMode Or QP_DiscoveryMode Or _
|
||||
QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root, "recovery.request")) Then _
|
||||
Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "invalid project session mode"
|
||||
Fields = Split(Trim(QPReadUtf8(Path)), vbTab)
|
||||
If UBound(Fields) <> 2 Then Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "invalid session request"
|
||||
QP_SessionToken = CStr(Fields(0))
|
||||
If Len(QP_SessionToken) <> 32 Or Fields(2) <> QP_ExpectedJobId Then _
|
||||
Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "session authorization mismatch"
|
||||
For Index = 1 To 32
|
||||
Character = Mid(QP_SessionToken, Index, 1)
|
||||
If InStr(1, "0123456789abcdef", Character, vbBinaryCompare) = 0 Then _
|
||||
Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "invalid session token"
|
||||
Next
|
||||
QP_SessionProject = CStr(Fields(1))
|
||||
If QPCanonicalPath(QPConfirmedProjectPath()) <> QPCanonicalPath(QP_SessionProject) Then _
|
||||
Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "session project mismatch"
|
||||
QP_SessionMode = True
|
||||
End Sub
|
||||
|
||||
Sub QPSessionNext()
|
||||
Dim Path, Fields, Attempt, TargetPath, Documents, Document, View
|
||||
Path = QP_Fso.BuildPath(QP_Root, "project-session-next.tsv")
|
||||
QPProgress "session_wait", 1, 1
|
||||
For Attempt = 1 To 1500
|
||||
If QP_Fso.FileExists(Path) Then
|
||||
Fields = Split(Trim(QPReadUtf8(Path)), vbTab)
|
||||
If UBound(Fields) <> 1 Then Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "invalid continuation"
|
||||
If Fields(0) <> QP_SessionToken Then Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "continuation token mismatch"
|
||||
QP_Fso.DeleteFile Path, True
|
||||
QPRequireSessionCheckpoint
|
||||
QP_SessionWaiting = False
|
||||
If Fields(1) = "close" Then
|
||||
QPCloseBatchProject QP_SessionProject, False
|
||||
QP_SessionMode = False
|
||||
Exit Sub
|
||||
End If
|
||||
QP_ExpectedJobId = CStr(Fields(1))
|
||||
QP_CurrentJobId = QP_ExpectedJobId
|
||||
QP_BatchMode = True
|
||||
QP_BatchState = ""
|
||||
QP_BatchSaveCommitted = False
|
||||
QP_NativeMutationPossible = False
|
||||
If Trim(QPReadUtf8(QP_Fso.BuildPath(QP_Root, "batch.request"))) <> QP_ExpectedJobId Then _
|
||||
Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "next batch authorization mismatch"
|
||||
TargetPath = QPConfirmedProjectPath()
|
||||
If QPCanonicalPath(TargetPath) <> QPCanonicalPath(QP_SessionProject) Then _
|
||||
Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "cannot switch project inside a session"
|
||||
Set View = QP_App.ActiveView
|
||||
If Not View Is Nothing Then
|
||||
If CStr(View.GetName(0)) <> QP_TargetSchematic Or CStr(View.Block.SheetNum) <> QP_TargetSheet Then
|
||||
Set Documents = QP_App.SchematicSheetDocuments()
|
||||
If Documents.Count <> 1 Then Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "owned sheet set changed"
|
||||
Set Document = Documents.Item(1)
|
||||
Document.Close False, ""
|
||||
End If
|
||||
End If
|
||||
QPEnsureProject QP_App, TargetPath
|
||||
Exit Sub
|
||||
End If
|
||||
WScript.Sleep 100
|
||||
Next
|
||||
Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "supervisor did not release project checkpoint"
|
||||
End Sub
|
||||
|
||||
Sub QPEvent_DocumentModified()
|
||||
If QP_SessionWaiting Then QP_SessionExternalChange = True
|
||||
End Sub
|
||||
|
||||
Sub QPEvent_BlockModified(ByVal Block)
|
||||
If QP_SessionWaiting Then QP_SessionExternalChange = True
|
||||
End Sub
|
||||
|
||||
Sub QPEvent_ProjectModified(ByVal NewProject)
|
||||
If QP_SessionWaiting Then QP_SessionExternalChange = True
|
||||
End Sub
|
||||
|
||||
Sub QPEvent_BeforeProjectModified()
|
||||
If QP_SessionWaiting Then QP_SessionExternalChange = True
|
||||
End Sub
|
||||
|
||||
Sub QPEvent_SourceFileModified(ByVal FileName)
|
||||
If QP_SessionWaiting Then QP_SessionExternalChange = True
|
||||
End Sub
|
||||
|
||||
Sub QPRequireSessionCheckpoint()
|
||||
Dim Documents, View
|
||||
If Not QP_OwnedProject Or Len(QP_OwnedProjectPath) = 0 Then _
|
||||
Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "session project ownership was lost"
|
||||
If QPCanonicalPath(QPProjectPath()) <> QPCanonicalPath(QP_OwnedProjectPath) Or _
|
||||
QPCanonicalPath(QP_OwnedProjectPath) <> QPCanonicalPath(QP_SessionProject) Then _
|
||||
Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "active project changed; no automatic save or close"
|
||||
If QP_SessionExternalChange Then _
|
||||
Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "project modified outside worker at checkpoint; no automatic save or close"
|
||||
Set Documents = QP_App.SchematicSheetDocuments()
|
||||
Set View = QP_App.ActiveView
|
||||
If Documents.Count <> 1 Or View Is Nothing Then _
|
||||
Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "owned sheet set changed at checkpoint"
|
||||
If CStr(View.GetName(0)) <> QP_CheckpointSchematic Or CStr(View.Block.SheetNum) <> QP_CheckpointSheet Then _
|
||||
Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "active sheet changed at checkpoint"
|
||||
End Sub
|
||||
|
||||
Sub QPInvalidatePinIndex()
|
||||
Set QP_PinIndex = Nothing
|
||||
QP_PinContext = ""
|
||||
@@ -405,7 +543,24 @@ Function QPTryAttach()
|
||||
End Function
|
||||
|
||||
Function QPAttachOrStart(ByVal ProcessCount)
|
||||
Dim App, Attempt
|
||||
Dim App, Attempt, Environment, PrivateDesktop, ExpectedGuid
|
||||
Set Environment = CreateObject("WScript.Shell").Environment("PROCESS")
|
||||
PrivateDesktop = CStr(Environment("DXPART_DESKTOP"))
|
||||
ExpectedGuid = CStr(Environment("DXPART_CAD_GUID"))
|
||||
If Len(PrivateDesktop) = 0 And (Len(ExpectedGuid) > 0 Or Len(CStr(Environment("DXPART_CAD_PID"))) > 0 Or _
|
||||
Len(CStr(Environment("DXPART_SESSION_TOKEN"))) > 0) Then _
|
||||
Err.Raise vbObjectError + 874, "QuickPartReplace.PrivateDesktop", "incomplete private CAD identity"
|
||||
If Len(PrivateDesktop) > 0 Then
|
||||
If Len(ExpectedGuid) = 0 Or Len(CStr(Environment("DXPART_CAD_PID"))) = 0 Or _
|
||||
Len(CStr(Environment("DXPART_SESSION_TOKEN"))) <> 32 Then _
|
||||
Err.Raise vbObjectError + 874, "QuickPartReplace.PrivateDesktop", "incomplete private CAD identity"
|
||||
Set App = QPTryAttach()
|
||||
If App Is Nothing Then Err.Raise vbObjectError + 874, "QuickPartReplace.PrivateDesktop", "owned private CAD is unavailable"
|
||||
If LCase(CStr(App.Guid())) <> LCase(ExpectedGuid) Then _
|
||||
Err.Raise vbObjectError + 874, "QuickPartReplace.PrivateDesktop", "private CAD GUID mismatch; no project was changed"
|
||||
Set QPAttachOrStart = App
|
||||
Exit Function
|
||||
End If
|
||||
If ProcessCount > 1 Then _
|
||||
Err.Raise vbObjectError + 851, "QuickPartReplace.Session", "multiple DxDesigner instances; no project was changed"
|
||||
Set App = QPTryAttach()
|
||||
@@ -413,6 +568,7 @@ Function QPAttachOrStart(ByVal ProcessCount)
|
||||
If ProcessCount = 0 Then
|
||||
QP_Stage = "launch_designer"
|
||||
QPLog QP_Root, "INFO", "stage=launch_designer method=COM"
|
||||
QPProgress "launch_designer", 0, 1
|
||||
Set App = CreateObject("Viewdraw.Application")
|
||||
App.Visible = True
|
||||
Else
|
||||
@@ -437,11 +593,12 @@ Sub QPEnsureProject(ByRef App, ByVal TargetPath)
|
||||
Err.Raise vbObjectError + 850, "QuickPartReplace.Session", "confirmed project file does not exist: " & TargetPath
|
||||
QP_Stage = "check_project"
|
||||
QPLog QP_Root, "INFO", "stage=check_project target=" & QPLogField(TargetPath)
|
||||
QPProgress "check_project", 0, 1
|
||||
Set ProjectData = App.GetProjectData()
|
||||
CurrentPath = ""
|
||||
If Not ProjectData Is Nothing Then CurrentPath = CStr(ProjectData.GetProjectFilePath())
|
||||
If Len(Trim(CurrentPath)) > 0 Then
|
||||
If QP_BatchMode Then Err.Raise vbObjectError + 870, "QuickPartReplace.Batch", _
|
||||
If QP_BatchMode And Not (QP_SessionMode And QP_OwnedProject) Then Err.Raise vbObjectError + 870, "QuickPartReplace.Batch", _
|
||||
"batch cannot take over an already open project; save your wanted edits and close the project before starting the queue"
|
||||
If QPCanonicalPath(CurrentPath) <> QPCanonicalPath(TargetPath) Then _
|
||||
Err.Raise vbObjectError + 853, "QuickPartReplace.Session", _
|
||||
@@ -449,9 +606,11 @@ Sub QPEnsureProject(ByRef App, ByVal TargetPath)
|
||||
Else
|
||||
QP_Stage = "open_project"
|
||||
QPLog QP_Root, "INFO", "stage=open_project target=" & QPLogField(TargetPath)
|
||||
QPProgress "open_project", 0, 1
|
||||
Opened = App.OpenProject(CStr(TargetPath))
|
||||
If Not Opened Then Err.Raise vbObjectError + 854, "QuickPartReplace.Session", "DxDesigner refused to open the target project"
|
||||
QP_OwnedProject = True
|
||||
QP_OwnedProjectPath = TargetPath
|
||||
End If
|
||||
Set ProjectData = App.GetProjectData()
|
||||
If ProjectData Is Nothing Then _
|
||||
@@ -460,6 +619,7 @@ Sub QPEnsureProject(ByRef App, ByVal TargetPath)
|
||||
Err.Raise vbObjectError + 854, "QuickPartReplace.Session", "opened project does not match the confirmed target"
|
||||
If QP_DiscoveryMode Then Exit Sub
|
||||
QP_Stage = "open_sheet"
|
||||
QPProgress "open_sheet", 0, 1
|
||||
Set View = App.ActiveView
|
||||
If Not View Is Nothing And Not QP_BatchMode Then Exit Sub
|
||||
Set Documents = App.SchematicSheetDocuments()
|
||||
@@ -523,10 +683,14 @@ End Sub
|
||||
|
||||
Sub QPDiscoverInventory(ByRef Documents)
|
||||
Dim Requested, Schematics, Schematic, Sheets, Sheet, Document, View
|
||||
Dim Components, Comp, PartAttr, PartNumber, PartKey, HitKey, Seen, Text, Count
|
||||
Dim Components, Comp, PartAttr, ValueAttr, PartNumber, PartKey, HitKey, Seen, Text, Count
|
||||
Dim ComponentText, ValueText, ComponentMode
|
||||
Set Requested = QPReadInventoryRequest()
|
||||
Set Seen = CreateObject("Scripting.Dictionary")
|
||||
Text = "project_path" & vbTab & "schematic_name" & vbTab & "sheet_number" & vbTab & "old_part" & vbCrLf
|
||||
ComponentMode = QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root, "component-inventory.request"))
|
||||
ComponentText = "project_path" & vbTab & "schematic_name" & vbTab & "sheet_number" & vbTab & _
|
||||
"uid" & vbTab & "refdes" & vbTab & "old_part" & vbTab & "old_value" & vbCrLf
|
||||
Count = 0
|
||||
Set Schematics = Documents.GetAvailableSchematics()
|
||||
For Each Schematic In Schematics
|
||||
@@ -548,6 +712,17 @@ Sub QPDiscoverInventory(ByRef Documents)
|
||||
If Not PartAttr Is Nothing Then PartNumber = QPEffectiveAttributeValue(PartAttr)
|
||||
PartKey = LCase(CStr(PartNumber))
|
||||
If Requested.Exists(PartKey) Then
|
||||
If ComponentMode Then
|
||||
ValueText = ""
|
||||
Set ValueAttr = QPFindCurrentAttribute(Comp, "Value")
|
||||
If Not ValueAttr Is Nothing Then ValueText = QPEffectiveAttributeValue(ValueAttr)
|
||||
If Len(CStr(Comp.UID)) = 0 Or Len(CStr(Comp.Refdes)) = 0 Then _
|
||||
Err.Raise vbObjectError + 872, "QuickPartReplace.Discovery", "component identity is incomplete"
|
||||
ComponentText = ComponentText & QPEncode(QPProjectPath()) & vbTab & _
|
||||
QPEncode(CStr(Schematic)) & vbTab & QPEncode(CStr(Sheet)) & vbTab & _
|
||||
QPEncode(CStr(Comp.UID)) & vbTab & QPEncode(CStr(Comp.Refdes)) & vbTab & _
|
||||
QPEncode(CStr(PartNumber)) & vbTab & QPEncode(CStr(ValueText)) & vbCrLf
|
||||
End If
|
||||
HitKey = QPSheetKey(Schematic, Sheet) & Chr(30) & PartKey
|
||||
If Not Seen.Exists(HitKey) Then
|
||||
Seen.Add HitKey, True
|
||||
@@ -563,6 +738,7 @@ Sub QPDiscoverInventory(ByRef Documents)
|
||||
Next
|
||||
Next
|
||||
QPWriteUtf8 QP_Fso.BuildPath(QP_Root, "inventory.tsv"), Text
|
||||
If ComponentMode Then QPWriteUtf8 QP_Fso.BuildPath(QP_Root, "components.tsv"), ComponentText
|
||||
End Sub
|
||||
|
||||
Function QPReadInventoryRequest()
|
||||
@@ -658,7 +834,9 @@ End Sub
|
||||
Sub QPCloseBatchProject(ByVal ExpectedPath, ByVal SaveChanges)
|
||||
Dim Documents, Document
|
||||
If Not QP_OwnedProject Or QP_RestoreTransactionOpen Then _
|
||||
Err.Raise vbObjectError + 871, "QuickPartReplace.Batch", "project ownership or restoration transaction is not safe to close"
|
||||
Err.Raise vbObjectError + 871, "QuickPartReplace.Batch", "project ownership or restoration transaction is not safe to close"
|
||||
If QPCanonicalPath(ExpectedPath) <> QPCanonicalPath(QP_OwnedProjectPath) Or QP_SessionExternalChange Then _
|
||||
Err.Raise vbObjectError + 871, "QuickPartReplace.Batch", "owned project changed; no automatic close"
|
||||
If QPCanonicalPath(QPProjectPath()) <> QPCanonicalPath(ExpectedPath) Then _
|
||||
Err.Raise vbObjectError + 871, "QuickPartReplace.Batch", "active project changed before save and close"
|
||||
Set Documents = QP_App.SchematicSheetDocuments()
|
||||
@@ -672,6 +850,7 @@ Sub QPCloseBatchProject(ByVal ExpectedPath, ByVal SaveChanges)
|
||||
If Len(CStr(QP_App.GetProjectData().GetProjectFilePath())) > 0 Then _
|
||||
Err.Raise vbObjectError + 871, "QuickPartReplace.Batch", "project did not close; queue stopped"
|
||||
QP_OwnedProject = False
|
||||
QP_OwnedProjectPath = ""
|
||||
QPInvalidatePinIndex
|
||||
QPInvalidateComponentIndex
|
||||
End Sub
|
||||
@@ -679,9 +858,9 @@ End Sub
|
||||
Sub QPDiscardFailedBatchProject(ByRef ErrorDescription)
|
||||
Dim ErrorNumber, ErrorSource, Description
|
||||
ErrorDescription = ""
|
||||
If Not QP_BatchMode 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
|
||||
On Error Resume Next
|
||||
QPCloseBatchProject QPProjectPath(), False
|
||||
QPCloseBatchProject QP_OwnedProjectPath, False
|
||||
ErrorNumber = Err.Number
|
||||
ErrorSource = Err.Source
|
||||
Description = Err.Description
|
||||
@@ -711,6 +890,7 @@ Sub QPFinishBatchItem()
|
||||
SnapshotPath = QPJobSnapshotPath(QP_CurrentJobId)
|
||||
QPRequireCommandSnapshot Command, SnapshotPath
|
||||
Set Records = QPReadSnapshot(SnapshotPath)
|
||||
QPVerifyUntouched Records
|
||||
Set ValueStates = CreateObject("Scripting.Dictionary")
|
||||
For Index = 0 To Records.Item("components").Count - 1
|
||||
Set Record = Records.Item("components").Item(CStr(Index))
|
||||
@@ -720,12 +900,15 @@ Sub QPFinishBatchItem()
|
||||
ValueStates.Item(CStr(Index)).Add "custom_value", QPCustomValue(Command)
|
||||
Next
|
||||
End If
|
||||
QPCloseBatchProject TargetPath, True
|
||||
QP_BatchSaveCommitted = True
|
||||
If FinalState = "restored_ok" Or Not QP_SessionMode Then
|
||||
QPCloseBatchProject TargetPath, True
|
||||
QP_BatchSaveCommitted = True
|
||||
End If
|
||||
If FinalState = "restored_ok" Then
|
||||
QPProgress "verify_saved_project", 0, 1
|
||||
QPEnsureProject QP_App, TargetPath
|
||||
QPRequireCommandSnapshot Command, SnapshotPath
|
||||
QPVerifyUntouched Records
|
||||
Set Plans = CreateObject("Scripting.Dictionary")
|
||||
For Index = 0 To Records.Item("components").Count - 1
|
||||
Set Record = Records.Item("components").Item(CStr(Index))
|
||||
@@ -735,12 +918,29 @@ Sub QPFinishBatchItem()
|
||||
Plans.Add CStr(Index), Candidate
|
||||
Next
|
||||
QPVerifyRestoredPlans Command, Records, Plans, ValueStates
|
||||
QPCloseBatchProject TargetPath, True
|
||||
If Not QP_SessionMode Then QPCloseBatchProject TargetPath, True
|
||||
FinalState = "saved_ok"
|
||||
QP_BatchMessage = QP_BatchMessage & " Saved, reopened for readback, and closed."
|
||||
If QP_SessionMode Then
|
||||
QP_BatchMessage = QP_BatchMessage & " Saved and reopened for readback; owned project checkpoint verified."
|
||||
Else
|
||||
QP_BatchMessage = QP_BatchMessage & " Saved, reopened for readback, and closed."
|
||||
End If
|
||||
End If
|
||||
QP_BatchMode = False
|
||||
QPWriteStatus QP_Root, QP_CurrentJobId, FinalState, "batch_closed", QP_BatchMessage
|
||||
If QP_SessionMode Then
|
||||
QP_NativeMutationPossible = False
|
||||
QP_SessionExternalChange = False
|
||||
QP_CheckpointSchematic = QP_TargetSchematic
|
||||
QP_CheckpointSheet = QP_TargetSheet
|
||||
QP_SessionWaiting = True
|
||||
QPWriteStatus QP_Root, QP_CurrentJobId, FinalState, "session_verified", QP_BatchMessage
|
||||
QPWriteUtf8 QP_Fso.BuildPath(QP_Root, "project-session-result.tsv"), _
|
||||
QP_SessionToken & vbTab & QP_CurrentJobId & vbTab & FinalState & vbTab & "session_verified"
|
||||
ElseIf QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root, "recovery.request")) Then
|
||||
QPWriteStatus QP_Root, QP_CurrentJobId, "restored_ok", "recovery_saved_verified", QP_BatchMessage
|
||||
Else
|
||||
QPWriteStatus QP_Root, QP_CurrentJobId, FinalState, "batch_closed", QP_BatchMessage
|
||||
End If
|
||||
QPProgress "finished", 1, 1
|
||||
End Sub
|
||||
|
||||
@@ -848,8 +1048,10 @@ Sub QPRollbackNativeReplacement(ByVal SnapshotPath)
|
||||
Lines = Split(QPReadUtf8(SnapshotPath), vbLf)
|
||||
Expected = ""
|
||||
For LineIndex = 1 To UBound(Lines)
|
||||
If Len(Replace(Lines(LineIndex), vbCr, "")) > 0 Then _
|
||||
Expected = Expected & Replace(Lines(LineIndex), vbCr, "") & vbCrLf
|
||||
If Len(Replace(Lines(LineIndex), vbCr, "")) > 0 Then
|
||||
If Left(CStr(Lines(LineIndex)), 2) <> "U" & vbTab Then _
|
||||
Expected = Expected & Replace(Lines(LineIndex), vbCr, "") & vbCrLf
|
||||
End If
|
||||
Next
|
||||
Actual = ""
|
||||
For Index = 0 To Records.Item("components").Count - 1
|
||||
@@ -858,6 +1060,7 @@ Sub QPRollbackNativeReplacement(ByVal SnapshotPath)
|
||||
Actual = Actual & QPSnapshotComponent(Candidate)
|
||||
QPProgress "verify_native_rollback", Index + 1, Records.Item("components").Count
|
||||
Next
|
||||
QPVerifyUntouched Records
|
||||
If Actual <> Expected Then Err.Raise vbObjectError + 842, _
|
||||
"QuickPartReplace", "native undo does not match the original snapshot"
|
||||
QPWriteUtf8 SnapshotPath & ".native.rolled-back", _
|
||||
@@ -874,6 +1077,7 @@ Sub QPCaptureAndSelect(ByRef Command, ByVal SnapshotPath)
|
||||
Dim PartAttr
|
||||
Dim Snapshot
|
||||
Dim Index
|
||||
Dim Selectors, Selector, Uid, ValueAttr, ValueText
|
||||
|
||||
If StrComp(CStr(Command("old_part_number")), CStr(Command("new_part_number")), vbTextCompare) = 0 Then _
|
||||
Err.Raise vbObjectError + 829, "QuickPartReplace", "source and target must differ"
|
||||
@@ -884,17 +1088,35 @@ Sub QPCaptureAndSelect(ByRef Command, ByVal SnapshotPath)
|
||||
QPLog QP_Root, "INFO", "stage=query_components"
|
||||
Set Components = QP_App.ActiveView.Query(VDM_COMP, VD_ALL)
|
||||
QPBuildComponentIndex Components
|
||||
Set Selectors = QPCommandTargets(Command)
|
||||
For Each Comp In Components
|
||||
PartNumber = ""
|
||||
Set PartAttr = QPFindCurrentAttribute(Comp, "Part Number")
|
||||
If Not PartAttr Is Nothing Then PartNumber = QPEffectiveAttributeValue(PartAttr)
|
||||
If StrComp(PartNumber, CStr(Command("old_part_number")), _
|
||||
vbTextCompare) = 0 Then
|
||||
Uid = CStr(Comp.UID)
|
||||
If Selectors Is Nothing Then
|
||||
If StrComp(PartNumber, CStr(Command("old_part_number")), _
|
||||
vbTextCompare) = 0 Then Matches.Add CStr(Matches.Count), Comp
|
||||
ElseIf Selectors.Exists(Uid) Then
|
||||
Selector = Selectors.Item(Uid)
|
||||
ValueText = ""
|
||||
Set ValueAttr = QPFindCurrentAttribute(Comp, "Value")
|
||||
If Not ValueAttr Is Nothing Then ValueText = QPEffectiveAttributeValue(ValueAttr)
|
||||
If CStr(Comp.Refdes) <> CStr(Selector(0)) Or _
|
||||
StrComp(PartNumber, CStr(Command("old_part_number")), vbTextCompare) <> 0 Or _
|
||||
ValueText <> CStr(Selector(1)) Then _
|
||||
Err.Raise vbObjectError + 873, "QuickPartReplace.Target", "selected component changed since inventory"
|
||||
Matches.Add CStr(Matches.Count), Comp
|
||||
End If
|
||||
QPProgress "find_components", Matches.Count, 0
|
||||
Next
|
||||
If Not Selectors Is Nothing Then
|
||||
If Matches.Count <> Selectors.Count Then _
|
||||
Err.Raise vbObjectError + 873, "QuickPartReplace.Target", "selected component is missing"
|
||||
End If
|
||||
If Matches.Count = 0 Then
|
||||
If Not Selectors Is Nothing Then _
|
||||
Err.Raise vbObjectError + 873, "QuickPartReplace.Target", "target scope is empty"
|
||||
QPWriteStatus QP_Root, CStr(Command("job_id")), "no_match", "", _
|
||||
"No components match old Part Number on the current sheet; no replacement was performed. " & _
|
||||
"Project=" & QPProjectPath() & "; sheet=" & QPSheetIdentity() & "; old_part=" & CStr(Command("old_part_number"))
|
||||
@@ -911,6 +1133,8 @@ Sub QPCaptureAndSelect(ByRef Command, ByVal SnapshotPath)
|
||||
Snapshot = Snapshot & vbTab & QPEncode(QPValueMode(Command)) & _
|
||||
vbTab & QPEncode(QPCustomValue(Command)) & vbTab & _
|
||||
QPEncode(QPBooleanText(QPSyncNc(Command)))
|
||||
If Not Selectors Is Nothing Then _
|
||||
Snapshot = Snapshot & vbTab & QPEncode("targets") & vbTab & CStr(Command("target_selectors"))
|
||||
Snapshot = Snapshot & vbCrLf
|
||||
For Index = 0 To Matches.Count - 1
|
||||
Set Comp = Matches.Item(CStr(Index))
|
||||
@@ -918,6 +1142,12 @@ Sub QPCaptureAndSelect(ByRef Command, ByVal SnapshotPath)
|
||||
Snapshot = Snapshot & QPSnapshotComponent(Comp)
|
||||
QPProgress "capture", Index + 1, Matches.Count
|
||||
Next
|
||||
If Not Selectors Is Nothing Then
|
||||
For Each Comp In Components
|
||||
If Not Selectors.Exists(CStr(Comp.UID)) Then _
|
||||
Snapshot = Snapshot & QPUntouchedComponent(Comp)
|
||||
Next
|
||||
End If
|
||||
QPWriteUtf8 SnapshotPath, Snapshot
|
||||
|
||||
For Each Comp In Components
|
||||
@@ -933,6 +1163,77 @@ Sub QPCaptureAndSelect(ByRef Command, ByVal SnapshotPath)
|
||||
QPLog QP_Root, "INFO", "awaiting_native_replace count=" & Matches.Count
|
||||
End Sub
|
||||
|
||||
Function QPUntouchedComponent(ByRef Comp)
|
||||
QPUntouchedComponent = "U" & vbTab & QPEncode(CStr(Comp.UID)) & vbTab & _
|
||||
QPEncode(CStr(Comp.Refdes)) & vbTab & QPEncode(QPEffectiveComponentAttribute(Comp, "Part Number")) & vbTab & _
|
||||
QPEncode(QPEffectiveComponentAttribute(Comp, "Value")) & vbTab & _
|
||||
QPEncode(QPEffectiveComponentAttribute(Comp, "Part Name")) & vbTab & _
|
||||
QPEncode(QPEffectiveComponentAttribute(Comp, "Part Label")) & vbCrLf
|
||||
End Function
|
||||
|
||||
Function QPEffectiveComponentAttribute(ByRef Comp, ByVal Name)
|
||||
Dim Attr
|
||||
QPEffectiveComponentAttribute = ""
|
||||
Set Attr = QPFindCurrentAttribute(Comp, Name)
|
||||
If Not Attr Is Nothing Then QPEffectiveComponentAttribute = QPEffectiveAttributeValue(Attr)
|
||||
End Function
|
||||
|
||||
Sub QPVerifyUntouched(ByRef Records)
|
||||
Dim Baseline, Components, Comp, Uid, Actual, Matched, Total, Seen
|
||||
If Not Records.Item("meta").Exists("target_scope") Then Exit Sub
|
||||
Set Baseline = Records.Item("untouched")
|
||||
Set Components = QP_App.ActiveView.Query(VDM_COMP, VD_ALL)
|
||||
Matched = 0
|
||||
Total = 0
|
||||
Set Seen = CreateObject("Scripting.Dictionary")
|
||||
For Each Comp In Components
|
||||
Total = Total + 1
|
||||
Uid = CStr(Comp.UID)
|
||||
If Seen.Exists(Uid) Then Err.Raise vbObjectError + 874, _
|
||||
"QuickPartReplace.Target", "duplicate component UID"
|
||||
Seen.Add Uid, True
|
||||
If Baseline.Exists(Uid) Then
|
||||
Matched = Matched + 1
|
||||
Actual = Replace(QPUntouchedComponent(Comp), vbCrLf, "")
|
||||
If Actual <> CStr(Baseline.Item(Uid)) Then _
|
||||
Err.Raise vbObjectError + 874, "QuickPartReplace.Target", "unselected component changed"
|
||||
End If
|
||||
Next
|
||||
If Total <> Baseline.Count + Records.Item("components").Count Then _
|
||||
Err.Raise vbObjectError + 874, "QuickPartReplace.Target", "component count changed outside selected targets"
|
||||
If Matched <> Baseline.Count Then Err.Raise vbObjectError + 874, _
|
||||
"QuickPartReplace.Target", "unselected component is missing"
|
||||
End Sub
|
||||
|
||||
Function QPCommandTargets(ByRef Command)
|
||||
Dim Scope, Text, Entries, Entry, Fields, Result, Index
|
||||
Set QPCommandTargets = Nothing
|
||||
If Not Command.Exists("target_scope") Then Exit Function
|
||||
Scope = CStr(Command("target_scope"))
|
||||
If Scope = "all" Then
|
||||
If Len(CStr(Command("target_selectors"))) <> 0 Then _
|
||||
Err.Raise vbObjectError + 873, "QuickPartReplace.Target", "all-match scope has selectors"
|
||||
Exit Function
|
||||
End If
|
||||
If Scope <> "targets" Then Err.Raise vbObjectError + 873, _
|
||||
"QuickPartReplace.Target", "target scope is invalid"
|
||||
Text = QPDecode(CStr(Command("target_selectors")))
|
||||
If Len(Text) = 0 Then Err.Raise vbObjectError + 873, _
|
||||
"QuickPartReplace.Target", "target scope is empty"
|
||||
Set Result = CreateObject("Scripting.Dictionary")
|
||||
Entries = Split(Text, Chr(30))
|
||||
For Index = 0 To UBound(Entries)
|
||||
Fields = Split(Entries(Index), Chr(31))
|
||||
If UBound(Fields) <> 2 Or Len(CStr(Fields(0))) = 0 Or _
|
||||
Len(CStr(Fields(1))) = 0 Then Err.Raise vbObjectError + 873, _
|
||||
"QuickPartReplace.Target", "target selector is malformed"
|
||||
If Result.Exists(CStr(Fields(0))) Then Err.Raise vbObjectError + 873, _
|
||||
"QuickPartReplace.Target", "duplicate target UID"
|
||||
Result.Add CStr(Fields(0)), Array(CStr(Fields(1)), CStr(Fields(2)))
|
||||
Next
|
||||
Set QPCommandTargets = Result
|
||||
End Function
|
||||
|
||||
Function QPSnapshotComponent(ByRef Comp)
|
||||
Dim AttributeCount
|
||||
Dim Point
|
||||
@@ -1086,6 +1387,8 @@ Sub QPRestoreAfterOperatorReplace(ByRef Command, ByVal SnapshotPath)
|
||||
QP_NcSyncSummary = ""
|
||||
QPProgress "restore_preflight", 0, 0
|
||||
Set Records = QPReadSnapshot(SnapshotPath)
|
||||
QPRequireCommandSnapshot Command, SnapshotPath
|
||||
QPVerifyUntouched Records
|
||||
Set Meta = Records.Item("meta")
|
||||
If QPCanonicalPath(CStr(Meta("project_path"))) <> QPCanonicalPath(QPProjectPath()) Or _
|
||||
CStr(Meta("sheet_name")) <> QPSheetIdentity() Then _
|
||||
@@ -1232,6 +1535,7 @@ Sub QPRecoverSavedJob(ByRef Command, ByVal SnapshotPath)
|
||||
Dim OldCount, NewCount, ErrorNumber, ErrorDescription, RecoveryDocuments, RecoveryDocument, RecoveryProjectData
|
||||
QPRequireCommandSnapshot Command, SnapshotPath
|
||||
Set Records = QPReadSnapshot(SnapshotPath)
|
||||
QPVerifyUntouched Records
|
||||
Set Plans = CreateObject("Scripting.Dictionary")
|
||||
Set Used = CreateObject("Scripting.Dictionary")
|
||||
Set ValueStates = CreateObject("Scripting.Dictionary")
|
||||
@@ -1700,6 +2004,19 @@ Sub QPRequireCommandSnapshot(ByRef Command, ByVal SnapshotPath)
|
||||
If QPCustomValue(Meta) <> QPCustomValue(Command) Or _
|
||||
QPSyncNc(Meta) <> QPSyncNc(Command) Then _
|
||||
Err.Raise vbObjectError + 842, "QuickPartReplace", "snapshot Value or NC option mismatch"
|
||||
If Command.Exists("target_scope") Then
|
||||
If CStr(Command("target_scope")) = "targets" Then
|
||||
If Not Meta.Exists("target_scope") Then Err.Raise vbObjectError + 873, _
|
||||
"QuickPartReplace.Target", "target selector missing from snapshot"
|
||||
If CStr(Meta("target_scope")) <> "targets" Or _
|
||||
CStr(Meta("target_selectors")) <> CStr(Command("target_selectors")) Then _
|
||||
Err.Raise vbObjectError + 873, "QuickPartReplace.Target", "target selector changed since snapshot"
|
||||
ElseIf Meta.Exists("target_scope") Then
|
||||
Err.Raise vbObjectError + 873, "QuickPartReplace.Target", "snapshot scope changed"
|
||||
End If
|
||||
ElseIf Meta.Exists("target_scope") Then
|
||||
Err.Raise vbObjectError + 873, "QuickPartReplace.Target", "target scope missing from command"
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Function QPValueMode(ByRef Record)
|
||||
@@ -2362,6 +2679,7 @@ Function QPReadSnapshot(ByVal Path)
|
||||
Dim Result
|
||||
Dim Components
|
||||
Dim Attributes
|
||||
Dim Untouched
|
||||
Dim Fields
|
||||
Dim Index
|
||||
Dim Record
|
||||
@@ -2370,13 +2688,14 @@ Function QPReadSnapshot(ByVal Path)
|
||||
Set Result = CreateObject("Scripting.Dictionary")
|
||||
Set Components = CreateObject("Scripting.Dictionary")
|
||||
Set Attributes = CreateObject("Scripting.Dictionary")
|
||||
Set Untouched = CreateObject("Scripting.Dictionary")
|
||||
Lines = Split(QPReadUtf8(Path), vbLf)
|
||||
For Index = 0 To UBound(Lines)
|
||||
If Len(Replace(Lines(Index), vbCr, "")) > 0 Then
|
||||
Fields = Split(Replace(Lines(Index), vbCr, ""), vbTab)
|
||||
Select Case Fields(0)
|
||||
Case "M"
|
||||
If UBound(Fields) <> 4 And UBound(Fields) <> 5 And UBound(Fields) <> 7 Then Err.Raise vbObjectError + 812, _
|
||||
If UBound(Fields) <> 4 And UBound(Fields) <> 5 And UBound(Fields) <> 7 And UBound(Fields) <> 9 Then Err.Raise vbObjectError + 812, _
|
||||
"QuickPartReplace", "invalid snapshot meta"
|
||||
Set Meta = CreateObject("Scripting.Dictionary")
|
||||
Meta.Add "project_path", QPDecode(Fields(1))
|
||||
@@ -2384,11 +2703,15 @@ Function QPReadSnapshot(ByVal Path)
|
||||
Meta.Add "new_part_number", QPDecode(Fields(3))
|
||||
Meta.Add "sheet_name", QPDecode(Fields(4))
|
||||
If UBound(Fields) = 5 Then Meta.Add "value_mode", QPDecode(Fields(5))
|
||||
If UBound(Fields) = 7 Then
|
||||
If UBound(Fields) >= 7 Then
|
||||
Meta.Add "value_mode", QPDecode(Fields(5))
|
||||
Meta.Add "custom_value", QPDecode(Fields(6))
|
||||
Meta.Add "sync_nc", QPDecode(Fields(7))
|
||||
End If
|
||||
If UBound(Fields) = 9 Then
|
||||
Meta.Add "target_scope", QPDecode(Fields(8))
|
||||
Meta.Add "target_selectors", CStr(Fields(9))
|
||||
End If
|
||||
Result.Add "meta", Meta
|
||||
Case "C"
|
||||
If UBound(Fields) <> 7 Then Err.Raise vbObjectError + 813, _
|
||||
@@ -2418,6 +2741,12 @@ Function QPReadSnapshot(ByVal Path)
|
||||
Record.Add "orientation", QPDecode(Fields(10))
|
||||
Record.Add "visible", QPDecode(Fields(11))
|
||||
Attributes.Add CStr(Attributes.Count), Record
|
||||
Case "U"
|
||||
If UBound(Fields) <> 6 Then Err.Raise vbObjectError + 874, _
|
||||
"QuickPartReplace.Target", "invalid unselected component snapshot"
|
||||
If Untouched.Exists(QPDecode(Fields(1))) Then Err.Raise vbObjectError + 874, _
|
||||
"QuickPartReplace.Target", "duplicate unselected component UID"
|
||||
Untouched.Add QPDecode(Fields(1)), Replace(Lines(Index), vbCr, "")
|
||||
End Select
|
||||
End If
|
||||
Next
|
||||
@@ -2426,6 +2755,7 @@ Function QPReadSnapshot(ByVal Path)
|
||||
End If
|
||||
Result.Add "components", Components
|
||||
Result.Add "attributes", Attributes
|
||||
Result.Add "untouched", Untouched
|
||||
Set QPReadSnapshot = Result
|
||||
End Function
|
||||
|
||||
|
||||
@@ -69,10 +69,12 @@ try {
|
||||
|
||||
Push-Location $repositoryRoot
|
||||
$locationPushed = $true
|
||||
& $PythonExecutable -m pytest -q tests\trial_task_center\test_application.py tests\packaging\test_dx_part_replace_build.py
|
||||
& $PythonExecutable -m pytest -q tests\v1_1 tests\trial_task_center\test_application.py tests\trial_task_center\test_execution_safety.py tests\part_replace\test_verification.py
|
||||
if ($LASTEXITCODE -ne 0) { throw "Release verification failed; build stopped" }
|
||||
Remove-VerifiedBuildTarget -RepositoryRoot $repositoryRoot -RelativeTarget "build\DxPartReplace"
|
||||
Remove-VerifiedBuildTarget -RepositoryRoot $repositoryRoot -RelativeTarget "dist\DxPartReplace"
|
||||
& $PythonExecutable -m PyInstaller --noconfirm packaging\DxPartReplace.spec
|
||||
if ($LASTEXITCODE -ne 0) { throw "PyInstaller failed; build stopped" }
|
||||
|
||||
$executable = [System.IO.Path]::GetFullPath((Join-Path $repositoryRoot "dist\DxPartReplace\DxPartReplace.exe"))
|
||||
if (-not (Test-Path -LiteralPath $executable -PathType Leaf)) {
|
||||
|
||||
+4
-3
@@ -4,9 +4,9 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "dx-productivity"
|
||||
version = "1.0.0"
|
||||
version = "1.1.1"
|
||||
requires-python = ">=3.12,<3.13"
|
||||
dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<1"]
|
||||
dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<1", "openpyxl>=3.1,<4"]
|
||||
|
||||
[project.scripts]
|
||||
dx-part-replace = "dx_productivity.part_replace.cli:main"
|
||||
@@ -19,6 +19,7 @@ dev = ["pytest>=8,<9", "pytest-cov>=5,<7", "coverage>=7,<8", "build>=1.2,<2", "p
|
||||
where = ["src"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
testpaths = ["tests/v1_1"]
|
||||
pythonpath = ["src"]
|
||||
addopts = "-ra"
|
||||
cache_dir = "build/pytest-cache"
|
||||
@@ -9,7 +9,7 @@ import platform
|
||||
import sys
|
||||
from typing import Sequence
|
||||
|
||||
from PySide6.QtCore import QTimer
|
||||
from PySide6.QtCore import QTimer, QThreadPool
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
from dx_productivity.trial_task_center.logging_setup import LoggingContext, configure_logging, install_exception_hooks
|
||||
@@ -35,6 +35,9 @@ def _parse_arguments(argv: Sequence[str] | None) -> argparse.Namespace:
|
||||
parser.add_argument("--native-helper", action="store_true", help=argparse.SUPPRESS)
|
||||
parser.add_argument("--snapshot", type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument("--sceneos-cli", action="store_true", help=argparse.SUPPRESS)
|
||||
parser.add_argument('--private-cad-action', choices=('probe', 'quit'), help=argparse.SUPPRESS)
|
||||
parser.add_argument('--private-cad-evidence', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--private-cad-pid', type=int, help=argparse.SUPPRESS)
|
||||
return parser.parse_args(list(argv) if argv is not None else None)
|
||||
|
||||
|
||||
@@ -91,6 +94,11 @@ def _flush(context: LoggingContext) -> None:
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
"""Run the Qt shell, returning a conventional process status code."""
|
||||
arguments = _parse_arguments(argv)
|
||||
if arguments.private_cad_action:
|
||||
if arguments.private_cad_evidence is None or arguments.private_cad_pid is None:
|
||||
return 2
|
||||
from dx_productivity.trial_task_center.isolated_cad import native_action
|
||||
return native_action(arguments.private_cad_action, arguments.private_cad_evidence, arguments.private_cad_pid)
|
||||
if arguments.native_helper:
|
||||
if arguments.snapshot is None:
|
||||
return 2
|
||||
@@ -129,6 +137,9 @@ def main(argv: Sequence[str] | None = None) -> int:
|
||||
return 1
|
||||
finally:
|
||||
if store is not None:
|
||||
# The window invalidates queued UI results on close. Finish the
|
||||
# remaining read before releasing the shared SQLite connection.
|
||||
QThreadPool.globalInstance().waitForDone()
|
||||
store.close()
|
||||
|
||||
|
||||
|
||||
@@ -1,15 +1,11 @@
|
||||
"""Serial, confirmed queue execution with safe between-item pausing."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from concurrent.futures import Future, ThreadPoolExecutor
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
from threading import Event
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .logging_setup import append_task_event
|
||||
@@ -17,7 +13,6 @@ from .models import TaskStatus
|
||||
from .quick_run import (
|
||||
BATCH_FAILED_STATE,
|
||||
BATCH_SAVED_UNVERIFIED_STATE,
|
||||
TERMINAL_STATES,
|
||||
QuickRunProgress,
|
||||
QuickRunStepResult,
|
||||
_path_key,
|
||||
@@ -25,10 +20,13 @@ from .quick_run import (
|
||||
)
|
||||
from .retention import maintain_quick_run_storage
|
||||
from .schematic_backup import create_schematic_backup
|
||||
|
||||
|
||||
_BACKUP_STATE_NAME = 'batch-backups.json'
|
||||
_BACKUP_DIRECTORY_NAME = 'batch-backups'
|
||||
from .execution_metrics import measure_phase
|
||||
# Keep legacy helper imports patchable for queue integrations.
|
||||
from .batch_backup import (
|
||||
BatchBackupCoordinator,
|
||||
_BACKUP_STATE_NAME, _BACKUP_DIRECTORY_NAME,
|
||||
_backup_key, _read_backup_state, _write_backup_state, _reusable_backup,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -47,9 +45,10 @@ def execute_batch(
|
||||
expected_item,
|
||||
stop_event: Event,
|
||||
continue_after_backup_failure: bool = False,
|
||||
reuse_project_session: bool = True,
|
||||
) -> BatchRunResult:
|
||||
preparer = service._quick_run_preparer
|
||||
retention = maintain_quick_run_storage(preparer._data_root)
|
||||
retention = maintain_quick_run_storage(preparer.data_root)
|
||||
if retention.removed_entries or retention.skipped_entries:
|
||||
service._logging.logger.info(
|
||||
'quick_run_retention removed=%s removed_bytes=%s skipped=%s',
|
||||
@@ -58,7 +57,7 @@ def execute_batch(
|
||||
)
|
||||
task = service._store.get_task(task_id)
|
||||
projects = service._store.list_projects(task_id)
|
||||
rules = service._store.list_rules(task_id)
|
||||
rules = service._execution_rules(task_id)
|
||||
progress = preparer.progress(task_id, projects, rules, copy_part_number_to_value=task.copy_part_number_to_value)
|
||||
mode = 'part_label' if task.copy_part_number_to_value else 'preserve'
|
||||
actual = (str(progress.next_project_path), progress.next_old_part_number, progress.next_new_part_number, mode)
|
||||
@@ -67,118 +66,26 @@ def execute_batch(
|
||||
return BatchRunResult(progress, False)
|
||||
if expected_item is None or actual != expected_item:
|
||||
raise TaskCenterError('quick_run_selection_changed', '队列起点或 Value 选项发生变化,请重新确认。')
|
||||
if (preparer._data_root / 'quick-run/uncertain.flag').exists():
|
||||
if (preparer.data_root / 'quick-run/uncertain.flag').exists():
|
||||
raise TaskCenterError('quick_run_uncertain', '队列存在待核验步骤,不能绕过保护开始批量执行。')
|
||||
if task.status is TaskStatus.PAUSED and not stop_event.is_set():
|
||||
service._store.set_task_status(task_id, TaskStatus.RUNNING, summary='automatic queue resumed after confirmation')
|
||||
session = preparer.begin_batch_session(
|
||||
task_id,
|
||||
projects,
|
||||
rules,
|
||||
copy_part_number_to_value=task.copy_part_number_to_value,
|
||||
)
|
||||
with measure_phase(service._logging, task_id, 'prepare_queue', unit='step') as metric:
|
||||
session = preparer.begin_batch_session(
|
||||
task_id,
|
||||
projects,
|
||||
rules,
|
||||
copy_part_number_to_value=task.copy_part_number_to_value,
|
||||
)
|
||||
metric['completed_units'] = len(session.commands)
|
||||
initial_progress = progress
|
||||
progress = session.progress
|
||||
backup_root = session.handoff.command_path.parent
|
||||
backup_state_path = backup_root / _BACKUP_STATE_NAME
|
||||
backup_state = _read_backup_state(backup_state_path, task_id)
|
||||
backed_up_roots = {
|
||||
root_key
|
||||
for root_key, entry in backup_state.items()
|
||||
if entry.get('status') == 'backed_up' and _reusable_backup(backup_root, root_key, entry)
|
||||
}
|
||||
unbacked_project_paths: list[Path] = [
|
||||
Path(str(entry['project_path']))
|
||||
for entry in backup_state.values()
|
||||
if entry.get('status') == 'unbacked' and entry.get('project_path')
|
||||
]
|
||||
backups = BatchBackupCoordinator(service, task_id, session, projects,
|
||||
continue_after_failure=continue_after_backup_failure,
|
||||
backup=_backup_project_root, write_state=_write_backup_state)
|
||||
last_result = None
|
||||
item_messages: list[str] = []
|
||||
|
||||
def backup_destination(root_key: str) -> Path:
|
||||
return backup_root / _BACKUP_DIRECTORY_NAME / f'project-{_backup_key(root_key)}'
|
||||
|
||||
def record_backup_failure(project_path: Path, root_key: str, destination: Path, error: TaskCenterError) -> None:
|
||||
backup_state[root_key] = {
|
||||
'status': 'unbacked',
|
||||
'project_path': str(project_path),
|
||||
'destination': str(destination.relative_to(backup_root)),
|
||||
'error_id': error.error_id,
|
||||
'error': error.message,
|
||||
}
|
||||
_write_backup_state(backup_state_path, task_id, backup_state)
|
||||
if not continue_after_backup_failure:
|
||||
raise error
|
||||
if project_path not in unbacked_project_paths:
|
||||
unbacked_project_paths.append(project_path)
|
||||
service._batch_feedback = (task_id, progress, f'备份失败已按确认跳过:{project_path.name}')
|
||||
append_task_event(
|
||||
service._logging,
|
||||
level='WARNING',
|
||||
task_id=task_id,
|
||||
operation='quick_run_backup_override',
|
||||
message='操作员明确确认在原理图精简备份失败后继续当前队列。',
|
||||
error_id=error.error_id,
|
||||
details={
|
||||
'state': 'continued_without_backup',
|
||||
'project_path': str(project_path),
|
||||
'backup_error': error.message,
|
||||
'rollback_available': False,
|
||||
},
|
||||
)
|
||||
|
||||
def record_backup_success(project_path: Path, root_key: str, destination: Path) -> None:
|
||||
backup_state[root_key] = {
|
||||
'status': 'backed_up',
|
||||
'project_path': str(project_path),
|
||||
'destination': str(destination.relative_to(backup_root)),
|
||||
}
|
||||
_write_backup_state(backup_state_path, task_id, backup_state)
|
||||
backed_up_roots.add(root_key)
|
||||
|
||||
def backup_project(project_path: Path) -> None:
|
||||
root_key = _path_key(project_path.resolve(strict=False).parent)
|
||||
if root_key in backed_up_roots:
|
||||
return
|
||||
previous = backup_state.get(root_key)
|
||||
if previous is not None and previous.get('status') == 'unbacked':
|
||||
if not continue_after_backup_failure:
|
||||
raise TaskCenterError(
|
||||
'quick_run_backup',
|
||||
f"工程此前备份失败,尚未建立可用回滚副本:{project_path};请排除原因后重试,或明确确认忽略备份失败。",
|
||||
error_id=str(previous.get('error_id') or '') or None,
|
||||
)
|
||||
if project_path not in unbacked_project_paths:
|
||||
unbacked_project_paths.append(project_path)
|
||||
backed_up_roots.add(root_key)
|
||||
return
|
||||
service._batch_feedback = (task_id, progress, f'正在备份 {project_path.name}')
|
||||
destination = backup_destination(root_key)
|
||||
try:
|
||||
_backup_project_root(
|
||||
preparer._data_root,
|
||||
project_path,
|
||||
destination,
|
||||
)
|
||||
except TaskCenterError as error:
|
||||
if error.code != 'quick_run_backup':
|
||||
raise
|
||||
record_backup_failure(project_path, root_key, destination, error)
|
||||
else:
|
||||
record_backup_success(project_path, root_key, destination)
|
||||
backed_up_roots.add(root_key)
|
||||
|
||||
def next_backup_candidate(start_index: int, active_root_key: str) -> tuple[Path, str] | None:
|
||||
for command in session.commands[start_index:]:
|
||||
state = session.latest.get(command[1])
|
||||
if state is not None and state[0] in TERMINAL_STATES:
|
||||
continue
|
||||
project_path = Path(command[2])
|
||||
root_key = _path_key(project_path.resolve(strict=False).parent)
|
||||
if root_key == active_root_key or root_key in backed_up_roots or root_key in backup_state:
|
||||
continue
|
||||
return project_path, root_key
|
||||
return None
|
||||
project_ids = {_path_key(project.path): project.project_id for project in projects}
|
||||
|
||||
if session.progress.completed_items > initial_progress.completed_items:
|
||||
discovered_no_match = session.progress.completed_items - initial_progress.completed_items
|
||||
@@ -206,64 +113,46 @@ def execute_batch(
|
||||
)
|
||||
else:
|
||||
progress = session.progress
|
||||
prefetched_backup: tuple[Path, str, Path, Future[None]] | None = None
|
||||
|
||||
def commit_prefetched_backup() -> None:
|
||||
nonlocal prefetched_backup
|
||||
if prefetched_backup is None:
|
||||
return
|
||||
project_path, root_key, destination, future = prefetched_backup
|
||||
try:
|
||||
future.result()
|
||||
except TaskCenterError as error:
|
||||
if error.code != 'quick_run_backup':
|
||||
raise
|
||||
record_backup_failure(project_path, root_key, destination, error)
|
||||
else:
|
||||
record_backup_success(project_path, root_key, destination)
|
||||
prefetched_backup = None
|
||||
|
||||
with ThreadPoolExecutor(max_workers=1, thread_name_prefix='dxpart-backup') as backup_executor:
|
||||
with backups, preparer.project_session_scope(enabled=reuse_project_session) as project_session:
|
||||
while not progress.queue_complete:
|
||||
if stop_event.is_set():
|
||||
commit_prefetched_backup()
|
||||
backups.commit_prefetched(progress)
|
||||
return BatchRunResult(
|
||||
progress, True, last_result, tuple(item_messages), tuple(unbacked_project_paths)
|
||||
progress, True, last_result, tuple(item_messages), tuple(backups.unbacked_project_paths)
|
||||
)
|
||||
current = progress.next_project_path
|
||||
if current is None:
|
||||
raise TaskCenterError('quick_run_queue_progress', '队列未结束但找不到下一项,已停止。')
|
||||
root_key = _path_key(current.resolve(strict=False).parent)
|
||||
if root_key not in backed_up_roots:
|
||||
if prefetched_backup is not None and prefetched_backup[1] == root_key:
|
||||
service._batch_feedback = (task_id, progress, f'正在确认预备份 {current.name}')
|
||||
commit_prefetched_backup()
|
||||
else:
|
||||
service._batch_feedback = (task_id, progress, f'正在备份 {current.name}')
|
||||
backup_project(current)
|
||||
if prefetched_backup is None:
|
||||
next_backup = next_backup_candidate(session.next_index + 1, root_key)
|
||||
if next_backup is not None:
|
||||
project_path, next_root_key = next_backup
|
||||
destination = backup_destination(next_root_key)
|
||||
future = backup_executor.submit(
|
||||
_backup_project_root,
|
||||
preparer._data_root,
|
||||
project_path,
|
||||
destination,
|
||||
)
|
||||
prefetched_backup = (project_path, next_root_key, destination, future)
|
||||
current_key = _path_key(current)
|
||||
project_session.prepare(current)
|
||||
backups.prepare(current, progress)
|
||||
service._batch_feedback = (task_id, progress, f'正在处理 {current.name}')
|
||||
if stop_event.is_set():
|
||||
commit_prefetched_backup()
|
||||
backups.commit_prefetched(progress)
|
||||
return BatchRunResult(
|
||||
progress, True, last_result, tuple(item_messages), tuple(unbacked_project_paths)
|
||||
progress, True, last_result, tuple(item_messages), tuple(backups.unbacked_project_paths)
|
||||
)
|
||||
expected = (str(current), progress.next_old_part_number, progress.next_new_part_number, mode)
|
||||
sheet = f'{progress.next_schematic_name}:{progress.next_sheet_number}' if progress.next_schematic_name else '当前图页'
|
||||
service._batch_feedback = (task_id, progress, f'正在执行 {current.name} | {sheet}:{expected[1]} → {expected[2]}')
|
||||
last_result = preparer.execute_step(task_id, projects, rules, copy_part_number_to_value=task.copy_part_number_to_value,
|
||||
expected_item=expected, batch_mode=True, batch_session=session)
|
||||
with measure_phase(service._logging, task_id, 'execute_step', unit='step', persist=False,
|
||||
project_path=str(current), schematic_name=progress.next_schematic_name,
|
||||
sheet_number=progress.next_sheet_number, old_part_number=expected[1],
|
||||
new_part_number=expected[2], job_id=session.commands[session.next_index][1]) as metric:
|
||||
try:
|
||||
last_result = preparer.execute_step(task_id, projects, rules, copy_part_number_to_value=task.copy_part_number_to_value,
|
||||
expected_item=expected, batch_mode=True, batch_session=session,
|
||||
**({'project_session': project_session} if project_session.enabled else {}))
|
||||
metric['state'] = last_result.state
|
||||
metric['completed_units'] = int(last_result.state in {'saved_ok', 'restored_ok', 'no_match'})
|
||||
finally:
|
||||
worker_progress = session.handoff.command_path.parent / 'worker-progress.json'
|
||||
try:
|
||||
native = json.loads(worker_progress.read_text(encoding='utf-8'))
|
||||
if isinstance(native, dict) and native.get('job_id') == metric['job_id']:
|
||||
metric['worker_stage_seconds'] = native.get('stage_seconds', {})
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
if 'NC synced:' in last_result.message or last_result.state in {
|
||||
BATCH_FAILED_STATE,
|
||||
BATCH_SAVED_UNVERIFIED_STATE,
|
||||
@@ -279,100 +168,51 @@ def execute_batch(
|
||||
or candidate.queue_complete
|
||||
or last_result.state in {BATCH_FAILED_STATE, BATCH_SAVED_UNVERIFIED_STATE}
|
||||
)
|
||||
updated = service._synchronize_quick_run_progress(task_id, progress=candidate) if synchronize else candidate
|
||||
if synchronize:
|
||||
with measure_phase(service._logging, task_id, 'persist_progress', job_id=metric['job_id']) as persistence:
|
||||
updated = service._synchronize_quick_run_progress(task_id, progress=candidate)
|
||||
persistence['completed_units'] = 1
|
||||
else:
|
||||
updated = candidate
|
||||
if updated.completed_items <= progress.completed_items or updated.total_items != progress.total_items:
|
||||
_write_uncertain_flag(preparer._data_root / 'quick-run/uncertain.flag', 'batch_progress_mismatch')
|
||||
_write_uncertain_flag(preparer.data_root / 'quick-run/uncertain.flag', 'batch_progress_mismatch')
|
||||
raise TaskCenterError('quick_run_queue_progress', '执行器返回后队列进度异常,已停止,避免重复执行。')
|
||||
if project_completed or updated.queue_complete or last_result.state in {
|
||||
# Keep every verified step: one project can contain many sheets and rules.
|
||||
project_id = project_ids.get(current_key)
|
||||
event_level = 'WARNING' if last_result.state in {
|
||||
BATCH_FAILED_STATE,
|
||||
BATCH_SAVED_UNVERIFIED_STATE,
|
||||
}:
|
||||
project_id = next(
|
||||
(project.project_id for project in projects if _path_key(project.path) == _path_key(current)),
|
||||
None,
|
||||
)
|
||||
event_level = 'WARNING' if last_result.state in {
|
||||
BATCH_FAILED_STATE,
|
||||
BATCH_SAVED_UNVERIFIED_STATE,
|
||||
} else 'INFO'
|
||||
append_task_event(service._logging, level=event_level,
|
||||
task_id=task_id, project_id=project_id, operation='quick_run_executed', message=last_result.message,
|
||||
details={'state': last_result.state, 'continue_queue': not updated.queue_complete,
|
||||
'completed_items': updated.completed_items, 'total_items': updated.total_items,
|
||||
'completed_projects': len(updated.completed_project_paths)})
|
||||
} else 'INFO'
|
||||
append_task_event(service._logging, level=event_level,
|
||||
task_id=task_id, project_id=project_id, operation='quick_run_executed', message=last_result.message,
|
||||
details={'state': last_result.state, 'continue_queue': not updated.queue_complete,
|
||||
'timing': metric,
|
||||
'project_path': str(current),
|
||||
'schematic_name': progress.next_schematic_name,
|
||||
'sheet_number': progress.next_sheet_number,
|
||||
'old_part_number': expected[1], 'new_part_number': expected[2],
|
||||
'completed_items': updated.completed_items, 'total_items': updated.total_items,
|
||||
'completed_projects': len(updated.completed_project_paths)})
|
||||
service._logging.logger.info('quick_run_batch_item task_id=%s state=%s completed=%s total=%s',
|
||||
task_id, last_result.state, updated.completed_items, updated.total_items)
|
||||
progress = updated
|
||||
if last_result.state == BATCH_SAVED_UNVERIFIED_STATE:
|
||||
_write_uncertain_flag(preparer.data_root / 'quick-run/uncertain.flag',
|
||||
'saved_readback_unverified')
|
||||
service._batch_feedback = (task_id, progress, '保存后回读未通过,队列已停止,请核验工程。')
|
||||
return BatchRunResult(progress, True, last_result, tuple(item_messages),
|
||||
tuple(backups.unbacked_project_paths))
|
||||
feedback = '未命中已跳过,继续下一项' if last_result.state == 'no_match' else (
|
||||
'已保存但回读校验失败,已记录,继续下一项'
|
||||
if last_result.state == BATCH_SAVED_UNVERIFIED_STATE
|
||||
else '失败已记录,继续下一项'
|
||||
'失败已记录,继续下一项'
|
||||
if last_result.state == BATCH_FAILED_STATE
|
||||
else '已保存并校验,继续下一项'
|
||||
)
|
||||
service._batch_feedback = (task_id, progress, feedback)
|
||||
return BatchRunResult(
|
||||
progress, False, last_result, tuple(item_messages), tuple(unbacked_project_paths)
|
||||
progress, False, last_result, tuple(item_messages), tuple(backups.unbacked_project_paths)
|
||||
)
|
||||
|
||||
|
||||
def _backup_key(root_key: str) -> str:
|
||||
return hashlib.sha256(root_key.encode('utf-8')).hexdigest()[:16]
|
||||
|
||||
|
||||
def _read_backup_state(path: Path, task_id: str) -> dict[str, dict[str, object]]:
|
||||
if not path.is_file():
|
||||
return {}
|
||||
try:
|
||||
payload = json.loads(path.read_text(encoding='utf-8'))
|
||||
if not isinstance(payload, dict) or payload.get('format_version') != 1 or payload.get('task_id') != task_id:
|
||||
raise ValueError('backup state does not belong to the current queue')
|
||||
projects = payload.get('projects')
|
||||
if not isinstance(projects, dict):
|
||||
raise ValueError('backup state projects are invalid')
|
||||
return {
|
||||
str(root_key): dict(entry)
|
||||
for root_key, entry in projects.items()
|
||||
if isinstance(entry, dict) and entry.get('status') in {'backed_up', 'unbacked'}
|
||||
}
|
||||
except (OSError, UnicodeError, json.JSONDecodeError, ValueError) as error:
|
||||
raise TaskCenterError('quick_run_backup', '当前队列的备份状态文件无效,已停止以避免重复或错误覆盖。') from error
|
||||
|
||||
|
||||
def _write_backup_state(path: Path, task_id: str, projects: dict[str, dict[str, object]]) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = path.with_name(f'.{path.name}.{uuid4().hex}.tmp')
|
||||
payload = {'format_version': 1, 'task_id': task_id, 'projects': projects}
|
||||
try:
|
||||
with temporary.open('w', encoding='utf-8', newline='\n') as stream:
|
||||
json.dump(payload, stream, ensure_ascii=False, indent=2)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, path)
|
||||
except OSError as error:
|
||||
temporary.unlink(missing_ok=True)
|
||||
raise TaskCenterError('quick_run_backup', '无法保存队列备份状态,已停止以避免重复执行。') from error
|
||||
|
||||
|
||||
def _reusable_backup(backup_root: Path, root_key: str, entry: dict[str, object]) -> bool:
|
||||
destination = backup_root / str(entry.get('destination') or '')
|
||||
manifest = destination / '.dxpartreplace-backup.json'
|
||||
if not manifest.is_file() or str(entry.get('destination') or '').replace('\\', '/') != (
|
||||
f'{_BACKUP_DIRECTORY_NAME}/project-{_backup_key(root_key)}'
|
||||
):
|
||||
return False
|
||||
try:
|
||||
payload = json.loads(manifest.read_text(encoding='utf-8'))
|
||||
return (
|
||||
isinstance(payload, dict)
|
||||
and payload.get('format_version') == 1
|
||||
and payload.get('scope') == 'dxdesigner_schematic_essentials'
|
||||
and isinstance(payload.get('files'), list)
|
||||
)
|
||||
except (OSError, UnicodeError, json.JSONDecodeError):
|
||||
return False
|
||||
|
||||
|
||||
def _backup_project_root(data_root: Path, project_path: Path, destination: Path) -> None:
|
||||
last_error: OSError | None = None
|
||||
for attempt in range(3):
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
"""Durable backup coordination and one-project prefetch for serial CAD queues."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .execution_metrics import measure_phase
|
||||
from .logging_setup import append_task_event
|
||||
from .quick_run import TERMINAL_STATES, _path_key
|
||||
|
||||
_BACKUP_STATE_NAME = 'batch-backups.json'
|
||||
_BACKUP_DIRECTORY_NAME = 'batch-backups'
|
||||
|
||||
|
||||
class BatchBackupCoordinator:
|
||||
"""Publish backup outcomes on the queue thread before allowing CAD work.
|
||||
|
||||
Only file copying runs in the prefetch thread. Durable state, failure policy
|
||||
and operator feedback remain on the serial queue thread.
|
||||
"""
|
||||
def __init__(self, service, task_id, session, projects, *, continue_after_failure,
|
||||
backup, write_state):
|
||||
self.service = service
|
||||
self.task_id = task_id
|
||||
self.session = session
|
||||
self.data_root = service._quick_run_preparer.data_root
|
||||
self.root = session.handoff.command_path.parent
|
||||
self.state_path = self.root / _BACKUP_STATE_NAME
|
||||
self.state = _read_backup_state(self.state_path, task_id)
|
||||
self.backed_up_roots = {
|
||||
key for key, entry in self.state.items()
|
||||
if entry.get('status') == 'backed_up' and _reusable_backup(self.root, key, entry)
|
||||
}
|
||||
self.unbacked_project_paths = [Path(str(entry['project_path']))
|
||||
for entry in self.state.values()
|
||||
if entry.get('status') == 'unbacked' and entry.get('project_path')]
|
||||
self.project_root_keys = {_path_key(project.path):
|
||||
_path_key(project.path.resolve(strict=False).parent) for project in projects}
|
||||
self.continue_after_failure = continue_after_failure
|
||||
self._backup = backup
|
||||
self._write_state = write_state
|
||||
self._search_exhausted = False
|
||||
self._prefetched = None
|
||||
self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix='dxpart-backup')
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
# Match the queue's original executor boundary: wait for copying even
|
||||
# when CAD fails, without publishing an unconsumed speculative result.
|
||||
self._executor.shutdown(wait=True)
|
||||
|
||||
def _destination(self, root_key):
|
||||
return self.root / _BACKUP_DIRECTORY_NAME / f'project-{_backup_key(root_key)}'
|
||||
|
||||
def perform_backup(self, project_path, destination):
|
||||
with measure_phase(self.service._logging, self.task_id, 'backup_project',
|
||||
project_path=str(project_path)) as metric:
|
||||
self._backup(self.data_root, project_path, destination)
|
||||
metric['completed_units'] = 1
|
||||
|
||||
def _failure(self, project_path, root_key, destination, error, progress):
|
||||
self.state[root_key] = {
|
||||
'status': 'unbacked', 'project_path': str(project_path),
|
||||
'destination': str(destination.relative_to(self.root)),
|
||||
'error_id': error.error_id, 'error': error.message,
|
||||
}
|
||||
self._write_state(self.state_path, self.task_id, self.state)
|
||||
if not self.continue_after_failure:
|
||||
raise error
|
||||
if project_path not in self.unbacked_project_paths:
|
||||
self.unbacked_project_paths.append(project_path)
|
||||
self.service._batch_feedback = (self.task_id, progress, f'备份失败已按确认跳过:{project_path.name}')
|
||||
append_task_event(self.service._logging, level='WARNING', task_id=self.task_id,
|
||||
operation='quick_run_backup_override',
|
||||
message='操作员明确确认在原理图精简备份失败后继续当前队列。', error_id=error.error_id,
|
||||
details={'state': 'continued_without_backup', 'project_path': str(project_path),
|
||||
'backup_error': error.message, 'rollback_available': False})
|
||||
|
||||
def _success(self, project_path, root_key, destination):
|
||||
self.state[root_key] = {
|
||||
'status': 'backed_up', 'project_path': str(project_path),
|
||||
'destination': str(destination.relative_to(self.root)),
|
||||
}
|
||||
self._write_state(self.state_path, self.task_id, self.state)
|
||||
self.backed_up_roots.add(root_key)
|
||||
|
||||
def _backup_project(self, project_path, progress):
|
||||
root_key = self.project_root_keys[_path_key(project_path)]
|
||||
if root_key in self.backed_up_roots:
|
||||
return
|
||||
previous = self.state.get(root_key)
|
||||
if previous is not None and previous.get('status') == 'unbacked':
|
||||
if not self.continue_after_failure:
|
||||
raise TaskCenterError('quick_run_backup',
|
||||
f"工程此前备份失败,尚未建立可用回滚副本:{project_path};请排除原因后重试,或明确确认忽略备份失败。",
|
||||
error_id=str(previous.get('error_id') or '') or None)
|
||||
if project_path not in self.unbacked_project_paths:
|
||||
self.unbacked_project_paths.append(project_path)
|
||||
self.backed_up_roots.add(root_key)
|
||||
return
|
||||
self.service._batch_feedback = (self.task_id, progress, f'正在备份 {project_path.name}')
|
||||
destination = self._destination(root_key)
|
||||
try:
|
||||
self.perform_backup(project_path, destination)
|
||||
except TaskCenterError as error:
|
||||
if error.code != 'quick_run_backup':
|
||||
raise
|
||||
self._failure(project_path, root_key, destination, error, progress)
|
||||
else:
|
||||
self._success(project_path, root_key, destination)
|
||||
self.backed_up_roots.add(root_key)
|
||||
|
||||
def _next_candidate(self, start_index, active_root_key):
|
||||
if self._search_exhausted:
|
||||
return None
|
||||
for command in self.session.commands[start_index:]:
|
||||
state = self.session.latest.get(command[1])
|
||||
if state is not None and state[0] in TERMINAL_STATES:
|
||||
continue
|
||||
project_path = Path(command[2])
|
||||
root_key = self.project_root_keys[_path_key(project_path)]
|
||||
if root_key == active_root_key or root_key in self.backed_up_roots or root_key in self.state:
|
||||
continue
|
||||
return project_path, root_key
|
||||
self._search_exhausted = True
|
||||
return None
|
||||
|
||||
def commit_prefetched(self, progress):
|
||||
if self._prefetched is None:
|
||||
return
|
||||
project_path, root_key, destination, future = self._prefetched
|
||||
try:
|
||||
future.result()
|
||||
except TaskCenterError as error:
|
||||
if error.code != 'quick_run_backup':
|
||||
raise
|
||||
self._failure(project_path, root_key, destination, error, progress)
|
||||
else:
|
||||
self._success(project_path, root_key, destination)
|
||||
self._prefetched = None
|
||||
|
||||
def prepare(self, current, progress):
|
||||
"""Confirm current backup, then prefetch at most one other project root."""
|
||||
root_key = self.project_root_keys[_path_key(current)]
|
||||
if root_key not in self.backed_up_roots:
|
||||
if self._prefetched is not None and self._prefetched[1] == root_key:
|
||||
self.service._batch_feedback = (self.task_id, progress, f'正在确认预备份 {current.name}')
|
||||
self.commit_prefetched(progress)
|
||||
else:
|
||||
self.service._batch_feedback = (self.task_id, progress, f'正在备份 {current.name}')
|
||||
self._backup_project(current, progress)
|
||||
if self._prefetched is None:
|
||||
candidate = self._next_candidate(self.session.next_index + 1, root_key)
|
||||
if candidate is not None:
|
||||
project_path, next_root_key = candidate
|
||||
destination = self._destination(next_root_key)
|
||||
future = self._executor.submit(self.perform_backup, project_path, destination)
|
||||
self._prefetched = (project_path, next_root_key, destination, future)
|
||||
|
||||
|
||||
def _backup_key(root_key: str) -> str:
|
||||
return hashlib.sha256(root_key.encode('utf-8')).hexdigest()[:16]
|
||||
|
||||
|
||||
def _read_backup_state(path: Path, task_id: str) -> dict[str, dict[str, object]]:
|
||||
if not path.is_file():
|
||||
return {}
|
||||
try:
|
||||
payload = json.loads(path.read_text(encoding='utf-8'))
|
||||
if not isinstance(payload, dict) or payload.get('format_version') != 1 or payload.get('task_id') != task_id:
|
||||
raise ValueError('backup state does not belong to the current queue')
|
||||
projects = payload.get('projects')
|
||||
if not isinstance(projects, dict):
|
||||
raise ValueError('backup state projects are invalid')
|
||||
return {
|
||||
str(root_key): dict(entry)
|
||||
for root_key, entry in projects.items()
|
||||
if isinstance(entry, dict) and entry.get('status') in {'backed_up', 'unbacked'}
|
||||
}
|
||||
except (OSError, UnicodeError, json.JSONDecodeError, ValueError) as error:
|
||||
raise TaskCenterError('quick_run_backup', '当前队列的备份状态文件无效,已停止以避免重复或错误覆盖。') from error
|
||||
|
||||
|
||||
def _write_backup_state(path: Path, task_id: str, projects: dict[str, dict[str, object]]) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = path.with_name(f'.{path.name}.{uuid4().hex}.tmp')
|
||||
payload = {'format_version': 1, 'task_id': task_id, 'projects': projects}
|
||||
try:
|
||||
with temporary.open('w', encoding='utf-8', newline='\n') as stream:
|
||||
json.dump(payload, stream, ensure_ascii=False, indent=2)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, path)
|
||||
except OSError as error:
|
||||
temporary.unlink(missing_ok=True)
|
||||
raise TaskCenterError('quick_run_backup', '无法保存队列备份状态,已停止以避免重复执行。') from error
|
||||
|
||||
|
||||
def _reusable_backup(backup_root: Path, root_key: str, entry: dict[str, object]) -> bool:
|
||||
destination = backup_root / str(entry.get('destination') or '')
|
||||
manifest = destination / '.dxpartreplace-backup.json'
|
||||
if not manifest.is_file() or str(entry.get('destination') or '').replace('\\', '/') != (
|
||||
f'{_BACKUP_DIRECTORY_NAME}/project-{_backup_key(root_key)}'
|
||||
):
|
||||
return False
|
||||
try:
|
||||
payload = json.loads(manifest.read_text(encoding='utf-8'))
|
||||
return (
|
||||
isinstance(payload, dict)
|
||||
and payload.get('format_version') == 1
|
||||
and payload.get('scope') == 'dxdesigner_schematic_essentials'
|
||||
and isinstance(payload.get('files'), list)
|
||||
)
|
||||
except (OSError, UnicodeError, json.JSONDecodeError):
|
||||
return False
|
||||
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
"""Safe BOM-template import for one-to-many RefDes replacement plans."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from openpyxl import Workbook, load_workbook
|
||||
from openpyxl.styles import Font, PatternFill
|
||||
from openpyxl.worksheet.datavalidation import DataValidation
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .target_plan import TargetPlanRow, compile_target_rules
|
||||
|
||||
|
||||
BOM_HEADERS = ('old_part_number', 'new_part_number', 'refdes', 'schematic_name',
|
||||
'sheet_number', 'uid', 'enabled', 'custom_value', 'sync_nc')
|
||||
_REFDES_SPLIT = re.compile(r'[,,;;、\s]+')
|
||||
_ALIASES = {
|
||||
'旧料号': 'old_part_number', '旧物料编码': 'old_part_number', 'old_part': 'old_part_number',
|
||||
'新料号': 'new_part_number', '新物料编码': 'new_part_number', 'new_part': 'new_part_number',
|
||||
'位号': 'refdes', '参考标号': 'refdes', 'refdes': 'refdes', 'reference_designator': 'refdes',
|
||||
'原理图': 'schematic_name', 'schematic': 'schematic_name', '图页': 'sheet_number', 'sheet': 'sheet_number',
|
||||
'uid': 'uid', '替换': 'enabled', '是否替换': 'enabled', 'enabled': 'enabled',
|
||||
'新value': 'custom_value', '自定义value': 'custom_value', 'custom_value': 'custom_value',
|
||||
'同步nc': 'sync_nc', '同步_nc': 'sync_nc', 'sync_nc': 'sync_nc',
|
||||
}
|
||||
|
||||
|
||||
def write_bom_template(path: Path, records=()) -> Path:
|
||||
workbook = Workbook()
|
||||
sheet = workbook.active
|
||||
sheet.title = 'BOM Replacement'
|
||||
sheet.append(BOM_HEADERS)
|
||||
for record in records:
|
||||
sheet.append(tuple(record.get(header, '') for header in BOM_HEADERS))
|
||||
for cell in sheet[1]:
|
||||
cell.font = Font(bold=True, color='FFFFFF')
|
||||
cell.fill = PatternFill('solid', fgColor='1D3557')
|
||||
sheet.freeze_panes = 'A2'
|
||||
sheet.auto_filter.ref = sheet.dimensions
|
||||
for column in ('G', 'I'):
|
||||
validation = DataValidation(type='list', formula1='"TRUE,FALSE"', allow_blank=False)
|
||||
sheet.add_data_validation(validation)
|
||||
validation.add(f'{column}2:{column}{max(2, sheet.max_row + 500)}')
|
||||
for column, width in {'A': 22, 'B': 22, 'C': 28, 'D': 18, 'E': 14,
|
||||
'F': 28, 'G': 12, 'H': 24, 'I': 12}.items():
|
||||
sheet.column_dimensions[column].width = width
|
||||
path = Path(path)
|
||||
workbook.save(path)
|
||||
return path
|
||||
|
||||
|
||||
def read_bom_plan(store, task_id: str, path: Path) -> tuple[TargetPlanRow, ...]:
|
||||
baseline = store.list_target_plan(task_id)
|
||||
if not baseline:
|
||||
raise TaskCenterError('target_inventory', 'collect component inventory before importing a BOM')
|
||||
by_key = {row.target.key: row for row in baseline}
|
||||
by_identity: dict[tuple[str, str], list[TargetPlanRow]] = {}
|
||||
for row in baseline:
|
||||
by_identity.setdefault((row.target.old_part_number.casefold(), row.target.refdes.casefold()), []).append(row)
|
||||
matched: dict[tuple[str, str, str, str], TargetPlanRow] = {}
|
||||
workbook = None
|
||||
try:
|
||||
workbook = load_workbook(Path(path), read_only=True, data_only=False)
|
||||
if len(workbook.worksheets) != 1:
|
||||
raise ValueError('BOM 工作簿只能包含一个工作表')
|
||||
sheet = workbook.active
|
||||
records = list(sheet.iter_rows(values_only=False))
|
||||
if not records:
|
||||
raise ValueError('BOM 工作表为空')
|
||||
headers = _normal_headers(tuple(cell.value for cell in records[0]))
|
||||
required = {'old_part_number', 'new_part_number', 'refdes'}
|
||||
if not required <= set(headers):
|
||||
raise ValueError('BOM 必须包含旧料号、新料号和位号列')
|
||||
positions = {name: index for index, name in enumerate(headers) if name}
|
||||
for cells in records[1:]:
|
||||
values = tuple(cell.value for cell in cells)
|
||||
if not any(value not in (None, '') for value in values):
|
||||
continue
|
||||
if any(cell.data_type == 'f' for cell in cells):
|
||||
raise ValueError('BOM 不接受公式,请填写实际值')
|
||||
old = _text(values, positions, 'old_part_number')
|
||||
new = _text(values, positions, 'new_part_number')
|
||||
refs = _split_refdes(_text(values, positions, 'refdes'))
|
||||
if not old or not new or not refs:
|
||||
raise ValueError('BOM 行的旧料号、新料号和位号不能为空')
|
||||
enabled = _bool(_value(values, positions, 'enabled', True))
|
||||
sync_nc = _bool(_value(values, positions, 'sync_nc', True))
|
||||
custom = _text(values, positions, 'custom_value')
|
||||
schematic = _text(values, positions, 'schematic_name')
|
||||
sheet_number = _text(values, positions, 'sheet_number')
|
||||
uid = _text(values, positions, 'uid')
|
||||
for refdes in refs:
|
||||
candidates = [row for row in by_identity.get((old.casefold(), refdes.casefold()), ())
|
||||
if (not schematic or row.target.schematic_name.casefold() == schematic.casefold())
|
||||
and (not sheet_number or row.target.sheet_number.casefold() == sheet_number.casefold())
|
||||
and (not uid or row.target.uid == uid)]
|
||||
if len(candidates) != 1:
|
||||
raise ValueError(f'位号 {refdes} 无法唯一匹配当前采集清单')
|
||||
target = candidates[0].target
|
||||
if target.key in matched:
|
||||
raise ValueError(f'位号 {refdes} 在 BOM 中重复')
|
||||
matched[target.key] = TargetPlanRow(target, enabled, new, bool(custom), custom, sync_nc)
|
||||
result = tuple(matched.get(key, TargetPlanRow(row.target)) for key, row in by_key.items())
|
||||
compile_target_rules(result)
|
||||
return result
|
||||
except (OSError, ValueError, TypeError, KeyError) as error:
|
||||
if isinstance(error, TaskCenterError):
|
||||
raise
|
||||
raise TaskCenterError('bom_import', str(error)) from error
|
||||
finally:
|
||||
if workbook is not None:
|
||||
workbook.close()
|
||||
|
||||
|
||||
def _normal_headers(values):
|
||||
result = []
|
||||
for value in values:
|
||||
raw = str(value or '').strip().casefold().replace(' ', '').replace('-', '_')
|
||||
result.append(raw if raw in BOM_HEADERS else _ALIASES.get(raw, ''))
|
||||
return tuple(result)
|
||||
|
||||
|
||||
def _value(values, positions, name, default=''):
|
||||
index = positions.get(name)
|
||||
if index is None or index >= len(values) or values[index] in (None, ''):
|
||||
return default
|
||||
return values[index]
|
||||
|
||||
|
||||
def _text(values, positions, name):
|
||||
value = _value(values, positions, name, '')
|
||||
return '' if value is None else str(value).strip()
|
||||
|
||||
|
||||
def _split_refdes(value):
|
||||
return tuple(item for item in _REFDES_SPLIT.split(value.strip()) if item)
|
||||
|
||||
|
||||
def _bool(value):
|
||||
if type(value) is bool:
|
||||
return value
|
||||
if isinstance(value, (int, float)) and value in (0, 1):
|
||||
return bool(value)
|
||||
if isinstance(value, str) and value.strip().casefold() in {'true', '是', '1', 'yes', 'y'}:
|
||||
return True
|
||||
if isinstance(value, str) and value.strip().casefold() in {'false', '否', '0', 'no', 'n', ''}:
|
||||
return False
|
||||
raise ValueError('BOM 布尔字段只能填写 TRUE/FALSE 或 是/否')
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Identity certificate shared by the private desktop worker and native helper."""
|
||||
from dataclasses import dataclass
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
import os
|
||||
import re
|
||||
|
||||
|
||||
def current_desktop_name():
|
||||
user = ctypes.WinDLL('user32', use_last_error=True)
|
||||
kernel = ctypes.WinDLL('kernel32', use_last_error=True)
|
||||
user.GetThreadDesktop.argtypes = [wintypes.DWORD]
|
||||
user.GetThreadDesktop.restype = wintypes.HANDLE
|
||||
user.GetUserObjectInformationW.argtypes = [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p,
|
||||
wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)]
|
||||
desktop = user.GetThreadDesktop(kernel.GetCurrentThreadId())
|
||||
value, required = ctypes.create_unicode_buffer(256), wintypes.DWORD()
|
||||
if not user.GetUserObjectInformationW(desktop, 2, value, ctypes.sizeof(value), ctypes.byref(required)):
|
||||
raise ctypes.WinError(ctypes.get_last_error())
|
||||
return value.value
|
||||
|
||||
|
||||
def window_pid(handle):
|
||||
import win32process
|
||||
return win32process.GetWindowThreadProcessId(handle)[1]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class CadBinding:
|
||||
desktop: str
|
||||
pid: int
|
||||
guid: str
|
||||
token: str
|
||||
|
||||
@classmethod
|
||||
def from_environment(cls, environment=None):
|
||||
environment = os.environ if environment is None else environment
|
||||
fields = ('DXPART_DESKTOP', 'DXPART_CAD_PID', 'DXPART_CAD_GUID', 'DXPART_SESSION_TOKEN')
|
||||
values = [environment.get(field, '') for field in fields]
|
||||
if not any(values):
|
||||
return None
|
||||
if not all(values):
|
||||
raise ValueError('incomplete private CAD identity')
|
||||
desktop, pid, guid, token = values
|
||||
if not re.fullmatch(r'dx-[A-Za-z0-9-]{1,80}', desktop) or int(pid) <= 0:
|
||||
raise ValueError('invalid private CAD desktop or PID')
|
||||
if not re.fullmatch(r'[0-9a-f]{32}', token):
|
||||
raise ValueError('invalid private CAD session token')
|
||||
return cls(desktop, int(pid), guid, token)
|
||||
|
||||
def environment(self):
|
||||
return dict(os.environ, DXPART_DESKTOP=self.desktop, DXPART_CAD_PID=str(self.pid),
|
||||
DXPART_CAD_GUID=self.guid, DXPART_SESSION_TOKEN=self.token)
|
||||
|
||||
|
||||
def verify_application(app, binding=None, *, require_view=True):
|
||||
binding = CadBinding.from_environment() if binding is None else binding
|
||||
if binding is None:
|
||||
return None
|
||||
if current_desktop_name() != binding.desktop:
|
||||
raise ValueError('CAD helper is not running on its owned desktop')
|
||||
if str(app.Guid()).casefold() != binding.guid.casefold():
|
||||
raise ValueError('CAD COM GUID does not match its owned session')
|
||||
if require_view:
|
||||
handle = int(app.ActiveViewHandle)
|
||||
if not handle or window_pid(handle) != binding.pid:
|
||||
raise ValueError('CAD view PID does not match its owned session')
|
||||
return binding
|
||||
@@ -0,0 +1,142 @@
|
||||
"""Conservative, bounded process-local reuse of read-only CAD discovery.
|
||||
|
||||
Content and metadata fingerprints cover every project-tree file except generated
|
||||
logs and explicit tool data. Links, unreadable paths and changing discovery are misses.
|
||||
This is an optimization, never a replacement for execution identity checks.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import OrderedDict
|
||||
from copy import deepcopy
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import stat
|
||||
from threading import RLock
|
||||
|
||||
from .errors import TaskCenterError
|
||||
|
||||
|
||||
def project_fingerprint(project: Path, excluded_root: Path) -> tuple | None:
|
||||
try:
|
||||
project = Path(project).absolute()
|
||||
root = project.parent
|
||||
excluded = excluded_root.resolve()
|
||||
if _unsafe(root.lstat()):
|
||||
return None
|
||||
# A project inside the evidence directory cannot be safely excluded.
|
||||
if project.resolve().is_relative_to(excluded):
|
||||
return None
|
||||
rows = []
|
||||
def fail(error):
|
||||
raise error
|
||||
for current, dirs, files in os.walk(root, onerror=fail, followlinks=False):
|
||||
current = Path(current)
|
||||
kept = []
|
||||
for name in sorted(dirs):
|
||||
path = current / name
|
||||
relative = tuple(part.casefold() for part in path.relative_to(root).parts)
|
||||
audit_directory = (len(relative) == 3 and relative[:2] == ('database', 'cdbsvr')
|
||||
and relative[2] in {'log', 'plog', 'events'})
|
||||
if path.resolve() == excluded or name.casefold() == '.git' or audit_directory:
|
||||
continue
|
||||
info = path.lstat()
|
||||
if _unsafe(info):
|
||||
return None
|
||||
kept.append(name)
|
||||
dirs[:] = kept
|
||||
for name in sorted(files):
|
||||
path = current / name
|
||||
if path.suffix.casefold() == '.log':
|
||||
continue
|
||||
info = path.lstat()
|
||||
if _unsafe(info) or not stat.S_ISREG(info.st_mode):
|
||||
return None
|
||||
before = _file_stamp(info)
|
||||
with path.open('rb') as stream:
|
||||
handle_before = _file_stamp(os.fstat(stream.fileno()))
|
||||
# Windows path stat and handle stat expose different ctime
|
||||
# semantics. Compare their identity/size/mtime, then compare
|
||||
# each source's full stamp against itself after hashing.
|
||||
if handle_before[:4] != before[:4]:
|
||||
return None
|
||||
digest = hashlib.file_digest(stream, 'sha256').digest()
|
||||
if _file_stamp(os.fstat(stream.fileno())) != handle_before:
|
||||
return None
|
||||
# Check the path as well as the handle: atomic replacement can
|
||||
# leave a readable handle referring to the obsolete file.
|
||||
after = path.lstat()
|
||||
if _unsafe(after) or _file_stamp(after) != before:
|
||||
return None
|
||||
rows.append((str(path.relative_to(root)), *before, digest))
|
||||
if not project.is_file():
|
||||
return None
|
||||
return (str(project.resolve()), tuple(sorted(rows)))
|
||||
except (OSError, ValueError, RuntimeError):
|
||||
return None
|
||||
|
||||
|
||||
def _file_stamp(info):
|
||||
return (info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns)
|
||||
|
||||
|
||||
def _unsafe(info):
|
||||
return stat.S_ISLNK(info.st_mode) or bool(
|
||||
getattr(info, 'st_file_attributes', 0) & getattr(stat, 'FILE_ATTRIBUTE_REPARSE_POINT', 0x400))
|
||||
|
||||
|
||||
class DiscoveryCache:
|
||||
"""One preparer owns one cache; the lock also serializes cache discovery."""
|
||||
def __init__(self, data_root: Path, capacity: int = 32):
|
||||
self.data_root = data_root
|
||||
self.capacity = capacity
|
||||
self.lock = RLock()
|
||||
self._entries = OrderedDict()
|
||||
|
||||
def invalidate(self, project: Path):
|
||||
with self.lock:
|
||||
self._entries.pop(_key(project), None)
|
||||
|
||||
def discover(self, project, parts, collect_components, loader):
|
||||
with self.lock:
|
||||
key = _key(project)
|
||||
requested = frozenset(part.casefold() for part in parts)
|
||||
before = project_fingerprint(project, self.data_root)
|
||||
entry = self._entries.pop(key, None)
|
||||
if entry is not None:
|
||||
stamp, covered, has_components, discovery = entry
|
||||
if (before is not None and before == stamp and requested <= covered
|
||||
and (not collect_components or has_components)):
|
||||
self._entries[key] = entry
|
||||
return deepcopy(discovery)
|
||||
# Fingerprinting is an optimization: an initially unverifiable
|
||||
# project still gets fresh native discovery, with no cache reuse.
|
||||
if before is None:
|
||||
return loader()
|
||||
# Native first-open may normalize an old database. Discard that
|
||||
# discovery and reopen once; only a verified stable pass is usable.
|
||||
for attempt in range(2):
|
||||
if attempt:
|
||||
before = project_fingerprint(project, self.data_root)
|
||||
discovery = loader()
|
||||
after = project_fingerprint(project, self.data_root)
|
||||
if before is not None and before == after:
|
||||
break
|
||||
else:
|
||||
raise TaskCenterError("quick_run_sheet_discovery",
|
||||
"project contents changed or could not be verified during discovery; retry read-only discovery")
|
||||
# Refuse incomplete inventories and bound both projects and row count.
|
||||
sheets = getattr(discovery, 'sheets', ())
|
||||
matches = getattr(discovery, 'matched_old_parts', {})
|
||||
if (before is not None and before == after and sheets
|
||||
and set(sheets) == set(matches)
|
||||
and (len(getattr(discovery, 'components', ())) + len(sheets)
|
||||
+ sum(len(parts) for parts in matches.values())) <= 100000):
|
||||
self._entries[key] = (after, requested, collect_components, deepcopy(discovery))
|
||||
while len(self._entries) > self.capacity:
|
||||
self._entries.popitem(last=False)
|
||||
return discovery
|
||||
|
||||
|
||||
def _key(project):
|
||||
return os.path.normcase(os.path.abspath(str(project)))
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Read-only execution feedback shared by the service and UI."""
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
from pathlib import Path
|
||||
import time
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ExecutionFeedback:
|
||||
task_id: str | None
|
||||
position: int = 1
|
||||
total: int = 1
|
||||
message: str = '正在准备执行'
|
||||
stage: str = ''
|
||||
stage_seconds: float = 0.0
|
||||
|
||||
|
||||
def read_feedback(task_id, position, total, message, root: Path, started_after: float):
|
||||
private = root / 'quick-run' / 'private-desktop.json'
|
||||
try:
|
||||
modified = private.stat().st_mtime
|
||||
if modified >= started_after:
|
||||
state = json.loads(private.read_text(encoding='utf-8')).get('state')
|
||||
if state in {'starting', 'closing'}:
|
||||
return ExecutionFeedback(task_id, position, total, message,
|
||||
'private_startup' if state == 'starting' else 'private_shutdown', max(0, time.time() - modified))
|
||||
except (OSError, ValueError, TypeError, AttributeError):
|
||||
pass
|
||||
path = root / 'quick-run' / 'worker-progress.json'
|
||||
stage, seconds = '', 0.0
|
||||
try:
|
||||
modified = path.stat().st_mtime
|
||||
if modified >= started_after:
|
||||
record = json.loads(path.read_text(encoding='utf-8'))
|
||||
candidate = record.get('stage', '')
|
||||
if candidate and candidate != 'finished':
|
||||
seconds = float(record.get('stage_seconds', {}).get(candidate, 0)) + max(0, time.time() - modified)
|
||||
stage = candidate
|
||||
except (OSError, ValueError, TypeError, AttributeError):
|
||||
pass # Display feedback is optional; it never changes execution state.
|
||||
return ExecutionFeedback(task_id, position, total, message, stage, seconds)
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Monotonic phase measurements persisted beside task execution evidence."""
|
||||
|
||||
from contextlib import contextmanager
|
||||
import time
|
||||
|
||||
from .logging_setup import append_task_event
|
||||
|
||||
|
||||
@contextmanager
|
||||
def measure_phase(logging, task_id: str, phase: str, *, unit: str = 'operation', persist: bool = True, **details):
|
||||
metric = {'phase': phase, 'unit': unit, 'completed_units': 0, 'state': 'completed', **details}
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
yield metric
|
||||
except Exception as error:
|
||||
metric.update(state='error', completed_units=0, error_code=getattr(error, 'code', type(error).__name__))
|
||||
raise
|
||||
finally:
|
||||
elapsed = max(0.0, time.perf_counter() - started)
|
||||
metric['elapsed_seconds'] = elapsed
|
||||
metric['units_per_minute'] = metric['completed_units'] * 60 / elapsed if elapsed > 0 else None
|
||||
if persist or metric['state'] == 'error':
|
||||
append_task_event(logging, level='WARNING' if metric['state'] == 'error' else 'INFO',
|
||||
task_id=task_id, operation='execution_timing', details=metric)
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Validate read-only component inventory produced by sheet discovery."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .target_plan import ComponentTarget
|
||||
|
||||
|
||||
HEADER = ("project_path", "schematic_name", "sheet_number", "uid", "refdes",
|
||||
"old_part", "old_value")
|
||||
|
||||
|
||||
def read_component_inventory(path: Path, project_path: Path,
|
||||
sheets: tuple[tuple[str, str], ...]) -> tuple[ComponentTarget, ...]:
|
||||
from .quick_run import _decode_vbs_field, _path_key
|
||||
|
||||
try:
|
||||
lines = Path(path).read_text(encoding="utf-8-sig").splitlines()
|
||||
if not lines or tuple(lines[0].split("\t")) != HEADER:
|
||||
raise ValueError("component inventory header changed")
|
||||
result: list[ComponentTarget] = []
|
||||
seen: set[tuple[str, str, str]] = set()
|
||||
for line in lines[1:]:
|
||||
if not line:
|
||||
continue
|
||||
fields = tuple(_decode_vbs_field(field) for field in line.split("\t"))
|
||||
if len(fields) != len(HEADER):
|
||||
raise ValueError("component inventory row is malformed")
|
||||
project, schematic, sheet, uid, refdes, old_part, old_value = fields
|
||||
if (_path_key(project) != _path_key(project_path) or (schematic, sheet) not in sheets or
|
||||
not all((uid, refdes, old_part)) or (schematic, sheet, uid) in seen):
|
||||
raise ValueError("component inventory identity is invalid")
|
||||
seen.add((schematic, sheet, uid))
|
||||
result.append(ComponentTarget(Path(project_path), schematic, sheet, uid, refdes,
|
||||
old_part, old_value))
|
||||
return tuple(result)
|
||||
except (OSError, UnicodeError, ValueError) as error:
|
||||
raise TaskCenterError("target_inventory", str(error)) from error
|
||||
|
||||
|
||||
def collect_target_inventory(preparer, project_path: Path,
|
||||
old_part_numbers: tuple[str, ...]) -> tuple[ComponentTarget, ...]:
|
||||
if not old_part_numbers:
|
||||
raise TaskCenterError("target_inventory", "at least one old Part Number is required")
|
||||
return preparer.collect_inventory(project_path, old_part_numbers)
|
||||
@@ -0,0 +1,240 @@
|
||||
"""Start the real CAD and its automation on one owned Windows desktop."""
|
||||
from dataclasses import asdict
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
from .cad_identity import CadBinding, current_desktop_name, verify_application
|
||||
from .isolated_desktop import PrivateDesktop
|
||||
from .worker_monitor import WorkerMonitorError
|
||||
|
||||
|
||||
class PrivateCadStartupError(WorkerMonitorError):
|
||||
"""The owned desktop was released before any project worker was launched."""
|
||||
|
||||
|
||||
def _helper_command(action, evidence, pid):
|
||||
if getattr(sys, 'frozen', False):
|
||||
return (sys.executable, '--private-cad-action', action, '--private-cad-evidence', str(evidence),
|
||||
'--private-cad-pid', str(pid))
|
||||
return (sys.executable, '-m', __name__, action, str(evidence), str(pid))
|
||||
|
||||
|
||||
def _child_environment(environment):
|
||||
environment = dict(environment)
|
||||
if not getattr(sys, 'frozen', False):
|
||||
environment['PYTHONPATH'] = str(Path(__file__).resolve().parents[2]) + os.pathsep + environment.get('PYTHONPATH', '')
|
||||
return environment
|
||||
|
||||
|
||||
def _replace_record(temporary, target):
|
||||
# Windows readers can temporarily deny delete access to the old JSON.
|
||||
# Keep the complete old record until replacement succeeds, with a finite
|
||||
# retry budget so persistent permissions failures still reach the caller.
|
||||
deadline = time.monotonic() + 1.0
|
||||
while True:
|
||||
try:
|
||||
temporary.replace(target)
|
||||
return
|
||||
except PermissionError:
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(0.02)
|
||||
|
||||
|
||||
def _designer_executable():
|
||||
import winreg
|
||||
with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r'Viewdraw.Application\CLSID') as key:
|
||||
clsid = winreg.QueryValue(key, None)
|
||||
with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, rf'CLSID\{clsid}\LocalServer32',
|
||||
0, winreg.KEY_READ | winreg.KEY_WOW64_32KEY) as key:
|
||||
command = winreg.QueryValue(key, None)
|
||||
# Mentor registers an absolute LocalServer32 path, sometimes quoted.
|
||||
command = command.strip()
|
||||
executable = command.split('"', 2)[1] if command.startswith('"') else command[:command.lower().index('.exe') + 4]
|
||||
path = Path(executable)
|
||||
if path.name.casefold() != 'viewdraw.exe' or not path.is_file():
|
||||
raise WorkerMonitorError('registered DxDesigner executable is unavailable')
|
||||
return path
|
||||
|
||||
|
||||
class IsolatedCadSession:
|
||||
"""The supervisor never attaches to COM on the user's input desktop."""
|
||||
def __init__(self, root, *, abort_event=None):
|
||||
self.root = Path(root)
|
||||
self.token = uuid4().hex
|
||||
self.desktop = PrivateDesktop('dx-' + self.token, enabled=True)
|
||||
self.cad = None
|
||||
self.binding = None
|
||||
self.started = time.monotonic()
|
||||
self.abort_event = abort_event
|
||||
self.record = {'desktop': self.desktop.name, 'token': self.token, 'state': 'starting'}
|
||||
|
||||
def _record(self, **values):
|
||||
self.record.update(values)
|
||||
self.root.mkdir(parents=True, exist_ok=True)
|
||||
target = self.root / 'private-desktop.json'
|
||||
temporary = target.with_suffix('.tmp')
|
||||
temporary.write_text(json.dumps(self.record, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
_replace_record(temporary, target)
|
||||
history = self.root / 'private-desktop-sessions'
|
||||
history.mkdir(exist_ok=True)
|
||||
archived = history / (self.token + '.json')
|
||||
pending = archived.with_suffix('.tmp')
|
||||
pending.write_text(json.dumps(self.record, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
_replace_record(pending, archived)
|
||||
|
||||
def __enter__(self):
|
||||
try:
|
||||
self._check_abort()
|
||||
self.desktop.__enter__()
|
||||
self.cad = self.desktop.start_process((str(_designer_executable()),))
|
||||
self._record(cad_pid=self.cad.pid)
|
||||
bootstrap = self.root / ('cad-binding-' + self.token + '.json')
|
||||
environment = dict(os.environ, DXPART_DESKTOP=self.desktop.name,
|
||||
DXPART_CAD_PID=str(self.cad.pid), DXPART_SESSION_TOKEN=self.token)
|
||||
environment.pop('DXPART_CAD_GUID', None)
|
||||
probe = self.desktop.start_process(_helper_command('probe', bootstrap, self.cad.pid), env=_child_environment(environment),
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
try:
|
||||
deadline = time.monotonic() + 75
|
||||
while probe.poll() is None:
|
||||
self._check_abort()
|
||||
if time.monotonic() >= deadline:
|
||||
raise WorkerMonitorError('private CAD bootstrap timed out')
|
||||
time.sleep(0.05)
|
||||
code = probe.poll()
|
||||
if code:
|
||||
raise WorkerMonitorError('private CAD startup identity failed: ' + probe.stderr.read().decode('utf-8', errors='replace'))
|
||||
finally:
|
||||
probe.close()
|
||||
result = json.loads(bootstrap.read_text(encoding='utf-8'))
|
||||
self.binding = CadBinding(**result)
|
||||
if (self.binding.pid, self.binding.desktop, self.binding.token) != (self.cad.pid, self.desktop.name, self.token):
|
||||
raise WorkerMonitorError('private CAD bootstrap returned a foreign identity')
|
||||
self._record(state='ready', guid=self.binding.guid, startup_seconds=time.monotonic() - self.started)
|
||||
return self
|
||||
except Exception as error:
|
||||
try:
|
||||
self.desktop.close()
|
||||
except Exception as failure:
|
||||
self._uncertain('startup cleanup failed: ' + str(failure))
|
||||
raise WorkerMonitorError('private CAD startup cleanup requires reconciliation: ' + str(failure)) from error
|
||||
self._record(state='released', clean=False, startup_error=str(error))
|
||||
raise PrivateCadStartupError(str(error)) from error
|
||||
|
||||
def _check_abort(self):
|
||||
if self.abort_event is not None and self.abort_event.is_set():
|
||||
raise WorkerMonitorError('private CAD startup was cancelled before execution')
|
||||
|
||||
def start_worker(self, command, **options):
|
||||
if self.binding is None or self.cad.poll() is not None:
|
||||
raise WorkerMonitorError('owned private CAD is unavailable')
|
||||
return self.desktop.start_process(command, env=_child_environment(self.binding.environment()), **options)
|
||||
|
||||
def __exit__(self, error_type, error, traceback):
|
||||
closing_started = time.monotonic()
|
||||
cleanup_error = None
|
||||
try:
|
||||
self._record(state='closing')
|
||||
if error is not None:
|
||||
self._uncertain(str(error))
|
||||
if self.cad is not None and self.cad.poll() is not None:
|
||||
raise WorkerMonitorError('owned CAD exited before the authorized quit request')
|
||||
if self.cad is not None and self.binding is not None:
|
||||
closing = self.desktop.start_process(_helper_command('quit', self.root / 'private-desktop.json', self.cad.pid),
|
||||
env=_child_environment(self.binding.environment()), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
try:
|
||||
if closing.wait(timeout=20):
|
||||
raise WorkerMonitorError('owned CAD refused orderly exit: ' + closing.stderr.read().decode('utf-8', errors='replace'))
|
||||
if self.cad.wait(timeout=15) != 0:
|
||||
raise WorkerMonitorError('owned CAD returned a nonzero exit code after quit')
|
||||
finally:
|
||||
closing.close()
|
||||
except Exception as failure:
|
||||
cleanup_error = failure
|
||||
self._uncertain(str(failure))
|
||||
finally:
|
||||
try:
|
||||
self.desktop.close()
|
||||
self._record(state='released', clean=error is None and cleanup_error is None,
|
||||
shutdown_seconds=time.monotonic() - closing_started)
|
||||
except Exception as failure:
|
||||
self._uncertain(str(failure))
|
||||
cleanup_error = failure
|
||||
if cleanup_error is not None:
|
||||
raise WorkerMonitorError('private CAD cleanup requires reconciliation: ' + str(cleanup_error)) from cleanup_error
|
||||
|
||||
def _uncertain(self, message):
|
||||
from .quick_run import _write_uncertain_flag
|
||||
_write_uncertain_flag(self.root / 'uncertain.flag', 'private_desktop: ' + message)
|
||||
self._record(state='uncertain', error=message)
|
||||
|
||||
|
||||
def run_isolated_process(command, timeout, *, abort_event=None):
|
||||
from .worker_monitor import run_monitored_process
|
||||
try:
|
||||
with IsolatedCadSession(Path(command[3]), abort_event=abort_event) as session:
|
||||
return run_monitored_process(command, timeout, abort_event=abort_event, process_factory=session.start_worker)
|
||||
except PrivateCadStartupError as error:
|
||||
# The existing handoff recognizes exit=2 with unchanged status as a
|
||||
# retryable pre-mutation startup failure, without an uncertainty lock.
|
||||
return subprocess.CompletedProcess(command, 2, '', str(error))
|
||||
|
||||
|
||||
def native_action(action, evidence, expected_pid):
|
||||
"""Runs in a child created with lpDesktop, never in a Python thread switch."""
|
||||
import pythoncom
|
||||
import win32com.client
|
||||
import win32gui
|
||||
import win32process
|
||||
pythoncom.CoInitialize()
|
||||
try:
|
||||
desktop = os.environ.get('DXPART_DESKTOP', '')
|
||||
token = os.environ.get('DXPART_SESSION_TOKEN', '')
|
||||
if not desktop.startswith('dx-') or current_desktop_name() != desktop:
|
||||
raise ValueError('CAD bootstrap is not on the requested private desktop')
|
||||
expected_pid = int(expected_pid)
|
||||
if expected_pid <= 0 or str(expected_pid) != os.environ.get('DXPART_CAD_PID'):
|
||||
raise ValueError('invalid CAD bootstrap PID')
|
||||
deadline = time.monotonic() + 60
|
||||
while True:
|
||||
try:
|
||||
app = win32com.client.GetActiveObject('Viewdraw.Application')
|
||||
break
|
||||
except pythoncom.com_error:
|
||||
if action != 'probe' or time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(0.2)
|
||||
if action == 'probe':
|
||||
cad_windows = []
|
||||
win32gui.EnumWindows(lambda handle, _: cad_windows.append(handle)
|
||||
if win32process.GetWindowThreadProcessId(handle)[1] == expected_pid else None, None)
|
||||
if not cad_windows:
|
||||
raise ValueError('owned CAD has no windows on its private desktop')
|
||||
# ROT is scoped to this desktop. Certify the freshly launched instance
|
||||
# here; every subsequent VBS/helper attachment checks its GUID.
|
||||
binding = CadBinding(desktop, expected_pid, str(app.Guid()), token)
|
||||
verify_application(app, binding, require_view=False)
|
||||
Path(evidence).write_text(json.dumps(asdict(binding)), encoding='utf-8')
|
||||
elif action == 'quit':
|
||||
binding = CadBinding.from_environment()
|
||||
# ActiveViewHandle can retain a destroyed/reused HWND after closing
|
||||
# the last project. The private ROT/GUID binds this empty instance.
|
||||
verify_application(app, binding, require_view=False)
|
||||
if app.GetProjectData().GetProjectFilePath():
|
||||
raise ValueError('owned CAD still has a project open; no implicit save or discard')
|
||||
app.Quit()
|
||||
else:
|
||||
raise ValueError('unknown private CAD action')
|
||||
finally:
|
||||
pythoncom.CoUninitialize()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(native_action(sys.argv[1], Path(sys.argv[2]), int(sys.argv[3])))
|
||||
@@ -0,0 +1,449 @@
|
||||
"""Owned Windows private-desktop process boundary for CAD and research workers.
|
||||
|
||||
This module deliberately contains no CAD automation. It only creates a
|
||||
desktop, starts a process on that desktop, and closes resources it owns.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from contextlib import ExitStack
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
from typing import Mapping, Sequence
|
||||
|
||||
from .errors import TaskCenterError
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class StartupInfo:
|
||||
lpDesktop: str
|
||||
|
||||
|
||||
def build_startup_info(desktop_name: str) -> StartupInfo:
|
||||
if not desktop_name or "\\" in desktop_name or "\x00" in desktop_name:
|
||||
raise TaskCenterError("private_desktop", "invalid private desktop name")
|
||||
return StartupInfo(lpDesktop=f"winsta0\\{desktop_name}")
|
||||
|
||||
|
||||
class _Win32Api:
|
||||
def __init__(self) -> None:
|
||||
try:
|
||||
import win32api, win32con, win32event, win32job, win32process, win32service
|
||||
except ImportError as error:
|
||||
raise TaskCenterError("private_desktop", "pywin32 is required for private desktop supervision") from error
|
||||
self.con, self.job, self.process, self.service = win32con, win32job, win32process, win32service
|
||||
self.event = win32event
|
||||
self.open_process = win32api.OpenProcess
|
||||
self._pending_cleanup = []
|
||||
|
||||
def create_desktop(self, name: str):
|
||||
return self.service.CreateDesktop(name, 0, self.con.GENERIC_ALL, None)
|
||||
|
||||
def confirm_desktop_released(self, name: str):
|
||||
deadline = time.monotonic() + 2.0
|
||||
while True:
|
||||
# EnumDesktops avoids reopening/closing a handle which Windows may
|
||||
# share with another desktop handle held by this process.
|
||||
names = self.service.GetProcessWindowStation().EnumDesktops()
|
||||
if name.casefold() not in {value.casefold() for value in names}:
|
||||
return
|
||||
if time.monotonic() >= deadline:
|
||||
raise TaskCenterError('private_desktop_cleanup', 'owned private desktop still exists after cleanup')
|
||||
time.sleep(0.05)
|
||||
|
||||
def create_process(self, command: Sequence[str], desktop: str, cwd: Path | None, env: Mapping[str, str] | None,
|
||||
*, stdout=None, stderr=None):
|
||||
startup = self.process.STARTUPINFO()
|
||||
startup.lpDesktop = desktop
|
||||
flags = self.con.CREATE_NO_WINDOW | self.con.CREATE_SUSPENDED
|
||||
job = self.job.CreateJobObject(None, "")
|
||||
process = None
|
||||
try:
|
||||
info = self.job.QueryInformationJobObject(job, self.job.JobObjectExtendedLimitInformation)
|
||||
info["BasicLimitInformation"]["LimitFlags"] |= self.job.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
||||
self.job.SetInformationJobObject(job, self.job.JobObjectExtendedLimitInformation, info)
|
||||
streams = (None, None)
|
||||
if stdout is not None or stderr is not None:
|
||||
(handle, thread, pid, _), streams = _create_redirected_process(command, desktop, cwd, env, flags, stdout, stderr)
|
||||
else:
|
||||
handle, thread, pid, _ = self.process.CreateProcess(
|
||||
str(command[0]), subprocess.list2cmdline([str(item) for item in command]),
|
||||
None, None, False, flags, env, str(cwd) if cwd else None, startup,
|
||||
)
|
||||
process = _Win32Process(self.process, self.job, self.event, handle, job, int(pid), command,
|
||||
open_process=getattr(self, 'open_process', None))
|
||||
process.stdout, process.stderr = streams
|
||||
process.thread = thread
|
||||
self.job.AssignProcessToJobObject(job, handle)
|
||||
process.job_assigned = True
|
||||
self.process.ResumeThread(thread)
|
||||
thread.Close()
|
||||
process.thread = None
|
||||
except Exception as error:
|
||||
try:
|
||||
if process is not None:
|
||||
# Assignment can fail before the job owns this suspended process.
|
||||
process.close()
|
||||
else:
|
||||
job.Close()
|
||||
except Exception as cleanup_error:
|
||||
pending = getattr(self, '_pending_cleanup', None)
|
||||
if pending is None:
|
||||
self._pending_cleanup = pending = []
|
||||
pending.append(process if process is not None else job)
|
||||
raise TaskCenterError('private_desktop', f'launch failed: {error}; cleanup failed: {cleanup_error}') from error
|
||||
raise
|
||||
return process
|
||||
|
||||
def close_pending(self):
|
||||
errors, remaining = [], []
|
||||
for resource in getattr(self, '_pending_cleanup', []):
|
||||
try:
|
||||
resource.close() if isinstance(resource, _Win32Process) else resource.Close()
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
remaining.append(resource)
|
||||
self._pending_cleanup = remaining
|
||||
_raise_cleanup_errors(errors)
|
||||
|
||||
|
||||
def _raise_cleanup_errors(errors):
|
||||
if errors:
|
||||
raise TaskCenterError('private_desktop_cleanup', '; '.join(str(error) for error in errors))
|
||||
|
||||
|
||||
def _stop_and_wait(process):
|
||||
errors = []
|
||||
running = True
|
||||
try:
|
||||
running = process.poll() is None
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
if running:
|
||||
try:
|
||||
process.terminate()
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
try:
|
||||
process.wait(timeout=5.0)
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
return errors
|
||||
|
||||
|
||||
def _create_redirected_process(command, desktop, cwd, env, flags, stdout, stderr):
|
||||
"""Use an explicit inheritance list; never inherit unrelated parent handles."""
|
||||
import msvcrt
|
||||
import pywintypes
|
||||
|
||||
class NativeStartup(ctypes.Structure):
|
||||
_fields_ = [
|
||||
('cb', wintypes.DWORD), ('lpReserved', wintypes.LPWSTR),
|
||||
('lpDesktop', wintypes.LPWSTR), ('lpTitle', wintypes.LPWSTR),
|
||||
('dwX', wintypes.DWORD), ('dwY', wintypes.DWORD),
|
||||
('dwXSize', wintypes.DWORD), ('dwYSize', wintypes.DWORD),
|
||||
('dwXCountChars', wintypes.DWORD), ('dwYCountChars', wintypes.DWORD),
|
||||
('dwFillAttribute', wintypes.DWORD), ('dwFlags', wintypes.DWORD),
|
||||
('wShowWindow', wintypes.WORD), ('cbReserved2', wintypes.WORD),
|
||||
('lpReserved2', ctypes.POINTER(ctypes.c_byte)),
|
||||
('hStdInput', wintypes.HANDLE), ('hStdOutput', wintypes.HANDLE), ('hStdError', wintypes.HANDLE),
|
||||
]
|
||||
class ExtendedStartup(ctypes.Structure):
|
||||
_fields_ = [('StartupInfo', NativeStartup), ('lpAttributeList', ctypes.c_void_p)]
|
||||
class ProcessInformation(ctypes.Structure):
|
||||
_fields_ = [('hProcess', wintypes.HANDLE), ('hThread', wintypes.HANDLE),
|
||||
('dwProcessId', wintypes.DWORD), ('dwThreadId', wintypes.DWORD)]
|
||||
|
||||
kernel = ctypes.WinDLL('kernel32', use_last_error=True)
|
||||
initialize = kernel.InitializeProcThreadAttributeList
|
||||
initialize.argtypes = [ctypes.c_void_p, wintypes.DWORD, wintypes.DWORD, ctypes.POINTER(ctypes.c_size_t)]
|
||||
initialize.restype = wintypes.BOOL
|
||||
update = kernel.UpdateProcThreadAttribute
|
||||
update.argtypes = [ctypes.c_void_p, wintypes.DWORD, ctypes.c_size_t, ctypes.c_void_p,
|
||||
ctypes.c_size_t, ctypes.c_void_p, ctypes.c_void_p]
|
||||
update.restype = wintypes.BOOL
|
||||
delete = kernel.DeleteProcThreadAttributeList
|
||||
delete.argtypes = [ctypes.c_void_p]
|
||||
delete.restype = None
|
||||
create = kernel.CreateProcessW
|
||||
create.argtypes = [wintypes.LPCWSTR, wintypes.LPWSTR, ctypes.c_void_p, ctypes.c_void_p,
|
||||
wintypes.BOOL, wintypes.DWORD, ctypes.c_void_p, wintypes.LPCWSTR,
|
||||
ctypes.POINTER(ExtendedStartup), ctypes.POINTER(ProcessInformation)]
|
||||
create.restype = wintypes.BOOL
|
||||
readers = [None, None]
|
||||
try:
|
||||
with ExitStack() as children:
|
||||
def output_handle(target, channel):
|
||||
if target == subprocess.PIPE:
|
||||
read_fd, write_fd = os.pipe()
|
||||
readers[channel] = os.fdopen(read_fd, 'rb')
|
||||
writer = children.enter_context(os.fdopen(write_fd, 'wb'))
|
||||
elif target is None or target == subprocess.DEVNULL:
|
||||
writer = children.enter_context(open(os.devnull, 'wb'))
|
||||
else:
|
||||
writer = children.enter_context(os.fdopen(os.dup(target.fileno()), 'wb'))
|
||||
handle = msvcrt.get_osfhandle(writer.fileno())
|
||||
os.set_handle_inheritable(handle, True)
|
||||
return handle
|
||||
|
||||
stdin_file = children.enter_context(open(os.devnull, 'rb'))
|
||||
stdin_handle = msvcrt.get_osfhandle(stdin_file.fileno())
|
||||
os.set_handle_inheritable(stdin_handle, True)
|
||||
stdout_handle = output_handle(stdout, 0)
|
||||
stderr_handle = stdout_handle if stderr == subprocess.STDOUT else output_handle(stderr, 1)
|
||||
handles = list(dict.fromkeys((stdin_handle, stdout_handle, stderr_handle)))
|
||||
inherited = (wintypes.HANDLE * len(handles))(*handles)
|
||||
size = ctypes.c_size_t()
|
||||
initialize(None, 1, 0, ctypes.byref(size))
|
||||
attributes = ctypes.create_string_buffer(size.value)
|
||||
if not initialize(attributes, 1, 0, ctypes.byref(size)):
|
||||
raise ctypes.WinError(ctypes.get_last_error())
|
||||
try:
|
||||
if not update(attributes, 0, 0x20002, inherited, ctypes.sizeof(inherited), None, None):
|
||||
raise ctypes.WinError(ctypes.get_last_error())
|
||||
startup = ExtendedStartup()
|
||||
startup.StartupInfo.cb = ctypes.sizeof(startup)
|
||||
startup.StartupInfo.lpDesktop = desktop
|
||||
startup.StartupInfo.dwFlags = 0x100 # STARTF_USESTDHANDLES
|
||||
startup.StartupInfo.hStdInput = stdin_handle
|
||||
startup.StartupInfo.hStdOutput = stdout_handle
|
||||
startup.StartupInfo.hStdError = stderr_handle
|
||||
startup.lpAttributeList = ctypes.addressof(attributes)
|
||||
information = ProcessInformation()
|
||||
environment = None if env is None else ctypes.create_unicode_buffer(
|
||||
'\0'.join(f'{key}={value}' for key, value in sorted(env.items(), key=lambda item: item[0].upper())) + '\0\0')
|
||||
command_line = ctypes.create_unicode_buffer(subprocess.list2cmdline([str(item) for item in command]))
|
||||
if not create(str(command[0]), command_line, None, None, True,
|
||||
flags | 0x80000 | 0x400, environment, str(cwd) if cwd else None,
|
||||
ctypes.byref(startup), ctypes.byref(information)):
|
||||
raise ctypes.WinError(ctypes.get_last_error())
|
||||
result = (pywintypes.HANDLE(information.hProcess), pywintypes.HANDLE(information.hThread),
|
||||
information.dwProcessId, information.dwThreadId)
|
||||
finally:
|
||||
delete(attributes)
|
||||
return result, readers
|
||||
except BaseException:
|
||||
for reader in readers:
|
||||
if reader is not None:
|
||||
reader.close()
|
||||
raise
|
||||
|
||||
|
||||
class _Win32Process:
|
||||
def __init__(self, process_api, job_api, event_api, handle, job, pid: int, args, *, open_process=None):
|
||||
self._process_api, self._job_api = process_api, job_api
|
||||
self._event_api = event_api
|
||||
self._open_process = open_process
|
||||
self._descendant_handles = []
|
||||
self._descendant_pids = set()
|
||||
self.handle, self.job, self.pid = handle, job, pid
|
||||
self.args = args
|
||||
self.thread = None
|
||||
self.job_assigned = False
|
||||
self.returncode = None
|
||||
self.stdout = self.stderr = None
|
||||
|
||||
def poll(self):
|
||||
if self.returncode is not None or self.handle is None:
|
||||
return self.returncode
|
||||
status = self._event_api.WaitForSingleObject(self.handle, 0)
|
||||
if status == 258: # WAIT_TIMEOUT: 259 is also a valid *completed* exit code.
|
||||
return None
|
||||
if status != 0:
|
||||
raise OSError(f'process wait failed with status {status}')
|
||||
self.returncode = self._process_api.GetExitCodeProcess(self.handle)
|
||||
return self.returncode
|
||||
|
||||
def wait(self, timeout=None):
|
||||
if self.returncode is not None:
|
||||
return self.returncode
|
||||
if self.handle is None:
|
||||
raise OSError('owned process handle is closed before exit was confirmed')
|
||||
milliseconds = 0xFFFFFFFF if timeout is None else min(max(math.ceil(timeout * 1000), 0), 0xFFFFFFFE)
|
||||
status = self._event_api.WaitForSingleObject(self.handle, milliseconds)
|
||||
if status == 258:
|
||||
raise subprocess.TimeoutExpired(self.args, timeout)
|
||||
if status != 0:
|
||||
raise OSError(f'process wait failed with status {status}')
|
||||
self.returncode = self._process_api.GetExitCodeProcess(self.handle)
|
||||
return self.returncode
|
||||
|
||||
def terminate(self):
|
||||
if self.handle is None:
|
||||
return
|
||||
if not self.job_assigned:
|
||||
self._process_api.TerminateProcess(self.handle, 1)
|
||||
return
|
||||
errors = []
|
||||
try:
|
||||
self._remember_descendants()
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
try:
|
||||
self._job_api.TerminateJobObject(self.job, 1)
|
||||
except Exception:
|
||||
self._process_api.TerminateProcess(self.handle, 1)
|
||||
_raise_cleanup_errors(errors)
|
||||
|
||||
kill = terminate
|
||||
|
||||
def _remember_descendants(self):
|
||||
if self._open_process is None or self.job is None:
|
||||
return
|
||||
for pid in self._job_api.QueryInformationJobObject(self.job, self._job_api.JobObjectBasicProcessIdList):
|
||||
if pid == self.pid or pid in self._descendant_pids:
|
||||
continue
|
||||
try:
|
||||
self._descendant_handles.append(self._open_process(0x100000, False, pid))
|
||||
self._descendant_pids.add(pid)
|
||||
except Exception as error:
|
||||
# pywintypes.error is not an OSError. A child that exited
|
||||
# between the job snapshot and OpenProcess reports error 87.
|
||||
code = getattr(error, 'winerror', None)
|
||||
if code is None and error.args:
|
||||
code = error.args[0]
|
||||
if code != 87:
|
||||
raise
|
||||
|
||||
def close(self):
|
||||
errors = []
|
||||
if self.handle is not None:
|
||||
errors.extend(_stop_and_wait(self))
|
||||
deadline = time.monotonic() + 5.0
|
||||
if self.job is not None and self.job_assigned:
|
||||
try:
|
||||
# A completed root can leave grandchildren holding the desktop.
|
||||
self._remember_descendants()
|
||||
self._job_api.TerminateJobObject(self.job, 1)
|
||||
while self._job_api.QueryInformationJobObject(
|
||||
self.job, self._job_api.JobObjectBasicAccountingInformation,
|
||||
)['ActiveProcesses']:
|
||||
if time.monotonic() >= deadline:
|
||||
raise TimeoutError('owned job descendants did not exit within 5 seconds')
|
||||
time.sleep(0.01)
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
retained = []
|
||||
for descendant in self._descendant_handles:
|
||||
try:
|
||||
# Job accounting can reach zero before a terminated process is signaled.
|
||||
remaining = max(0, math.ceil((deadline - time.monotonic()) * 1000))
|
||||
if self._event_api.WaitForSingleObject(descendant, remaining) != 0:
|
||||
raise TimeoutError('owned job descendant exit was not confirmed within 5 seconds')
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
retained.append(descendant)
|
||||
continue
|
||||
try:
|
||||
descendant.Close()
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
retained.append(descendant)
|
||||
self._descendant_handles = retained
|
||||
for name in ('job', 'thread', 'handle'):
|
||||
handle = getattr(self, name)
|
||||
if name == 'handle' and self.returncode is None:
|
||||
# Keep the only termination/wait capability until cleanup can retry.
|
||||
continue
|
||||
if handle is not None:
|
||||
try:
|
||||
handle.Close()
|
||||
setattr(self, name, None)
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
for stream in (self.stdout, self.stderr):
|
||||
if stream is not None:
|
||||
try:
|
||||
stream.close()
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
_raise_cleanup_errors(errors)
|
||||
|
||||
|
||||
class PrivateDesktop:
|
||||
"""Own a private Windows desktop and processes started on it."""
|
||||
|
||||
def __init__(self, name: str, *, enabled: bool = False, api=None) -> None:
|
||||
self.name = name
|
||||
self.enabled = enabled
|
||||
self._handle = None
|
||||
self._processes: list[subprocess.Popen[str]] = []
|
||||
self._api = api
|
||||
|
||||
def __enter__(self) -> "PrivateDesktop":
|
||||
if not self.enabled:
|
||||
raise TaskCenterError("private_desktop_opt_in", "private desktop backend requires explicit opt-in")
|
||||
self._create()
|
||||
if self._handle is None:
|
||||
raise TaskCenterError("private_desktop", "private desktop could not be created")
|
||||
return self
|
||||
|
||||
def __exit__(self, *_exc: object) -> None:
|
||||
self.close()
|
||||
|
||||
def _create(self) -> None:
|
||||
if os.name != "nt" and self._api is None:
|
||||
return
|
||||
self._api = self._api or _Win32Api()
|
||||
self._handle = self._api.create_desktop(self.name)
|
||||
|
||||
def start_process(
|
||||
self,
|
||||
command: Sequence[str],
|
||||
*,
|
||||
cwd: Path | None = None,
|
||||
env: Mapping[str, str] | None = None,
|
||||
stdout=None,
|
||||
stderr=None,
|
||||
) -> subprocess.Popen[str]:
|
||||
if not self.enabled or self._handle is None:
|
||||
raise TaskCenterError("private_desktop", "process launch requires an owned private desktop")
|
||||
if not command:
|
||||
raise TaskCenterError("private_desktop", "private desktop command is empty")
|
||||
if self._api is None:
|
||||
raise TaskCenterError("private_desktop", "private desktop process API is unavailable")
|
||||
options = {} if stdout is None and stderr is None else {'stdout': stdout, 'stderr': stderr}
|
||||
process = self._api.create_process(command, build_startup_info(self.name).lpDesktop, cwd, env, **options)
|
||||
self._processes.append(process)
|
||||
return process
|
||||
|
||||
def close(self) -> None:
|
||||
errors, remaining = [], []
|
||||
for process in reversed(self._processes):
|
||||
process_errors = _stop_and_wait(process)
|
||||
errors.extend(process_errors)
|
||||
failed = bool(process_errors)
|
||||
try:
|
||||
process.close()
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
failed = True
|
||||
if failed:
|
||||
remaining.append(process)
|
||||
self._processes = list(reversed(remaining))
|
||||
close_pending = getattr(self._api, 'close_pending', None)
|
||||
if close_pending:
|
||||
try:
|
||||
close_pending()
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
close_desktop = getattr(self._handle, "CloseDesktop", None)
|
||||
if close_desktop:
|
||||
try:
|
||||
close_desktop()
|
||||
self._handle = None
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
confirm = getattr(self._api, 'confirm_desktop_released', None)
|
||||
if confirm and self._handle is None:
|
||||
try:
|
||||
confirm(self.name)
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
_raise_cleanup_errors(errors)
|
||||
@@ -0,0 +1,137 @@
|
||||
"""Legacy research-only request protocol; production uses isolated_cad.
|
||||
|
||||
The worker writes versioned request/evidence files and delegates process
|
||||
launching to an injected callback. It never attaches to an existing CAD
|
||||
process and does not perform CAD writes itself.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, asdict
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .isolated_desktop import PrivateDesktop
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class IsolatedWorkerRequest:
|
||||
protocol_version: str
|
||||
task_id: str
|
||||
project_path: Path
|
||||
target_uids: tuple[str, ...]
|
||||
plan_hash: str
|
||||
allow_writes: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class IsolatedWorkerEvidence:
|
||||
protocol_version: str
|
||||
task_id: str
|
||||
state: str
|
||||
request_hash: str
|
||||
cad_pid: int | None = None
|
||||
project_path: str | None = None
|
||||
message: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class CadIdentity:
|
||||
pid: int
|
||||
project_path: Path
|
||||
|
||||
|
||||
class IsolatedDesktopWorker:
|
||||
"""An explicit opt-in supervision boundary; disabled by default."""
|
||||
|
||||
protocol_version = "1"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
enabled: bool = False,
|
||||
desktop_factory: Callable[[str], PrivateDesktop] | None = None,
|
||||
existing_cad_validator: Callable[[Path], bool] | None = None,
|
||||
) -> None:
|
||||
self.enabled = enabled
|
||||
self._desktop_factory = desktop_factory or (lambda name: PrivateDesktop(name, enabled=True))
|
||||
self._existing_cad_validator = existing_cad_validator or (lambda _path: False)
|
||||
|
||||
@staticmethod
|
||||
def request_hash(request: IsolatedWorkerRequest) -> str:
|
||||
payload = json.dumps(_json_request(request), sort_keys=True, separators=(",", ":")).encode()
|
||||
return hashlib.sha256(payload).hexdigest()
|
||||
|
||||
def run(self, request: IsolatedWorkerRequest, *, evidence_root: Path | None = None) -> IsolatedWorkerEvidence:
|
||||
if not self.enabled:
|
||||
raise TaskCenterError("private_desktop_opt_in", "isolated worker is research-only and requires explicit opt-in")
|
||||
self._validate_request(request)
|
||||
if self._existing_cad_validator(request.project_path):
|
||||
raise TaskCenterError("isolated_cad_attachment", "an unrelated CAD process is already associated with this project")
|
||||
digest = self.request_hash(request)
|
||||
root = Path(evidence_root) if evidence_root is not None else None
|
||||
if root is not None:
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
(root / "request.json").write_text(json.dumps(_json_request(request), indent=2), encoding="utf-8")
|
||||
evidence = IsolatedWorkerEvidence(self.protocol_version, request.task_id, "prepared", digest, project_path=str(request.project_path))
|
||||
if root is not None:
|
||||
(root / "evidence.json").write_text(json.dumps(asdict(evidence), indent=2), encoding="utf-8")
|
||||
return evidence
|
||||
|
||||
def read_only_probe(
|
||||
self,
|
||||
request: IsolatedWorkerRequest,
|
||||
cad_probe: Callable[[Path], CadIdentity],
|
||||
*,
|
||||
evidence_root: Path | None = None,
|
||||
) -> IsolatedWorkerEvidence:
|
||||
"""Validate an injected callback result; this does not move CAD desktops.
|
||||
|
||||
The callback is the only native integration point and must return the
|
||||
PID and project identity it observed. Tests inject it; production can
|
||||
later provide a COM reader without changing the request contract.
|
||||
"""
|
||||
prepared = self.run(request, evidence_root=evidence_root)
|
||||
desktop = self._desktop_factory(f"dx-{request.task_id[:12]}")
|
||||
try:
|
||||
with desktop:
|
||||
identity = cad_probe(request.project_path)
|
||||
except TaskCenterError:
|
||||
raise
|
||||
except Exception as error:
|
||||
raise TaskCenterError("isolated_probe", "private desktop read-only probe failed") from error
|
||||
if identity.pid <= 0 or Path(identity.project_path).resolve(strict=False) != request.project_path.resolve(strict=False):
|
||||
raise TaskCenterError("isolated_cad_identity", "read-only probe did not validate CAD PID/project identity")
|
||||
evidence = IsolatedWorkerEvidence(
|
||||
self.protocol_version, request.task_id, "read_only_verified", prepared.request_hash,
|
||||
cad_pid=identity.pid, project_path=str(identity.project_path),
|
||||
message="read-only CAD identity verified",
|
||||
)
|
||||
if evidence_root is not None:
|
||||
root = Path(evidence_root)
|
||||
(root / "evidence.json").write_text(json.dumps(asdict(evidence), indent=2), encoding="utf-8")
|
||||
return evidence
|
||||
|
||||
def _validate_request(self, request: IsolatedWorkerRequest) -> None:
|
||||
if request.protocol_version != self.protocol_version:
|
||||
raise TaskCenterError("isolated_protocol", "unsupported isolated worker protocol")
|
||||
if not request.task_id or not request.project_path:
|
||||
raise TaskCenterError("isolated_request", "task and project are required")
|
||||
if any(not uid or "\x00" in uid for uid in request.target_uids):
|
||||
raise TaskCenterError("isolated_request", "target UID is invalid")
|
||||
if request.allow_writes:
|
||||
raise TaskCenterError("isolated_write_boundary", "research worker cannot enable CAD writes")
|
||||
|
||||
|
||||
def _json_request(request: IsolatedWorkerRequest) -> dict[str, object]:
|
||||
return {
|
||||
"protocol_version": request.protocol_version,
|
||||
"task_id": request.task_id,
|
||||
"project_path": str(request.project_path),
|
||||
"target_uids": list(request.target_uids),
|
||||
"plan_hash": request.plan_hash,
|
||||
"allow_writes": request.allow_writes,
|
||||
}
|
||||
@@ -45,6 +45,10 @@ class TaskRecord:
|
||||
error_id: str | None = None
|
||||
summary: str = ""
|
||||
copy_part_number_to_value: bool = False
|
||||
group_id: str | None = None
|
||||
group_position: int = 0
|
||||
primary_project_id: str | None = None
|
||||
target_plan_mode: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
|
||||
@@ -34,11 +34,11 @@ def read_snapshot(path):
|
||||
for line in Path(path).read_text(encoding="utf-8-sig").splitlines() if line]
|
||||
metadata = [row for row in rows if row[0] == "M"]
|
||||
components = [row for row in rows if row[0] == "C"]
|
||||
if len(metadata) != 1 or len(metadata[0]) not in {5, 6, 8} or not components:
|
||||
if len(metadata) != 1 or len(metadata[0]) not in {5, 6, 8, 10} or not components:
|
||||
raise ValueError("Incomplete snapshot")
|
||||
if len(metadata[0]) >= 6 and metadata[0][5] not in {"preserve", "part_label", "part_number", "custom"}:
|
||||
raise ValueError("Invalid snapshot Value policy")
|
||||
if len(metadata[0]) == 8:
|
||||
if len(metadata[0]) >= 8:
|
||||
if metadata[0][7] not in {"0", "1"} or (metadata[0][5] == "custom") != bool(metadata[0][6]):
|
||||
raise ValueError("Invalid snapshot Value or NC option")
|
||||
if any(len(row) != 8 for row in components):
|
||||
@@ -47,6 +47,8 @@ def read_snapshot(path):
|
||||
raise ValueError("Duplicate snapshot UID")
|
||||
if metadata[0][2].casefold() == metadata[0][3].casefold():
|
||||
raise ValueError("Source and target must differ")
|
||||
if len(metadata[0]) == 10 and (metadata[0][8] != "targets" or not metadata[0][9]):
|
||||
raise ValueError("Target snapshot has no selector")
|
||||
return metadata[0], components
|
||||
|
||||
|
||||
@@ -71,6 +73,7 @@ def transaction_binding(snapshot, metadata, records, library_row, symbol, slot_c
|
||||
"old_part_number": metadata[2],
|
||||
"new_part_number": metadata[3],
|
||||
"source_uids": sorted(row[1] for row in records),
|
||||
"target_selectors": metadata[9] if len(metadata) == 10 else None,
|
||||
"library_row": [str(value) for value in library_row],
|
||||
"target_symbol": str(symbol),
|
||||
"slot_count": slots,
|
||||
@@ -93,6 +96,7 @@ def require_resumable_transaction(snapshot, report, metadata, records):
|
||||
"old_part_number": metadata[2],
|
||||
"new_part_number": metadata[3],
|
||||
"source_uids": sorted(row[1] for row in records),
|
||||
"target_selectors": metadata[9] if len(metadata) == 10 else None,
|
||||
}
|
||||
if not isinstance(binding, dict) or any(binding.get(key) != value for key, value in expected.items()):
|
||||
raise ValueError("Native replacement evidence does not match this snapshot")
|
||||
@@ -201,6 +205,8 @@ def attach():
|
||||
api = win32com.client.gencache.EnsureModule(
|
||||
"{4ADEF4E1-690A-11CE-9261-0020C5E26659}", 0, 1, 0)
|
||||
app = api.IVdApp(win32com.client.GetActiveObject("Viewdraw.Application")._oleobj_)
|
||||
from .cad_identity import verify_application
|
||||
verify_application(app)
|
||||
return app, api
|
||||
|
||||
|
||||
@@ -222,6 +228,8 @@ def components_on_sheet(app, api):
|
||||
|
||||
|
||||
def check_active_context(app, metadata):
|
||||
from .cad_identity import verify_application
|
||||
verify_application(app)
|
||||
if os.path.normcase(os.path.abspath(app.GetProjectData().GetProjectFilePath())) != os.path.normcase(os.path.abspath(metadata[1])):
|
||||
raise ValueError("Active project changed")
|
||||
if f"{app.ActiveView.GetName(0)}:{app.ActiveView.Block.SheetNum}" != metadata[4]:
|
||||
@@ -232,15 +240,63 @@ def check_context(app, api, metadata, records, require_selection=True):
|
||||
check_active_context(app, metadata)
|
||||
components = components_on_sheet(app, api)
|
||||
wanted = {row[1] for row in records}
|
||||
actual = {str(component.UID) for component in components if attribute_value(component, "Part Number").casefold() == metadata[2].casefold()}
|
||||
if actual != wanted:
|
||||
raise ValueError(f"Source batch changed since snapshot: expected={sorted(wanted)!r} actual={sorted(actual)!r}")
|
||||
by_uid = {str(component.UID): component for component in components}
|
||||
if len(by_uid) != len(components):
|
||||
raise ValueError("Duplicate component UID on sheet")
|
||||
if len(metadata) == 10:
|
||||
selectors = _target_selectors(metadata[9])
|
||||
if set(selectors) != wanted:
|
||||
raise ValueError("Target selector differs from snapshot components")
|
||||
for uid, (refdes, old_value) in selectors.items():
|
||||
component = by_uid.get(uid)
|
||||
if (component is None or str(component.Refdes) != refdes or
|
||||
attribute_value(component, "Part Number").casefold() != metadata[2].casefold() or
|
||||
attribute_value(component, "Value") != old_value):
|
||||
raise ValueError("Selected target changed since inventory")
|
||||
else:
|
||||
actual = {str(component.UID) for component in components if attribute_value(component, "Part Number").casefold() == metadata[2].casefold()}
|
||||
if actual != wanted:
|
||||
raise ValueError(f"Source batch changed since snapshot: expected={sorted(wanted)!r} actual={sorted(actual)!r}")
|
||||
selected = {str(api.IVdComp(component._oleobj_).UID) for component in app.ActiveView.Query(128, 1)}
|
||||
if require_selection and selected != wanted:
|
||||
raise ValueError(f"Selected component set differs from snapshot: expected={sorted(wanted)!r} actual={sorted(selected)!r}")
|
||||
return components
|
||||
|
||||
|
||||
def _target_selectors(value):
|
||||
result = {}
|
||||
for item in value.split("\x1e"):
|
||||
fields = item.split("\x1f")
|
||||
if len(fields) != 3 or not fields[0] or not fields[1] or fields[0] in result:
|
||||
raise ValueError("Target selector is malformed")
|
||||
result[fields[0]] = (fields[1], fields[2])
|
||||
if not result:
|
||||
raise ValueError("Target selector is empty")
|
||||
return result
|
||||
|
||||
|
||||
def verify_unselected_snapshot(snapshot, components, selected_uids):
|
||||
"""Compare the full identity/value baseline for components outside target scope."""
|
||||
selected_uids = {str(uid) for uid in selected_uids}
|
||||
rows = [line.split("\t") for line in Path(snapshot).read_text(encoding="utf-8-sig").splitlines()
|
||||
if line.startswith("U\t")]
|
||||
if any(len(row) != 7 for row in rows):
|
||||
raise ValueError("Unselected component baseline is malformed")
|
||||
baseline = {decode(row[1]): tuple(decode(value) for value in row[2:]) for row in rows}
|
||||
if len(baseline) != len(rows):
|
||||
raise ValueError("Duplicate unselected component UID")
|
||||
current = {}
|
||||
for component in components:
|
||||
uid = str(component.UID)
|
||||
if uid in selected_uids:
|
||||
continue
|
||||
current[uid] = (str(component.Refdes), *(attribute_value(component, name)
|
||||
for name in ("Part Number", "Value", "Part Name", "Part Label")))
|
||||
if baseline != current:
|
||||
raise ValueError("An unselected component was changed")
|
||||
return True
|
||||
|
||||
|
||||
def select_snapshot_batch(app, api, metadata, records):
|
||||
components = check_context(app, api, metadata, records, require_selection=False)
|
||||
wanted = {row[1] for row in records}
|
||||
@@ -344,10 +400,12 @@ def run_native(snapshot, report):
|
||||
check_active_context(app, metadata)
|
||||
components = components_on_sheet(app, api)
|
||||
wanted = {row[1] for row in records}
|
||||
if len(metadata) == 10:
|
||||
verify_unselected_snapshot(snapshot, components, wanted)
|
||||
source_uids = {
|
||||
str(component.UID)
|
||||
for component in components
|
||||
if attribute_value(component, "Part Number").casefold() == metadata[2].casefold()
|
||||
if str(component.UID) in wanted and attribute_value(component, "Part Number").casefold() == metadata[2].casefold()
|
||||
}
|
||||
if source_uids != wanted:
|
||||
binding = require_resumable_transaction(snapshot, report, metadata, records)
|
||||
@@ -368,7 +426,10 @@ def run_native(snapshot, report):
|
||||
return
|
||||
components = select_snapshot_batch(app, api, metadata, records)
|
||||
before_uids = {str(component.UID) for component in components}
|
||||
untouched = {str(component.UID): attribute_value(component, "Part Number") for component in components if str(component.UID) not in wanted}
|
||||
untouched = {str(component.UID): (
|
||||
str(component.Refdes),
|
||||
*(attribute_value(component, name) for name in ("Part Number", "Value", "Part Name", "Part Label"))
|
||||
) for component in components if str(component.UID) not in wanted}
|
||||
view_handle = int(app.ActiveViewHandle)
|
||||
process_id = win32process.GetWindowThreadProcessId(view_handle)[1]
|
||||
main_handle = win32gui.GetAncestor(view_handle, 2)
|
||||
@@ -536,11 +597,18 @@ def run_native(snapshot, report):
|
||||
selected_replaced, "Native replacement did not complete", timeout=30
|
||||
)
|
||||
current = components_on_sheet(app, api)
|
||||
if len(metadata) == 10:
|
||||
verify_unselected_snapshot(snapshot, current, wanted)
|
||||
if len(current) != len(before_uids):
|
||||
raise ValueError("Component count changed during replacement")
|
||||
current_by_uid = {str(component.UID): component for component in current}
|
||||
for uid, number in untouched.items():
|
||||
if uid not in current_by_uid or attribute_value(current_by_uid[uid], "Part Number") != number:
|
||||
for uid, identity in untouched.items():
|
||||
component = current_by_uid.get(uid)
|
||||
current_identity = None if component is None else (
|
||||
str(component.Refdes),
|
||||
*(attribute_value(component, name) for name in ("Part Number", "Value", "Part Name", "Part Label"))
|
||||
)
|
||||
if current_identity != identity:
|
||||
raise ValueError("An unselected component was changed")
|
||||
verified_uids = replacement_matches(current, records, metadata[3], require_part_label)
|
||||
if verified_uids is None or set(verified_uids) != set(report["replaced_uids"]):
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Frozen, read-only data presented by the single-project task UI."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from .models import ProjectRecord, RuleRecord, TaskRecord
|
||||
from .quick_run import QuickRunProgress
|
||||
from .target_plan import TargetPlanRow
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ProjectTaskContext:
|
||||
"""One refreshable snapshot of a task and its bound project.
|
||||
|
||||
``project`` is ``None`` for historical tasks that do not have exactly one
|
||||
immutable project binding. Such contexts are intentionally read-only.
|
||||
"""
|
||||
|
||||
task: TaskRecord
|
||||
project: ProjectRecord | None
|
||||
rules: tuple[RuleRecord, ...]
|
||||
targets: tuple[TargetPlanRow, ...]
|
||||
progress: QuickRunProgress
|
||||
phase: str
|
||||
has_evidence: bool
|
||||
interrupted: bool
|
||||
legacy: bool
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Read-only project discovery worker orchestration, independent of execution queues."""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
from uuid import uuid4
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .quick_run_protocol import ProjectDiscovery, _encode_vbs_field
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class DiscoveryRuntime:
|
||||
"""Worker and evidence adapters shared with the execution entry point."""
|
||||
process_runner: Callable[[tuple[str, ...], int], subprocess.CompletedProcess[str]]
|
||||
cscript_resolver: Callable[[], Path]
|
||||
worker_paths: Callable[[Path, Path], tuple[str, str]]
|
||||
helper_launch_arguments: Callable[[], tuple[str, ...]]
|
||||
failure_message: Callable[[str], str]
|
||||
read_sheets: Callable[[Path, Path], tuple[tuple[str, str], ...]]
|
||||
read_matches: Callable[[Path, Path, tuple[tuple[str, str], ...]], dict[tuple[str, str], frozenset[str]]]
|
||||
timeout: int
|
||||
|
||||
|
||||
def discover_project(
|
||||
project_path: Path,
|
||||
old_part_numbers: tuple[str, ...],
|
||||
*,
|
||||
data_root: Path,
|
||||
script_source: Path,
|
||||
runtime: DiscoveryRuntime,
|
||||
collect_components: bool = False,
|
||||
) -> ProjectDiscovery:
|
||||
"""Enumerate sheets and requested source parts while the owned project is open."""
|
||||
project = project_path.resolve(strict=True)
|
||||
token = uuid4().hex
|
||||
job_id = "discover_" + token
|
||||
root = data_root / "quick-run-history" / ("sheet-discovery-" + token)
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
script = root / "QuickPartReplace.vbs"
|
||||
shutil.copyfile(script_source, script)
|
||||
(root / "command.tsv").write_text(
|
||||
"task_id\tjob_id\tproject_path\told_part\tnew_part\tvalue_mode\r\n"
|
||||
f"sheet_discovery\t{job_id}\t{project}\tDISCOVERY_OLD\tDISCOVERY_NEW\tpreserve\r\n",
|
||||
encoding="utf-8",
|
||||
newline="",
|
||||
)
|
||||
(root / "status.tsv").write_text("job_id\tstate\tcode\tmessage\r\n", encoding="utf-8", newline="")
|
||||
(root / "batch.request").write_text(job_id, encoding="ascii")
|
||||
(root / "sheet-discovery.request").write_text(job_id, encoding="ascii")
|
||||
requested: dict[str, str] = {}
|
||||
for old_part_number in old_part_numbers:
|
||||
requested.setdefault(old_part_number.casefold(), old_part_number)
|
||||
(root / "inventory-request.tsv").write_text(
|
||||
"old_part\r\n" + "".join(
|
||||
f"{_encode_vbs_field(old_part_number)}\r\n"
|
||||
for old_part_number in requested.values()
|
||||
),
|
||||
encoding="utf-8",
|
||||
newline="",
|
||||
)
|
||||
if collect_components:
|
||||
(root / "component-inventory.request").write_text(job_id, encoding="ascii")
|
||||
script_argument, root_argument = runtime.worker_paths(script, root)
|
||||
command = (
|
||||
str(runtime.cscript_resolver()),
|
||||
"//nologo",
|
||||
script_argument,
|
||||
root_argument,
|
||||
*runtime.helper_launch_arguments(),
|
||||
job_id,
|
||||
)
|
||||
try:
|
||||
completed = runtime.process_runner(command, runtime.timeout)
|
||||
except (OSError, subprocess.SubprocessError) as error:
|
||||
raise TaskCenterError(
|
||||
"quick_run_sheet_discovery",
|
||||
f"枚举工程图页时执行器未能安全结束:{project};{error}",
|
||||
) from error
|
||||
(root / "worker-output.txt").write_text(completed.stdout + "\n" + completed.stderr, encoding="utf-8")
|
||||
if completed.returncode != 0:
|
||||
detail = completed.stderr.strip() or completed.stdout.strip() or "sheet discovery failed"
|
||||
raise TaskCenterError("quick_run_sheet_discovery", runtime.failure_message(detail))
|
||||
sheets = runtime.read_sheets(root / "sheets.tsv", project)
|
||||
matches = runtime.read_matches(root / "inventory.tsv", project, sheets)
|
||||
if collect_components:
|
||||
from .inventory import read_component_inventory
|
||||
components = read_component_inventory(root / "components.tsv", project, sheets)
|
||||
else:
|
||||
components = ()
|
||||
return ProjectDiscovery(sheets, matches, components)
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
"""A supervised worker retained between verified steps of one owned project."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
from threading import Event, Thread
|
||||
from uuid import uuid4
|
||||
|
||||
from .worker_monitor import WorkerMonitorError, run_monitored_process
|
||||
|
||||
|
||||
def _write_control(path: Path, value: str):
|
||||
temporary = path.with_name(path.name + '.' + uuid4().hex + '.tmp')
|
||||
temporary.write_text(value, encoding='utf-8')
|
||||
temporary.replace(path)
|
||||
|
||||
|
||||
class ProjectSessionWorker:
|
||||
"""Only a saved-and-reopened checkpoint releases the caller for its next step.
|
||||
|
||||
The VBS worker owns CAD. This driver never attaches to COM or terminates CAD.
|
||||
A separate monitor thread retains the existing idle watchdog and worker job.
|
||||
"""
|
||||
def __init__(self, project: Path, root: Path, *, private_desktop=False):
|
||||
self.project, self.root = Path(project), Path(root)
|
||||
self.token = uuid4().hex
|
||||
self._done, self._abort = Event(), Event()
|
||||
self._thread = None
|
||||
self._command = None
|
||||
self._result = self._error = None
|
||||
self._waiting = False
|
||||
self._closed = False
|
||||
self._failure_delivered = False
|
||||
self._timeout = 150
|
||||
self.starts = 0
|
||||
self.private_desktop = private_desktop
|
||||
|
||||
def _monitor(self, command, timeout):
|
||||
try:
|
||||
if self.private_desktop:
|
||||
from .isolated_cad import run_isolated_process
|
||||
self._result = run_isolated_process(command, timeout, abort_event=self._abort)
|
||||
else:
|
||||
self._result = run_monitored_process(command, timeout, abort_event=self._abort)
|
||||
except Exception as error:
|
||||
self._error = error
|
||||
finally:
|
||||
self._done.set()
|
||||
|
||||
def run_step(self, command: tuple[str, ...], timeout: float):
|
||||
if self._closed:
|
||||
raise WorkerMonitorError('project session is already closed')
|
||||
if Path(command[3]).resolve() != self.root.resolve():
|
||||
raise WorkerMonitorError('project session evidence root changed')
|
||||
if self._command is not None and command[:-1] != self._command[:-1]:
|
||||
raise WorkerMonitorError('project session worker configuration changed')
|
||||
job = command[-1]
|
||||
if self._thread is None:
|
||||
self.root.mkdir(parents=True, exist_ok=True)
|
||||
_write_control(self.root / 'project-session.request', f'{self.token}\t{self.project}\t{job}')
|
||||
(self.root / 'project-session-next.tsv').unlink(missing_ok=True)
|
||||
(self.root / 'project-session-result.tsv').unlink(missing_ok=True)
|
||||
self._command, self._timeout = command, timeout
|
||||
self._thread = Thread(target=self._monitor, args=(command, timeout), daemon=True,
|
||||
name='dxpart-project-session')
|
||||
self.starts += 1
|
||||
self._thread.start()
|
||||
else:
|
||||
if not self._waiting:
|
||||
raise WorkerMonitorError('project session has no verified checkpoint')
|
||||
self._waiting = False
|
||||
_write_control(self.root / 'project-session-next.tsv', f'{self.token}\t{job}')
|
||||
while True:
|
||||
if self._done.is_set():
|
||||
if self._error is not None:
|
||||
raise self._error
|
||||
if self._result.returncode == 0:
|
||||
raise WorkerMonitorError('project session exited before authorized closing')
|
||||
self._failure_delivered = True
|
||||
return self._result
|
||||
try:
|
||||
fields = (self.root / 'project-session-result.tsv').read_text(encoding='utf-8-sig').strip().split('\t')
|
||||
except (FileNotFoundError, PermissionError):
|
||||
fields = ()
|
||||
if len(fields) == 4 and fields[:2] == [self.token, job]:
|
||||
if fields[2] not in {'saved_ok', 'no_match'} or fields[3] != 'session_verified':
|
||||
raise WorkerMonitorError('project session returned an invalid checkpoint')
|
||||
self._waiting = True
|
||||
return subprocess.CompletedProcess(command, 0, '', '')
|
||||
self._done.wait(0.025)
|
||||
|
||||
def close(self):
|
||||
if self._closed:
|
||||
return
|
||||
try:
|
||||
if self._thread is None:
|
||||
self._closed = True
|
||||
return
|
||||
if not self._done.is_set():
|
||||
_write_control(self.root / 'project-session-next.tsv', f'{self.token}\tclose')
|
||||
close_grace = 60 if self.private_desktop else min(30, max(10, self._timeout))
|
||||
if not self._done.wait(close_grace):
|
||||
self._abort.set()
|
||||
if not self._done.wait(30):
|
||||
raise WorkerMonitorError('owned project cleanup is still pending; retry closing before another task')
|
||||
self._closed = True
|
||||
raise WorkerMonitorError('owned project did not acknowledge session closing')
|
||||
self._closed = True
|
||||
if self._error is not None:
|
||||
raise self._error
|
||||
if self._result.returncode != 0 and not self._failure_delivered:
|
||||
raise WorkerMonitorError('owned project session did not close cleanly: ' + self._result.stderr)
|
||||
finally:
|
||||
if self._done.is_set():
|
||||
for name in ('project-session.request', 'project-session-next.tsv', 'project-session-result.tsv'):
|
||||
(self.root / name).unlink(missing_ok=True)
|
||||
|
||||
|
||||
class ProjectSessionScope:
|
||||
"""One serial task can visit projects, but can hold only one worker at a time."""
|
||||
def __init__(self, fallback, *, enabled, private_desktop=False):
|
||||
self.fallback, self.enabled = fallback, enabled
|
||||
self.worker = None
|
||||
self.private_desktop = private_desktop
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def run_step(self, project, command, timeout):
|
||||
if not self.enabled:
|
||||
return self.fallback(command, timeout)
|
||||
self.prepare(project)
|
||||
if self.worker is None:
|
||||
self.worker = ProjectSessionWorker(Path(project), Path(command[3]), private_desktop=self.private_desktop)
|
||||
return self.worker.run_step(command, timeout)
|
||||
|
||||
def prepare(self, project):
|
||||
if self.worker is not None and (self.worker.project.resolve() != Path(project).resolve()
|
||||
or self.worker._done.is_set()):
|
||||
self.worker.close()
|
||||
self.worker = None
|
||||
|
||||
def __exit__(self, error_type, error, traceback):
|
||||
if self.worker is not None:
|
||||
try:
|
||||
self.worker.close()
|
||||
except Exception:
|
||||
self.worker._abort.set()
|
||||
raise
|
||||
@@ -0,0 +1,143 @@
|
||||
"""Create one task for each discovered schematic project."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from threading import Event
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import stat
|
||||
from uuid import uuid4
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .models import TaskRecord, TaskStatus
|
||||
from .scanner import _is_schematic_project, _reject_reparse
|
||||
from .store import TaskStore
|
||||
|
||||
|
||||
def _validated_root(root: Path, excluded_roots: tuple[Path, ...]) -> tuple[Path, tuple[Path, ...]]:
|
||||
root = Path(os.path.abspath(root))
|
||||
for ancestor in (*reversed(root.parents), root):
|
||||
_reject_reparse(ancestor.lstat(), ancestor)
|
||||
root = root.resolve(strict=True)
|
||||
if not root.is_dir():
|
||||
raise TaskCenterError("discovery_root", "project root is not a directory")
|
||||
excluded = tuple(Path(path).resolve(strict=False) for path in excluded_roots)
|
||||
if any(root.is_relative_to(blocked) for blocked in excluded):
|
||||
raise TaskCenterError("discovery_root", "project root is inside an excluded directory")
|
||||
return root, excluded
|
||||
|
||||
|
||||
def scan_project_directory(root: Path, *, excluded_roots: tuple[Path, ...] = (),
|
||||
stop_event: Event | None = None,
|
||||
on_progress: Callable[[Path, int, int], None] | None = None) -> tuple[Path, ...]:
|
||||
"""Scan cooperatively; cancellation raises rather than returning partial results.
|
||||
|
||||
Progress reports (current directory, visited directories, discovered projects).
|
||||
The callback runs on the scanning thread.
|
||||
"""
|
||||
def check_cancelled():
|
||||
if stop_event is not None and stop_event.is_set():
|
||||
raise TaskCenterError("discovery_cancelled", "directory scan cancelled")
|
||||
|
||||
check_cancelled()
|
||||
root, excluded = _validated_root(root, excluded_roots)
|
||||
found: list[Path] = []
|
||||
pending = [root]
|
||||
visited = 0
|
||||
while pending:
|
||||
check_cancelled()
|
||||
directory = pending.pop()
|
||||
_reject_reparse(directory.lstat(), directory)
|
||||
children = []
|
||||
with os.scandir(directory) as entries:
|
||||
for entry in entries:
|
||||
check_cancelled()
|
||||
children.append(entry)
|
||||
projects: list[Path] = []
|
||||
folders: list[Path] = []
|
||||
for entry in sorted(children, key=lambda item: item.name.casefold()):
|
||||
check_cancelled()
|
||||
path = Path(entry.path)
|
||||
if any(path.is_relative_to(blocked) for blocked in excluded):
|
||||
continue
|
||||
details = entry.stat(follow_symlinks=False)
|
||||
_reject_reparse(details, path)
|
||||
if stat.S_ISDIR(details.st_mode):
|
||||
folders.append(path)
|
||||
elif stat.S_ISREG(details.st_mode) and path.suffix.casefold() == ".prj" and _is_schematic_project(path):
|
||||
projects.append(path.resolve(strict=True))
|
||||
found.extend(projects)
|
||||
visited += 1
|
||||
if on_progress is not None:
|
||||
on_progress(directory, visited, len(found))
|
||||
check_cancelled()
|
||||
if not projects:
|
||||
pending.extend(reversed(folders))
|
||||
return tuple(found)
|
||||
|
||||
|
||||
def _validate_selected(root: Path, selected_paths: tuple[Path, ...], excluded: tuple[Path, ...]) -> tuple[Path, ...]:
|
||||
selected: set[Path] = set()
|
||||
ancestor_projects: dict[Path, bool] = {}
|
||||
for candidate in selected_paths:
|
||||
path = Path(os.path.abspath(candidate))
|
||||
if not path.is_relative_to(root) or any(path.is_relative_to(blocked) for blocked in excluded):
|
||||
raise TaskCenterError("project_selection", "selected project is outside discovery results")
|
||||
relative = path.relative_to(root)
|
||||
cursor = root
|
||||
for part in relative.parts:
|
||||
cursor /= part
|
||||
_reject_reparse(cursor.lstat(), cursor)
|
||||
if not path.is_file() or path.suffix.casefold() != ".prj" or not _is_schematic_project(path):
|
||||
raise TaskCenterError("project_selection", "selected file is not a schematic project")
|
||||
# A project in any ancestor directory stops discovery below that directory.
|
||||
directory = path.parent
|
||||
while directory != root:
|
||||
directory = directory.parent
|
||||
if directory not in ancestor_projects:
|
||||
has_project = False
|
||||
with os.scandir(directory) as entries:
|
||||
for entry in entries:
|
||||
sibling = Path(entry.path)
|
||||
if sibling.suffix.casefold() != ".prj" or any(sibling.is_relative_to(b) for b in excluded):
|
||||
continue
|
||||
details = entry.stat(follow_symlinks=False)
|
||||
_reject_reparse(details, sibling)
|
||||
if stat.S_ISREG(details.st_mode) and _is_schematic_project(sibling):
|
||||
has_project = True
|
||||
break
|
||||
ancestor_projects[directory] = has_project
|
||||
if ancestor_projects[directory]:
|
||||
raise TaskCenterError("project_selection", "selected project is hidden by an ancestor project")
|
||||
selected.add(path.resolve(strict=True))
|
||||
return tuple(sorted(selected, key=lambda path: str(path).casefold()))
|
||||
|
||||
|
||||
def create_project_tasks(store: TaskStore, root: Path, *, selected_paths: tuple[Path, ...] | None = None,
|
||||
excluded_roots: tuple[Path, ...] = ()) -> tuple[TaskRecord, ...]:
|
||||
root, excluded = _validated_root(root, excluded_roots)
|
||||
discovered = (scan_project_directory(root, excluded_roots=excluded) if selected_paths is None
|
||||
else _validate_selected(root, selected_paths, excluded))
|
||||
active_paths = {project.path.resolve(strict=False) for task in store.list_tasks()
|
||||
if task.status not in {TaskStatus.DELETED, TaskStatus.COMPLETED}
|
||||
for project in store.list_projects(task.task_id)}
|
||||
pending = [path for path in discovered if path not in active_paths]
|
||||
group_id = uuid4().hex
|
||||
created: list[TaskRecord] = []
|
||||
with store.transaction():
|
||||
names = {task.name.casefold() for task in store.list_tasks()}
|
||||
for position, path in enumerate(pending):
|
||||
base_name = path.relative_to(root).as_posix()
|
||||
name = base_name
|
||||
suffix = 2
|
||||
while name.casefold() in names:
|
||||
name = f"{base_name} ({suffix})"
|
||||
suffix += 1
|
||||
names.add(name.casefold())
|
||||
task = store.create_task(name)
|
||||
project = store.sync_projects(task.task_id, root, (path,))[0]
|
||||
store.set_project_selected(project.project_id, True)
|
||||
created.append(store.bind_project_task(task.task_id, project.project_id, group_id, position))
|
||||
return tuple(created)
|
||||
@@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from functools import lru_cache
|
||||
@@ -31,60 +32,9 @@ _BATCH_LOG_ROTATION_INTERVAL = 16
|
||||
_MISSING_PROJECT_SHEET = ("__missing_project__", "0")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class QuickRunResult:
|
||||
"""The files an operator needs to run and diagnose one quick replacement pass."""
|
||||
|
||||
script_path: Path
|
||||
command_path: Path
|
||||
status_path: Path
|
||||
log_path: Path
|
||||
vbs_root_compatible: bool
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class QuickRunStepResult:
|
||||
"""The correlated result produced by one automatic replacement pass."""
|
||||
|
||||
script_path: Path
|
||||
command_path: Path
|
||||
status_path: Path
|
||||
log_path: Path
|
||||
state: str
|
||||
message: str
|
||||
next_project_path: Path | None = None
|
||||
next_old_part_number: str | None = None
|
||||
next_new_part_number: str | None = None
|
||||
next_schematic_name: str | None = None
|
||||
next_sheet_number: str | None = None
|
||||
progress: QuickRunProgress | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class QuickRunProgress:
|
||||
"""Durable progress reconstructed from the correlated handoff files."""
|
||||
|
||||
completed_items: int
|
||||
total_items: int
|
||||
next_project_path: Path | None
|
||||
next_old_part_number: str | None
|
||||
next_new_part_number: str | None
|
||||
completed_project_paths: tuple[Path, ...]
|
||||
queue_complete: bool
|
||||
no_match_items: int = 0
|
||||
project_summaries: tuple[tuple[Path, str], ...] = ()
|
||||
saved_items: int = 0
|
||||
next_schematic_name: str | None = None
|
||||
next_sheet_number: str | None = None
|
||||
page_addressed: bool = False
|
||||
failed_items: int = 0
|
||||
failed_project_summaries: tuple[tuple[Path, str], ...] = ()
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _ProjectDiscovery:
|
||||
sheets: tuple[tuple[str, str], ...]
|
||||
matched_old_parts: dict[tuple[str, str], frozenset[str]]
|
||||
from .quick_run_protocol import (QuickRunResult, QuickRunStepResult, QuickRunProgress,
|
||||
ProjectDiscovery, _ProjectDiscovery, _encode_vbs_field, _decode_vbs_field)
|
||||
from .quick_run_snapshot import QuickRunSnapshot, read_snapshot
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
@@ -106,6 +56,10 @@ class QuickRunBatchSession:
|
||||
command_stamp: tuple[int, int, int, int, int]
|
||||
manifest_stamp: tuple[int, int, int, int, int] | None
|
||||
completed_project_keys: set[str]
|
||||
status_stamp: tuple[int, int, int, int, int]
|
||||
command_header: str
|
||||
target_command_rows: dict[str, str]
|
||||
worker_paths: tuple[str, str]
|
||||
|
||||
|
||||
class _ProcessRunner(Protocol):
|
||||
@@ -131,6 +85,8 @@ class QuickRunPreparer:
|
||||
self._process_runner = process_runner or _run_process
|
||||
self._cscript_resolver = cscript_resolver or _resolve_cscript
|
||||
self._sheet_discoverer = sheet_discoverer
|
||||
from .discovery_cache import DiscoveryCache
|
||||
self._discovery_cache = DiscoveryCache(self._data_root)
|
||||
|
||||
def prepare(
|
||||
self,
|
||||
@@ -151,6 +107,7 @@ class QuickRunPreparer:
|
||||
raise TaskCenterError("enabled_rule_required", "at least one replacement rule must be enabled")
|
||||
source = self._required_script_source()
|
||||
self._validate_fields(selected_projects, enabled_rules)
|
||||
_validate_target_scope(selected_projects, enabled_rules, sheet_targets)
|
||||
run_token = _safe_run_token(self._run_token_factory())
|
||||
maintain_quick_run_storage(self._data_root)
|
||||
|
||||
@@ -240,7 +197,7 @@ class QuickRunPreparer:
|
||||
if before_sheet_discovery is not None:
|
||||
before_sheet_discovery(project.path)
|
||||
if self._sheet_discoverer is None:
|
||||
discovery = self._discover_project_sheets(project.path, old_part_numbers)
|
||||
discovery = self.discover_project(project.path, old_part_numbers)
|
||||
targets = discovery.sheets
|
||||
assert discovery_matches is not None
|
||||
discovery_matches[_path_key(project.path)] = discovery.matched_old_parts
|
||||
@@ -308,6 +265,10 @@ class QuickRunPreparer:
|
||||
project_keys_by_index = tuple(_path_key(command[2]) for command in commands)
|
||||
status_stat = _required_stat(handoff.status_path, "quick_run_status", "cannot inspect quick-run status")
|
||||
manifest_path = handoff.command_path.with_name("sheets.tsv")
|
||||
command_lines = handoff.command_path.read_text(encoding='utf-8-sig').splitlines()
|
||||
job_column = command_lines[0].split('\t').index('job_id')
|
||||
target_command_rows = ({line.split('\t')[job_column]: line for line in command_lines[1:] if line}
|
||||
if 'target_scope' in command_lines[0].split('\t') else {})
|
||||
return QuickRunBatchSession(
|
||||
task_id,
|
||||
_value_mode(copy_part_number_to_value),
|
||||
@@ -326,8 +287,26 @@ class QuickRunPreparer:
|
||||
_file_stamp(handoff.command_path),
|
||||
_file_stamp(manifest_path) if sheets is not None else None,
|
||||
{_path_key(path) for path in progress.completed_project_paths},
|
||||
_stat_stamp(status_stat),
|
||||
command_lines[0],
|
||||
target_command_rows,
|
||||
_vbs_worker_paths(handoff.script_path, handoff.script_path.parent),
|
||||
)
|
||||
|
||||
@contextmanager
|
||||
def project_session_scope(self, *, enabled=True):
|
||||
"""Retain only the built-in supervised worker; injected workers stay compatible."""
|
||||
from .project_session import ProjectSessionScope
|
||||
from .worker_monitor import WorkerMonitorError
|
||||
try:
|
||||
with ProjectSessionScope(self._process_runner,
|
||||
enabled=enabled and self._process_runner is _run_process, private_desktop=True) as scope:
|
||||
yield scope
|
||||
except (WorkerMonitorError, subprocess.TimeoutExpired) as error:
|
||||
_write_uncertain_flag(self._data_root / 'quick-run/uncertain.flag', 'project_session_cleanup')
|
||||
raise TaskCenterError('quick_run_uncertain',
|
||||
'工程会话未能确认安全关闭,队列已停止;请保留工程和执行证据后核验恢复。') from error
|
||||
|
||||
def execute_step(
|
||||
self,
|
||||
task_id: str,
|
||||
@@ -338,11 +317,26 @@ class QuickRunPreparer:
|
||||
expected_item: tuple[str, str, str, str] | None = None,
|
||||
batch_mode: bool = False,
|
||||
batch_session: QuickRunBatchSession | None = None,
|
||||
project_session=None,
|
||||
) -> QuickRunStepResult:
|
||||
"""Prepare or resume a queue, then execute one replacement rule end to end."""
|
||||
uncertain_path = self._data_root / "quick-run" / "uncertain.flag"
|
||||
if uncertain_path.exists():
|
||||
raise TaskCenterError("quick_run_uncertain", "a previous quick-run worker timed out or returned an uncorrelated status; reconcile the project before retrying")
|
||||
if self._process_runner is _run_process and not batch_mode:
|
||||
from .single_step import prepare_private_single_step
|
||||
prepare_private_single_step(self, task_id, projects, rules, copy_part_number_to_value)
|
||||
batch_mode = True
|
||||
current_root = self._data_root / "quick-run"
|
||||
if batch_session is None and self.evidence_path(task_id) == current_root and (current_root / "status.tsv").is_file():
|
||||
recorded = _read_status_details(current_root / "status.tsv")
|
||||
latest_states = {job_id: state for job_id, state, _, _ in recorded}
|
||||
if any(state == BATCH_SAVED_UNVERIFIED_STATE for state in latest_states.values()):
|
||||
_write_uncertain_flag(uncertain_path, "saved_readback_unverified")
|
||||
raise TaskCenterError("quick_run_uncertain", "saved readback was not verified; reconcile before continuing")
|
||||
if batch_session is not None and any(state == BATCH_SAVED_UNVERIFIED_STATE for state, _ in batch_session.latest.values()):
|
||||
_write_uncertain_flag(uncertain_path, 'saved_readback_unverified')
|
||||
raise TaskCenterError('quick_run_uncertain', 'saved readback was not verified; reconcile before continuing')
|
||||
value_mode = _value_mode(copy_part_number_to_value)
|
||||
if batch_session is not None:
|
||||
if not batch_mode or batch_session.task_id != task_id or batch_session.value_mode != value_mode:
|
||||
@@ -364,7 +358,12 @@ class QuickRunPreparer:
|
||||
self._validate_fields(selected_projects, enabled_rules)
|
||||
handoff = self._resumable_handoff(task_id, selected_projects, enabled_rules, value_mode)
|
||||
if handoff is None:
|
||||
handoff = self.prepare(task_id, projects, rules, copy_part_number_to_value=copy_part_number_to_value)
|
||||
if any(getattr(rule, "scope", "all") == "targets" for rule in enabled_rules):
|
||||
handoff = self.ensure_batch_handoff(task_id, projects, rules,
|
||||
copy_part_number_to_value=copy_part_number_to_value)
|
||||
else:
|
||||
handoff = self.prepare(task_id, projects, rules,
|
||||
copy_part_number_to_value=copy_part_number_to_value)
|
||||
else:
|
||||
source = self._required_script_source()
|
||||
if source.resolve() != handoff.script_path.resolve():
|
||||
@@ -377,11 +376,13 @@ class QuickRunPreparer:
|
||||
actual_item = (*selected_command[2:], value_mode)
|
||||
if expected_item is not None and actual_item != expected_item:
|
||||
raise TaskCenterError("quick_run_selection_changed", "confirmed queue item or Value policy changed; confirm again")
|
||||
script_argument, root_argument = (batch_session.worker_paths if batch_session is not None
|
||||
else _vbs_worker_paths(handoff.script_path, handoff.script_path.parent))
|
||||
command = (
|
||||
str(self._cscript_resolver()),
|
||||
"//nologo",
|
||||
str(handoff.script_path),
|
||||
str(handoff.script_path.parent),
|
||||
script_argument,
|
||||
root_argument,
|
||||
*_native_helper_launch_arguments(),
|
||||
selected_command[1],
|
||||
)
|
||||
@@ -395,8 +396,12 @@ class QuickRunPreparer:
|
||||
batch_request.unlink(missing_ok=True)
|
||||
from .worker_monitor import WorkerMonitorError
|
||||
|
||||
self.invalidate_discovery(Path(selected_command[2]))
|
||||
try:
|
||||
completed = self._process_runner(command, IDLE_PROGRESS_TIMEOUT_SECONDS)
|
||||
if project_session is not None:
|
||||
completed = project_session.run_step(Path(selected_command[2]), command, IDLE_PROGRESS_TIMEOUT_SECONDS)
|
||||
else:
|
||||
completed = self._process_runner(command, IDLE_PROGRESS_TIMEOUT_SECONDS)
|
||||
except subprocess.TimeoutExpired as error:
|
||||
_write_uncertain_flag(uncertain_path, "worker_timeout")
|
||||
_append_log(handoff.log_path, "quick_run_uncertain worker_timeout")
|
||||
@@ -433,7 +438,7 @@ class QuickRunPreparer:
|
||||
status_offset = 0
|
||||
status_identity = (0, 0)
|
||||
else:
|
||||
appended, status_offset, status_identity = _read_appended_status_details(batch_session)
|
||||
appended, status_offset, status_identity, status_stamp = _read_appended_status_details(batch_session)
|
||||
after = before + appended
|
||||
except TaskCenterError as error:
|
||||
_write_uncertain_flag(uncertain_path, "malformed_status_after_worker")
|
||||
@@ -457,7 +462,9 @@ class QuickRunPreparer:
|
||||
_append_log(handoff.log_path, f"quick_run_uncertain uncorrelated_status exit_code={completed.returncode}")
|
||||
raise TaskCenterError("quick_run_uncertain", "quick-run worker returned an uncorrelated status; reconcile the project before retrying")
|
||||
_, state, code, message = changed
|
||||
if batch_mode and completed.returncode == 0 and state in DONE_STATES and code != "batch_closed":
|
||||
verified_session = bool(project_session is not None and project_session.enabled
|
||||
and code == 'session_verified')
|
||||
if batch_mode and completed.returncode == 0 and state in DONE_STATES and code != "batch_closed" and not verified_session:
|
||||
_write_uncertain_flag(uncertain_path, "batch_save_close_unverified")
|
||||
raise TaskCenterError("quick_run_uncertain", "批量步骤未确认保存关闭完成,队列已停止,不会继续下一工程。")
|
||||
check_log_rotation = (
|
||||
@@ -482,6 +489,8 @@ class QuickRunPreparer:
|
||||
_write_uncertain_flag(uncertain_path, "worker_exited_before_native_completion")
|
||||
_append_log(handoff.log_path, "quick_run_uncertain worker_exited_before_native_completion")
|
||||
raise TaskCenterError("quick_run_uncertain", "执行器已退出,但未返回替换收尾结果;请核验恢复,不要重复替换。")
|
||||
if state == BATCH_SAVED_UNVERIFIED_STATE:
|
||||
_write_uncertain_flag(uncertain_path, "saved_readback_unverified")
|
||||
if state in {BATCH_FAILED_STATE, BATCH_SAVED_UNVERIFIED_STATE} and (not batch_mode or batch_session is None):
|
||||
raise TaskCenterError("quick_run_execution", message or "batch project failed")
|
||||
if (completed.returncode != 0 or state == "hard_failure") and state not in {
|
||||
@@ -523,6 +532,7 @@ class QuickRunPreparer:
|
||||
batch_session.statuses = after
|
||||
batch_session.status_offset = status_offset
|
||||
batch_session.status_identity = status_identity
|
||||
batch_session.status_stamp = status_stamp
|
||||
_advance_batch_session(batch_session, changed)
|
||||
progress = batch_session.progress
|
||||
next_command = commands[batch_session.next_index] if batch_session.next_index < len(commands) else None
|
||||
@@ -546,142 +556,28 @@ class QuickRunPreparer:
|
||||
progress,
|
||||
)
|
||||
|
||||
def read_snapshot(self, task_id, projects, rules, *, copy_part_number_to_value=False,
|
||||
read_control=None) -> QuickRunSnapshot:
|
||||
"""Read one consistent set of handoff evidence without changing it."""
|
||||
return read_snapshot(self, task_id, projects, rules,
|
||||
copy_part_number_to_value=copy_part_number_to_value, read_control=read_control)
|
||||
|
||||
def has_interrupted(self, task_id: str) -> bool:
|
||||
root = self._data_root / "quick-run"
|
||||
if self.evidence_path(task_id) != root:
|
||||
return False
|
||||
if (root / "uncertain.flag").is_file():
|
||||
return True
|
||||
try:
|
||||
commands = _read_commands(root / "command.tsv")
|
||||
statuses = _read_status_details(root / "status.tsv")
|
||||
current = _next_unfinished_command(commands, statuses)
|
||||
if current is None:
|
||||
return False
|
||||
final_state = next((entry[1] for entry in reversed(statuses) if entry[0] == current[1]), None)
|
||||
if final_state == "awaiting_native_replace":
|
||||
return True
|
||||
return final_state == "hard_failure" and _recover_pre_mutation_hard_failures(root, commands, statuses) == statuses
|
||||
except TaskCenterError:
|
||||
return False
|
||||
return self.read_snapshot(task_id, (), ()).interrupted
|
||||
|
||||
def current_phase(
|
||||
self,
|
||||
task_id: str,
|
||||
projects: tuple[ProjectRecord, ...],
|
||||
rules: tuple[RuleRecord, ...],
|
||||
*,
|
||||
copy_part_number_to_value: bool = False,
|
||||
) -> str:
|
||||
"""Read the matching local handoff queue without starting DxDesigner."""
|
||||
selected_projects = _selected_projects(projects)
|
||||
enabled_rules = tuple(rule for rule in rules if rule.enabled)
|
||||
if not selected_projects or not enabled_rules:
|
||||
return "selection"
|
||||
try:
|
||||
self._validate_fields(selected_projects, enabled_rules)
|
||||
root = self.evidence_path(task_id) or self._data_root / "quick-run"
|
||||
command_path = root / "command.tsv"
|
||||
status_path = root / "status.tsv"
|
||||
if not command_path.is_file() or not status_path.is_file():
|
||||
return "selection"
|
||||
commands = _read_commands(command_path)
|
||||
command_project_keys = {_path_key(command[2]) for command in commands}
|
||||
queued_projects = tuple(
|
||||
project for project in selected_projects
|
||||
if _path_key(project.path) in command_project_keys
|
||||
)
|
||||
if not _value_mode_matches_option(_queue_value_mode(command_path), copy_part_number_to_value):
|
||||
return "selection"
|
||||
command_task_ids = {command_task_id for command_task_id, *_ in commands}
|
||||
if command_task_ids != {task_id} or not _queue_matches_inputs(
|
||||
command_path, commands, queued_projects, enabled_rules
|
||||
):
|
||||
return "selection"
|
||||
statuses = {job_id: state for job_id, state, _, _ in _read_status_details(status_path)}
|
||||
except TaskCenterError:
|
||||
return "selection"
|
||||
relevant_states = tuple(statuses.get(job_id, "") for _, job_id, *_ in commands)
|
||||
if any(state == "hard_failure" for state in relevant_states):
|
||||
return "selection"
|
||||
if relevant_states and all(state in TERMINAL_STATES for state in relevant_states):
|
||||
return "complete"
|
||||
return "selection"
|
||||
def current_phase(self, task_id, projects, rules, *, copy_part_number_to_value=False,
|
||||
read_control=None) -> str:
|
||||
snapshot = self.read_snapshot(task_id, projects, rules,
|
||||
copy_part_number_to_value=copy_part_number_to_value, read_control=read_control)
|
||||
return "complete" if snapshot.phase == "retry" else snapshot.phase
|
||||
|
||||
def progress(
|
||||
self,
|
||||
task_id: str,
|
||||
projects: tuple[ProjectRecord, ...],
|
||||
rules: tuple[RuleRecord, ...],
|
||||
*,
|
||||
copy_part_number_to_value: bool = False,
|
||||
) -> QuickRunProgress:
|
||||
"""Reconstruct task progress without executing or modifying DxDesigner."""
|
||||
all_selected_projects = _selected_projects(projects)
|
||||
selected_projects = _queue_projects(projects)
|
||||
enabled_rules = tuple(rule for rule in rules if rule.enabled)
|
||||
expected = tuple(
|
||||
(str(project.path), rule.old_part_number, rule.new_part_number)
|
||||
for project in selected_projects
|
||||
for rule in enabled_rules
|
||||
)
|
||||
fallback = expected[0] if expected else (None, None, None)
|
||||
empty = QuickRunProgress(
|
||||
completed_items=0,
|
||||
total_items=len(expected),
|
||||
next_project_path=_optional_path(fallback[0]),
|
||||
next_old_part_number=fallback[1],
|
||||
next_new_part_number=fallback[2],
|
||||
completed_project_paths=(),
|
||||
queue_complete=False,
|
||||
)
|
||||
root = self.evidence_path(task_id) or self._data_root / "quick-run"
|
||||
command_path = root / "command.tsv"
|
||||
status_path = root / "status.tsv"
|
||||
if not command_path.is_file() or not status_path.is_file():
|
||||
return empty
|
||||
try:
|
||||
commands = _read_commands(command_path)
|
||||
details = _read_status_details(status_path)
|
||||
if not _value_mode_matches_option(_queue_value_mode(command_path), copy_part_number_to_value):
|
||||
return empty
|
||||
command_project_paths = {command[2] for command in commands}
|
||||
queued_projects = tuple(
|
||||
project for project in all_selected_projects
|
||||
if str(project.path) in command_project_paths
|
||||
)
|
||||
if {command_task_id for command_task_id, *_ in commands} != {task_id} or not _queue_matches_inputs(
|
||||
command_path, commands, queued_projects, enabled_rules
|
||||
):
|
||||
return empty
|
||||
sheets = _read_command_sheet_targets(command_path)
|
||||
except TaskCenterError:
|
||||
return empty
|
||||
return _progress_from_queue(queued_projects, commands, details, sheets)
|
||||
def progress(self, task_id, projects, rules, *, copy_part_number_to_value=False,
|
||||
read_control=None) -> QuickRunProgress:
|
||||
return self.read_snapshot(task_id, projects, rules,
|
||||
copy_part_number_to_value=copy_part_number_to_value, read_control=read_control).progress
|
||||
|
||||
def evidence_path(self, task_id: str, project_path: Path | None = None) -> Path | None:
|
||||
"""Return the current or archived handoff directory bound to the task."""
|
||||
current = self._data_root / "quick-run"
|
||||
history = self._data_root / "quick-run-history"
|
||||
archived = tuple(sorted((path for path in history.glob("obsolete-*") if path.is_dir()), reverse=True))
|
||||
for root in (current, *archived):
|
||||
command_path = root / "command.tsv"
|
||||
status_path = root / "status.tsv"
|
||||
if not command_path.is_file() or not status_path.is_file():
|
||||
continue
|
||||
try:
|
||||
commands = _read_commands(command_path)
|
||||
except TaskCenterError:
|
||||
continue
|
||||
matching = tuple(command for command in commands if command[0] == task_id)
|
||||
if not matching or len(matching) != len(commands):
|
||||
continue
|
||||
if project_path is not None and not any(
|
||||
_path_key(command[2]) == _path_key(project_path) for command in matching
|
||||
):
|
||||
continue
|
||||
return root
|
||||
return None
|
||||
return read_snapshot(self, task_id, (), (), project_path=project_path).evidence_path
|
||||
|
||||
def _resumable_handoff(
|
||||
self,
|
||||
@@ -756,61 +652,58 @@ class QuickRunPreparer:
|
||||
self.vbs_root_compatible,
|
||||
)
|
||||
|
||||
@property
|
||||
def data_root(self) -> Path:
|
||||
"""Task evidence root, exposed without private configuration coupling."""
|
||||
return self._data_root
|
||||
|
||||
def for_data_root(self, data_root: Path) -> QuickRunPreparer:
|
||||
"""Clone executor configuration with an independent task-local cache."""
|
||||
return type(self)(data_root, script_source=self._script_source,
|
||||
run_token_factory=self._run_token_factory, process_runner=self._process_runner,
|
||||
cscript_resolver=self._cscript_resolver, sheet_discoverer=self._sheet_discoverer)
|
||||
|
||||
def invalidate_discovery(self, project_path: Path) -> None:
|
||||
"""Discard read-only evidence before any potentially mutating worker."""
|
||||
self._discovery_cache.invalidate(project_path)
|
||||
|
||||
def discover_project(self, project_path: Path, old_part_numbers: tuple[str, ...], *,
|
||||
collect_components: bool = False) -> ProjectDiscovery:
|
||||
def load():
|
||||
if collect_components:
|
||||
return self._discover_project_sheets(project_path, old_part_numbers,
|
||||
collect_components=True)
|
||||
return self._discover_project_sheets(project_path, old_part_numbers)
|
||||
return self._discovery_cache.discover(
|
||||
Path(project_path), old_part_numbers, collect_components, load)
|
||||
|
||||
def collect_inventory(self, project_path: Path, old_part_numbers: tuple[str, ...]) -> tuple:
|
||||
"""Collect validated component targets, retaining reusable sheet evidence."""
|
||||
if not old_part_numbers:
|
||||
raise TaskCenterError("target_inventory", "at least one old Part Number is required")
|
||||
requested = {part.casefold() for part in old_part_numbers}
|
||||
return tuple(component for component in self.discover_project(
|
||||
project_path, old_part_numbers, collect_components=True).components
|
||||
if component.old_part_number.casefold() in requested)
|
||||
|
||||
def _discover_project_sheets(
|
||||
self,
|
||||
project_path: Path,
|
||||
old_part_numbers: tuple[str, ...],
|
||||
*,
|
||||
collect_components: bool = False,
|
||||
) -> _ProjectDiscovery:
|
||||
"""Enumerate sheets and requested source parts while the owned project is open."""
|
||||
project = project_path.resolve(strict=True)
|
||||
token = uuid4().hex
|
||||
job_id = _safe_run_token("discover_" + token)
|
||||
root = self._data_root / "quick-run-history" / ("sheet-discovery-" + token)
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
script = root / "QuickPartReplace.vbs"
|
||||
shutil.copyfile(self._required_script_source(), script)
|
||||
(root / "command.tsv").write_text(
|
||||
"task_id\tjob_id\tproject_path\told_part\tnew_part\tvalue_mode\r\n"
|
||||
f"sheet_discovery\t{job_id}\t{project}\tDISCOVERY_OLD\tDISCOVERY_NEW\tpreserve\r\n",
|
||||
encoding="utf-8",
|
||||
newline="",
|
||||
)
|
||||
(root / "status.tsv").write_text("job_id\tstate\tcode\tmessage\r\n", encoding="utf-8", newline="")
|
||||
(root / "batch.request").write_text(job_id, encoding="ascii")
|
||||
(root / "sheet-discovery.request").write_text(job_id, encoding="ascii")
|
||||
requested: dict[str, str] = {}
|
||||
for old_part_number in old_part_numbers:
|
||||
requested.setdefault(old_part_number.casefold(), old_part_number)
|
||||
(root / "inventory-request.tsv").write_text(
|
||||
"old_part\r\n" + "".join(
|
||||
f"{_encode_vbs_field(old_part_number)}\r\n"
|
||||
for old_part_number in requested.values()
|
||||
),
|
||||
encoding="utf-8",
|
||||
newline="",
|
||||
)
|
||||
command = (
|
||||
str(self._cscript_resolver()),
|
||||
"//nologo",
|
||||
str(script),
|
||||
str(root),
|
||||
*_native_helper_launch_arguments(),
|
||||
job_id,
|
||||
)
|
||||
try:
|
||||
completed = self._process_runner(command, IDLE_PROGRESS_TIMEOUT_SECONDS)
|
||||
except (OSError, subprocess.SubprocessError) as error:
|
||||
raise TaskCenterError(
|
||||
"quick_run_sheet_discovery",
|
||||
f"枚举工程图页时执行器未能安全结束:{project};{error}",
|
||||
) from error
|
||||
(root / "worker-output.txt").write_text(completed.stdout + "\n" + completed.stderr, encoding="utf-8")
|
||||
if completed.returncode != 0:
|
||||
detail = completed.stderr.strip() or completed.stdout.strip() or "sheet discovery failed"
|
||||
raise TaskCenterError("quick_run_sheet_discovery", _session_failure_message(detail))
|
||||
sheets = _read_discovered_sheets(root / "sheets.tsv", project)
|
||||
matches = _read_discovery_inventory(root / "inventory.tsv", project, sheets)
|
||||
return _ProjectDiscovery(sheets, matches)
|
||||
from .project_discovery import DiscoveryRuntime, discover_project
|
||||
|
||||
return discover_project(project_path, old_part_numbers,
|
||||
data_root=self._data_root, script_source=self._required_script_source(),
|
||||
collect_components=collect_components,
|
||||
runtime=DiscoveryRuntime(
|
||||
self._process_runner, self._cscript_resolver, _vbs_worker_paths,
|
||||
_native_helper_launch_arguments, _session_failure_message,
|
||||
_read_discovered_sheets, _read_discovery_inventory,
|
||||
IDLE_PROGRESS_TIMEOUT_SECONDS))
|
||||
|
||||
@property
|
||||
def vbs_root_compatible(self) -> bool:
|
||||
@@ -1436,6 +1329,7 @@ def _initial_discovery_status(
|
||||
return rows[0] + "\r\n"
|
||||
commands = _read_commands(command_path)
|
||||
sheets = _read_command_sheet_targets(command_path)
|
||||
targeted = "target_scope" in command_path.read_text(encoding="utf-8-sig").splitlines()[0].split("\t")
|
||||
if sheets is None:
|
||||
raise TaskCenterError("quick_run_sheet_discovery", "discovery inventory requires page-addressed commands")
|
||||
possible_by_sheet: dict[tuple[str, str, str], set[str]] = {}
|
||||
@@ -1454,7 +1348,7 @@ def _initial_discovery_status(
|
||||
raise TaskCenterError("quick_run_sheet_discovery", "discovery inventory does not match the command queue")
|
||||
possible_key = project_key, sheet[0], sheet[1]
|
||||
possible = possible_by_sheet.setdefault(possible_key, set(project_matches[sheet]))
|
||||
if old_part.casefold() not in possible:
|
||||
if old_part.casefold() not in possible and not targeted:
|
||||
message = (
|
||||
"Read-only discovery found no components matching the old Part Number; "
|
||||
f"the project was closed without replacement. Project={project_path}; "
|
||||
@@ -1476,6 +1370,15 @@ def _queue_matches_inputs(
|
||||
rules: tuple[RuleRecord, ...],
|
||||
) -> bool:
|
||||
base_mode = _queue_value_mode(command_path)
|
||||
if "target_scope" in command_path.read_text(encoding="utf-8-sig").splitlines()[0].split("\t"):
|
||||
sheets = _read_command_sheet_targets(command_path)
|
||||
manifest = _read_sheet_manifest(command_path.with_name("sheets.tsv"), projects) if sheets is not None else None
|
||||
expected = _command_text("expected", "expected", projects, rules, base_mode,
|
||||
sheet_targets=manifest).splitlines()
|
||||
actual = command_path.read_text(encoding="utf-8-sig").splitlines()
|
||||
return (expected[0] == actual[0] and len(expected) == len(actual) and
|
||||
all(expected_row.split("\t")[2:] == actual_row.split("\t")[2:]
|
||||
for expected_row, actual_row in zip(expected[1:], actual[1:])))
|
||||
options = _read_command_options(command_path)
|
||||
sheets = _read_command_sheet_targets(command_path)
|
||||
if sheets is None:
|
||||
@@ -1532,7 +1435,7 @@ def _read_status_details(path: Path) -> tuple[tuple[str, str, str, str], ...]:
|
||||
|
||||
def _read_appended_status_details(
|
||||
session: QuickRunBatchSession,
|
||||
) -> tuple[tuple[tuple[str, str, str, str], ...], int, tuple[int, int]]:
|
||||
) -> tuple[tuple[tuple[str, str, str, str], ...], int, tuple[int, int], tuple[int, int, int, int, int]]:
|
||||
path = session.handoff.status_path
|
||||
try:
|
||||
with path.open("rb") as handle:
|
||||
@@ -1543,7 +1446,7 @@ def _read_appended_status_details(
|
||||
handle.seek(session.status_offset)
|
||||
payload = handle.read()
|
||||
final = os.fstat(handle.fileno())
|
||||
if _file_identity(final) != identity or final.st_size != current.st_size:
|
||||
if _stat_stamp(final)[:4] != _stat_stamp(current)[:4]:
|
||||
raise ValueError("status file changed while it was being read")
|
||||
if len(payload) != final.st_size - session.status_offset:
|
||||
raise ValueError("status tail length is inconsistent")
|
||||
@@ -1558,7 +1461,7 @@ def _read_appended_status_details(
|
||||
if len(fields) != 4 or not fields[0] or not fields[1]:
|
||||
raise ValueError("status tail is malformed")
|
||||
entries.append(tuple(_decode_vbs_field(field) for field in fields))
|
||||
return tuple(entries), final.st_size, identity
|
||||
return tuple(entries), final.st_size, identity, _stat_stamp(final)
|
||||
except (OSError, UnicodeError, ValueError) as error:
|
||||
raise TaskCenterError("quick_run_status", "cannot incrementally read quick-run status") from error
|
||||
|
||||
@@ -1576,10 +1479,22 @@ def _file_identity(stat: os.stat_result) -> tuple[int, int]:
|
||||
|
||||
def _file_stamp(path: Path) -> tuple[int, int, int, int, int]:
|
||||
stat = _required_stat(path, "quick_run_command", "cannot inspect quick-run queue")
|
||||
return _stat_stamp(stat)
|
||||
|
||||
|
||||
def _stat_stamp(stat: os.stat_result) -> tuple[int, int, int, int, int]:
|
||||
return stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns
|
||||
|
||||
|
||||
def _assert_batch_files_unchanged(session: QuickRunBatchSession) -> None:
|
||||
try:
|
||||
# On Windows, stat() and fstat() report different ctime semantics.
|
||||
changed_status = _file_stamp(session.handoff.status_path)[:4] != session.status_stamp[:4]
|
||||
except TaskCenterError:
|
||||
changed_status = True
|
||||
if changed_status:
|
||||
_write_uncertain_flag(session.handoff.command_path.with_name('uncertain.flag'), 'status_changed_between_workers')
|
||||
raise TaskCenterError('quick_run_uncertain', '执行状态文件在步骤间发生变化,尚未启动下一项,请先核验。')
|
||||
if _file_stamp(session.handoff.command_path) != session.command_stamp:
|
||||
raise TaskCenterError("quick_run_selection_changed", "batch command queue changed during execution")
|
||||
manifest_path = session.handoff.command_path.with_name("sheets.tsv")
|
||||
@@ -1592,6 +1507,23 @@ def _write_current_command(
|
||||
command: tuple[str, str, str, str, str],
|
||||
) -> tuple[int, int, int, int, int]:
|
||||
task_id, job_id, project_path, old_part, new_part = command
|
||||
if session.target_command_rows:
|
||||
matching = session.target_command_rows.get(job_id)
|
||||
if matching is None:
|
||||
raise TaskCenterError("quick_run_command", "target command is missing or duplicated")
|
||||
path = session.handoff.command_path.with_name("current-command.tsv")
|
||||
_write_atomic_queue_text(path, session.command_header + "\r\n" + matching + "\r\n",
|
||||
"quick_run_command", "cannot publish the current target command")
|
||||
state = session.latest.get(job_id)
|
||||
state_path = path.with_name("current-state.tsv")
|
||||
if state is None:
|
||||
state_path.unlink(missing_ok=True)
|
||||
else:
|
||||
_write_atomic_queue_text(state_path,
|
||||
"job_id\tstate\tcode\tmessage\r\n" + "\t".join(
|
||||
_encode_vbs_field(field) for field in (job_id, state[0], state[1], "")) + "\r\n",
|
||||
"quick_run_status", "cannot publish the current target state")
|
||||
return _file_stamp(path)
|
||||
value_mode, custom_value, sync_nc, base_value_mode = session.command_options[job_id]
|
||||
if session.sheets is None:
|
||||
header = "task_id\tjob_id\tproject_path\told_part\tnew_part\tvalue_mode\tcustom_value\tsync_nc\tbase_value_mode"
|
||||
@@ -1659,39 +1591,6 @@ def _write_atomic_queue_text(path: Path, text: str, code: str, message: str) ->
|
||||
raise TaskCenterError(code, message) from error
|
||||
|
||||
|
||||
def _encode_vbs_field(value: str) -> str:
|
||||
encoded: list[str] = []
|
||||
for character in str(value):
|
||||
code = ord(character)
|
||||
if character != "%" and 32 <= code <= 126:
|
||||
encoded.append(character)
|
||||
continue
|
||||
units = character.encode("utf-16-le")
|
||||
encoded.extend(
|
||||
f"%{int.from_bytes(units[index:index + 2], 'little'):04X}"
|
||||
for index in range(0, len(units), 2)
|
||||
)
|
||||
return "".join(encoded)
|
||||
|
||||
|
||||
def _decode_vbs_field(value: str) -> str:
|
||||
characters: list[str] = []
|
||||
index = 0
|
||||
while index < len(value):
|
||||
if value[index] == "%" and index + 4 < len(value):
|
||||
token = value[index + 1:index + 5]
|
||||
if all(character in "0123456789abcdefABCDEF" for character in token):
|
||||
characters.append(chr(int(token, 16)))
|
||||
index += 5
|
||||
continue
|
||||
characters.append(value[index])
|
||||
index += 1
|
||||
try:
|
||||
return "".join(characters).encode("utf-16-le", errors="surrogatepass").decode("utf-16-le")
|
||||
except UnicodeError as error:
|
||||
raise ValueError("VBS field contains malformed UTF-16") from error
|
||||
|
||||
|
||||
def _path_key(path: str | Path) -> str:
|
||||
return os.path.normcase(os.path.abspath(str(path)))
|
||||
|
||||
@@ -1758,6 +1657,22 @@ def _next_unfinished_command(
|
||||
return next((command for command in commands if final_states.get(command[1]) not in TERMINAL_STATES), None)
|
||||
|
||||
|
||||
def _vbs_worker_paths(script: Path, root: Path) -> tuple[str, str]:
|
||||
"""FSO cannot see some paths beyond MAX_PATH, including monitor handshakes."""
|
||||
if os.name != 'nt' or len(str(root)) + 100 < 260:
|
||||
return str(script), str(root)
|
||||
import ctypes
|
||||
get_short_path = ctypes.WinDLL('kernel32', use_last_error=True).GetShortPathNameW
|
||||
get_short_path.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint]
|
||||
get_short_path.restype = ctypes.c_uint
|
||||
buffer = ctypes.create_unicode_buffer(32768)
|
||||
count = get_short_path(str(root.resolve(strict=True)), buffer, len(buffer))
|
||||
if not count or count >= len(buffer) or len(buffer.value) + 100 >= 260:
|
||||
raise TaskCenterError('quick_run_path_length',
|
||||
'执行证据目录过长,且系统未提供可用短路径。请将工具和数据放到较短目录后重试;尚未启动 CAD 操作。')
|
||||
return str(Path(buffer.value) / script.name), buffer.value
|
||||
|
||||
|
||||
def _resolve_cscript(windows_root: Path | None = None, is_64_bit: bool | None = None) -> Path:
|
||||
windows = Path(windows_root) if windows_root is not None else Path(os.environ.get("WINDIR", r"C:\Windows"))
|
||||
if is_64_bit is None:
|
||||
@@ -1781,9 +1696,9 @@ def _cached_native_helper_launch_arguments(frozen: bool, executable: str) -> tup
|
||||
|
||||
|
||||
def _run_process(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
|
||||
from .worker_monitor import run_monitored_process
|
||||
from .isolated_cad import run_isolated_process
|
||||
|
||||
return run_monitored_process(command, timeout)
|
||||
return run_isolated_process(command, timeout)
|
||||
|
||||
|
||||
def _log_text(value: str) -> str:
|
||||
@@ -1897,15 +1812,32 @@ def _command_text(
|
||||
*,
|
||||
sheet_targets: dict[str, tuple[tuple[str, str], ...]] | None = None,
|
||||
) -> str:
|
||||
_validate_target_scope(projects, rules, sheet_targets)
|
||||
targeted = any(getattr(rule, "scope", "all") == "targets" for rule in rules)
|
||||
if targeted and sheet_targets is None:
|
||||
raise TaskCenterError("target_scope", "target execution requires sheet-addressed commands")
|
||||
suffix = "\ttarget_scope\ttarget_selectors" if targeted else ""
|
||||
if sheet_targets is None:
|
||||
rows = ["task_id\tjob_id\tproject_path\told_part\tnew_part\tvalue_mode\tcustom_value\tsync_nc\tbase_value_mode"]
|
||||
rows = ["task_id\tjob_id\tproject_path\told_part\tnew_part\tvalue_mode\tcustom_value\tsync_nc\tbase_value_mode" + suffix]
|
||||
else:
|
||||
rows = ["task_id\tjob_id\tproject_path\tschematic_name\tsheet_number\told_part\tnew_part\tvalue_mode\tcustom_value\tsync_nc\tbase_value_mode"]
|
||||
rows = ["task_id\tjob_id\tproject_path\tschematic_name\tsheet_number\told_part\tnew_part\tvalue_mode\tcustom_value\tsync_nc\tbase_value_mode" + suffix]
|
||||
job_index = 0
|
||||
for project in projects:
|
||||
targets = ((None, None),) if sheet_targets is None else sheet_targets[_path_key(project.path)]
|
||||
for schematic_name, sheet_number in targets:
|
||||
for rule in rules:
|
||||
scope = getattr(rule, "scope", "all")
|
||||
if scope == "targets":
|
||||
targets_for_sheet = tuple(target for target in rule.targets
|
||||
if _path_key(target.project_path) == _path_key(project.path)
|
||||
and (target.schematic_name, target.sheet_number) == (schematic_name, sheet_number))
|
||||
if not targets_for_sheet:
|
||||
continue
|
||||
selectors = _encode_vbs_field("\x1e".join(
|
||||
"\x1f".join((target.uid, target.refdes, target.old_value))
|
||||
for target in targets_for_sheet))
|
||||
else:
|
||||
selectors = ""
|
||||
job_id = f"{run_token}_{job_index}"
|
||||
sheet_fields = "" if schematic_name is None else f"\t{schematic_name}\t{sheet_number}"
|
||||
rule_mode, custom_value, sync_nc, base_mode = _rule_command_options(rule, value_mode)
|
||||
@@ -1913,6 +1845,26 @@ def _command_text(
|
||||
f"{task_id}\t{job_id}\t{project.path}{sheet_fields}\t"
|
||||
f"{rule.old_part_number}\t{rule.new_part_number}\t{rule_mode}\t{custom_value}\t"
|
||||
f"{'1' if sync_nc else '0'}\t{base_mode}"
|
||||
+ (f"\t{scope}\t{selectors}" if targeted else "")
|
||||
)
|
||||
job_index += 1
|
||||
return "\r\n".join(rows) + "\r\n"
|
||||
|
||||
|
||||
def _validate_target_scope(projects, rules, sheet_targets) -> None:
|
||||
scopes = {getattr(rule, "scope", "all") for rule in rules}
|
||||
if scopes - {"all", "targets"} or len(scopes) > 1:
|
||||
raise TaskCenterError("target_scope", "all-match and target rules cannot share a queue")
|
||||
if scopes != {"targets"}:
|
||||
return
|
||||
if sheet_targets is None:
|
||||
raise TaskCenterError("target_scope", "target queue requires sheet discovery")
|
||||
available = {(_path_key(project.path), schematic, sheet)
|
||||
for project in projects
|
||||
for schematic, sheet in sheet_targets.get(_path_key(project.path), ())}
|
||||
for rule in rules:
|
||||
if not rule.targets:
|
||||
raise TaskCenterError("empty_target_scope", "target rule has no components")
|
||||
for target in rule.targets:
|
||||
if (_path_key(target.project_path), target.schematic_name, target.sheet_number) not in available:
|
||||
raise TaskCenterError("target_identity", "selected target sheet is missing from discovery")
|
||||
@@ -0,0 +1,101 @@
|
||||
"""Immutable execution protocol models and VBS field codec."""
|
||||
from __future__ import annotations
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class QuickRunResult:
|
||||
"""The files an operator needs to run and diagnose one quick replacement pass."""
|
||||
|
||||
script_path: Path
|
||||
command_path: Path
|
||||
status_path: Path
|
||||
log_path: Path
|
||||
vbs_root_compatible: bool
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class QuickRunStepResult:
|
||||
"""The correlated result produced by one automatic replacement pass."""
|
||||
|
||||
script_path: Path
|
||||
command_path: Path
|
||||
status_path: Path
|
||||
log_path: Path
|
||||
state: str
|
||||
message: str
|
||||
next_project_path: Path | None = None
|
||||
next_old_part_number: str | None = None
|
||||
next_new_part_number: str | None = None
|
||||
next_schematic_name: str | None = None
|
||||
next_sheet_number: str | None = None
|
||||
progress: QuickRunProgress | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class QuickRunProgress:
|
||||
"""Durable progress reconstructed from the correlated handoff files."""
|
||||
|
||||
completed_items: int
|
||||
total_items: int
|
||||
next_project_path: Path | None
|
||||
next_old_part_number: str | None
|
||||
next_new_part_number: str | None
|
||||
completed_project_paths: tuple[Path, ...]
|
||||
queue_complete: bool
|
||||
no_match_items: int = 0
|
||||
project_summaries: tuple[tuple[Path, str], ...] = ()
|
||||
saved_items: int = 0
|
||||
next_schematic_name: str | None = None
|
||||
next_sheet_number: str | None = None
|
||||
page_addressed: bool = False
|
||||
failed_items: int = 0
|
||||
failed_project_summaries: tuple[tuple[Path, str], ...] = ()
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ProjectDiscovery:
|
||||
sheets: tuple[tuple[str, str], ...]
|
||||
matched_old_parts: dict[tuple[str, str], frozenset[str]]
|
||||
components: tuple = ()
|
||||
|
||||
|
||||
# Preserve callers that injected the original discovery boundary.
|
||||
_ProjectDiscovery = ProjectDiscovery
|
||||
|
||||
|
||||
def _encode_vbs_field(value: str) -> str:
|
||||
encoded: list[str] = []
|
||||
for character in str(value):
|
||||
code = ord(character)
|
||||
if character != "%" and 32 <= code <= 126:
|
||||
encoded.append(character)
|
||||
continue
|
||||
units = character.encode("utf-16-le")
|
||||
encoded.extend(
|
||||
f"%{int.from_bytes(units[index:index + 2], 'little'):04X}"
|
||||
for index in range(0, len(units), 2)
|
||||
)
|
||||
return "".join(encoded)
|
||||
|
||||
|
||||
def _decode_vbs_field(value: str) -> str:
|
||||
if value.isascii() and '%' not in value:
|
||||
return value
|
||||
characters: list[str] = []
|
||||
index = 0
|
||||
while index < len(value):
|
||||
if value[index] == "%" and index + 4 < len(value):
|
||||
token = value[index + 1:index + 5]
|
||||
if all(character in "0123456789abcdefABCDEF" for character in token):
|
||||
characters.append(chr(int(token, 16)))
|
||||
index += 5
|
||||
continue
|
||||
characters.append(value[index])
|
||||
index += 1
|
||||
try:
|
||||
return "".join(characters).encode("utf-16-le", errors="surrogatepass").decode("utf-16-le")
|
||||
except UnicodeError as error:
|
||||
raise ValueError("VBS field contains malformed UTF-16") from error
|
||||
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
"""Read-only execution view reconstructed from one cached set of handoff files."""
|
||||
from __future__ import annotations
|
||||
from dataclasses import dataclass, replace
|
||||
from pathlib import Path
|
||||
from .errors import TaskCenterError
|
||||
from .quick_run_protocol import QuickRunProgress
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class QuickRunSnapshot:
|
||||
progress: QuickRunProgress
|
||||
has_evidence: bool
|
||||
evidence_path: Path | None
|
||||
interrupted: bool
|
||||
phase: str
|
||||
|
||||
|
||||
class _ReadFiles:
|
||||
def __init__(self, control):
|
||||
self.control = control
|
||||
self.texts = {}
|
||||
self.roots = {}
|
||||
|
||||
def checkpoint(self):
|
||||
if self.control is not None:
|
||||
self.control.checkpoint()
|
||||
|
||||
def _manifest(self, root):
|
||||
self.checkpoint()
|
||||
def stamp(path):
|
||||
self.checkpoint()
|
||||
try:
|
||||
stat = path.stat()
|
||||
return (stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns)
|
||||
except OSError:
|
||||
return None
|
||||
root_stamp = stamp(root)
|
||||
try:
|
||||
# Include sidecar evidence used by hard-failure recovery as well as
|
||||
# command/status and flags; creation/removal changes the root stamp.
|
||||
entries = tuple(root.iterdir())
|
||||
except OSError:
|
||||
entries = ()
|
||||
result = {path.name: stamp(path) for path in entries}
|
||||
self.checkpoint()
|
||||
return root_stamp, result
|
||||
|
||||
def track_root(self, root):
|
||||
if root not in self.roots:
|
||||
self.roots[root] = self._manifest(root)
|
||||
|
||||
def stable(self):
|
||||
return all(self._manifest(root) == before for root, before in self.roots.items())
|
||||
|
||||
def path(self, path):
|
||||
return _CachedPath(Path(path), self)
|
||||
|
||||
def read(self, path):
|
||||
self.checkpoint()
|
||||
if path not in self.texts:
|
||||
chunks = []
|
||||
with path.open('r', encoding='utf-8-sig') as source:
|
||||
while True:
|
||||
self.checkpoint()
|
||||
chunk = source.read(65536)
|
||||
self.checkpoint()
|
||||
if not chunk:
|
||||
break
|
||||
chunks.append(chunk)
|
||||
self.texts[path] = ''.join(chunks)
|
||||
return self.texts[path]
|
||||
|
||||
|
||||
class _CachedPath:
|
||||
"""Path-shaped parser input: every parser sees the same immutable text."""
|
||||
def __init__(self, path, files):
|
||||
self.path, self.files = path, files
|
||||
|
||||
def read_text(self, **kwargs):
|
||||
return self.files.read(self.path)
|
||||
|
||||
def with_name(self, name):
|
||||
return self.files.path(self.path.with_name(name))
|
||||
|
||||
def exists(self):
|
||||
self.files.checkpoint()
|
||||
return self.path.exists()
|
||||
|
||||
|
||||
def read_snapshot(preparer, task_id, projects, rules, *, copy_part_number_to_value=False,
|
||||
read_control=None, project_path=None):
|
||||
for _ in range(3):
|
||||
files = _ReadFiles(read_control)
|
||||
snapshot = _read_snapshot_once(preparer, task_id, projects, rules,
|
||||
copy_part_number_to_value=copy_part_number_to_value, project_path=project_path, files=files)
|
||||
if files.stable():
|
||||
return snapshot
|
||||
# Never publish executable continuation coordinates from a changing set.
|
||||
progress = replace(snapshot.progress, next_project_path=None, next_old_part_number=None,
|
||||
next_new_part_number=None, next_schematic_name=None, next_sheet_number=None)
|
||||
files.checkpoint()
|
||||
return replace(snapshot, progress=progress, interrupted=True)
|
||||
|
||||
|
||||
def _read_snapshot_once(preparer, task_id, projects, rules, *, copy_part_number_to_value=False,
|
||||
project_path=None, files):
|
||||
# Import lazily to preserve the historical quick_run private parser boundaries.
|
||||
from . import quick_run as api
|
||||
files.checkpoint()
|
||||
selected = api._selected_projects(projects)
|
||||
queued = api._queue_projects(projects)
|
||||
enabled = tuple(rule for rule in rules if rule.enabled)
|
||||
expected = tuple((str(project.path), rule.old_part_number, rule.new_part_number)
|
||||
for project in queued for rule in enabled)
|
||||
first = expected[0] if expected else (None, None, None)
|
||||
progress = QuickRunProgress(0, len(expected), api._optional_path(first[0]), first[1], first[2], (), False)
|
||||
current = preparer._data_root / 'quick-run'
|
||||
history = preparer._data_root / 'quick-run-history'
|
||||
root = None
|
||||
commands = ()
|
||||
# Avoid enumerating history when the active handoff already matches.
|
||||
def candidates():
|
||||
yield current
|
||||
files.checkpoint()
|
||||
yield from sorted((path for path in history.glob('obsolete-*') if path.is_dir()), reverse=True)
|
||||
for candidate in candidates():
|
||||
files.checkpoint()
|
||||
files.track_root(candidate)
|
||||
command = candidate / 'command.tsv'
|
||||
if not command.is_file() or not (candidate / 'status.tsv').is_file():
|
||||
continue
|
||||
try:
|
||||
parsed = api._read_commands(files.path(command))
|
||||
except TaskCenterError:
|
||||
continue
|
||||
if not parsed or {row[0] for row in parsed} != {task_id}:
|
||||
continue
|
||||
if project_path is not None and not any(api._path_key(row[2]) == api._path_key(project_path) for row in parsed):
|
||||
continue
|
||||
root, commands = candidate, parsed
|
||||
break
|
||||
if root is None:
|
||||
files.checkpoint()
|
||||
return QuickRunSnapshot(progress, False, None, False, 'selection')
|
||||
interrupted = root == current and (root / 'uncertain.flag').is_file()
|
||||
phase = 'selection'
|
||||
try:
|
||||
details = api._read_status_details(files.path(root / 'status.tsv'))
|
||||
files.checkpoint()
|
||||
if root == current:
|
||||
latest = {job_id: state for job_id, state, _, _ in details}
|
||||
interrupted = interrupted or any(state == api.BATCH_SAVED_UNVERIFIED_STATE for state in latest.values())
|
||||
unfinished = api._next_unfinished_command(commands, details)
|
||||
if unfinished is not None:
|
||||
final = latest.get(unfinished[1])
|
||||
interrupted = interrupted or final == 'awaiting_native_replace'
|
||||
if final == 'hard_failure':
|
||||
interrupted = interrupted or api._recover_pre_mutation_hard_failures(root, commands, details) == details
|
||||
if selected and enabled:
|
||||
preparer._validate_fields(selected, enabled)
|
||||
command_path = files.path(root / 'command.tsv')
|
||||
queued_projects = tuple(project for project in selected
|
||||
if str(project.path) in {command[2] for command in commands})
|
||||
if (api._value_mode_matches_option(api._queue_value_mode(command_path), copy_part_number_to_value)
|
||||
and api._queue_matches_inputs(command_path, commands, queued_projects, enabled)):
|
||||
sheets = api._read_command_sheet_targets(command_path)
|
||||
files.checkpoint()
|
||||
progress = api._progress_from_queue(queued_projects, commands, details, sheets)
|
||||
if progress.queue_complete:
|
||||
phase = 'retry' if progress.failed_items else 'complete'
|
||||
except TaskCenterError:
|
||||
pass
|
||||
files.checkpoint()
|
||||
return QuickRunSnapshot(progress, True, root, interrupted, phase)
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Cooperative cancellation for read-only work; deadlines use monotonic time."""
|
||||
from threading import Event
|
||||
from time import monotonic
|
||||
|
||||
|
||||
class QueryCancelled(Exception):
|
||||
"""The caller no longer needs this read result."""
|
||||
|
||||
|
||||
class QueryControl:
|
||||
def __init__(self, deadline=None):
|
||||
self.deadline = deadline
|
||||
self._cancelled = Event()
|
||||
|
||||
@property
|
||||
def cancelled(self):
|
||||
return self._cancelled.is_set() or (self.deadline is not None and monotonic() >= self.deadline)
|
||||
|
||||
def cancel(self):
|
||||
self._cancelled.set()
|
||||
|
||||
def checkpoint(self):
|
||||
if self.cancelled:
|
||||
raise QueryCancelled('Read request cancelled')
|
||||
@@ -18,7 +18,7 @@ from .quick_run import (
|
||||
_native_helper_launch_arguments, _next_unfinished_command, _path_key,
|
||||
_queue_matches_inputs, _queue_value_mode, _read_command_sheet_targets,
|
||||
_read_command_options, _read_commands, _read_status_details, _safe_run_token,
|
||||
_value_mode_matches_option, _write_status_details, _write_uncertain_flag,
|
||||
_value_mode_matches_option, _write_status_details, _write_uncertain_flag, _decode_vbs_field,
|
||||
)
|
||||
from .retention import maintain_quick_run_storage
|
||||
from .schematic_backup import create_schematic_backup
|
||||
@@ -34,6 +34,17 @@ def _is_link_or_reparse(path: Path) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def _recovery_command(commands, statuses):
|
||||
latest = {entry[0]: entry[1] for entry in statuses}
|
||||
unverified = tuple(command for command in commands
|
||||
if latest.get(command[1]) == 'batch_saved_unverified')
|
||||
if len(unverified) > 1:
|
||||
raise TaskCenterError('quick_run_recovery', '多个保存后未核验步骤需要逐项人工核对,保护状态保持。')
|
||||
if unverified:
|
||||
return unverified[0]
|
||||
return _next_unfinished_command(commands, statuses)
|
||||
|
||||
|
||||
def _hashes(
|
||||
root: Path,
|
||||
*,
|
||||
@@ -88,7 +99,7 @@ def recover(preparer, task_id, projects, rules, *, copy_part_number_to_value=Fal
|
||||
raise TaskCenterError('quick_run_recovery', '当前工程或规则与中断队列不同,不能恢复其他任务。')
|
||||
if not _value_mode_matches_option(mode, copy_part_number_to_value) or len({command[1] for command in commands}) != len(commands):
|
||||
raise TaskCenterError('quick_run_recovery', 'Value 策略变化或队列编号重复,已停止恢复。')
|
||||
selected = _next_unfinished_command(commands, before)
|
||||
selected = _recovery_command(commands, before)
|
||||
if selected is None:
|
||||
raise TaskCenterError('quick_run_recovery', '队列记录已完成但仍有保护锁,需要单独核对,未自动解除。')
|
||||
job_id = _safe_run_token(selected[1])
|
||||
@@ -105,15 +116,28 @@ def recover(preparer, task_id, projects, rules, *, copy_part_number_to_value=Fal
|
||||
metadata, components = read_snapshot(snapshot)
|
||||
snapshot_options = (
|
||||
(metadata[5], metadata[6], metadata[7])
|
||||
if len(metadata) == 8
|
||||
if len(metadata) >= 8
|
||||
else (metadata[5], '', '1')
|
||||
)
|
||||
if len(metadata) not in {6, 8} or (_path_key(metadata[1]), metadata[2], metadata[3]) != (
|
||||
if len(metadata) not in {6, 8, 10} or (_path_key(metadata[1]), metadata[2], metadata[3]) != (
|
||||
_path_key(selected[2]), selected[3], selected[4]) or snapshot_options != (
|
||||
selected_mode, selected_custom_value, '1' if selected_sync_nc else '0'):
|
||||
raise ValueError('snapshot command mismatch')
|
||||
if selected_sheet is not None and metadata[4] != f'{selected_sheet[0]}:{selected_sheet[1]}':
|
||||
raise ValueError('snapshot sheet mismatch')
|
||||
command_lines = (root / 'command.tsv').read_text(encoding='utf-8-sig').splitlines()
|
||||
command_header = command_lines[0].split('\t')
|
||||
if 'target_scope' in command_header:
|
||||
candidates = [line.split('\t') for line in command_lines[1:]
|
||||
if line.split('\t')[command_header.index('job_id')] == job_id]
|
||||
if len(candidates) != 1:
|
||||
raise ValueError('target command missing or duplicated')
|
||||
scope = candidates[0][command_header.index('target_scope')]
|
||||
selectors = candidates[0][command_header.index('target_selectors')]
|
||||
if scope != 'targets' or len(metadata) != 10 or metadata[8:] != ['targets', _decode_vbs_field(selectors)]:
|
||||
raise ValueError('snapshot target selector mismatch')
|
||||
elif len(metadata) == 10:
|
||||
raise ValueError('snapshot target scope missing from command')
|
||||
report = json.loads(snapshot.with_suffix('.tsv.native.json').read_text(encoding='utf-8'))
|
||||
binding = require_resumable_transaction(snapshot, report, metadata, components)
|
||||
identity = binding['library_row'][4:6]
|
||||
@@ -161,9 +185,14 @@ def recover(preparer, task_id, projects, rules, *, copy_part_number_to_value=Fal
|
||||
header = 'task_id\tjob_id\tproject_path\tschematic_name\tsheet_number\told_part\tnew_part\tvalue_mode\tcustom_value\tsync_nc\tbase_value_mode\trecovery_part_name\trecovery_part_label'
|
||||
row = (*selected[:3], *selected_sheet, *selected[3:], *option_fields, *identity)
|
||||
shutil.copyfile(root / 'sheets.tsv', worker / 'sheets.tsv')
|
||||
if len(metadata) == 10:
|
||||
header += '\ttarget_scope\ttarget_selectors'
|
||||
row = (*row, 'targets', selectors)
|
||||
(worker / 'command.tsv').write_text(header + '\n' + '\t'.join(row) + '\n', encoding='utf-8')
|
||||
_write_status_details(worker / 'status.tsv', ())
|
||||
launch = (str(preparer._cscript_resolver()), '//nologo', str(script), str(worker),
|
||||
from .quick_run import _vbs_worker_paths
|
||||
script_argument, root_argument = _vbs_worker_paths(script, worker)
|
||||
launch = (str(preparer._cscript_resolver()), '//nologo', script_argument, root_argument,
|
||||
*_native_helper_launch_arguments(), job_id)
|
||||
try:
|
||||
result = preparer._process_runner(launch, IDLE_PROGRESS_TIMEOUT_SECONDS)
|
||||
@@ -208,7 +237,10 @@ def recover(preparer, task_id, projects, rules, *, copy_part_number_to_value=Fal
|
||||
raise
|
||||
progress = preparer.progress(task_id, projects, rules, copy_part_number_to_value=copy_part_number_to_value)
|
||||
message = ('磁盘工程与替换前快照一致,只读核验工程已关闭,已准备新的执行编号;尚未再次替换,请确认后执行。'
|
||||
if state == 'retry_ready' else '已核验并恢复本项任务记录;没有重复执行原生替换。若补做了属性恢复,请保存当前工程。')
|
||||
if state == 'retry_ready' else
|
||||
'已核验并恢复本项任务记录,属性已保存并重开回读,工程已关闭;没有重复执行原生替换。'
|
||||
if after[0][2] == 'recovery_saved_verified' else
|
||||
'已核验并恢复本项任务记录;没有重复执行原生替换。若补做了属性恢复,请保存当前工程。')
|
||||
return QuickRunStepResult(root / 'QuickPartReplace.vbs', root / 'command.tsv', root / 'status.tsv',
|
||||
audit / 'worker-output.txt', state, message, progress.next_project_path,
|
||||
progress.next_old_part_number, progress.next_new_part_number,
|
||||
|
||||
@@ -11,12 +11,20 @@ import threading
|
||||
from typing import TypeVar
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .logging_setup import LoggingContext, _tail_utf8_lines, append_task_event
|
||||
from .logging_setup import LoggingContext, _EVENT_BACKUP_COUNT, _tail_utf8_lines, append_task_event
|
||||
from .models import ProjectRecord, ProjectStatus, RuleRecord, TaskRecord, TaskStatus
|
||||
from .quick_run import QuickRunPreparer, QuickRunProgress, QuickRunResult, QuickRunStepResult, _path_key
|
||||
from .runner import OperatorInstruction, RunnerSnapshot, TrialRunner
|
||||
from .scanner import scan_projects
|
||||
from .store import TaskStore
|
||||
from .target_plan import compile_target_rules
|
||||
from .project_tasks import create_project_tasks as _create_project_tasks
|
||||
from .inventory import collect_target_inventory
|
||||
from .spreadsheet_plan import export_target_plan as _export_target_plan, import_target_plan as _import_target_plan
|
||||
from .bom_plan import read_bom_plan as _read_bom_plan, write_bom_template as _write_bom_template
|
||||
from .project_context import ProjectTaskContext
|
||||
from .execution_metrics import measure_phase
|
||||
from .read_control import QueryCancelled
|
||||
|
||||
|
||||
_Result = TypeVar("_Result")
|
||||
@@ -84,23 +92,162 @@ class TaskCenterService:
|
||||
clock: Callable[[], datetime] = datetime.now,
|
||||
probe_source_resolver: Callable[[TaskRecord, ProjectRecord], Path] | None = None,
|
||||
quick_run_preparer: QuickRunPreparer | None = None,
|
||||
runner: TrialRunner | None = None,
|
||||
) -> None:
|
||||
self._store = store
|
||||
self._logging = logging_context
|
||||
self._path_opener = path_opener
|
||||
self._clock = clock
|
||||
self._runner = TrialRunner(store, logging_context, probe_source_resolver=probe_source_resolver)
|
||||
self._runner = runner or TrialRunner(store, logging_context, probe_source_resolver=probe_source_resolver)
|
||||
self._quick_run_preparer = quick_run_preparer or QuickRunPreparer(logging_context.root)
|
||||
self._batch_feedback = None
|
||||
self._project_facades: dict[str, TaskCenterService] = {}
|
||||
self._facade_lock = threading.RLock()
|
||||
|
||||
def create_task(self, name: str, *, note: str = "") -> TaskRecord:
|
||||
return self._operation("create_task", None, lambda: self._store.create_task(name, note))
|
||||
return self._idle_quick_run_operation("create_task", None, lambda: self._store.create_task(name, note))
|
||||
|
||||
def create_project_tasks(self, root: Path, *, selected_paths: tuple[Path, ...] | None = None) -> tuple[TaskRecord, ...]:
|
||||
return self._idle_quick_run_operation("create_project_tasks", None,
|
||||
lambda: _create_project_tasks(self._store, root, selected_paths=selected_paths,
|
||||
excluded_roots=(self._logging.root,)))
|
||||
|
||||
def target_plan(self, task_id: str):
|
||||
return self._operation("list_target_plan", task_id, lambda: self._store.list_target_plan(task_id))
|
||||
|
||||
def replace_target_plan(self, task_id: str, rows) -> tuple:
|
||||
return self._idle_quick_run_operation("replace_target_plan", task_id,
|
||||
lambda: self._store.replace_target_plan(task_id, tuple(rows)))
|
||||
|
||||
def preview_target_plan(self, task_id: str, path: Path):
|
||||
from .spreadsheet_plan import read_target_plan
|
||||
return self._operation("preview_target_plan", task_id, lambda: read_target_plan(self._store, task_id, path))
|
||||
|
||||
def import_target_plan(self, task_id: str, path: Path) -> tuple:
|
||||
return self._idle_quick_run_operation("import_target_plan", task_id,
|
||||
lambda: _import_target_plan(self._store, task_id, path))
|
||||
|
||||
def export_target_plan(self, task_id: str, path: Path) -> Path:
|
||||
return self._operation("export_target_plan", task_id,
|
||||
lambda: _export_target_plan(self._store, task_id, path))
|
||||
|
||||
def preview_bom_plan(self, task_id: str, path: Path) -> tuple:
|
||||
return self._operation("preview_bom_plan", task_id,
|
||||
lambda: _read_bom_plan(self._store, task_id, path))
|
||||
|
||||
def export_bom_template(self, task_id: str, path: Path) -> Path:
|
||||
def export():
|
||||
rows = self._store.list_target_plan(task_id)
|
||||
records = ({
|
||||
'old_part_number': row.target.old_part_number,
|
||||
'new_part_number': row.new_part_number,
|
||||
'refdes': row.target.refdes,
|
||||
'schematic_name': row.target.schematic_name,
|
||||
'sheet_number': row.target.sheet_number,
|
||||
'uid': row.target.uid,
|
||||
'enabled': row.enabled,
|
||||
'custom_value': row.custom_value if row.custom_value_enabled else '',
|
||||
'sync_nc': row.sync_nc,
|
||||
} for row in rows)
|
||||
return _write_bom_template(path, records)
|
||||
return self._operation("export_bom_template", task_id, export)
|
||||
|
||||
def for_project_task(self, task_id: str) -> "TaskCenterService":
|
||||
"""Return a facade whose evidence root is isolated to this task."""
|
||||
return self._facade_for_task_record(self._store.get_task(task_id), force=True)
|
||||
|
||||
def _facade_for_task_record(self, task: TaskRecord, *, force: bool = False) -> "TaskCenterService":
|
||||
"""Resolve evidence routing from the caller's already consistent task record."""
|
||||
if not force and not task.primary_project_id:
|
||||
return self
|
||||
task_id = task.task_id
|
||||
child_root = self._logging.root / "tasks" / task_id
|
||||
if self._quick_run_preparer.data_root == child_root:
|
||||
return self
|
||||
with self._facade_lock:
|
||||
if task_id not in self._project_facades:
|
||||
child_preparer = self._quick_run_preparer.for_data_root(child_root)
|
||||
# Initializing a new runner replays startup recovery and mutates
|
||||
# the database. A facade shares the initialized runner instead.
|
||||
child = TaskCenterService(self._store, self._logging, path_opener=self._path_opener,
|
||||
clock=self._clock, quick_run_preparer=child_preparer, runner=self._runner)
|
||||
self._project_facades[task_id] = child
|
||||
return self._project_facades[task_id]
|
||||
|
||||
def _project_task_service(self, task_id: str) -> "TaskCenterService":
|
||||
return self._facade_for_task_record(self._store.get_task(task_id))
|
||||
|
||||
def scan_project_directory(self, root: Path, *, stop_event=None, on_progress=None):
|
||||
from .project_tasks import scan_project_directory
|
||||
return self._operation("scan_project_directory", None,
|
||||
lambda: scan_project_directory(root, excluded_roots=(self._logging.root,),
|
||||
stop_event=stop_event, on_progress=on_progress))
|
||||
|
||||
def move_project_task(self, task_id: str, offset: int):
|
||||
return self._idle_quick_run_operation("move_project_task", task_id,
|
||||
lambda: self._store.move_project_task(task_id, offset))
|
||||
|
||||
def get_task(self, task_id: str) -> TaskRecord:
|
||||
return self._operation("get_task", task_id, lambda: self._store.get_task(task_id))
|
||||
|
||||
def tasks(self, status: TaskStatus | None = None) -> tuple[TaskRecord, ...]:
|
||||
return self._operation("list_tasks", None, lambda: self._store.list_tasks(status))
|
||||
def task_context(self, task_id: str, *, read_control=None) -> ProjectTaskContext:
|
||||
"""Read a fresh immutable snapshot; only the per-task facade is cached."""
|
||||
return self._refresh_project_context(task_id, allow_legacy=True, read_control=read_control)
|
||||
|
||||
def refresh_bound_project(self, task_id: str) -> ProjectTaskContext:
|
||||
"""Check the bound file only; never recurse or change project membership."""
|
||||
def refresh():
|
||||
task = self._store.get_task(task_id)
|
||||
projects = self._store.list_projects(task_id)
|
||||
if task.primary_project_id is None or len(projects) != 1 or projects[0].project_id != task.primary_project_id:
|
||||
raise TaskCenterError("project_binding", "refresh requires one bound project")
|
||||
project = projects[0]
|
||||
from .scanner import _reject_reparse
|
||||
paths = ()
|
||||
try:
|
||||
_reject_reparse(project.path.lstat(), project.path)
|
||||
if project.path.is_file():
|
||||
paths = (project.path,)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
self._store.sync_projects(task_id, project.discovery_root, paths)
|
||||
return self._refresh_project_context(task_id, allow_legacy=False)
|
||||
return self._idle_quick_run_operation("refresh_bound_project", task_id, refresh)
|
||||
|
||||
def _refresh_project_context(self, task_id: str, *, allow_legacy: bool, read_control=None) -> ProjectTaskContext:
|
||||
def refresh() -> ProjectTaskContext:
|
||||
if read_control is not None:
|
||||
read_control.checkpoint()
|
||||
bundle = self._store.read_task_bundle(task_id, read_control=read_control)
|
||||
task, projects = bundle.task, bundle.projects
|
||||
bound = None
|
||||
if task.primary_project_id is not None and len(projects) == 1:
|
||||
candidate = projects[0]
|
||||
if candidate.project_id == task.primary_project_id:
|
||||
bound = candidate
|
||||
legacy = bound is None
|
||||
if not allow_legacy and (task.primary_project_id is None or bound is None or len(projects) != 1):
|
||||
raise TaskCenterError("project_binding", "bound task must own exactly one project")
|
||||
rules, targets = bundle.rules, bundle.targets
|
||||
facade = self._facade_for_task_record(task)
|
||||
effective_rules = compile_target_rules(tuple(targets)) if task.target_plan_mode else rules
|
||||
snapshot = facade._quick_run_preparer.read_snapshot(task_id, projects, effective_rules,
|
||||
copy_part_number_to_value=task.copy_part_number_to_value, read_control=read_control)
|
||||
progress = snapshot.progress
|
||||
interrupted = snapshot.interrupted
|
||||
has_evidence = snapshot.has_evidence
|
||||
phase = snapshot.phase
|
||||
context = ProjectTaskContext(task, bound, tuple(rules), tuple(targets), progress,
|
||||
phase, has_evidence, interrupted, legacy)
|
||||
return context
|
||||
return self._operation("refresh_bound_project", task_id, refresh)
|
||||
|
||||
def _assert_mutable_membership(self, task_id: str) -> None:
|
||||
if self._store.get_task(task_id).primary_project_id is not None:
|
||||
raise TaskCenterError("project_binding", "bound project membership is immutable")
|
||||
|
||||
def tasks(self, status: TaskStatus | None = None, *, read_control=None) -> tuple[TaskRecord, ...]:
|
||||
return self._operation("list_tasks", None, lambda: self._store.list_tasks(status, read_control=read_control))
|
||||
|
||||
def update_task(self, task_id: str, *, name: str, note: str) -> TaskRecord:
|
||||
return self._idle_quick_run_operation(
|
||||
@@ -121,11 +268,21 @@ class TaskCenterService:
|
||||
raise TaskCenterError("task_not_deleted", "move the task to deleted before permanently removing it")
|
||||
return self._store.purge_task(task_id)
|
||||
|
||||
return self._operation("purge_task", task_id, purge)
|
||||
return self._idle_quick_run_operation("purge_task", task_id, purge)
|
||||
|
||||
def rules(self, task_id: str) -> tuple[RuleRecord, ...]:
|
||||
return self._operation("list_rules", task_id, lambda: self._store.list_rules(task_id))
|
||||
|
||||
def _execution_rules(self, task_id: str):
|
||||
task = self._store.get_task(task_id)
|
||||
if task.target_plan_mode:
|
||||
rows = self._store.list_target_plan(task_id)
|
||||
rules = compile_target_rules(tuple(rows))
|
||||
if not rules:
|
||||
raise TaskCenterError("enabled_rule_required", "target plan has no enabled targets")
|
||||
return rules
|
||||
return self._store.list_rules(task_id)
|
||||
|
||||
def add_rule(
|
||||
self,
|
||||
task_id: str,
|
||||
@@ -199,8 +356,44 @@ class TaskCenterService:
|
||||
def projects(self, task_id: str) -> tuple[ProjectRecord, ...]:
|
||||
return self._operation("list_projects", task_id, lambda: self._store.list_projects(task_id))
|
||||
|
||||
def collect_target_inventory(self, task_id: str, old_part_numbers: tuple[str, ...] | None = None):
|
||||
delegated = self._project_task_service(task_id)
|
||||
if delegated is not self:
|
||||
return delegated.collect_target_inventory(task_id, old_part_numbers)
|
||||
def collect():
|
||||
rules = self._store.list_rules(task_id)
|
||||
parts = old_part_numbers or tuple(rule.old_part_number for rule in rules if rule.enabled)
|
||||
if not parts:
|
||||
raise TaskCenterError("target_inventory", "add an old Part Number before collecting inventory")
|
||||
project = self._store.list_projects(task_id)
|
||||
if len(project) != 1:
|
||||
raise TaskCenterError("target_inventory", "target inventory requires one project task")
|
||||
with measure_phase(self._logging, task_id, 'collect_inventory', unit='component',
|
||||
project_path=str(project[0].path)) as metric:
|
||||
rows = collect_target_inventory(self._quick_run_preparer, project[0].path, parts)
|
||||
metric['completed_units'] = len(rows)
|
||||
prior = self._store.list_target_plan(task_id)
|
||||
current = self._store.record_target_inventory(task_id, rows)
|
||||
if not current:
|
||||
return ()
|
||||
if prior:
|
||||
return current
|
||||
existing = {row.target.key: row for row in current}
|
||||
from .target_plan import TargetPlanRow
|
||||
return self._store.replace_target_plan(task_id, tuple(
|
||||
TargetPlanRow(row, False, next((r.new_part_number for r in rules
|
||||
if r.old_part_number.casefold() == row.old_part_number.casefold()), ""),
|
||||
next((r.custom_value_enabled for r in rules
|
||||
if r.old_part_number.casefold() == row.old_part_number.casefold()), False),
|
||||
next((r.custom_value for r in rules
|
||||
if r.old_part_number.casefold() == row.old_part_number.casefold()), ""),
|
||||
next((r.sync_nc for r in rules
|
||||
if r.old_part_number.casefold() == row.old_part_number.casefold()), True)) for row in rows))
|
||||
return self._idle_quick_run_operation("collect_target_inventory", task_id, collect)
|
||||
|
||||
def scan_projects(self, task_id: str, root: Path) -> tuple[ProjectRecord, ...]:
|
||||
def scan_and_sync() -> tuple[ProjectRecord, ...]:
|
||||
self._assert_mutable_membership(task_id)
|
||||
task = self._store.get_task(task_id)
|
||||
if self._has_current_quick_run_evidence(task_id):
|
||||
raise TaskCenterError(
|
||||
@@ -248,6 +441,7 @@ class TaskCenterService:
|
||||
def set_project_selected(self, project_id: str, selected: bool) -> ProjectRecord:
|
||||
def set_selected() -> ProjectRecord:
|
||||
project = self._project_owner(project_id)
|
||||
self._assert_mutable_membership(project.task_id)
|
||||
if self._has_current_quick_run_evidence(project.task_id) and not self._retryable_quick_run(project.task_id):
|
||||
raise TaskCenterError("quick_run_options_locked", "project selection is frozen while queue evidence exists")
|
||||
snapshot = self._runner.set_project_selected(project.task_id, project_id, selected)
|
||||
@@ -257,6 +451,7 @@ class TaskCenterService:
|
||||
|
||||
def select_all_projects(self, task_id: str) -> tuple[ProjectRecord, ...]:
|
||||
def select() -> tuple[ProjectRecord, ...]:
|
||||
self._assert_mutable_membership(task_id)
|
||||
if self._has_current_quick_run_evidence(task_id) and not self._retryable_quick_run(task_id):
|
||||
raise TaskCenterError("quick_run_options_locked", "project selection is frozen while queue evidence exists")
|
||||
return self._runner.set_projects_selected(
|
||||
@@ -269,6 +464,7 @@ class TaskCenterService:
|
||||
|
||||
def clear_project_selection(self, task_id: str) -> tuple[ProjectRecord, ...]:
|
||||
def clear() -> tuple[ProjectRecord, ...]:
|
||||
self._assert_mutable_membership(task_id)
|
||||
if self._has_current_quick_run_evidence(task_id) and not self._retryable_quick_run(task_id):
|
||||
raise TaskCenterError("quick_run_options_locked", "project selection is frozen while queue evidence exists")
|
||||
return self._runner.set_projects_selected(task_id, False).projects
|
||||
@@ -329,12 +525,17 @@ class TaskCenterService:
|
||||
|
||||
def prepare_quick_run(self, task_id: str) -> QuickRunResult:
|
||||
"""Create the legacy VBS handoff without starting a task-center trial."""
|
||||
delegated = self._project_task_service(task_id)
|
||||
if delegated is not self:
|
||||
return delegated.prepare_quick_run(task_id)
|
||||
def prepare() -> QuickRunResult:
|
||||
task = self._store.get_task(task_id)
|
||||
result = self._quick_run_preparer.prepare(
|
||||
preparer = (self._quick_run_preparer.ensure_batch_handoff
|
||||
if task.target_plan_mode else self._quick_run_preparer.prepare)
|
||||
result = preparer(
|
||||
task_id,
|
||||
self._store.list_projects(task_id),
|
||||
self._store.list_rules(task_id),
|
||||
self._execution_rules(task_id),
|
||||
copy_part_number_to_value=task.copy_part_number_to_value,
|
||||
)
|
||||
append_task_event(
|
||||
@@ -361,6 +562,8 @@ class TaskCenterService:
|
||||
)
|
||||
return result
|
||||
|
||||
from .task_queue import assert_task_queue_idle
|
||||
assert_task_queue_idle(self._logging.root)
|
||||
with _quick_run_lease(self._logging.root):
|
||||
return self._operation("prepare_quick_run", task_id, prepare)
|
||||
|
||||
@@ -384,17 +587,22 @@ class TaskCenterService:
|
||||
details={"copy_part_label_to_value": enabled})
|
||||
return task
|
||||
|
||||
from .task_queue import assert_task_queue_idle
|
||||
assert_task_queue_idle(self._logging.root)
|
||||
with _quick_run_lease(self._logging.root):
|
||||
return self._operation("set_value_policy", task_id, update)
|
||||
|
||||
def execute_quick_run(self, task_id: str, *, expected_item: tuple[str, str, str, str] | None = None) -> QuickRunStepResult:
|
||||
"""Execute one replacement rule through restoration and verification."""
|
||||
delegated = self._project_task_service(task_id)
|
||||
if delegated is not self:
|
||||
return delegated.execute_quick_run(task_id, expected_item=expected_item)
|
||||
def execute() -> QuickRunStepResult:
|
||||
task = self._store.get_task(task_id)
|
||||
result = self._quick_run_preparer.execute_step(
|
||||
task_id,
|
||||
self._store.list_projects(task_id),
|
||||
self._store.list_rules(task_id),
|
||||
self._execution_rules(task_id),
|
||||
copy_part_number_to_value=task.copy_part_number_to_value,
|
||||
**({"expected_item": expected_item} if expected_item is not None else {}),
|
||||
)
|
||||
@@ -410,6 +618,8 @@ class TaskCenterService:
|
||||
self._logging.logger.info("quick_run_executed task_id=%s state=%s", task_id, result.state)
|
||||
return result
|
||||
|
||||
from .task_queue import assert_task_queue_idle
|
||||
assert_task_queue_idle(self._logging.root)
|
||||
with _quick_run_lease(self._logging.root):
|
||||
return self._operation("execute_quick_run", task_id, execute)
|
||||
|
||||
@@ -420,26 +630,41 @@ class TaskCenterService:
|
||||
expected_item,
|
||||
stop_event: threading.Event,
|
||||
continue_after_backup_failure: bool = False,
|
||||
reuse_project_session: bool = True,
|
||||
):
|
||||
delegated = self._project_task_service(task_id)
|
||||
if delegated is not self:
|
||||
return delegated.execute_quick_run_queue(task_id, expected_item=expected_item,
|
||||
stop_event=stop_event, continue_after_backup_failure=continue_after_backup_failure,
|
||||
reuse_project_session=reuse_project_session)
|
||||
from .batch import execute_batch
|
||||
from .task_queue import assert_task_queue_idle
|
||||
|
||||
assert_task_queue_idle(self._logging.root)
|
||||
with _quick_run_lease(self._logging.root):
|
||||
if self._store.has_active_project():
|
||||
raise TaskCenterError('active_project_exists', '人工流程已有活动工程,不能同时启动自动队列。')
|
||||
if self._store.get_task(task_id).status not in {TaskStatus.DRAFT, TaskStatus.READY, TaskStatus.RUNNING, TaskStatus.PAUSED}:
|
||||
raise TaskCenterError('quick_run_task_state', '当前任务状态不允许启动自动队列。')
|
||||
try:
|
||||
result = self._operation(
|
||||
'execute_quick_run_queue',
|
||||
task_id,
|
||||
lambda: execute_batch(
|
||||
self,
|
||||
with measure_phase(self._logging, task_id, 'task_total', unit='task') as metric:
|
||||
result = self._operation(
|
||||
'execute_quick_run_queue',
|
||||
task_id,
|
||||
expected_item=expected_item,
|
||||
stop_event=stop_event,
|
||||
continue_after_backup_failure=continue_after_backup_failure,
|
||||
),
|
||||
)
|
||||
lambda: execute_batch(
|
||||
self,
|
||||
task_id,
|
||||
expected_item=expected_item,
|
||||
stop_event=stop_event,
|
||||
continue_after_backup_failure=continue_after_backup_failure,
|
||||
reuse_project_session=reuse_project_session,
|
||||
),
|
||||
)
|
||||
metric['state'] = 'paused' if result.paused else 'failed' if result.progress.failed_items else 'completed'
|
||||
metric['completed_units'] = int(result.progress.queue_complete and not result.progress.failed_items and not result.paused)
|
||||
metric['completed_steps'] = result.progress.completed_items
|
||||
metric['saved_steps'] = result.progress.saved_items
|
||||
metric['failed_steps'] = result.progress.failed_items
|
||||
if result.paused:
|
||||
self._pause_quick_run_queue(task_id, 'queue paused at item boundary')
|
||||
return result
|
||||
@@ -451,6 +676,9 @@ class TaskCenterService:
|
||||
|
||||
def prepare_failed_quick_run(self, task_id: str) -> QuickRunProgress:
|
||||
"""Reset only failed projects and discard the finished queue handoff."""
|
||||
delegated = self._project_task_service(task_id)
|
||||
if delegated is not self:
|
||||
return delegated.prepare_failed_quick_run(task_id)
|
||||
def prepare_retry() -> QuickRunProgress:
|
||||
task = self._store.get_task(task_id)
|
||||
if task.status is not TaskStatus.RUNNING:
|
||||
@@ -458,7 +686,7 @@ class TaskCenterService:
|
||||
progress = self._quick_run_preparer.progress(
|
||||
task_id,
|
||||
self._store.list_projects(task_id),
|
||||
self._store.list_rules(task_id),
|
||||
self._execution_rules(task_id),
|
||||
copy_part_number_to_value=task.copy_part_number_to_value,
|
||||
)
|
||||
failed_paths = {
|
||||
@@ -492,16 +720,18 @@ class TaskCenterService:
|
||||
self._quick_run_preparer.ensure_batch_handoff(
|
||||
task_id,
|
||||
self._store.list_projects(task_id),
|
||||
self._store.list_rules(task_id),
|
||||
self._execution_rules(task_id),
|
||||
copy_part_number_to_value=task.copy_part_number_to_value,
|
||||
)
|
||||
return self._quick_run_preparer.progress(
|
||||
task_id,
|
||||
self._store.list_projects(task_id),
|
||||
self._store.list_rules(task_id),
|
||||
self._execution_rules(task_id),
|
||||
copy_part_number_to_value=task.copy_part_number_to_value,
|
||||
)
|
||||
|
||||
from .task_queue import assert_task_queue_idle
|
||||
assert_task_queue_idle(self._logging.root)
|
||||
with _quick_run_lease(self._logging.root):
|
||||
return self._operation("prepare_failed_quick_run", task_id, prepare_retry)
|
||||
|
||||
@@ -514,8 +744,34 @@ class TaskCenterService:
|
||||
def batch_feedback(self):
|
||||
return self._batch_feedback
|
||||
|
||||
def execution_feedback(self, task_id: str | None, *, started_after: float, read_control=None):
|
||||
"""Read the actual executing task, independent of the selected task."""
|
||||
from .execution_feedback import ExecutionFeedback, read_feedback
|
||||
if read_control is not None:
|
||||
read_control.checkpoint()
|
||||
queue = getattr(self, '_task_queue_feedback', None)
|
||||
position, total = 1, 1
|
||||
if queue:
|
||||
_, task_id, position, total = queue
|
||||
if not task_id:
|
||||
return ExecutionFeedback(None)
|
||||
child = self._facade_for_task_record(
|
||||
self._store.get_task(task_id, read_control=read_control), force=True)
|
||||
if read_control is not None:
|
||||
read_control.checkpoint()
|
||||
batch = child.batch_feedback()
|
||||
message = batch[2] if batch else '正在准备执行'
|
||||
value = read_feedback(task_id, position, total, message,
|
||||
child._quick_run_preparer.data_root, started_after)
|
||||
if read_control is not None:
|
||||
read_control.checkpoint()
|
||||
return value
|
||||
|
||||
def quick_run_phase(self, task_id: str) -> str:
|
||||
"""Read the current task's local quick-run phase without executing COM work."""
|
||||
delegated = self._project_task_service(task_id)
|
||||
if delegated is not self:
|
||||
return delegated.quick_run_phase(task_id)
|
||||
def read_phase() -> str:
|
||||
self._store.get_task(task_id)
|
||||
if self._retryable_quick_run(task_id):
|
||||
@@ -528,9 +784,15 @@ class TaskCenterService:
|
||||
return self._operation("quick_run_phase", task_id, read_phase)
|
||||
|
||||
def has_interrupted_quick_run(self, task_id: str) -> bool:
|
||||
delegated = self._project_task_service(task_id)
|
||||
if delegated is not self:
|
||||
return delegated.has_interrupted_quick_run(task_id)
|
||||
return self._quick_run_preparer.has_interrupted(task_id)
|
||||
|
||||
def recover_quick_run(self, task_id: str, *, confirmed: bool = False) -> QuickRunStepResult:
|
||||
delegated = self._project_task_service(task_id)
|
||||
if delegated is not self:
|
||||
return delegated.recover_quick_run(task_id, confirmed=confirmed)
|
||||
from .recovery import recover
|
||||
|
||||
def reconcile() -> QuickRunStepResult:
|
||||
@@ -541,7 +803,7 @@ class TaskCenterService:
|
||||
if any(project.selected and project.status not in {ProjectStatus.PENDING, ProjectStatus.COMPLETED} for project in projects):
|
||||
raise TaskCenterError("quick_run_recovery", "工程包含手动执行阶段或失败记录,不能混用自动队列恢复。")
|
||||
result = recover(self._quick_run_preparer, task_id, projects,
|
||||
self._store.list_rules(task_id), copy_part_number_to_value=task.copy_part_number_to_value,
|
||||
self._execution_rules(task_id), copy_part_number_to_value=task.copy_part_number_to_value,
|
||||
confirmed=confirmed)
|
||||
if task.status in {TaskStatus.PAUSED, TaskStatus.FAILED}:
|
||||
self._store.set_task_status(task_id, TaskStatus.READY, summary="interrupted quick-run reconciled")
|
||||
@@ -550,28 +812,60 @@ class TaskCenterService:
|
||||
message=result.message, details={"state": result.state, "evidence": str(result.log_path.parent)})
|
||||
return result
|
||||
|
||||
from .task_queue import assert_task_queue_idle
|
||||
assert_task_queue_idle(self._logging.root)
|
||||
with _quick_run_lease(self._logging.root):
|
||||
return self._operation("recover_quick_run", task_id, reconcile)
|
||||
|
||||
def quick_run_progress(self, task_id: str) -> QuickRunProgress:
|
||||
delegated = self._project_task_service(task_id)
|
||||
if delegated is not self:
|
||||
return delegated.quick_run_progress(task_id)
|
||||
return self._operation("quick_run_progress", task_id, lambda: self._synchronize_quick_run_progress(task_id))
|
||||
|
||||
def has_quick_run_evidence(self, task_id: str) -> bool:
|
||||
return self._quick_run_preparer.evidence_path(task_id) is not None
|
||||
return self._project_task_service(task_id)._quick_run_preparer.evidence_path(task_id) is not None
|
||||
|
||||
def _has_current_quick_run_evidence(self, task_id: str) -> bool:
|
||||
evidence = self._quick_run_preparer.evidence_path(task_id)
|
||||
return evidence == self._quick_run_preparer._data_root / "quick-run"
|
||||
preparer = self._project_task_service(task_id)._quick_run_preparer
|
||||
evidence = preparer.evidence_path(task_id)
|
||||
return evidence == preparer.data_root / "quick-run"
|
||||
|
||||
def tail_log(self, task_id: str, *, limit: int = 100) -> tuple[str, ...]:
|
||||
if limit < 1:
|
||||
def tail_log(self, task_id: str, *, limit: int | None = 100) -> tuple[str, ...]:
|
||||
if limit is not None and limit < 1:
|
||||
raise TaskCenterError("log_limit", "log line limit must be positive")
|
||||
self._store.get_task(task_id)
|
||||
path = self._logging.root / "tasks" / task_id / "events.jsonl"
|
||||
try:
|
||||
if limit is None:
|
||||
# Completed tasks show all retained steps, including rotated logs.
|
||||
with self._logging._event_lock:
|
||||
paths = [path.with_name(f'{path.name}.{i}') for i in range(_EVENT_BACKUP_COUNT, 0, -1)]
|
||||
paths.append(path)
|
||||
return tuple(line for source in paths if source.exists()
|
||||
for line in source.read_text(encoding='utf-8').splitlines())
|
||||
return _tail_utf8_lines(path, limit) if path.exists() else ()
|
||||
except (OSError, UnicodeError) as error:
|
||||
raise TaskCenterError("log_read", "cannot read task event log") from error
|
||||
|
||||
def read_task_log(self, task_id: str, *, mode='latest', cursor=None, limit=200, read_control=None):
|
||||
"""Read a bounded page; callers may keep physical cursors across rotation."""
|
||||
from .task_logs import TaskLogReader
|
||||
if read_control is not None:
|
||||
read_control.checkpoint()
|
||||
self._store.get_task(task_id, read_control=read_control)
|
||||
if mode not in {'latest', 'older', 'poll'} or not 1 <= limit <= 1000:
|
||||
raise TaskCenterError('log_page', 'invalid log page request')
|
||||
reader = TaskLogReader(self._logging.root / 'tasks' / task_id / 'events.jsonl',
|
||||
self._logging._event_lock, backup_count=_EVENT_BACKUP_COUNT,
|
||||
read_control=read_control)
|
||||
try:
|
||||
if mode == 'latest':
|
||||
return reader.latest(limit=limit)
|
||||
return reader.older(cursor, limit=limit) if mode == 'older' else reader.poll(cursor, limit=limit)
|
||||
except (OSError, UnicodeError) as error:
|
||||
raise TaskCenterError('log_read', 'cannot read task event log') from error
|
||||
|
||||
def open_task_log(self, task_id: str) -> Path:
|
||||
def open_path() -> Path:
|
||||
self._store.get_task(task_id)
|
||||
@@ -589,6 +883,9 @@ class TaskCenterService:
|
||||
return self._logging.report_exception("ui", error)
|
||||
|
||||
def open_evidence(self, task_id: str, project_id: str) -> Path:
|
||||
delegated = self._project_task_service(task_id)
|
||||
if delegated is not self:
|
||||
return delegated.open_evidence(task_id, project_id)
|
||||
def open_path() -> Path:
|
||||
project = next((item for item in self._store.list_projects(task_id) if item.project_id == project_id), None)
|
||||
if project is None:
|
||||
@@ -605,6 +902,9 @@ class TaskCenterService:
|
||||
return self._operation("open_evidence", task_id, open_path)
|
||||
|
||||
def open_quick_run_evidence(self, task_id: str) -> Path:
|
||||
delegated = self._project_task_service(task_id)
|
||||
if delegated is not self:
|
||||
return delegated.open_quick_run_evidence(task_id)
|
||||
def open_path() -> Path:
|
||||
self._store.get_task(task_id)
|
||||
path = self._quick_run_preparer.evidence_path(task_id)
|
||||
@@ -620,6 +920,8 @@ class TaskCenterService:
|
||||
self._logging.logger.info("operation_start=%s task_id=%s at=%s", name, task_id or "", timestamp)
|
||||
try:
|
||||
result = action()
|
||||
except QueryCancelled:
|
||||
raise
|
||||
except TaskCenterError as error:
|
||||
self._logging.report_exception(name, error)
|
||||
raise
|
||||
@@ -635,12 +937,14 @@ class TaskCenterService:
|
||||
task_id: str | None,
|
||||
action: Callable[[], _Result],
|
||||
) -> _Result:
|
||||
from .task_queue import assert_task_queue_idle
|
||||
assert_task_queue_idle(self._logging.root)
|
||||
with _quick_run_lease(self._logging.root):
|
||||
return self._operation(name, task_id, action)
|
||||
|
||||
def _manual_operation(self, name: str, task_id: str, action: Callable[[], _Result]) -> _Result:
|
||||
def checked_action():
|
||||
if self._quick_run_preparer.evidence_path(task_id) is not None:
|
||||
if self._project_task_service(task_id)._quick_run_preparer.evidence_path(task_id) is not None:
|
||||
raise TaskCenterError('quick_run_manual_operation', '此任务属于自动队列,不能混用人工采集、跳过或重试。请使用继续队列或核验恢复。')
|
||||
return action()
|
||||
|
||||
@@ -658,7 +962,7 @@ class TaskCenterService:
|
||||
progress = self._quick_run_preparer.progress(
|
||||
task_id,
|
||||
projects,
|
||||
self._store.list_rules(task_id),
|
||||
self._execution_rules(task_id),
|
||||
copy_part_number_to_value=task.copy_part_number_to_value,
|
||||
)
|
||||
by_path = {os.path.normcase(os.path.abspath(str(project.path))): project.project_id for project in projects}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Give the legacy single-step entry the same durable private execution boundary."""
|
||||
from uuid import uuid4
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .schematic_backup import create_schematic_backup
|
||||
|
||||
|
||||
def prepare_private_single_step(preparer, task_id, projects, rules, copy_part_number_to_value):
|
||||
progress = preparer.progress(task_id, projects, rules,
|
||||
copy_part_number_to_value=copy_part_number_to_value)
|
||||
if progress.queue_complete or progress.next_project_path is None:
|
||||
raise TaskCenterError('quick_run_complete', 'all replacement rules in this queue are complete')
|
||||
# Back up before discovery or any CAD activation. A standalone invocation
|
||||
# has no batch backup coordinator to provide this boundary.
|
||||
create_schematic_backup(preparer.data_root, progress.next_project_path,
|
||||
preparer.data_root / 'quick-run-history' / ('batch-' + uuid4().hex))
|
||||
preparer.ensure_batch_handoff(task_id, projects, rules,
|
||||
copy_part_number_to_value=copy_part_number_to_value)
|
||||
@@ -0,0 +1,122 @@
|
||||
"""Optional Excel interchange for target plans."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from openpyxl import Workbook, load_workbook
|
||||
from openpyxl.styles import Font, PatternFill
|
||||
from openpyxl.worksheet.datavalidation import DataValidation
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .target_plan import TargetPlanRow, compile_target_rules
|
||||
|
||||
|
||||
HEADERS = ("project_path", "project_name", "schematic_name", "sheet_number", "uid",
|
||||
"refdes", "old_part_number", "old_value", "enabled", "new_part_number",
|
||||
"custom_value_enabled", "custom_value", "sync_nc")
|
||||
|
||||
|
||||
def export_target_plan(store, task_id: str, path: Path) -> Path:
|
||||
rows = store.list_target_plan(task_id)
|
||||
workbook = Workbook()
|
||||
sheet = workbook.active
|
||||
sheet.title = "Target Plan"
|
||||
sheet.append(HEADERS)
|
||||
for row in rows:
|
||||
target = row.target
|
||||
values = (str(target.project_path), target.project_path.name, target.schematic_name,
|
||||
target.sheet_number, target.uid, target.refdes, target.old_part_number,
|
||||
target.old_value, row.enabled, row.new_part_number, row.custom_value_enabled,
|
||||
row.custom_value, row.sync_nc)
|
||||
sheet.append(values)
|
||||
for cell in sheet[sheet.max_row]:
|
||||
if isinstance(cell.value, str):
|
||||
cell.data_type = "s"
|
||||
for cell in sheet[1]:
|
||||
cell.font = Font(bold=True, color="FFFFFF")
|
||||
cell.fill = PatternFill("solid", fgColor="28545A")
|
||||
sheet.freeze_panes = "I2"
|
||||
sheet.auto_filter.ref = sheet.dimensions
|
||||
for column in ("I", "K", "M"):
|
||||
check = DataValidation(type="list", formula1='"TRUE,FALSE"')
|
||||
sheet.add_data_validation(check)
|
||||
check.add(f"{column}2:{column}{max(sheet.max_row, 2)}")
|
||||
for column, width in {"A": 45, "B": 22, "C": 20, "D": 12, "E": 26,
|
||||
"F": 14, "G": 20, "H": 20, "I": 12, "J": 20,
|
||||
"K": 22, "L": 20, "M": 12}.items():
|
||||
sheet.column_dimensions[column].width = width
|
||||
path = Path(path)
|
||||
workbook.save(path)
|
||||
return path
|
||||
|
||||
|
||||
def import_target_plan(store, task_id: str, path: Path) -> tuple[TargetPlanRow, ...]:
|
||||
rows = read_target_plan(store, task_id, path)
|
||||
return store.replace_target_plan(task_id, rows)
|
||||
|
||||
|
||||
def read_target_plan(store, task_id: str, path: Path) -> tuple[TargetPlanRow, ...]:
|
||||
baseline = store.list_target_plan(task_id)
|
||||
expected = {row.target.key: row for row in baseline}
|
||||
if not expected:
|
||||
raise TaskCenterError("target_inventory", "collect component inventory before importing a plan")
|
||||
try:
|
||||
workbook = load_workbook(Path(path), read_only=True, data_only=False)
|
||||
if len(workbook.worksheets) != 1:
|
||||
raise ValueError("workbook must have exactly one plan sheet")
|
||||
records = list(workbook.active.iter_rows(values_only=False))
|
||||
if not records or tuple(cell.value for cell in records[0]) != HEADERS:
|
||||
raise ValueError("plan columns changed")
|
||||
by_key: dict[tuple[str, str, str, str], TargetPlanRow] = {}
|
||||
for cells in records[1:]:
|
||||
values = tuple(cell.value for cell in cells)
|
||||
if all(value is None for value in values):
|
||||
continue
|
||||
if len(values) != len(HEADERS) or any(cell.data_type == "f" for cell in cells):
|
||||
raise ValueError("invalid or formula plan row")
|
||||
identity = tuple("" if value is None else str(value) for value in values[:8])
|
||||
key = (str(Path(identity[0]).resolve(strict=False)).casefold(),
|
||||
identity[2], identity[3], identity[4])
|
||||
original = expected.get(key)
|
||||
if original is None or key in by_key:
|
||||
raise ValueError("forged or duplicate target")
|
||||
target = original.target
|
||||
if identity != (str(target.project_path), target.project_path.name, target.schematic_name,
|
||||
target.sheet_number, target.uid, target.refdes, target.old_part_number,
|
||||
target.old_value):
|
||||
raise ValueError("target baseline changed")
|
||||
enabled, new_part, custom_enabled, custom_value, sync_nc = values[8:13]
|
||||
enabled = _excel_bool(enabled)
|
||||
custom_enabled = _excel_bool(custom_enabled)
|
||||
sync_nc = _excel_bool(sync_nc)
|
||||
if not isinstance(new_part, str) and new_part is not None:
|
||||
raise ValueError("new Part Number must be text")
|
||||
if not isinstance(custom_value, str) and custom_value is not None:
|
||||
raise ValueError("custom Value must be text")
|
||||
by_key[key] = TargetPlanRow(target, enabled, new_part or "", custom_enabled,
|
||||
custom_value or "", sync_nc)
|
||||
if set(by_key) != set(expected):
|
||||
raise ValueError("plan rows are missing")
|
||||
result = tuple(by_key.values())
|
||||
compile_target_rules(result)
|
||||
return result
|
||||
except (OSError, ValueError, TypeError, KeyError) as error:
|
||||
raise TaskCenterError("target_plan_import", str(error)) from error
|
||||
finally:
|
||||
try:
|
||||
workbook.close()
|
||||
except (UnboundLocalError, AttributeError):
|
||||
pass
|
||||
|
||||
|
||||
def _excel_bool(value) -> bool:
|
||||
if type(value) is bool:
|
||||
return value
|
||||
if isinstance(value, (int, float)) and value in (0, 1):
|
||||
return bool(value)
|
||||
if isinstance(value, str) and value.strip().casefold() in {"true", "是", "1"}:
|
||||
return True
|
||||
if isinstance(value, str) and value.strip().casefold() in {"false", "否", "0"}:
|
||||
return False
|
||||
raise ValueError("plan switches must be Boolean")
|
||||
@@ -17,11 +17,13 @@ from uuid import uuid4
|
||||
|
||||
from dx_productivity.part_replace.inputs import InputError, parse_mapping_bytes
|
||||
|
||||
from .store_schema import StoreSchema, _SCHEMA_VERSION
|
||||
from .store_target_plan import TargetPlanRepository
|
||||
from .store_read_model import TaskBundle, checkpoint, read_lock, read_task_bundle
|
||||
from .errors import TaskCenterError
|
||||
from .models import ProjectRecord, ProjectStatus, RuleRecord, TaskRecord, TaskStatus
|
||||
|
||||
|
||||
_SCHEMA_VERSION = 5
|
||||
_INTERRUPTED_PROJECT_STATES = {
|
||||
ProjectStatus.CAPTURING_BEFORE,
|
||||
ProjectStatus.CAPTURING_AFTER,
|
||||
@@ -133,217 +135,61 @@ class TaskStore:
|
||||
self._connection.row_factory = sqlite3.Row
|
||||
with self._lock:
|
||||
self._connection.execute("PRAGMA foreign_keys = ON")
|
||||
self._schema = StoreSchema(self)
|
||||
self._target_plans = TargetPlanRepository(self)
|
||||
self._initialize_schema()
|
||||
|
||||
def read_task_bundle(self, task_id: str, read_control=None) -> TaskBundle:
|
||||
return read_task_bundle(self, task_id, read_control)
|
||||
|
||||
def close(self) -> None:
|
||||
with self._lock:
|
||||
self._connection.close()
|
||||
|
||||
def _initialize_schema(self) -> None:
|
||||
with self.transaction():
|
||||
self._connection.execute(
|
||||
"CREATE TABLE IF NOT EXISTS metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL)"
|
||||
)
|
||||
version_row = self._connection.execute(
|
||||
"SELECT value FROM metadata WHERE key = 'schema_version'"
|
||||
).fetchone()
|
||||
if version_row is None:
|
||||
self._create_schema_v1()
|
||||
self._create_attempt_schema()
|
||||
self._create_migration_recovery_schema()
|
||||
self._create_external_request_schema()
|
||||
self._connection.execute(
|
||||
"INSERT INTO metadata(key, value) VALUES ('schema_version', ?)",
|
||||
(str(_SCHEMA_VERSION),),
|
||||
)
|
||||
elif int(version_row["value"]) == 1:
|
||||
self._create_attempt_schema()
|
||||
self._create_migration_recovery_schema()
|
||||
self._create_external_request_schema()
|
||||
self._migrate_v1_attemptless_active_work()
|
||||
self._connection.execute("UPDATE metadata SET value = ? WHERE key = 'schema_version'", (str(_SCHEMA_VERSION),))
|
||||
elif int(version_row["value"]) == 2:
|
||||
self._create_migration_recovery_schema()
|
||||
self._create_external_request_schema()
|
||||
self._connection.execute("UPDATE metadata SET value = ? WHERE key = 'schema_version'", (str(_SCHEMA_VERSION),))
|
||||
elif int(version_row["value"]) == 3:
|
||||
self._create_external_request_schema()
|
||||
self._connection.execute("UPDATE metadata SET value = ? WHERE key = 'schema_version'", (str(_SCHEMA_VERSION),))
|
||||
elif int(version_row["value"]) == 4:
|
||||
self._connection.execute("UPDATE metadata SET value = ? WHERE key = 'schema_version'", (str(_SCHEMA_VERSION),))
|
||||
elif int(version_row["value"]) != _SCHEMA_VERSION:
|
||||
raise TaskCenterError("schema_version", "task database schema version is unsupported")
|
||||
else:
|
||||
self._create_migration_recovery_schema()
|
||||
self._create_external_request_schema()
|
||||
self._ensure_task_columns()
|
||||
self._ensure_rule_columns()
|
||||
return self._schema._initialize_schema()
|
||||
|
||||
def _create_schema_v1(self) -> None:
|
||||
statements = (
|
||||
"""CREATE TABLE IF NOT EXISTS tasks (
|
||||
task_id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL COLLATE NOCASE UNIQUE,
|
||||
note TEXT NOT NULL,
|
||||
discovery_root TEXT,
|
||||
status TEXT NOT NULL,
|
||||
created_utc TEXT NOT NULL,
|
||||
updated_utc TEXT NOT NULL,
|
||||
started_utc TEXT,
|
||||
completed_utc TEXT,
|
||||
deleted_utc TEXT,
|
||||
status_before_delete TEXT,
|
||||
error_id TEXT,
|
||||
summary TEXT NOT NULL DEFAULT ''
|
||||
)""",
|
||||
"""CREATE TABLE IF NOT EXISTS rules (
|
||||
rule_id TEXT PRIMARY KEY,
|
||||
task_id TEXT NOT NULL REFERENCES tasks(task_id),
|
||||
position INTEGER NOT NULL,
|
||||
old_part_number TEXT NOT NULL,
|
||||
new_part_number TEXT NOT NULL,
|
||||
enabled INTEGER NOT NULL CHECK(enabled IN (0, 1)),
|
||||
custom_value_enabled INTEGER NOT NULL DEFAULT 0 CHECK(custom_value_enabled IN (0, 1)),
|
||||
custom_value TEXT NOT NULL DEFAULT '',
|
||||
sync_nc INTEGER NOT NULL DEFAULT 1 CHECK(sync_nc IN (0, 1)),
|
||||
UNIQUE(task_id, position)
|
||||
)""",
|
||||
"""CREATE TABLE IF NOT EXISTS projects (
|
||||
project_id TEXT PRIMARY KEY,
|
||||
task_id TEXT NOT NULL REFERENCES tasks(task_id),
|
||||
display_name TEXT NOT NULL,
|
||||
path TEXT NOT NULL,
|
||||
path_identity TEXT NOT NULL,
|
||||
discovery_root TEXT NOT NULL,
|
||||
selected INTEGER NOT NULL CHECK(selected IN (0, 1)),
|
||||
available INTEGER NOT NULL CHECK(available IN (0, 1)),
|
||||
status TEXT NOT NULL,
|
||||
retry_count INTEGER NOT NULL DEFAULT 0,
|
||||
error_id TEXT,
|
||||
summary TEXT NOT NULL DEFAULT '',
|
||||
UNIQUE(task_id, path_identity)
|
||||
)""",
|
||||
)
|
||||
for statement in statements:
|
||||
self._connection.execute(statement)
|
||||
return self._schema._create_schema_v1()
|
||||
|
||||
def _create_attempt_schema(self) -> None:
|
||||
self._connection.execute(
|
||||
"""CREATE TABLE IF NOT EXISTS attempts (
|
||||
project_id TEXT NOT NULL REFERENCES projects(project_id),
|
||||
attempt_number INTEGER NOT NULL,
|
||||
probe_source TEXT NOT NULL,
|
||||
baseline_size INTEGER NOT NULL,
|
||||
baseline_sha256 TEXT NOT NULL,
|
||||
baseline_modified_ns INTEGER NOT NULL,
|
||||
rules_json TEXT NOT NULL,
|
||||
before_path TEXT,
|
||||
before_size INTEGER,
|
||||
before_sha256 TEXT,
|
||||
before_modified_ns INTEGER,
|
||||
instruction_json TEXT,
|
||||
PRIMARY KEY(project_id, attempt_number)
|
||||
)"""
|
||||
)
|
||||
return self._schema._create_attempt_schema()
|
||||
|
||||
def _create_migration_recovery_schema(self) -> None:
|
||||
self._connection.execute(
|
||||
"""CREATE TABLE IF NOT EXISTS migration_recoveries (
|
||||
project_id TEXT PRIMARY KEY REFERENCES projects(project_id),
|
||||
task_id TEXT NOT NULL REFERENCES tasks(task_id),
|
||||
project_before TEXT NOT NULL,
|
||||
project_after TEXT NOT NULL,
|
||||
task_before TEXT,
|
||||
task_after TEXT,
|
||||
error_id TEXT NOT NULL,
|
||||
project_summary TEXT NOT NULL,
|
||||
task_summary TEXT
|
||||
)"""
|
||||
)
|
||||
return self._schema._create_migration_recovery_schema()
|
||||
|
||||
def _create_external_request_schema(self) -> None:
|
||||
self._connection.execute(
|
||||
"""CREATE TABLE IF NOT EXISTS external_requests (
|
||||
source TEXT NOT NULL,
|
||||
idempotency_key TEXT NOT NULL,
|
||||
request_hash TEXT NOT NULL,
|
||||
task_id TEXT NOT NULL,
|
||||
created_utc TEXT NOT NULL,
|
||||
PRIMARY KEY(source, idempotency_key)
|
||||
)"""
|
||||
)
|
||||
return self._schema._create_external_request_schema()
|
||||
|
||||
def _migrate_v1_attemptless_active_work(self) -> None:
|
||||
"""Fail closed because v1 active projects cannot have an attempt evidence context."""
|
||||
states = tuple(status.value for status in _V1_ATTEMPTLESS_ACTIVE_STATES)
|
||||
rows = self._connection.execute(
|
||||
f"SELECT project_id, task_id, status FROM projects WHERE status IN ({', '.join('?' for _ in states)})",
|
||||
states,
|
||||
).fetchall()
|
||||
if not rows:
|
||||
return
|
||||
error = TaskCenterError("v1_attempt_context_missing", "migration interrupted active project; retry the project")
|
||||
for row in rows:
|
||||
summary = f"migration interrupted prior project state: {row['status']}; retry the project"
|
||||
task = self.get_task(row["task_id"])
|
||||
task_summary = "migration interrupted active project; retry the project"
|
||||
self._connection.execute(
|
||||
"UPDATE projects SET status = ?, error_id = ?, summary = ? WHERE project_id = ?",
|
||||
(ProjectStatus.FAILED.value, error.error_id, summary, row["project_id"]),
|
||||
)
|
||||
self._connection.execute(
|
||||
"""INSERT OR REPLACE INTO migration_recoveries(
|
||||
project_id, task_id, project_before, project_after, task_before, task_after,
|
||||
error_id, project_summary, task_summary
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||
(
|
||||
row["project_id"],
|
||||
row["task_id"],
|
||||
row["status"],
|
||||
ProjectStatus.FAILED.value,
|
||||
TaskStatus.RUNNING.value if task.status is TaskStatus.RUNNING else None,
|
||||
TaskStatus.PAUSED.value if task.status is TaskStatus.RUNNING else None,
|
||||
error.error_id,
|
||||
summary,
|
||||
task_summary if task.status is TaskStatus.RUNNING else None,
|
||||
),
|
||||
)
|
||||
for task_id in sorted({row["task_id"] for row in rows}):
|
||||
task = self.get_task(task_id)
|
||||
if task.status is TaskStatus.RUNNING:
|
||||
now = self._next_timestamp(task.updated_utc)
|
||||
self._connection.execute(
|
||||
"UPDATE tasks SET status = ?, updated_utc = ?, error_id = ?, summary = ? WHERE task_id = ?",
|
||||
(
|
||||
TaskStatus.PAUSED.value,
|
||||
_utc_text(now),
|
||||
error.error_id,
|
||||
"migration interrupted active project; retry the project",
|
||||
task_id,
|
||||
),
|
||||
)
|
||||
return self._schema._migrate_v1_attemptless_active_work()
|
||||
|
||||
def _ensure_task_columns(self) -> None:
|
||||
columns = {row["name"] for row in self._connection.execute("PRAGMA table_info(tasks)")}
|
||||
if "status_before_delete" not in columns:
|
||||
self._connection.execute("ALTER TABLE tasks ADD COLUMN status_before_delete TEXT")
|
||||
if "copy_part_number_to_value" not in columns:
|
||||
self._connection.execute(
|
||||
"ALTER TABLE tasks ADD COLUMN copy_part_number_to_value INTEGER NOT NULL DEFAULT 0 CHECK(copy_part_number_to_value IN (0, 1))"
|
||||
)
|
||||
return self._schema._ensure_task_columns()
|
||||
|
||||
def _create_target_plan_schema(self) -> None:
|
||||
return self._schema._create_target_plan_schema()
|
||||
|
||||
def bind_project_task(self, task_id: str, project_id: str, group_id: str, position: int) -> TaskRecord:
|
||||
return self._target_plans.bind_project_task(task_id, project_id, group_id, position)
|
||||
|
||||
def move_project_task(self, task_id: str, offset: int) -> tuple[TaskRecord, ...]:
|
||||
return self._target_plans.move_project_task(task_id, offset)
|
||||
|
||||
def list_project_group(self, group_id: str) -> tuple[TaskRecord, ...]:
|
||||
return self._target_plans.list_project_group(group_id)
|
||||
|
||||
def replace_target_plan(self, task_id: str, rows) -> tuple:
|
||||
return self._target_plans.replace_target_plan(task_id, rows)
|
||||
|
||||
def record_target_inventory(self, task_id: str, targets) -> tuple:
|
||||
return self._target_plans.record_target_inventory(task_id, targets)
|
||||
|
||||
def list_target_plan(self, task_id: str) -> tuple:
|
||||
return self._target_plans.list_target_plan(task_id)
|
||||
|
||||
def _ensure_rule_columns(self) -> None:
|
||||
columns = {row["name"] for row in self._connection.execute("PRAGMA table_info(rules)")}
|
||||
if "custom_value_enabled" not in columns:
|
||||
self._connection.execute(
|
||||
"ALTER TABLE rules ADD COLUMN custom_value_enabled INTEGER NOT NULL DEFAULT 0 CHECK(custom_value_enabled IN (0, 1))"
|
||||
)
|
||||
if "custom_value" not in columns:
|
||||
self._connection.execute("ALTER TABLE rules ADD COLUMN custom_value TEXT NOT NULL DEFAULT ''")
|
||||
if "sync_nc" not in columns:
|
||||
self._connection.execute(
|
||||
"ALTER TABLE rules ADD COLUMN sync_nc INTEGER NOT NULL DEFAULT 1 CHECK(sync_nc IN (0, 1))"
|
||||
)
|
||||
return self._schema._ensure_rule_columns()
|
||||
|
||||
@contextmanager
|
||||
def transaction(self) -> Iterator[None]:
|
||||
@@ -432,25 +278,31 @@ class TaskStore:
|
||||
)
|
||||
return self.get_task(task.task_id), projects, True
|
||||
|
||||
def get_task(self, task_id: str) -> TaskRecord:
|
||||
with self._lock:
|
||||
def get_task(self, task_id: str, *, read_control=None) -> TaskRecord:
|
||||
with read_lock(self, read_control):
|
||||
row = self._connection.execute("SELECT * FROM tasks WHERE task_id = ?", (task_id,)).fetchone()
|
||||
checkpoint(read_control)
|
||||
if row is None:
|
||||
raise TaskCenterError("unknown_task", "task does not exist")
|
||||
return self._task_record(row)
|
||||
|
||||
def list_tasks(self, status: TaskStatus | None = None) -> tuple[TaskRecord, ...]:
|
||||
with self._lock:
|
||||
def list_tasks(self, status: TaskStatus | None = None, *, read_control=None) -> tuple[TaskRecord, ...]:
|
||||
with read_lock(self, read_control):
|
||||
if status is None:
|
||||
rows = self._connection.execute(
|
||||
"SELECT * FROM tasks WHERE status != ? ORDER BY updated_utc DESC, task_id",
|
||||
(TaskStatus.DELETED.value,),
|
||||
).fetchall()
|
||||
)
|
||||
else:
|
||||
rows = self._connection.execute(
|
||||
"SELECT * FROM tasks WHERE status = ? ORDER BY updated_utc DESC, task_id", (TaskStatus(status).value,)
|
||||
).fetchall()
|
||||
return tuple(self._task_record(row) for row in rows)
|
||||
)
|
||||
result = []
|
||||
for row in rows:
|
||||
checkpoint(read_control)
|
||||
result.append(self._task_record(row))
|
||||
checkpoint(read_control)
|
||||
return tuple(result)
|
||||
|
||||
def update_task(self, task_id: str, *, name: str, note: str) -> TaskRecord:
|
||||
normalized_name = self._task_name(name)
|
||||
@@ -631,6 +483,7 @@ class TaskStore:
|
||||
)
|
||||
self._connection.execute("DELETE FROM migration_recoveries WHERE task_id = ?", (task_id,))
|
||||
self._connection.execute("DELETE FROM external_requests WHERE task_id = ?", (task_id,))
|
||||
self._connection.execute("DELETE FROM target_plan WHERE task_id = ?", (task_id,))
|
||||
self._connection.execute("DELETE FROM rules WHERE task_id = ?", (task_id,))
|
||||
self._connection.execute("DELETE FROM projects WHERE task_id = ?", (task_id,))
|
||||
self._connection.execute("DELETE FROM tasks WHERE task_id = ?", (task_id,))
|
||||
@@ -1193,6 +1046,10 @@ class TaskStore:
|
||||
error_id=row["error_id"],
|
||||
summary=row["summary"],
|
||||
copy_part_number_to_value=bool(row["copy_part_number_to_value"]),
|
||||
group_id=row["group_id"],
|
||||
group_position=row["group_position"],
|
||||
primary_project_id=row["primary_project_id"],
|
||||
target_plan_mode=bool(row["target_plan_mode"]),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Consistent, cancellable task read models on the owning SQLite connection."""
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from .models import TaskRecord, ProjectRecord, RuleRecord
|
||||
from .target_plan import ComponentTarget, TargetPlanRow
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class TaskBundle:
|
||||
"""One database snapshot including task binding/status and its target plan."""
|
||||
|
||||
task: TaskRecord
|
||||
projects: tuple[ProjectRecord, ...]
|
||||
rules: tuple[RuleRecord, ...]
|
||||
targets: tuple[TargetPlanRow, ...]
|
||||
|
||||
|
||||
def checkpoint(read_control):
|
||||
if read_control is not None:
|
||||
read_control.checkpoint()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def read_lock(store, read_control=None):
|
||||
checkpoint(read_control)
|
||||
while not store._lock.acquire(timeout=0.05):
|
||||
checkpoint(read_control)
|
||||
try:
|
||||
checkpoint(read_control)
|
||||
yield
|
||||
finally:
|
||||
store._lock.release()
|
||||
|
||||
|
||||
def read_task_bundle(store, task_id: str, read_control=None) -> TaskBundle:
|
||||
def checkpoint():
|
||||
if read_control is not None:
|
||||
read_control.checkpoint()
|
||||
|
||||
with read_lock(store, read_control):
|
||||
started = False
|
||||
try:
|
||||
checkpoint()
|
||||
if store._transaction_depth == 0:
|
||||
store._connection.execute("BEGIN")
|
||||
started = True
|
||||
task = store.get_task(task_id)
|
||||
checkpoint()
|
||||
|
||||
def records(sql, convert):
|
||||
result = []
|
||||
for row in store._connection.execute(sql, (task_id,)):
|
||||
checkpoint()
|
||||
result.append(convert(row))
|
||||
checkpoint()
|
||||
return tuple(result)
|
||||
|
||||
projects = records(
|
||||
"SELECT * FROM projects WHERE task_id = ? ORDER BY path_identity, project_id",
|
||||
store._project_record,
|
||||
)
|
||||
rules = records(
|
||||
"SELECT * FROM rules WHERE task_id = ? ORDER BY position", store._rule_record,
|
||||
)
|
||||
def target_record(row):
|
||||
return TargetPlanRow(
|
||||
ComponentTarget(Path(row['project_path']), row['schematic_name'], row['sheet_number'],
|
||||
row['uid'], row['refdes'], row['old_part_number'], row['old_value']),
|
||||
bool(row['enabled']), row['new_part_number'], bool(row['custom_value_enabled']),
|
||||
row['custom_value'], bool(row['sync_nc']),
|
||||
)
|
||||
targets = records(
|
||||
"SELECT * FROM target_plan WHERE task_id = ? ORDER BY project_path, schematic_name, sheet_number, refdes, uid",
|
||||
target_record,
|
||||
)
|
||||
checkpoint()
|
||||
if started:
|
||||
store._connection.execute("COMMIT")
|
||||
started = False
|
||||
return TaskBundle(task, projects, rules, targets)
|
||||
except BaseException:
|
||||
if started:
|
||||
store._connection.execute("ROLLBACK")
|
||||
raise
|
||||
@@ -0,0 +1,244 @@
|
||||
"""Transactional schema upgrades using the owning store connection."""
|
||||
from __future__ import annotations
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .models import ProjectStatus, TaskStatus
|
||||
|
||||
_SCHEMA_VERSION = 6
|
||||
_V1_ATTEMPTLESS_ACTIVE_STATES = {ProjectStatus.CAPTURING_BEFORE, ProjectStatus.AWAITING_OPERATOR, ProjectStatus.CAPTURING_AFTER, ProjectStatus.VERIFYING}
|
||||
|
||||
|
||||
class StoreSchema:
|
||||
def __init__(self, store) -> None:
|
||||
self._store = store
|
||||
|
||||
def _initialize_schema(self) -> None:
|
||||
with self._store.transaction():
|
||||
self._store._connection.execute(
|
||||
"CREATE TABLE IF NOT EXISTS metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL)"
|
||||
)
|
||||
version_row = self._store._connection.execute(
|
||||
"SELECT value FROM metadata WHERE key = 'schema_version'"
|
||||
).fetchone()
|
||||
if version_row is None:
|
||||
self._store._create_schema_v1()
|
||||
self._store._create_attempt_schema()
|
||||
self._store._create_migration_recovery_schema()
|
||||
self._store._create_external_request_schema()
|
||||
self._store._connection.execute(
|
||||
"INSERT INTO metadata(key, value) VALUES ('schema_version', ?)",
|
||||
(str(_SCHEMA_VERSION),),
|
||||
)
|
||||
elif int(version_row["value"]) == 1:
|
||||
self._store._create_attempt_schema()
|
||||
self._store._create_migration_recovery_schema()
|
||||
self._store._create_external_request_schema()
|
||||
self._store._migrate_v1_attemptless_active_work()
|
||||
self._store._connection.execute("UPDATE metadata SET value = ? WHERE key = 'schema_version'", (str(_SCHEMA_VERSION),))
|
||||
elif int(version_row["value"]) == 2:
|
||||
self._store._create_migration_recovery_schema()
|
||||
self._store._create_external_request_schema()
|
||||
self._store._connection.execute("UPDATE metadata SET value = ? WHERE key = 'schema_version'", (str(_SCHEMA_VERSION),))
|
||||
elif int(version_row["value"]) == 3:
|
||||
self._store._create_external_request_schema()
|
||||
self._store._connection.execute("UPDATE metadata SET value = ? WHERE key = 'schema_version'", (str(_SCHEMA_VERSION),))
|
||||
elif int(version_row["value"]) in {4, 5}:
|
||||
self._store._connection.execute("UPDATE metadata SET value = ? WHERE key = 'schema_version'", (str(_SCHEMA_VERSION),))
|
||||
elif int(version_row["value"]) != _SCHEMA_VERSION:
|
||||
raise TaskCenterError("schema_version", "task database schema version is unsupported")
|
||||
else:
|
||||
self._store._create_migration_recovery_schema()
|
||||
self._store._create_external_request_schema()
|
||||
self._store._ensure_task_columns()
|
||||
self._store._ensure_rule_columns()
|
||||
self._store._create_target_plan_schema()
|
||||
|
||||
def _create_schema_v1(self) -> None:
|
||||
statements = (
|
||||
"""CREATE TABLE IF NOT EXISTS tasks (
|
||||
task_id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL COLLATE NOCASE UNIQUE,
|
||||
note TEXT NOT NULL,
|
||||
discovery_root TEXT,
|
||||
status TEXT NOT NULL,
|
||||
created_utc TEXT NOT NULL,
|
||||
updated_utc TEXT NOT NULL,
|
||||
started_utc TEXT,
|
||||
completed_utc TEXT,
|
||||
deleted_utc TEXT,
|
||||
status_before_delete TEXT,
|
||||
error_id TEXT,
|
||||
summary TEXT NOT NULL DEFAULT ''
|
||||
)""",
|
||||
"""CREATE TABLE IF NOT EXISTS rules (
|
||||
rule_id TEXT PRIMARY KEY,
|
||||
task_id TEXT NOT NULL REFERENCES tasks(task_id),
|
||||
position INTEGER NOT NULL,
|
||||
old_part_number TEXT NOT NULL,
|
||||
new_part_number TEXT NOT NULL,
|
||||
enabled INTEGER NOT NULL CHECK(enabled IN (0, 1)),
|
||||
custom_value_enabled INTEGER NOT NULL DEFAULT 0 CHECK(custom_value_enabled IN (0, 1)),
|
||||
custom_value TEXT NOT NULL DEFAULT '',
|
||||
sync_nc INTEGER NOT NULL DEFAULT 1 CHECK(sync_nc IN (0, 1)),
|
||||
UNIQUE(task_id, position)
|
||||
)""",
|
||||
"""CREATE TABLE IF NOT EXISTS projects (
|
||||
project_id TEXT PRIMARY KEY,
|
||||
task_id TEXT NOT NULL REFERENCES tasks(task_id),
|
||||
display_name TEXT NOT NULL,
|
||||
path TEXT NOT NULL,
|
||||
path_identity TEXT NOT NULL,
|
||||
discovery_root TEXT NOT NULL,
|
||||
selected INTEGER NOT NULL CHECK(selected IN (0, 1)),
|
||||
available INTEGER NOT NULL CHECK(available IN (0, 1)),
|
||||
status TEXT NOT NULL,
|
||||
retry_count INTEGER NOT NULL DEFAULT 0,
|
||||
error_id TEXT,
|
||||
summary TEXT NOT NULL DEFAULT '',
|
||||
UNIQUE(task_id, path_identity)
|
||||
)""",
|
||||
)
|
||||
for statement in statements:
|
||||
self._store._connection.execute(statement)
|
||||
|
||||
def _create_attempt_schema(self) -> None:
|
||||
self._store._connection.execute(
|
||||
"""CREATE TABLE IF NOT EXISTS attempts (
|
||||
project_id TEXT NOT NULL REFERENCES projects(project_id),
|
||||
attempt_number INTEGER NOT NULL,
|
||||
probe_source TEXT NOT NULL,
|
||||
baseline_size INTEGER NOT NULL,
|
||||
baseline_sha256 TEXT NOT NULL,
|
||||
baseline_modified_ns INTEGER NOT NULL,
|
||||
rules_json TEXT NOT NULL,
|
||||
before_path TEXT,
|
||||
before_size INTEGER,
|
||||
before_sha256 TEXT,
|
||||
before_modified_ns INTEGER,
|
||||
instruction_json TEXT,
|
||||
PRIMARY KEY(project_id, attempt_number)
|
||||
)"""
|
||||
)
|
||||
|
||||
def _create_migration_recovery_schema(self) -> None:
|
||||
self._store._connection.execute(
|
||||
"""CREATE TABLE IF NOT EXISTS migration_recoveries (
|
||||
project_id TEXT PRIMARY KEY REFERENCES projects(project_id),
|
||||
task_id TEXT NOT NULL REFERENCES tasks(task_id),
|
||||
project_before TEXT NOT NULL,
|
||||
project_after TEXT NOT NULL,
|
||||
task_before TEXT,
|
||||
task_after TEXT,
|
||||
error_id TEXT NOT NULL,
|
||||
project_summary TEXT NOT NULL,
|
||||
task_summary TEXT
|
||||
)"""
|
||||
)
|
||||
|
||||
def _create_external_request_schema(self) -> None:
|
||||
self._store._connection.execute(
|
||||
"""CREATE TABLE IF NOT EXISTS external_requests (
|
||||
source TEXT NOT NULL,
|
||||
idempotency_key TEXT NOT NULL,
|
||||
request_hash TEXT NOT NULL,
|
||||
task_id TEXT NOT NULL,
|
||||
created_utc TEXT NOT NULL,
|
||||
PRIMARY KEY(source, idempotency_key)
|
||||
)"""
|
||||
)
|
||||
|
||||
def _migrate_v1_attemptless_active_work(self) -> None:
|
||||
"""Fail closed because v1 active projects cannot have an attempt evidence context."""
|
||||
from .store import _utc_text
|
||||
|
||||
states = tuple(status.value for status in _V1_ATTEMPTLESS_ACTIVE_STATES)
|
||||
rows = self._store._connection.execute(
|
||||
f"SELECT project_id, task_id, status FROM projects WHERE status IN ({', '.join('?' for _ in states)})",
|
||||
states,
|
||||
).fetchall()
|
||||
if not rows:
|
||||
return
|
||||
error = TaskCenterError("v1_attempt_context_missing", "migration interrupted active project; retry the project")
|
||||
for row in rows:
|
||||
summary = f"migration interrupted prior project state: {row['status']}; retry the project"
|
||||
task = self._store.get_task(row["task_id"])
|
||||
task_summary = "migration interrupted active project; retry the project"
|
||||
self._store._connection.execute(
|
||||
"UPDATE projects SET status = ?, error_id = ?, summary = ? WHERE project_id = ?",
|
||||
(ProjectStatus.FAILED.value, error.error_id, summary, row["project_id"]),
|
||||
)
|
||||
self._store._connection.execute(
|
||||
"""INSERT OR REPLACE INTO migration_recoveries(
|
||||
project_id, task_id, project_before, project_after, task_before, task_after,
|
||||
error_id, project_summary, task_summary
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||
(
|
||||
row["project_id"],
|
||||
row["task_id"],
|
||||
row["status"],
|
||||
ProjectStatus.FAILED.value,
|
||||
TaskStatus.RUNNING.value if task.status is TaskStatus.RUNNING else None,
|
||||
TaskStatus.PAUSED.value if task.status is TaskStatus.RUNNING else None,
|
||||
error.error_id,
|
||||
summary,
|
||||
task_summary if task.status is TaskStatus.RUNNING else None,
|
||||
),
|
||||
)
|
||||
for task_id in sorted({row["task_id"] for row in rows}):
|
||||
task = self._store.get_task(task_id)
|
||||
if task.status is TaskStatus.RUNNING:
|
||||
now = self._store._next_timestamp(task.updated_utc)
|
||||
self._store._connection.execute(
|
||||
"UPDATE tasks SET status = ?, updated_utc = ?, error_id = ?, summary = ? WHERE task_id = ?",
|
||||
(
|
||||
TaskStatus.PAUSED.value,
|
||||
_utc_text(now),
|
||||
error.error_id,
|
||||
"migration interrupted active project; retry the project",
|
||||
task_id,
|
||||
),
|
||||
)
|
||||
|
||||
def _ensure_task_columns(self) -> None:
|
||||
columns = {row["name"] for row in self._store._connection.execute("PRAGMA table_info(tasks)")}
|
||||
if "status_before_delete" not in columns:
|
||||
self._store._connection.execute("ALTER TABLE tasks ADD COLUMN status_before_delete TEXT")
|
||||
if "copy_part_number_to_value" not in columns:
|
||||
self._store._connection.execute(
|
||||
"ALTER TABLE tasks ADD COLUMN copy_part_number_to_value INTEGER NOT NULL DEFAULT 0 CHECK(copy_part_number_to_value IN (0, 1))"
|
||||
)
|
||||
if "group_id" not in columns:
|
||||
self._store._connection.execute("ALTER TABLE tasks ADD COLUMN group_id TEXT")
|
||||
if "group_position" not in columns:
|
||||
self._store._connection.execute("ALTER TABLE tasks ADD COLUMN group_position INTEGER NOT NULL DEFAULT 0")
|
||||
if "primary_project_id" not in columns:
|
||||
self._store._connection.execute("ALTER TABLE tasks ADD COLUMN primary_project_id TEXT")
|
||||
if "target_plan_mode" not in columns:
|
||||
self._store._connection.execute("ALTER TABLE tasks ADD COLUMN target_plan_mode INTEGER NOT NULL DEFAULT 0 CHECK(target_plan_mode IN (0,1))")
|
||||
|
||||
def _create_target_plan_schema(self) -> None:
|
||||
self._store._connection.execute("""CREATE TABLE IF NOT EXISTS target_plan (
|
||||
task_id TEXT NOT NULL REFERENCES tasks(task_id), project_path TEXT NOT NULL,
|
||||
schematic_name TEXT NOT NULL, sheet_number TEXT NOT NULL, uid TEXT NOT NULL,
|
||||
refdes TEXT NOT NULL, old_part_number TEXT NOT NULL, old_value TEXT NOT NULL,
|
||||
enabled INTEGER NOT NULL DEFAULT 0 CHECK(enabled IN (0,1)),
|
||||
new_part_number TEXT NOT NULL DEFAULT '',
|
||||
custom_value_enabled INTEGER NOT NULL DEFAULT 0 CHECK(custom_value_enabled IN (0,1)),
|
||||
custom_value TEXT NOT NULL DEFAULT '', sync_nc INTEGER NOT NULL DEFAULT 1 CHECK(sync_nc IN (0,1)),
|
||||
PRIMARY KEY(task_id, project_path, schematic_name, sheet_number, uid)
|
||||
)""")
|
||||
|
||||
def _ensure_rule_columns(self) -> None:
|
||||
columns = {row["name"] for row in self._store._connection.execute("PRAGMA table_info(rules)")}
|
||||
if "custom_value_enabled" not in columns:
|
||||
self._store._connection.execute(
|
||||
"ALTER TABLE rules ADD COLUMN custom_value_enabled INTEGER NOT NULL DEFAULT 0 CHECK(custom_value_enabled IN (0, 1))"
|
||||
)
|
||||
if "custom_value" not in columns:
|
||||
self._store._connection.execute("ALTER TABLE rules ADD COLUMN custom_value TEXT NOT NULL DEFAULT ''")
|
||||
if "sync_nc" not in columns:
|
||||
self._store._connection.execute(
|
||||
"ALTER TABLE rules ADD COLUMN sync_nc INTEGER NOT NULL DEFAULT 1 CHECK(sync_nc IN (0, 1))"
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
"""Project binding and immutable target inventory persistence."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from .errors import TaskCenterError
|
||||
from .models import TaskRecord, TaskStatus
|
||||
|
||||
def _target_baseline(target) -> tuple:
|
||||
return (target.key, target.refdes, target.old_part_number, target.old_value)
|
||||
|
||||
|
||||
class TargetPlanRepository:
|
||||
def __init__(self, store) -> None:
|
||||
self._store = store
|
||||
|
||||
def bind_project_task(self, task_id: str, project_id: str, group_id: str, position: int) -> TaskRecord:
|
||||
with self._store.transaction():
|
||||
project = self._store.get_project(project_id)
|
||||
if project.task_id != task_id or len(self._store.list_projects(task_id)) != 1:
|
||||
raise TaskCenterError("project_binding", "new task must own exactly one project")
|
||||
self._store._connection.execute("UPDATE tasks SET group_id = ?, group_position = ?, primary_project_id = ? WHERE task_id = ?",
|
||||
(group_id, position, project_id, task_id))
|
||||
return self._store.get_task(task_id)
|
||||
|
||||
def move_project_task(self, task_id: str, offset: int) -> tuple[TaskRecord, ...]:
|
||||
with self._store.transaction():
|
||||
task = self._store.get_task(task_id)
|
||||
if task.group_id is None:
|
||||
raise TaskCenterError("project_order", "task is not in a project group")
|
||||
tasks = list(self._store.list_project_group(task.group_id))
|
||||
if any(item.status in {TaskStatus.RUNNING, TaskStatus.PAUSED} for item in tasks):
|
||||
raise TaskCenterError("project_order", "project group is active")
|
||||
index = next(index for index, item in enumerate(tasks) if item.task_id == task_id)
|
||||
destination = max(0, min(len(tasks) - 1, index + int(offset)))
|
||||
if destination != index:
|
||||
tasks.insert(destination, tasks.pop(index))
|
||||
for position, item in enumerate(tasks):
|
||||
self._store._connection.execute("UPDATE tasks SET group_position = ? WHERE task_id = ?",
|
||||
(position, item.task_id))
|
||||
return self._store.list_project_group(task.group_id)
|
||||
|
||||
def list_project_group(self, group_id: str) -> tuple[TaskRecord, ...]:
|
||||
with self._store._lock:
|
||||
rows = self._store._connection.execute("SELECT * FROM tasks WHERE group_id = ? ORDER BY group_position, created_utc",
|
||||
(group_id,)).fetchall()
|
||||
return tuple(self._store._task_record(row) for row in rows)
|
||||
|
||||
def replace_target_plan(self, task_id: str, rows) -> tuple:
|
||||
from .target_plan import compile_target_rules
|
||||
with self._store.transaction():
|
||||
task = self._store.get_task(task_id)
|
||||
if task.status not in {TaskStatus.DRAFT, TaskStatus.READY}:
|
||||
raise TaskCenterError("target_plan_locked", "task plan is locked")
|
||||
rows = tuple(rows)
|
||||
compile_target_rules(rows)
|
||||
projects = self._store.list_projects(task_id)
|
||||
allowed = {str(project.path.resolve(strict=False)).casefold() for project in projects}
|
||||
if any(str(row.target.project_path.resolve(strict=False)).casefold() not in allowed for row in rows):
|
||||
raise TaskCenterError("target_identity", "target project is not in task")
|
||||
inventory = {row.target.key: row.target for row in self._store.list_target_plan(task_id)}
|
||||
if not inventory and not (task.target_plan_mode and not rows):
|
||||
raise TaskCenterError("target_inventory", "collect component inventory before editing the plan")
|
||||
if set(inventory) != {row.target.key for row in rows} or any(
|
||||
_target_baseline(inventory[row.target.key]) != _target_baseline(row.target)
|
||||
for row in rows):
|
||||
raise TaskCenterError("target_identity", "target baseline identity changed")
|
||||
self._store._connection.execute("DELETE FROM target_plan WHERE task_id = ?", (task_id,))
|
||||
for row in rows:
|
||||
target = row.target
|
||||
self._store._connection.execute("""INSERT INTO target_plan VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||
(task_id, str(target.project_path.resolve(strict=False)).casefold(), target.schematic_name,
|
||||
target.sheet_number, target.uid, target.refdes, target.old_part_number, target.old_value,
|
||||
int(row.enabled), row.new_part_number, int(row.custom_value_enabled), row.custom_value,
|
||||
int(row.sync_nc)))
|
||||
self._store._connection.execute("UPDATE tasks SET target_plan_mode = 1 WHERE task_id = ?", (task_id,))
|
||||
return self._store.list_target_plan(task_id)
|
||||
|
||||
def record_target_inventory(self, task_id: str, targets) -> tuple:
|
||||
from .target_plan import TargetPlanRow
|
||||
with self._store.transaction():
|
||||
task = self._store.get_task(task_id)
|
||||
if task.status not in {TaskStatus.DRAFT, TaskStatus.READY}:
|
||||
raise TaskCenterError("target_plan_locked", "task plan is locked")
|
||||
targets = tuple(targets)
|
||||
if not targets:
|
||||
if self._store.list_target_plan(task_id):
|
||||
raise TaskCenterError("target_identity", "inventory unexpectedly became empty")
|
||||
self._store._connection.execute("UPDATE tasks SET target_plan_mode = 1 WHERE task_id = ?", (task_id,))
|
||||
return ()
|
||||
if len({target.key for target in targets}) != len(targets):
|
||||
raise TaskCenterError("target_identity", "component inventory contains duplicate UID")
|
||||
existing = self._store.list_target_plan(task_id)
|
||||
if existing:
|
||||
known = {row.target.key: row.target for row in existing}
|
||||
if set(known) != {target.key for target in targets} or any(
|
||||
_target_baseline(known[target.key]) != _target_baseline(target)
|
||||
for target in targets):
|
||||
raise TaskCenterError("target_identity", "component inventory identity changed")
|
||||
return existing
|
||||
rows = tuple(TargetPlanRow(target) for target in targets)
|
||||
projects = self._store.list_projects(task_id)
|
||||
allowed = {str(project.path.resolve(strict=False)).casefold() for project in projects}
|
||||
if any(str(row.target.project_path.resolve(strict=False)).casefold() not in allowed for row in rows):
|
||||
raise TaskCenterError("target_identity", "inventory project is not in task")
|
||||
for row in rows:
|
||||
target = row.target
|
||||
self._store._connection.execute("""INSERT INTO target_plan VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, '', 0, '', 1)""",
|
||||
(task_id, str(target.project_path.resolve(strict=False)).casefold(), target.schematic_name,
|
||||
target.sheet_number, target.uid, target.refdes, target.old_part_number, target.old_value))
|
||||
self._store._connection.execute("UPDATE tasks SET target_plan_mode = 1 WHERE task_id = ?", (task_id,))
|
||||
return self._store.list_target_plan(task_id)
|
||||
|
||||
def list_target_plan(self, task_id: str) -> tuple:
|
||||
from .target_plan import ComponentTarget, TargetPlanRow
|
||||
with self._store._lock:
|
||||
self._store.get_task(task_id)
|
||||
rows = self._store._connection.execute("SELECT * FROM target_plan WHERE task_id = ? ORDER BY project_path, schematic_name, sheet_number, refdes, uid", (task_id,)).fetchall()
|
||||
return tuple(TargetPlanRow(
|
||||
ComponentTarget(Path(row["project_path"]), row["schematic_name"], row["sheet_number"],
|
||||
row["uid"], row["refdes"], row["old_part_number"], row["old_value"]),
|
||||
bool(row["enabled"]), row["new_part_number"], bool(row["custom_value_enabled"]),
|
||||
row["custom_value"], bool(row["sync_nc"])) for row in rows)
|
||||
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
"""Stable component identities and editable replacement plans."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from .errors import TaskCenterError
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ComponentTarget:
|
||||
project_path: Path
|
||||
schematic_name: str
|
||||
sheet_number: str
|
||||
uid: str
|
||||
refdes: str
|
||||
old_part_number: str
|
||||
old_value: str
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
fields = (self.schematic_name, self.sheet_number, self.uid, self.refdes, self.old_part_number)
|
||||
if any(not isinstance(value, str) or not value for value in fields):
|
||||
raise TaskCenterError("target_identity", "component identity is incomplete")
|
||||
if any(any(ord(char) < 32 for char in value) for value in fields):
|
||||
raise TaskCenterError("target_identity", "component identity contains control characters")
|
||||
|
||||
@property
|
||||
def key(self) -> tuple[str, str, str, str]:
|
||||
return (str(self.project_path.resolve(strict=False)).casefold(),
|
||||
self.schematic_name, self.sheet_number, self.uid)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class TargetPlanRow:
|
||||
target: ComponentTarget
|
||||
enabled: bool = False
|
||||
new_part_number: str = ""
|
||||
custom_value_enabled: bool = False
|
||||
custom_value: str = ""
|
||||
sync_nc: bool = True
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if any(type(value) is not bool for value in (self.enabled, self.custom_value_enabled, self.sync_nc)):
|
||||
raise TaskCenterError("target_plan", "plan switches must be Boolean")
|
||||
if not isinstance(self.new_part_number, str) or not isinstance(self.custom_value, str):
|
||||
raise TaskCenterError("target_plan", "Part Number and Value must be text")
|
||||
if any(character in value for value in (self.new_part_number, self.custom_value)
|
||||
for character in "\t\r\n"):
|
||||
raise TaskCenterError("target_plan", "Part Number and Value cannot contain TSV controls")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class TargetRule:
|
||||
old_part_number: str
|
||||
new_part_number: str
|
||||
targets: tuple[ComponentTarget, ...]
|
||||
custom_value_enabled: bool = False
|
||||
custom_value: str = ""
|
||||
sync_nc: bool = True
|
||||
enabled: bool = True
|
||||
rule_id: str = ""
|
||||
task_id: str = ""
|
||||
position: int = 0
|
||||
scope: str = "targets"
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not self.targets:
|
||||
raise TaskCenterError("empty_target_scope", "target rule needs at least one component")
|
||||
if any(target.old_part_number.casefold() != self.old_part_number.casefold() for target in self.targets):
|
||||
raise TaskCenterError("target_identity", "target old Part Number differs from rule")
|
||||
|
||||
|
||||
def compile_target_rules(rows: tuple[TargetPlanRow, ...]) -> tuple[TargetRule, ...]:
|
||||
"""Group selected rows by sheet and replacement options, retaining UID scope."""
|
||||
seen: set[tuple[str, str, str, str]] = set()
|
||||
grouped: dict[tuple[str, str, str, str, str, str, bool, str, bool], list[ComponentTarget]] = {}
|
||||
old_parts: set[str] = set()
|
||||
new_parts: set[str] = set()
|
||||
for row in rows:
|
||||
target = row.target
|
||||
if not all((target.uid, target.refdes, target.schematic_name, target.sheet_number,
|
||||
target.old_part_number)):
|
||||
raise TaskCenterError("target_identity", "component identity is incomplete")
|
||||
if target.key in seen:
|
||||
raise TaskCenterError("target_overlap", "target UID appears more than once")
|
||||
seen.add(target.key)
|
||||
if not row.enabled:
|
||||
continue
|
||||
new = row.new_part_number.strip()
|
||||
old = target.old_part_number.strip()
|
||||
if not new or old.casefold() == new.casefold():
|
||||
raise TaskCenterError("mapping_rule", "source and target Part Numbers must differ")
|
||||
if row.custom_value_enabled and not row.custom_value:
|
||||
raise TaskCenterError("value_option", "custom Value is empty")
|
||||
old_parts.add(old.casefold())
|
||||
new_parts.add(new.casefold())
|
||||
key = (str(target.project_path.resolve(strict=False)).casefold(), target.schematic_name,
|
||||
target.sheet_number, old, new, row.custom_value_enabled,
|
||||
row.custom_value if row.custom_value_enabled else "", row.sync_nc)
|
||||
grouped.setdefault(key, []).append(target)
|
||||
if old_parts & new_parts:
|
||||
raise TaskCenterError("mapping_chain", "chain or cycle replacement is not allowed")
|
||||
return tuple(TargetRule(key[3], key[4], tuple(targets), key[5], key[6], key[7],
|
||||
position=index) for index, (key, targets) in enumerate(grouped.items()))
|
||||
@@ -0,0 +1,174 @@
|
||||
"""Bounded event-log pages and physical cursors, independent of the UI."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from contextlib import contextmanager
|
||||
import os
|
||||
from pathlib import Path
|
||||
from threading import RLock
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LogCursor:
|
||||
identity: tuple[int, int]
|
||||
offset: int
|
||||
anchor: bytes = b''
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LogPage:
|
||||
lines: tuple[str, ...] = ()
|
||||
cursor: LogCursor | None = None
|
||||
older_cursor: LogCursor | None = None
|
||||
has_older: bool = False
|
||||
reset: bool = False
|
||||
|
||||
|
||||
def _identity(handle):
|
||||
value = os.fstat(handle.fileno())
|
||||
return value.st_dev, value.st_ino
|
||||
|
||||
|
||||
def _cursor(handle, offset):
|
||||
handle.seek(max(0, offset - 64))
|
||||
return LogCursor(_identity(handle), offset, handle.read(min(64, offset)))
|
||||
|
||||
|
||||
def _matches(handle, cursor):
|
||||
if _identity(handle) != cursor.identity or os.fstat(handle.fileno()).st_size < cursor.offset:
|
||||
return False
|
||||
return _cursor(handle, cursor.offset).anchor == cursor.anchor
|
||||
|
||||
|
||||
def _backward(handle, end, limit, check=lambda: None):
|
||||
"""Read complete lines backwards, retaining their exact byte boundaries."""
|
||||
position = end
|
||||
chunks = []
|
||||
count = 0
|
||||
while position > 0 and count <= limit:
|
||||
check()
|
||||
amount = min(8192, position)
|
||||
position -= amount
|
||||
handle.seek(position)
|
||||
chunk = handle.read(amount)
|
||||
chunks.append(chunk)
|
||||
count += chunk.count(b'\n')
|
||||
payload = b''.join(reversed(chunks))
|
||||
if position:
|
||||
cut = payload.find(b'\n') + 1
|
||||
payload = payload[cut:]
|
||||
position += cut
|
||||
rows = []
|
||||
for line in payload.splitlines(keepends=True):
|
||||
check()
|
||||
next_position = position + len(line)
|
||||
if line.endswith(b'\n'):
|
||||
rows.append((position, next_position, line.rstrip(b'\r\n').decode('utf-8')))
|
||||
position = next_position
|
||||
return rows[-limit:]
|
||||
|
||||
|
||||
class TaskLogReader:
|
||||
def __init__(self, path: Path, lock: RLock, *, backup_count: int = 5, read_control=None):
|
||||
self.path, self.lock, self.backup_count = path, lock, backup_count
|
||||
self.read_control = read_control
|
||||
|
||||
def _check(self):
|
||||
if self.read_control is not None:
|
||||
self.read_control.checkpoint()
|
||||
|
||||
@contextmanager
|
||||
def _locked(self):
|
||||
self._check()
|
||||
while not self.lock.acquire(timeout=0.05):
|
||||
self._check()
|
||||
try:
|
||||
self._check()
|
||||
yield
|
||||
finally:
|
||||
self.lock.release()
|
||||
|
||||
def _paths(self):
|
||||
return [self.path.with_name(f'{self.path.name}.{i}') for i in range(self.backup_count, 0, -1)] + [self.path]
|
||||
|
||||
def latest(self, *, limit=200):
|
||||
return self.older(None, limit=limit)
|
||||
|
||||
def older(self, before: LogCursor | None, *, limit=200):
|
||||
if limit < 1:
|
||||
raise ValueError('log page limit must be positive')
|
||||
with self._locked():
|
||||
paths = [path for path in self._paths() if path.is_file()]
|
||||
result = []
|
||||
started = before is None
|
||||
newest_cursor = oldest_cursor = None
|
||||
has_older = False
|
||||
for index in range(len(paths) - 1, -1, -1):
|
||||
self._check()
|
||||
with paths[index].open('rb') as handle:
|
||||
if not started:
|
||||
if not _matches(handle, before):
|
||||
continue
|
||||
end = before.offset
|
||||
started = True
|
||||
else:
|
||||
end = os.fstat(handle.fileno()).st_size
|
||||
rows = _backward(handle, end, limit - len(result), self._check)
|
||||
if rows:
|
||||
if newest_cursor is None:
|
||||
newest_cursor = _cursor(handle, rows[-1][1])
|
||||
oldest_cursor = _cursor(handle, rows[0][0])
|
||||
result[0:0] = [row[2] for row in rows]
|
||||
elif newest_cursor is None and before is None:
|
||||
# Incomplete trailing line must be retried from its start.
|
||||
newest_cursor = _cursor(handle, 0)
|
||||
if len(result) >= limit:
|
||||
has_older = bool(rows and rows[0][0] > 0) or any(p.stat().st_size for p in paths[:index])
|
||||
break
|
||||
if before is not None and not started:
|
||||
page = self.latest(limit=limit)
|
||||
return LogPage(page.lines, page.cursor, page.older_cursor, page.has_older, True)
|
||||
return LogPage(tuple(result), newest_cursor, oldest_cursor, has_older)
|
||||
|
||||
def poll(self, after: LogCursor | None, *, limit=200):
|
||||
if after is None:
|
||||
return self.latest(limit=limit)
|
||||
if limit < 1:
|
||||
raise ValueError('log page limit must be positive')
|
||||
with self._locked():
|
||||
paths = [path for path in self._paths() if path.is_file()]
|
||||
found = False
|
||||
lines = []
|
||||
cursor = after
|
||||
for path in paths:
|
||||
self._check()
|
||||
with path.open('rb') as handle:
|
||||
if not found:
|
||||
if not _matches(handle, after):
|
||||
continue
|
||||
found = True
|
||||
offset = after.offset
|
||||
else:
|
||||
offset = 0
|
||||
handle.seek(offset)
|
||||
while len(lines) < limit:
|
||||
self._check()
|
||||
chunks = []
|
||||
while True:
|
||||
self._check()
|
||||
chunk = handle.readline(65536)
|
||||
chunks.append(chunk)
|
||||
if not chunk or chunk.endswith(b'\n'):
|
||||
break
|
||||
line = b''.join(chunks)
|
||||
if not line or not line.endswith(b'\n'):
|
||||
break
|
||||
lines.append(line.rstrip(b'\r\n').decode('utf-8'))
|
||||
offset = handle.tell()
|
||||
cursor = _cursor(handle, offset)
|
||||
if len(lines) >= limit:
|
||||
break
|
||||
if not found:
|
||||
page = self.latest(limit=limit)
|
||||
return LogPage(page.lines, page.cursor, page.older_cursor, page.has_older, True)
|
||||
return LogPage(tuple(lines), cursor)
|
||||
@@ -0,0 +1,212 @@
|
||||
"""Durable serial scheduling of single-project tasks, above the existing runner."""
|
||||
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import asdict, dataclass, is_dataclass
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from threading import Event, Lock, get_ident
|
||||
from uuid import uuid4
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .quick_run import _write_atomic_queue_text
|
||||
|
||||
|
||||
_QUEUE_LOCK = Lock()
|
||||
_QUEUE_OWNER: int | None = None
|
||||
_SAFE_FAILURES = frozenset({'quick_run_preflight', 'quick_run_session', 'quick_run_backup',
|
||||
'target_identity', 'empty_target_scope', 'enabled_rule_required'})
|
||||
_TERMINAL = frozenset({'completed', 'failed', 'skipped'})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TaskQueueEntry:
|
||||
task_id: str
|
||||
state: str
|
||||
message: str = ''
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TaskQueueResult:
|
||||
queue_id: str
|
||||
entries: tuple[TaskQueueEntry, ...]
|
||||
paused: bool
|
||||
current_task_id: str | None = None
|
||||
|
||||
|
||||
def _os_lock(handle, acquire):
|
||||
handle.seek(0)
|
||||
if os.name == 'nt':
|
||||
import msvcrt
|
||||
msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK if acquire else msvcrt.LK_UNLCK, 1)
|
||||
else:
|
||||
import fcntl
|
||||
fcntl.flock(handle.fileno(), (fcntl.LOCK_EX | fcntl.LOCK_NB) if acquire else fcntl.LOCK_UN)
|
||||
|
||||
|
||||
def _lock_file(root: Path):
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
handle = (root / '.task-queue.execution.lock').open('a+b')
|
||||
if handle.seek(0, os.SEEK_END) == 0:
|
||||
handle.write(b'\0')
|
||||
handle.flush()
|
||||
return handle
|
||||
|
||||
|
||||
def assert_task_queue_idle(root: Path) -> None:
|
||||
"""Reject external mutations while a queue owns CAD; its runner may call services."""
|
||||
if _QUEUE_OWNER == get_ident():
|
||||
return
|
||||
if _QUEUE_LOCK.locked():
|
||||
raise TaskCenterError('quick_run_busy', '任务队列正在执行,请先安全暂停。')
|
||||
with _lock_file(Path(root)) as handle:
|
||||
try:
|
||||
_os_lock(handle, True)
|
||||
except OSError as error:
|
||||
raise TaskCenterError('quick_run_busy', '另一窗口正在执行任务队列。') from error
|
||||
_os_lock(handle, False)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _queue_lease(root: Path):
|
||||
global _QUEUE_OWNER
|
||||
if not _QUEUE_LOCK.acquire(blocking=False):
|
||||
raise TaskCenterError('quick_run_busy', '已有任务队列正在执行。')
|
||||
handle = None
|
||||
locked = False
|
||||
try:
|
||||
handle = _lock_file(root)
|
||||
try:
|
||||
_os_lock(handle, True)
|
||||
locked = True
|
||||
except OSError as error:
|
||||
raise TaskCenterError('quick_run_busy', '另一窗口正在执行任务队列。') from error
|
||||
_QUEUE_OWNER = get_ident()
|
||||
yield
|
||||
finally:
|
||||
_QUEUE_OWNER = None
|
||||
if handle is not None:
|
||||
if locked:
|
||||
_os_lock(handle, False)
|
||||
handle.close()
|
||||
_QUEUE_LOCK.release()
|
||||
|
||||
|
||||
def _record(value):
|
||||
if is_dataclass(value):
|
||||
return asdict(value)
|
||||
return vars(value)
|
||||
|
||||
|
||||
def _plan_hash(child, task_id: str) -> str:
|
||||
task = child.get_task(task_id)
|
||||
payload = {
|
||||
'projects': [(str(project.path.resolve(strict=False)).casefold(), project.selected, project.available)
|
||||
for project in child.projects(task_id)],
|
||||
'rules': [_record(rule) for rule in child.rules(task_id)],
|
||||
'targets': [_record(row) for row in child.target_plan(task_id)],
|
||||
'copy_value': task.copy_part_number_to_value,
|
||||
'target_plan_mode': getattr(task, 'target_plan_mode', False),
|
||||
}
|
||||
return hashlib.sha256(json.dumps(payload, sort_keys=True, ensure_ascii=False,
|
||||
default=str).encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def _save(path: Path, state: dict) -> None:
|
||||
_write_atomic_queue_text(path, json.dumps(state, ensure_ascii=False, indent=2),
|
||||
'task_queue_state', '不能保存任务队列检查点。')
|
||||
|
||||
|
||||
def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||
queue_id: str | None = None) -> TaskQueueResult:
|
||||
"""Execute the frozen order; uncertain state stops before the next project."""
|
||||
ids = tuple(task_ids)
|
||||
if not ids or len(set(ids)) != len(ids):
|
||||
raise TaskCenterError('task_queue_selection', '请选择不同的单工程任务。')
|
||||
root = service._logging.root
|
||||
with _queue_lease(root):
|
||||
children = {task_id: service.for_project_task(task_id) for task_id in ids}
|
||||
project_paths = []
|
||||
for task_id, child in children.items():
|
||||
task = child.get_task(task_id)
|
||||
projects = child.projects(task_id)
|
||||
if not getattr(task, 'primary_project_id', None) or len(projects) != 1:
|
||||
raise TaskCenterError('project_binding', '顺序执行仅支持绑定单个工程的任务。')
|
||||
project_paths.append(str(projects[0].path.resolve(strict=False)).casefold())
|
||||
if len(set(project_paths)) != len(ids):
|
||||
raise TaskCenterError('task_queue_selection', '不能在同一队列重复处理同一个工程。')
|
||||
hashes = {task_id: _plan_hash(child, task_id) for task_id, child in children.items()}
|
||||
token = queue_id or uuid4().hex
|
||||
if len(token) != 32 or any(char not in '0123456789abcdef' for char in token):
|
||||
raise TaskCenterError('task_queue_state', '任务队列编号无效。')
|
||||
path = root / 'task-queues' / f'{token}.json'
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if queue_id is not None:
|
||||
try:
|
||||
state = json.loads(path.read_text(encoding='utf-8'))
|
||||
if (state['version'] != 1 or state['task_ids'] != list(ids)
|
||||
or state['plan_hashes'] != hashes or set(state['entries']) != set(ids)
|
||||
or any(not isinstance(entry, dict) or set(entry) != {'state', 'message'}
|
||||
or entry['state'] not in {'pending', 'running', 'paused', 'blocked', *_TERMINAL}
|
||||
or not isinstance(entry['message'], str)
|
||||
for entry in state['entries'].values())):
|
||||
raise ValueError('queue inputs changed')
|
||||
except (OSError, ValueError, KeyError, TypeError) as error:
|
||||
raise TaskCenterError('task_queue_state', '任务顺序或计划已变化,不能恢复原队列。') from error
|
||||
else:
|
||||
state = {'version': 1, 'task_ids': list(ids), 'plan_hashes': hashes,
|
||||
'entries': {task_id: {'state': 'pending', 'message': ''} for task_id in ids}}
|
||||
_save(path, state)
|
||||
paused = False
|
||||
current = None
|
||||
try:
|
||||
for task_id in ids:
|
||||
if state['entries'][task_id]['state'] in _TERMINAL:
|
||||
continue
|
||||
if stop_event.is_set():
|
||||
paused = True
|
||||
break
|
||||
current = task_id
|
||||
child = children[task_id]
|
||||
service._task_queue_feedback = (token, task_id, ids.index(task_id) + 1, len(ids))
|
||||
try:
|
||||
if child.has_interrupted_quick_run(task_id):
|
||||
raise TaskCenterError('quick_run_uncertain', '该任务有待核验步骤。')
|
||||
progress = child.quick_run_progress(task_id)
|
||||
if progress.queue_complete:
|
||||
entry = {'state': 'failed' if getattr(progress, 'failed_items', 0) else 'completed',
|
||||
'message': '该任务队列已有完整执行结果。'}
|
||||
else:
|
||||
state['entries'][task_id] = {'state': 'running', 'message': ''}
|
||||
_save(path, state)
|
||||
expected = (str(progress.next_project_path), progress.next_old_part_number,
|
||||
progress.next_new_part_number,
|
||||
'part_label' if child.get_task(task_id).copy_part_number_to_value else 'preserve')
|
||||
result = child.execute_quick_run_queue(task_id, expected_item=expected,
|
||||
stop_event=stop_event)
|
||||
if child.has_interrupted_quick_run(task_id) or (
|
||||
result.last_result is not None and result.last_result.state == 'batch_saved_unverified'
|
||||
):
|
||||
raise TaskCenterError('quick_run_uncertain', '保存结果尚未确认,任务队列已停止。')
|
||||
incomplete = result.paused or not result.progress.queue_complete
|
||||
entry = {'state': 'paused' if incomplete else (
|
||||
'failed' if getattr(result.progress, 'failed_items', 0) else 'completed'),
|
||||
'message': '已安全暂停。' if incomplete else '任务已收尾。'}
|
||||
if incomplete:
|
||||
paused = True
|
||||
except TaskCenterError as error:
|
||||
safe = error.code in _SAFE_FAILURES and not child.has_interrupted_quick_run(task_id)
|
||||
entry = {'state': 'failed' if safe else 'blocked', 'message': error.message}
|
||||
paused = not safe
|
||||
except Exception as error:
|
||||
entry = {'state': 'blocked', 'message': str(error)}
|
||||
paused = True
|
||||
state['entries'][task_id] = entry
|
||||
_save(path, state)
|
||||
if paused:
|
||||
break
|
||||
return TaskQueueResult(token, tuple(TaskQueueEntry(task_id, **state['entries'][task_id])
|
||||
for task_id in ids), paused, current if paused else None)
|
||||
finally:
|
||||
service._task_queue_feedback = None
|
||||
@@ -0,0 +1,100 @@
|
||||
"""Task metadata and replacement-rule editing dialogs."""
|
||||
from PySide6.QtWidgets import QWidget, QDialog, QLineEdit, QTextEdit, QFormLayout, QLabel, QDialogButtonBox, QCheckBox
|
||||
|
||||
class _TaskDialog(QDialog):
|
||||
def __init__(self, parent: QWidget | None, name: str = "", note: str = "") -> None:
|
||||
super().__init__(parent)
|
||||
self.setWindowTitle("任务")
|
||||
self.name_edit = QLineEdit(name)
|
||||
self.note_edit = QTextEdit(note)
|
||||
self.note_edit.setFixedHeight(70)
|
||||
form = QFormLayout(self)
|
||||
form.addRow("名称", self.name_edit)
|
||||
form.addRow("备注", self.note_edit)
|
||||
self.validation = QLabel(objectName="taskValidation")
|
||||
self.validation.setStyleSheet("color: #b42318")
|
||||
self.buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
|
||||
self.buttons.button(QDialogButtonBox.StandardButton.Ok).setText("确定")
|
||||
self.buttons.button(QDialogButtonBox.StandardButton.Cancel).setText("取消")
|
||||
self.buttons.accepted.connect(self._accept_if_valid)
|
||||
self.buttons.rejected.connect(self.reject)
|
||||
form.addRow(self.validation)
|
||||
form.addRow(self.buttons)
|
||||
|
||||
def values(self) -> tuple[str, str]:
|
||||
return self.name_edit.text().strip(), self.note_edit.toPlainText().strip()
|
||||
|
||||
def _accept_if_valid(self) -> None:
|
||||
if not self.name_edit.text().strip():
|
||||
self.validation.setText("请输入任务名称。")
|
||||
return
|
||||
self.accept()
|
||||
|
||||
|
||||
class _MappingDialog(QDialog):
|
||||
def __init__(
|
||||
self,
|
||||
parent: QWidget | None,
|
||||
old: str = "",
|
||||
new: str = "",
|
||||
enabled: bool = True,
|
||||
custom_value_enabled: bool = False,
|
||||
custom_value: str = "",
|
||||
sync_nc: bool = True,
|
||||
) -> None:
|
||||
super().__init__(parent)
|
||||
self.setWindowTitle("替换规则")
|
||||
self.old_edit = QLineEdit(old)
|
||||
self.new_edit = QLineEdit(new)
|
||||
self.enabled_check = QCheckBox("启用此规则")
|
||||
self.enabled_check.setChecked(enabled)
|
||||
self.custom_value_check = QCheckBox("替换后写入自定义 Value")
|
||||
self.custom_value_check.setChecked(custom_value_enabled)
|
||||
self.custom_value_edit = QLineEdit(custom_value)
|
||||
self.custom_value_edit.setPlaceholderText("输入替换后的 Value")
|
||||
self.custom_value_edit.setEnabled(custom_value_enabled)
|
||||
self.custom_value_check.toggled.connect(self.custom_value_edit.setEnabled)
|
||||
self.sync_nc_check = QCheckBox("识别并同步原 Value 中的 /NC")
|
||||
self.sync_nc_check.setChecked(sync_nc)
|
||||
form = QFormLayout(self)
|
||||
form.addRow("旧物料编码", self.old_edit)
|
||||
form.addRow("新物料编码", self.new_edit)
|
||||
form.addRow("执行状态", self.enabled_check)
|
||||
form.addRow("自定义 Value", self.custom_value_check)
|
||||
form.addRow("Value 内容", self.custom_value_edit)
|
||||
form.addRow("NC 处理", self.sync_nc_check)
|
||||
self.validation = QLabel(objectName="mappingValidation")
|
||||
self.validation.setStyleSheet("color: #b42318")
|
||||
self.buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
|
||||
self.buttons.button(QDialogButtonBox.StandardButton.Ok).setText("确定")
|
||||
self.buttons.button(QDialogButtonBox.StandardButton.Cancel).setText("取消")
|
||||
self.buttons.accepted.connect(self._accept_if_valid)
|
||||
self.buttons.rejected.connect(self.reject)
|
||||
form.addRow(self.validation)
|
||||
form.addRow(self.buttons)
|
||||
|
||||
def values(self) -> tuple[str, str, bool, bool, str, bool]:
|
||||
return (
|
||||
self.old_edit.text().strip(),
|
||||
self.new_edit.text().strip(),
|
||||
self.enabled_check.isChecked(),
|
||||
self.custom_value_check.isChecked(),
|
||||
self.custom_value_edit.text().strip(),
|
||||
self.sync_nc_check.isChecked(),
|
||||
)
|
||||
|
||||
def _accept_if_valid(self) -> None:
|
||||
old, new, _enabled, custom_enabled, custom_value, _sync_nc = self.values()
|
||||
if not old or not new:
|
||||
self.validation.setText("请输入旧料号和新料号。")
|
||||
return
|
||||
if old.casefold() == new.casefold():
|
||||
self.validation.setText("旧料号和新料号不能相同。")
|
||||
return
|
||||
if custom_enabled and not custom_value:
|
||||
self.validation.setText("勾选自定义 Value 后请输入 Value 内容。")
|
||||
return
|
||||
if any(character in custom_value for character in "\t\r\n"):
|
||||
self.validation.setText("自定义 Value 不能包含制表符或换行。")
|
||||
return
|
||||
self.accept()
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Translate worker phases for display without exposing transport details."""
|
||||
STAGES = {
|
||||
'private_startup': '启动后台 CAD', 'private_shutdown': '关闭 CAD 并释放后台会话',
|
||||
'starting': '启动执行器', 'session_startup': '连接 CAD',
|
||||
'check_project': '检查工程', 'open_project': '打开工程',
|
||||
'open_sheet': '打开图页', 'session_ready': '工程就绪',
|
||||
'query_components': '读取器件', 'index_components': '建立器件索引',
|
||||
'find_components': '定位目标位号', 'index_pins': '建立引脚索引',
|
||||
'snapshot_attributes': '记录原始属性', 'capture': '采集替换前快照',
|
||||
'before_native': '准备原生替换', 'native_replace': '执行原生替换',
|
||||
'restore_preflight': '检查属性恢复条件',
|
||||
'before_restore_transaction': '准备恢复属性',
|
||||
'restore_attribute_fields': '恢复属性字段', 'restore_attributes': '恢复属性',
|
||||
'verify_restoration': '核验恢复结果', 'verify_attribute_fields': '核验属性字段',
|
||||
'save_and_close': '保存并关闭工程', 'verify_saved_project': '回读已保存工程',
|
||||
}
|
||||
|
||||
|
||||
def format_feedback(value, task_name, elapsed, stopping):
|
||||
stage = STAGES.get(value.stage, '')
|
||||
details = f'{stage}({value.stage_seconds:.1f} 秒)' if stage else value.message
|
||||
prefix = '等待当前步骤保存核验后暂停 · ' if stopping else ''
|
||||
return f'{prefix}任务 {value.position}/{value.total}:{task_name} · {details} · 总计 {elapsed} 秒'
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Pure execution gates, calculated from one context without service calls."""
|
||||
from dataclasses import dataclass
|
||||
from ..models import TaskStatus
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ExecutionState:
|
||||
editable: bool = False
|
||||
execute: bool = False
|
||||
retry: bool = False
|
||||
recover: bool = False
|
||||
execute_text: str = '执行当前任务'
|
||||
message: str = '点击新建,在弹窗中选择工程。'
|
||||
|
||||
|
||||
def execution_state(context, *, busy=False, dirty=False):
|
||||
if context is None:
|
||||
return ExecutionState()
|
||||
if context.legacy:
|
||||
return ExecutionState(message='历史任务仅供查看,请为工程创建独立任务。')
|
||||
task = context.task
|
||||
project = context.project
|
||||
if not project or task.status is TaskStatus.DELETED:
|
||||
return ExecutionState(message='任务已删除,可从已删除列表恢复。')
|
||||
editable = task.status in {TaskStatus.DRAFT, TaskStatus.READY, TaskStatus.FAILED} and not context.has_evidence and not busy
|
||||
retry = context.phase == 'retry' and not context.interrupted and not busy and not dirty
|
||||
pending = bool(context.progress.next_project_path) and not context.progress.queue_complete
|
||||
execute = (pending and task.status in {TaskStatus.DRAFT, TaskStatus.READY, TaskStatus.RUNNING, TaskStatus.PAUSED}
|
||||
and project.available and not context.interrupted and not busy and not dirty)
|
||||
text = '继续当前任务' if task.status is TaskStatus.PAUSED else '执行当前任务'
|
||||
message = ('结果待核验,请先恢复中断步骤。' if context.interrupted else
|
||||
'位号计划有未保存编辑,请先保存。' if dirty else
|
||||
'正在处理当前步骤,暂停会等待安全收尾。' if busy else
|
||||
'任务已完成。' if context.progress.queue_complete and not retry else
|
||||
'有失败项,可核对原因后重试。' if retry else
|
||||
'工程不可用,请检查路径。' if not project.available else
|
||||
'先填写旧、新料号,再采集并勾选位号。' if not pending else
|
||||
'配置就绪,可执行当前任务或按顺序执行本批任务。')
|
||||
return ExecutionState(editable, execute, retry, context.interrupted and not busy and not dirty, text, message)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,194 @@
|
||||
"""Operator messages and log formatting shared by the desktop UI."""
|
||||
from datetime import datetime
|
||||
import json
|
||||
import re
|
||||
|
||||
ERROR_TEXT = {
|
||||
"task_required": "请先选择任务。",
|
||||
"directory_required": "请先选择工程目录。",
|
||||
"discovery_root_locked": "旧目录已有执行记录,不能在同一任务中更换目录;请新建任务。",
|
||||
"disposable_copy_required": "请确认所选工程已保存,并允许程序在执行前创建完整备份。",
|
||||
"selected_project_required": "请至少选择一个可用工程。",
|
||||
"enabled_rule_required": "请至少添加并启用一条替换规则。",
|
||||
"active_project_exists": "已有其他工程正在处理,请等待其结束。",
|
||||
"probe_baseline_missing": "未找到探测结果文件,请先在 DxDesigner 中运行只读探测。",
|
||||
"profile_unchanged": "探测结果没有更新,请重新运行只读探测。",
|
||||
"comparison_failed": "替换前后数据核验失败,请查看日志和错误编号。",
|
||||
"rules_locked": "任务执行期间不能修改替换规则。",
|
||||
"task_running": "请先暂停任务,再删除任务。",
|
||||
"task_not_deleted": "只有“已删除”中的任务可以彻底删除;任务状态可能已变化,请刷新后重试。",
|
||||
"permanent_delete_confirmation": "彻底删除需要明确确认,此操作不能通过“恢复”撤销。",
|
||||
"quick_run_pending": "检测到可能已改动图纸的旧替换任务,请先核对工程后再继续。",
|
||||
"quick_run_status": "执行状态文件无效,已拒绝覆盖,请查看日志。",
|
||||
"quick_run_execution": "当前替换步骤失败,图页可能已被修改,请查看具体原因和执行证据。",
|
||||
"quick_run_rollback_verified": "替换校验失败,但原生回滚已验证,工程已恢复到替换前状态;请排除原因后重新确认。",
|
||||
"quick_run_preflight": "当前项在替换前校验失败,未调用原生替换;后续项已停止。请核对目标料号及库配置,排除原因后再确认继续。",
|
||||
"quick_run_session": "本次执行在启动或工程检查阶段停止,尚未开始本项替换。请按具体原因处理后重试。",
|
||||
"quick_run_complete": "当前任务中的替换规则已经全部完成。",
|
||||
"quick_run_cscript": "未找到 Windows 脚本运行组件,无法连接 DxDesigner。",
|
||||
"quick_run_path_length": "执行目录过长,请使用较短的工具及数据目录。",
|
||||
"quick_run_command": "替换命令文件无效,请查看日志。",
|
||||
"quick_run_uncertain": "无法确认本次替换结果,请使用“核验并恢复中断任务”,不要直接清锁重跑。",
|
||||
"quick_run_recovery": "中断任务恢复未通过,原保护状态仍保留。",
|
||||
"quick_run_recovery_confirmation": "请先确认核验恢复范围。",
|
||||
"quick_run_busy": "已有替换操作正在执行,请等待当前操作结束。",
|
||||
"quick_run_manual_operation": "此任务使用自动队列,不能混用人工流程的跳过、采集和重试操作。",
|
||||
"quick_run_task_state": "当前任务状态不允许执行自动队列,请先恢复任务或检查其状态。",
|
||||
"quick_run_backup": "本项工程精简备份未通过,队列已停止,尚未开始本项替换。可排除原因后重试,或使用“忽略备份失败并继续”。",
|
||||
"quick_run_queue_progress": "队列进度异常,已停止自动继续。",
|
||||
"quick_run_options_locked": "已有自动队列证据,工程目录、工程选择及规则选项已冻结;请先完成或恢复当前队列。",
|
||||
"quick_run_selection_changed": "待执行工程、规则或 Value 选项发生变化,请重新确认。",
|
||||
"evidence_missing": "没有找到当前任务的执行证据。",
|
||||
"duplicate_source": "同一旧料号只能配置一次。",
|
||||
"mapping_chain": "替换规则不能形成连续替换链。",
|
||||
"mapping_cycle": "替换规则不能形成循环。",
|
||||
"equal_rule": "旧料号和新料号不能相同。",
|
||||
"blank_part_number": "旧料号和新料号不能为空。",
|
||||
"custom_value": "勾选自定义 Value 后必须填写内容,且不能包含制表符或换行。",
|
||||
"task_name": "任务名称为空或已经存在。",
|
||||
}
|
||||
|
||||
DIALOG_ERROR_TEXT = {
|
||||
"duplicate_source": "该旧料号已经存在,请修改现有规则或输入其他旧料号。",
|
||||
"mapping_chain": "目标料号同时是另一条规则的旧料号,请拆分任务后再执行。",
|
||||
"mapping_cycle": "这些规则形成了循环,请修改旧料号或新料号。",
|
||||
"equal_rule": "旧料号和新料号不能相同。",
|
||||
"blank_part_number": "请输入旧料号和新料号。",
|
||||
"custom_value": "勾选自定义 Value 后必须填写内容,且不能包含制表符或换行。",
|
||||
"task_name": "任务名称为空或已经存在,请使用其他名称。",
|
||||
}
|
||||
|
||||
|
||||
def _nc_sync_log_lines(message: str) -> tuple[str, ...]:
|
||||
_, marker, details = str(message).partition("NC synced:")
|
||||
if not marker:
|
||||
return ()
|
||||
suffix = " (detected /NC and synchronized)"
|
||||
return tuple(
|
||||
f"位号 {entry.removesuffix(suffix).strip()},识别到 NC,已同步"
|
||||
for entry in details.strip().split("; ")
|
||||
if entry.strip()
|
||||
)
|
||||
|
||||
|
||||
def _replacement_log_lines(message: str, state: str) -> tuple[str, ...]:
|
||||
"""Render native readback results; never turn a plan or failed step into success."""
|
||||
if state not in {'saved_ok', 'restored_ok'}:
|
||||
return ()
|
||||
_, marker, summary = message.partition('Replacements:')
|
||||
if not marker:
|
||||
return ()
|
||||
for suffix in (' Display verified:', ' NC synced:', ' Saved, reopened'):
|
||||
summary = summary.partition(suffix)[0]
|
||||
status = '已保存并核验' if state == 'saved_ok' else '已替换并回读,尚未确认保存'
|
||||
lines = []
|
||||
for entry in summary.strip().split('; '):
|
||||
match = re.fullmatch(r'(\S+) (.+?) -> (.+)', entry.strip())
|
||||
if not match:
|
||||
return () # Preserve unfamiliar native output verbatim for diagnosis.
|
||||
refdes, old, new = match.groups()
|
||||
lines.append(f'{status} · 位号 {refdes}:{old} → {new}')
|
||||
return tuple(lines)
|
||||
|
||||
|
||||
def _format_task_log_lines(lines: tuple[str, ...]) -> tuple[str, ...]:
|
||||
return tuple(_format_task_log_line(line) for line in lines)
|
||||
|
||||
|
||||
def _format_task_log_line(line: str) -> str:
|
||||
try:
|
||||
event = json.loads(line)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
return _aligned_log_line("", "INFO", "legacy", str(line))
|
||||
if not isinstance(event, dict):
|
||||
return _aligned_log_line("", "INFO", "legacy", str(line))
|
||||
|
||||
timestamp = str(event.get("timestamp_utc") or "").replace("T", " ").removesuffix("Z")[:19]
|
||||
level = str(event.get("level") or "INFO").upper()
|
||||
if level not in {"INFO", "WARNING", "ERROR"}:
|
||||
level = "INFO"
|
||||
operation = str(event.get("operation") or "")
|
||||
details = event.get("details") if isinstance(event.get("details"), dict) else {}
|
||||
message = str(event.get("message") or "").strip()
|
||||
|
||||
if operation == "value_policy_changed":
|
||||
enabled = bool(
|
||||
details.get(
|
||||
"copy_part_label_to_value",
|
||||
details.get("copy_part_number_to_value", False),
|
||||
)
|
||||
)
|
||||
message = (
|
||||
"Value 选项已更新:替换后写入目标 Part Label。"
|
||||
if enabled
|
||||
else "Value 选项已更新:保留原生替换后的 Value。"
|
||||
)
|
||||
elif operation == "quick_run_prepared":
|
||||
message = "自动替换运行环境已准备。"
|
||||
elif operation == "quick_run_executed" and details.get("state") == "no_match":
|
||||
message = "当前规则在该图页未命中,已正常跳过。"
|
||||
elif operation == "quick_run_executed":
|
||||
state = details.get('state')
|
||||
replacements = _replacement_log_lines(message, state)
|
||||
if replacements:
|
||||
location = ':'.join(str(details[key]) for key in ('schematic_name', 'sheet_number')
|
||||
if details.get(key))
|
||||
prefix = f'图页 {location} · ' if location else ''
|
||||
message = '\n'.join(prefix + entry for entry in (*replacements, *_nc_sync_log_lines(message)))
|
||||
elif state == 'batch_saved_unverified':
|
||||
message = f'已保存但核验未通过,修改结果待确认。{message}'
|
||||
elif state in {'batch_failed', 'hard_failure'}:
|
||||
message = f'本步骤失败,未计入成功修改。{message}'
|
||||
elif operation == 'execution_timing':
|
||||
phases = {'prepare_queue': '图页枚举与队列准备', 'backup_project': '工程备份',
|
||||
'execute_step': '执行步骤(含保存回读)', 'persist_progress': '进度同步',
|
||||
'task_total': '本次任务执行合计', 'collect_inventory': '采集位号'}
|
||||
elapsed = details.get('elapsed_seconds', 0)
|
||||
location = ':'.join(str(details[key]) for key in ('schematic_name', 'sheet_number') if details.get(key))
|
||||
message = f"{phases.get(details.get('phase'), details.get('phase', '执行'))}:{elapsed:.3f} 秒"
|
||||
if location:
|
||||
message += f' · 图页 {location}'
|
||||
if details.get('old_part_number'):
|
||||
message += f" · {details['old_part_number']} → {details.get('new_part_number', '')}"
|
||||
message += f" · 状态 {details.get('state', '')}"
|
||||
rate = details.get('units_per_minute')
|
||||
units = {'step': '步骤', 'task': '任务', 'component': '器件', 'operation': '次'}
|
||||
if rate and details.get('completed_units'):
|
||||
message += f" · {rate:.2f} {units.get(details.get('unit'), '次')}/分钟"
|
||||
elif operation == "quick_run_queue_paused":
|
||||
message = "自动队列已在项目边界暂停。"
|
||||
elif operation == "confirm_native_attempt":
|
||||
message = "已确认原生替换操作。"
|
||||
elif not message:
|
||||
message = operation.replace("_", " ") or "任务状态已更新。"
|
||||
|
||||
timing = details.get('timing')
|
||||
if operation == 'quick_run_executed' and isinstance(timing, dict):
|
||||
message += f"\n本步骤耗时 {timing['elapsed_seconds']:.3f} 秒"
|
||||
if timing.get('completed_units') and timing.get('units_per_minute'):
|
||||
message += f" · {timing['units_per_minute']:.2f} 步骤/分钟"
|
||||
error_id = str(event.get("error_id") or "").strip()
|
||||
if error_id:
|
||||
message = f"{message} 错误编号:{error_id}"
|
||||
return _aligned_log_line(timestamp, level, operation or "task", message)
|
||||
|
||||
|
||||
def _format_live_log_line(line: str) -> str:
|
||||
message = str(line)
|
||||
level = "ERROR" if message.startswith("错误") else "WARNING" if message.startswith(("失败", "警告")) else "INFO"
|
||||
return _aligned_log_line(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), level, "ui", message)
|
||||
|
||||
|
||||
def _aligned_log_line(timestamp: str, level: str, operation: str, message: str) -> str:
|
||||
return (
|
||||
f"{_fit_log_column(timestamp, 19)} | "
|
||||
f"{_fit_log_column(level, 7)} | "
|
||||
f"{_fit_log_column(operation, 28)} | {message}"
|
||||
)
|
||||
|
||||
|
||||
def _fit_log_column(value: str, width: int) -> str:
|
||||
text = str(value)
|
||||
if len(text) <= width:
|
||||
return text.ljust(width)
|
||||
return f"{text[: width - 3]}..."
|
||||
@@ -0,0 +1,358 @@
|
||||
"""Directory task creation and optional spreadsheet/direct plan editing."""
|
||||
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
from time import monotonic
|
||||
|
||||
from PySide6.QtCore import Qt, QThreadPool, QObject, Signal, QSignalBlocker
|
||||
from PySide6.QtWidgets import (QDialog, QDialogButtonBox, QFileDialog, QHBoxLayout, QLabel,
|
||||
QLineEdit, QListWidget, QListWidgetItem, QMessageBox, QPushButton,
|
||||
QVBoxLayout, QWidget)
|
||||
|
||||
from ..errors import TaskCenterError
|
||||
from .target_table import TargetTable
|
||||
from .workers import ServiceWorker
|
||||
|
||||
|
||||
class _ScanProgress(QObject):
|
||||
changed = Signal(object, int, int)
|
||||
|
||||
|
||||
class DirectoryTaskDialog(QDialog):
|
||||
def __init__(self, service, parent=None):
|
||||
super().__init__(parent)
|
||||
self.service = service
|
||||
self.setWindowTitle('从目录创建工程任务')
|
||||
self.resize(700, 450)
|
||||
self.directory = QLineEdit(objectName='taskDirectory')
|
||||
self.directory.setPlaceholderText('选择根目录,每个原理图工程创建一个任务')
|
||||
self.browse = QPushButton('选择目录')
|
||||
self.scan = QPushButton('读取工程', objectName='readTaskProjects')
|
||||
self.projects = QListWidget(objectName='taskProjectCandidates')
|
||||
self.summary = QLabel('先读取工程,再勾选需要创建任务的项目。')
|
||||
self.buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
|
||||
self.buttons.button(QDialogButtonBox.StandardButton.Ok).setText('创建任务')
|
||||
self.buttons.button(QDialogButtonBox.StandardButton.Ok).setEnabled(False)
|
||||
row = QHBoxLayout()
|
||||
row.addWidget(self.directory, 1)
|
||||
row.addWidget(self.browse)
|
||||
row.addWidget(self.scan)
|
||||
layout = QVBoxLayout(self)
|
||||
layout.addLayout(row)
|
||||
layout.addWidget(self.projects, 1)
|
||||
layout.addWidget(self.summary)
|
||||
layout.addWidget(self.buttons)
|
||||
self._worker = None
|
||||
self._stop_event = Event()
|
||||
self._closed = False
|
||||
self._scanned_root = None
|
||||
self.browse.clicked.connect(self._browse)
|
||||
self.scan.clicked.connect(self.read_projects)
|
||||
self.directory.textChanged.connect(self._directory_changed)
|
||||
self.projects.itemChanged.connect(self._update_selection)
|
||||
self.buttons.accepted.connect(self.accept)
|
||||
self.buttons.rejected.connect(self.reject)
|
||||
|
||||
def _browse(self):
|
||||
selected = QFileDialog.getExistingDirectory(self, '工程目录')
|
||||
if selected:
|
||||
self.directory.setText(selected)
|
||||
|
||||
def _directory_changed(self):
|
||||
self.projects.clear()
|
||||
self._scanned_root = None
|
||||
self.buttons.button(QDialogButtonBox.StandardButton.Ok).setEnabled(False)
|
||||
|
||||
def read_projects(self):
|
||||
if self._worker is not None:
|
||||
self._stop_event.set()
|
||||
self.scan.setEnabled(False)
|
||||
self.summary.setText('正在取消读取…')
|
||||
return
|
||||
if not self.directory.text().strip():
|
||||
return
|
||||
root = Path(self.directory.text().strip())
|
||||
self.directory.setEnabled(False)
|
||||
self.browse.setEnabled(False)
|
||||
self.scan.setText('取消读取')
|
||||
self.projects.clear()
|
||||
self._scanned_root = None
|
||||
self.buttons.button(QDialogButtonBox.StandardButton.Ok).setEnabled(False)
|
||||
self.summary.setText('正在读取工程…')
|
||||
self._stop_event = Event()
|
||||
self._closed = False
|
||||
service, stop_event = self.service, self._stop_event
|
||||
progress = _ScanProgress()
|
||||
progress.changed.connect(self._progress)
|
||||
self._progress_signals = progress
|
||||
last_report = 0.0
|
||||
def report(directory, visited, found):
|
||||
nonlocal last_report
|
||||
now = monotonic()
|
||||
if now - last_report >= 0.1:
|
||||
last_report = now
|
||||
progress.changed.emit(directory, visited, found)
|
||||
self._worker = ServiceWorker(lambda: service.scan_project_directory(
|
||||
root, stop_event=stop_event, on_progress=report))
|
||||
self._worker.signals.succeeded.connect(self._received)
|
||||
self._worker.signals.failed.connect(self._failed)
|
||||
self._worker.signals.finished.connect(self._finished)
|
||||
QThreadPool.globalInstance().start(self._worker)
|
||||
|
||||
def _progress(self, directory, visited, found):
|
||||
if not self._closed and not self._stop_event.is_set():
|
||||
self.summary.setText(f'已读取 {visited} 个目录,发现 {found} 个工程;{directory}')
|
||||
|
||||
def _received(self, projects):
|
||||
if self._closed or self._stop_event.is_set():
|
||||
return
|
||||
blocker = QSignalBlocker(self.projects)
|
||||
self.projects.clear()
|
||||
self._scanned_root = Path(self.directory.text().strip()).resolve()
|
||||
for path in projects:
|
||||
path = Path(path)
|
||||
item = QListWidgetItem(path.relative_to(self._scanned_root).as_posix())
|
||||
item.setData(Qt.ItemDataRole.UserRole, str(path))
|
||||
item.setFlags(item.flags() | Qt.ItemFlag.ItemIsUserCheckable)
|
||||
item.setCheckState(Qt.CheckState.Checked)
|
||||
self.projects.addItem(item)
|
||||
del blocker
|
||||
self._update_selection()
|
||||
|
||||
def _failed(self, error):
|
||||
if self._closed:
|
||||
return
|
||||
self._scanned_root = None
|
||||
self.summary.setText(getattr(error, 'message', str(error)))
|
||||
|
||||
def _finished(self):
|
||||
self._worker = None
|
||||
if self._closed:
|
||||
return
|
||||
self.scan.setText('读取工程')
|
||||
self.directory.setEnabled(True)
|
||||
self.browse.setEnabled(True)
|
||||
self.scan.setEnabled(True)
|
||||
self._update_selection()
|
||||
|
||||
def _update_selection(self):
|
||||
selected = sum(self.projects.item(i).checkState() == Qt.CheckState.Checked
|
||||
for i in range(self.projects.count()))
|
||||
if self._scanned_root is not None:
|
||||
self.summary.setText(f'读取到 {self.projects.count()} 个工程,已选 {selected} 个;一个工程一个任务。')
|
||||
self.buttons.button(QDialogButtonBox.StandardButton.Ok).setEnabled(
|
||||
self._worker is None and self._scanned_root is not None and selected > 0)
|
||||
|
||||
def values(self):
|
||||
return self._scanned_root, tuple(Path(self.projects.item(i).data(Qt.ItemDataRole.UserRole))
|
||||
for i in range(self.projects.count()) if self.projects.item(i).checkState() == Qt.CheckState.Checked)
|
||||
|
||||
def reject(self):
|
||||
self._closed = True
|
||||
self._stop_event.set()
|
||||
super().reject()
|
||||
|
||||
def closeEvent(self, event):
|
||||
self._closed = True
|
||||
self._stop_event.set()
|
||||
super().closeEvent(event)
|
||||
|
||||
|
||||
class ProjectPlanPanel(QWidget):
|
||||
def __init__(self, window):
|
||||
super().__init__()
|
||||
self.window = window
|
||||
self.task_id = None
|
||||
self._drafts = {}
|
||||
self._editable = False
|
||||
self.table = TargetTable(self)
|
||||
self.collect_button = QPushButton('采集所有匹配位号', objectName='collectTargetInventory')
|
||||
self.save_button = QPushButton('保存位号计划', objectName='saveTargetPlan')
|
||||
self.import_button = QPushButton('导入位号计划', objectName='importTargetPlan')
|
||||
self.export_button = QPushButton('导出位号计划', objectName='exportTargetPlan')
|
||||
self.import_bom_button = QPushButton('导入 BOM', objectName='importBomPlan')
|
||||
self.export_bom_button = QPushButton('BOM 模板', objectName='exportBomTemplate')
|
||||
self.select_all = QPushButton('全部替换')
|
||||
self.select_none = QPushButton('全部保留')
|
||||
self.bulk_part = QLineEdit(objectName='bulkTargetPart')
|
||||
self.bulk_part.setPlaceholderText('对选中行批量填写新料号')
|
||||
self.bulk_apply = QPushButton('填入选中行')
|
||||
self.find_text = QLineEdit(objectName='findTargetText')
|
||||
self.find_text.setPlaceholderText('查找位号 / UID / 料号 / 图页 / Value')
|
||||
self.find_button = QPushButton('查找', objectName='findTargets')
|
||||
self.find_next_button = QPushButton('下一条')
|
||||
self.clear_find_button = QPushButton('清空查找')
|
||||
self.find_result = QLabel()
|
||||
self.summary = QLabel('先添加旧、新料号规则,再采集位号;可直接在这里编辑,也可选用 Excel。')
|
||||
self.summary.setWordWrap(True)
|
||||
actions = QHBoxLayout()
|
||||
for button in (self.collect_button, self.save_button, self.import_button, self.export_button,
|
||||
self.import_bom_button, self.export_bom_button):
|
||||
actions.addWidget(button)
|
||||
actions.addStretch()
|
||||
selection = QHBoxLayout()
|
||||
selection.addWidget(self.select_all)
|
||||
selection.addWidget(self.select_none)
|
||||
selection.addWidget(self.bulk_part, 1)
|
||||
selection.addWidget(self.bulk_apply)
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
layout.addLayout(actions)
|
||||
layout.addWidget(self.summary)
|
||||
search = QHBoxLayout()
|
||||
for widget in (self.find_text, self.find_button, self.find_next_button,
|
||||
self.clear_find_button, self.find_result):
|
||||
search.addWidget(widget)
|
||||
layout.addLayout(search)
|
||||
layout.addWidget(self.table, 1)
|
||||
layout.addLayout(selection)
|
||||
self.collect_button.clicked.connect(self.collect)
|
||||
self.save_button.clicked.connect(self.save)
|
||||
self.import_button.clicked.connect(self.import_excel)
|
||||
self.export_button.clicked.connect(self.export_excel)
|
||||
self.import_bom_button.clicked.connect(self.import_bom)
|
||||
self.export_bom_button.clicked.connect(self.export_bom)
|
||||
self.select_all.clicked.connect(lambda: self.table.select_all_targets(True))
|
||||
self.select_none.clicked.connect(lambda: self.table.select_all_targets(False))
|
||||
self.bulk_apply.clicked.connect(lambda: self.table.apply_to_selected(self.bulk_part.text()))
|
||||
self.table.changed.connect(self._changed)
|
||||
self.find_button.clicked.connect(self.find)
|
||||
self.find_text.returnPressed.connect(self.find)
|
||||
self.find_next_button.clicked.connect(self.table.find_next)
|
||||
self.clear_find_button.clicked.connect(self.clear_find)
|
||||
|
||||
def bind_task(self, task_id, rows=None):
|
||||
if self.task_id == task_id and self.table.dirty:
|
||||
return
|
||||
if self.task_id and self.table.dirty:
|
||||
self._drafts[self.task_id] = self.table.rows()
|
||||
self.task_id = task_id
|
||||
self.clear_find()
|
||||
if task_id in self._drafts:
|
||||
self.table.populate(self._drafts[task_id])
|
||||
self.table.dirty = True
|
||||
self._summary()
|
||||
return
|
||||
if rows is None:
|
||||
rows = self.window.service.target_plan(task_id) if task_id else ()
|
||||
self.table.populate(rows)
|
||||
self._summary()
|
||||
|
||||
def find(self):
|
||||
count = self.table.set_find_text(self.find_text.text())
|
||||
self.find_result.setText(f'{count} 条匹配')
|
||||
self.select_all.setText('替换可见行' if self.find_text.text().strip() else '全部替换')
|
||||
self.select_none.setText('保留可见行' if self.find_text.text().strip() else '全部保留')
|
||||
self.table.find_next()
|
||||
|
||||
def clear_find(self):
|
||||
self.find_text.clear()
|
||||
self.table.set_find_text('')
|
||||
self.find_result.clear()
|
||||
self.select_all.setText('全部替换')
|
||||
self.select_none.setText('全部保留')
|
||||
|
||||
def has_unsaved_plan(self, task_ids):
|
||||
return any(task_id in self._drafts or
|
||||
(task_id == self.task_id and self.table.dirty) for task_id in task_ids)
|
||||
|
||||
def _summary(self):
|
||||
rows = self.table.rows()
|
||||
if not rows:
|
||||
self.summary.setText('先添加旧、新料号规则,再采集位号;可直接编辑,Excel 导入导出为可选操作。')
|
||||
if rows:
|
||||
selected = sum(row.enabled for row in rows)
|
||||
suffix = ';有未保存编辑,请先保存' if self.table.dirty else ''
|
||||
self.summary.setText(f'共 {len(rows)} 个位号,替换 {selected} 个、保留 {len(rows)-selected} 个{suffix}。同步 NC 可按行勾选。')
|
||||
|
||||
def _changed(self):
|
||||
self._summary()
|
||||
self.window._update_gates()
|
||||
|
||||
def set_plan_editable(self, editable):
|
||||
self._editable = bool(editable)
|
||||
self.table.set_plan_editable(self._editable)
|
||||
for widget in (self.collect_button, self.save_button, self.import_button, self.import_bom_button,
|
||||
self.select_all, self.select_none, self.bulk_part, self.bulk_apply):
|
||||
widget.setEnabled(self._editable and bool(self.task_id))
|
||||
self.export_button.setEnabled(self._editable and bool(self.task_id)
|
||||
and bool(self.table.rows()) and not self.table.dirty)
|
||||
self.export_bom_button.setEnabled(self._editable and bool(self.task_id)
|
||||
and bool(self.table.rows()) and not self.table.dirty)
|
||||
|
||||
def _dispatch(self, operation, callback, button):
|
||||
self.window._run_async(operation, callback, button, expected_task_id=self.task_id)
|
||||
self.window._update_gates()
|
||||
|
||||
def collect(self):
|
||||
if not self.task_id:
|
||||
return
|
||||
if self.table.dirty and QMessageBox.question(
|
||||
self, '重新采集位号', '重新采集会丢弃未保存编辑,并核对已有位号。确认继续?',
|
||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
|
||||
QMessageBox.StandardButton.No) != QMessageBox.StandardButton.Yes:
|
||||
return
|
||||
task_id = self.task_id
|
||||
self._dispatch(lambda: self.window.service.collect_target_inventory(task_id),
|
||||
self._saved, self.collect_button)
|
||||
|
||||
def _saved(self, rows):
|
||||
self._drafts.pop(self.task_id, None)
|
||||
self.table.populate(rows)
|
||||
self.window._load_task_data()
|
||||
self._summary()
|
||||
|
||||
def save(self):
|
||||
if not self.task_id:
|
||||
return
|
||||
task_id = self.task_id
|
||||
rows = self.table.rows()
|
||||
self._dispatch(lambda: self.window.service.replace_target_plan(task_id, rows),
|
||||
self._saved, self.save_button)
|
||||
|
||||
def import_excel(self):
|
||||
if not self.task_id:
|
||||
return
|
||||
path, _ = QFileDialog.getOpenFileName(self, '导入位号计划', '', 'Excel (*.xlsx)')
|
||||
if path:
|
||||
task_id = self.task_id
|
||||
self._dispatch(lambda: self.window.service.preview_target_plan(task_id, Path(path)),
|
||||
self._preview_import, self.import_button)
|
||||
|
||||
def _preview_import(self, rows):
|
||||
self.table.populate(rows)
|
||||
self.table.dirty = True
|
||||
self._changed()
|
||||
|
||||
def export_excel(self):
|
||||
if not self.task_id or self.table.dirty:
|
||||
return
|
||||
path, _ = QFileDialog.getSaveFileName(self, '导出位号计划(可选)', '替换计划.xlsx', 'Excel (*.xlsx)')
|
||||
if path:
|
||||
task_id = self.task_id
|
||||
self._dispatch(lambda: self.window.service.export_target_plan(task_id, Path(path)),
|
||||
lambda result: self.summary.setText(f'已导出:{result}'), self.export_button)
|
||||
|
||||
def import_bom(self):
|
||||
if not self.task_id:
|
||||
return
|
||||
path, _ = QFileDialog.getOpenFileName(self, '导入 BOM 模板', '', 'BOM Excel (*.xlsx)')
|
||||
if path:
|
||||
task_id = self.task_id
|
||||
self._dispatch(lambda: self.window.service.preview_bom_plan(task_id, Path(path)),
|
||||
self._preview_bom, self.import_bom_button)
|
||||
|
||||
def _preview_bom(self, rows):
|
||||
self.table.populate(rows)
|
||||
self.table.dirty = True
|
||||
self.summary.setText(f'BOM 已匹配 {sum(row.enabled for row in rows)} 个位号;请检查预览后点击保存位号计划。')
|
||||
self._changed()
|
||||
|
||||
def export_bom(self):
|
||||
if not self.task_id or self.table.dirty:
|
||||
return
|
||||
path, _ = QFileDialog.getSaveFileName(self, '导出 BOM 模板', '替换BOM模板.xlsx', 'Excel (*.xlsx)')
|
||||
if path:
|
||||
task_id = self.task_id
|
||||
self._dispatch(lambda: self.window.service.export_bom_template(task_id, Path(path)),
|
||||
lambda result: self.summary.setText(f'已导出 BOM 模板:{result}'), self.export_bom_button)
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Read-only identity and result of the task's single bound project."""
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtWidgets import QHBoxLayout, QLabel, QPushButton, QVBoxLayout, QWidget
|
||||
|
||||
|
||||
class ProjectSummary(QWidget):
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
self.name = QLabel('未选择任务')
|
||||
self.path = QLabel(objectName='boundProjectPath')
|
||||
self.path.setWordWrap(True)
|
||||
self.path.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
|
||||
self.state = QLabel()
|
||||
self.state.setWordWrap(True)
|
||||
self.refresh_button = QPushButton('重新读取工程', objectName='refreshBoundProject')
|
||||
heading = QHBoxLayout()
|
||||
heading.addWidget(self.name, 1)
|
||||
heading.addWidget(self.refresh_button)
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
layout.addLayout(heading)
|
||||
layout.addWidget(self.path)
|
||||
layout.addWidget(self.state)
|
||||
|
||||
def populate(self, context):
|
||||
if context is None:
|
||||
self.name.setText('未选择任务')
|
||||
self.path.clear()
|
||||
self.state.setText('点击新建,在弹窗中读取并选择工程。')
|
||||
return
|
||||
project = context.project
|
||||
self.name.setText(project.display_name if project else context.task.name)
|
||||
self.path.setText(str(project.path) if project else '')
|
||||
if context.legacy:
|
||||
self.state.setText('历史任务仅供查看;请通过新建弹窗为工程创建独立任务。')
|
||||
elif not project.available:
|
||||
self.state.setText('工程不可用,请检查原路径后重新读取。')
|
||||
else:
|
||||
labels = {'draft': '待配置', 'ready': '待执行', 'running': '执行中', 'paused': '已暂停',
|
||||
'completed': '已完成', 'failed': '失败', 'deleted': '已删除'}
|
||||
self.state.setText(f'工程已绑定 · {labels.get(context.task.status.value, context.task.status.value)}'
|
||||
+ (f' · {project.summary}' if project.summary else ''))
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Latest-result reads with two in-flight slots and one coalesced pending read."""
|
||||
from PySide6.QtCore import QObject, QThreadPool, Signal, Slot
|
||||
|
||||
from ..read_control import QueryCancelled, QueryControl
|
||||
from .workers import ServiceWorker
|
||||
|
||||
|
||||
class LatestQuery(QObject):
|
||||
settled = Signal()
|
||||
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
self._generation = 0
|
||||
self._active = {}
|
||||
self._pending = None
|
||||
self._closed = False
|
||||
|
||||
@property
|
||||
def busy(self):
|
||||
return bool(self._active)
|
||||
|
||||
@property
|
||||
def current_busy(self):
|
||||
"""Whether the current selection has a pending or running read."""
|
||||
return self._pending is not None or any(
|
||||
request[0] == self._generation for _, request in self._active.values())
|
||||
|
||||
def request(self, action, received, failed, *, cancellable=False):
|
||||
if self._closed:
|
||||
return
|
||||
self.invalidate()
|
||||
control = QueryControl()
|
||||
self._pending = (self._generation, action, received, failed, control, cancellable)
|
||||
self._start()
|
||||
|
||||
def invalidate(self):
|
||||
self._generation += 1
|
||||
if self._pending is not None:
|
||||
self._pending[4].cancel()
|
||||
self._pending = None
|
||||
for _, request in self._active.values():
|
||||
request[4].cancel()
|
||||
|
||||
def close(self):
|
||||
self._closed = True
|
||||
self.invalidate()
|
||||
|
||||
def _start(self):
|
||||
if self._closed or self._pending is None or len(self._active) >= 2:
|
||||
return
|
||||
request, self._pending = self._pending, None
|
||||
_, action, _, _, control, cancellable = request
|
||||
def read():
|
||||
control.checkpoint()
|
||||
result = action(control) if cancellable else action()
|
||||
control.checkpoint()
|
||||
return result
|
||||
worker = ServiceWorker(read)
|
||||
self._active[worker.signals] = (worker, request)
|
||||
# QObject receiver slots deliver callbacks on the GUI thread. Each
|
||||
# sender identifies its own request when reads finish out of order.
|
||||
worker.signals.succeeded.connect(self._received)
|
||||
worker.signals.failed.connect(self._failed)
|
||||
worker.signals.finished.connect(self._finished)
|
||||
QThreadPool.globalInstance().start(worker)
|
||||
|
||||
def _current(self):
|
||||
entry = self._active.get(self.sender())
|
||||
if entry is None or self._closed:
|
||||
return None
|
||||
request = entry[1]
|
||||
return request if request[0] == self._generation and not request[4].cancelled else None
|
||||
|
||||
@Slot(object)
|
||||
def _received(self, result):
|
||||
request = self._current()
|
||||
if request is not None:
|
||||
request[2](result)
|
||||
|
||||
@Slot(object)
|
||||
def _failed(self, error):
|
||||
request = self._current()
|
||||
if request is not None and not isinstance(error, QueryCancelled):
|
||||
request[3](error)
|
||||
|
||||
@Slot()
|
||||
def _finished(self):
|
||||
self._active.pop(self.sender(), None)
|
||||
self._start()
|
||||
if not self._closed:
|
||||
self.settled.emit()
|
||||
@@ -1,71 +1,60 @@
|
||||
"""Operator guidance, commands, and read-only task log widgets."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from PySide6.QtWidgets import QCheckBox, QHBoxLayout, QLabel, QProgressBar, QPushButton, QTextEdit, QToolButton, QVBoxLayout, QWidget
|
||||
"""Explicit single-task execution, recovery and safe pause controls."""
|
||||
from PySide6.QtWidgets import (QCheckBox, QHBoxLayout, QLabel, QProgressBar,
|
||||
QPushButton, QPlainTextEdit, QToolButton, QVBoxLayout, QWidget)
|
||||
|
||||
|
||||
class RunPanel(QWidget):
|
||||
def __init__(self) -> None:
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.operator_band = QLabel("请选择任务,并扫描工程目录。", objectName="operatorBand")
|
||||
self.operator_band.setWordWrap(True)
|
||||
self.queue_summary = QLabel("未选择任务", objectName="queueSummary")
|
||||
self.execution_status = QLabel("空闲", objectName="executionStatus")
|
||||
self.queue_summary = QLabel('未选择任务', objectName='queueSummary')
|
||||
self.execution_status = QLabel('空闲', objectName='executionStatus')
|
||||
self.execution_status.setWordWrap(True)
|
||||
self.busy_indicator = QProgressBar(objectName="quickRunBusyIndicator")
|
||||
self.operator_band = QLabel(objectName='operatorBand')
|
||||
self.operator_band.setWordWrap(True)
|
||||
self.busy_indicator = QProgressBar(objectName='quickRunBusyIndicator')
|
||||
self.busy_indicator.setRange(0, 0)
|
||||
self.busy_indicator.setTextVisible(False)
|
||||
self.busy_indicator.setFixedHeight(4)
|
||||
self.busy_indicator.hide()
|
||||
self.start_button = QPushButton("开始任务", objectName="startTaskButton")
|
||||
self.quick_run_button = QPushButton("确认并执行替换", objectName="quickRunButton")
|
||||
self.stop_queue_button = QPushButton("完成当前项后暂停", objectName="stopQueueButton")
|
||||
self.stop_queue_button.hide()
|
||||
self.continue_without_backup_button = QPushButton(
|
||||
"忽略备份失败并继续", objectName="continueWithoutBackupButton"
|
||||
)
|
||||
self.continue_without_backup_button.setToolTip(
|
||||
"仅在精简原理图备份失败后启用。继续执行将无法保证该工程可从本工具备份回滚。"
|
||||
)
|
||||
self.continue_without_backup_button.hide()
|
||||
self.recover_button = QPushButton("核验并恢复中断任务", objectName="recoverQuickRunButton")
|
||||
self.recover_button.setToolTip("先备份并核验已保存工程;不重复调用原生替换。混合状态或连接异常时保留保护。")
|
||||
self.pause_button = QPushButton("暂停", objectName="pauseTaskButton")
|
||||
self.resume_button = QPushButton("继续", objectName="resumeTaskButton")
|
||||
self.capture_before_button = QPushButton("采集替换前结果", objectName="captureBeforeButton")
|
||||
self.confirm_attempt_button = QPushButton("已完成原生替换", objectName="confirmNativeAttemptButton")
|
||||
self.capture_after_button = QPushButton("采集替换后结果", objectName="captureAfterButton")
|
||||
self.copy_value_check = QCheckBox("替换后将 Part Label 写入 Value", objectName="copyPartNumberToValue")
|
||||
self.copy_value_check.setToolTip("勾选:将替换后目标器件的 Part Label 写入 Value。未勾选:保留原生替换后的 Value,不创建缺失字段。两种模式均继承已有 Value 的位置、字体等显示样式。队列生成后不可更改。")
|
||||
self.toggle_log_button = QToolButton(objectName="toggleLogButton")
|
||||
self.toggle_log_button.setText("显示日志")
|
||||
self.quick_run_button = QPushButton('执行当前任务', objectName='quickRunButton')
|
||||
self.stop_queue_button = QPushButton('完成当前项后暂停', objectName='stopQueueButton')
|
||||
self.retry_button = QPushButton('重试失败项', objectName='retryTaskItems')
|
||||
self.recover_button = QPushButton('核验并恢复', objectName='recoverQuickRunButton')
|
||||
self.copy_value_check = QCheckBox('替换后将 Part Label 写入 Value', objectName='copyPartNumberToValue')
|
||||
self.copy_value_check.setToolTip('每行自定义 Value 优先;同步 NC 由每行开关控制。开始执行后选项冻结。')
|
||||
self.toggle_log_button = QToolButton(objectName='toggleLogButton')
|
||||
self.toggle_log_button.setText('显示日志')
|
||||
self.toggle_log_button.setCheckable(True)
|
||||
self.reset_layout_button = QToolButton(objectName="resetLayoutButton")
|
||||
self.reset_layout_button.setText("重置布局")
|
||||
self.log_view = QTextEdit(objectName="logView")
|
||||
self.reset_layout_button = QToolButton(objectName='resetLayoutButton')
|
||||
self.reset_layout_button.setText('重置布局')
|
||||
self.log_view = QPlainTextEdit(objectName='logView')
|
||||
self.log_view.setReadOnly(True)
|
||||
self.log_view.setMinimumHeight(40)
|
||||
self.log_view.setMinimumHeight(60)
|
||||
self.log_view.hide()
|
||||
self.older_log_button = QPushButton('上一页日志', objectName='olderTaskLog')
|
||||
self.latest_log_button = QPushButton('最新日志', objectName='latestTaskLog')
|
||||
self.log_page_status = QLabel()
|
||||
self.log_navigation = QWidget()
|
||||
log_actions = QHBoxLayout(self.log_navigation)
|
||||
log_actions.setContentsMargins(0, 0, 0, 0)
|
||||
for widget in (self.older_log_button, self.latest_log_button, self.log_page_status):
|
||||
log_actions.addWidget(widget)
|
||||
log_actions.addStretch()
|
||||
self.log_navigation.hide()
|
||||
self.toggle_log_button.toggled.connect(self.log_view.setVisible)
|
||||
self.toggle_log_button.toggled.connect(lambda checked: self.toggle_log_button.setText("收起日志" if checked else "显示日志"))
|
||||
commands = QHBoxLayout()
|
||||
for button in (
|
||||
self.quick_run_button,
|
||||
self.stop_queue_button,
|
||||
self.continue_without_backup_button,
|
||||
self.recover_button,
|
||||
):
|
||||
commands.addWidget(button)
|
||||
commands.addStretch(1)
|
||||
commands.addWidget(self.toggle_log_button)
|
||||
commands.addWidget(self.reset_layout_button)
|
||||
self.toggle_log_button.toggled.connect(self.log_navigation.setVisible)
|
||||
self.toggle_log_button.toggled.connect(lambda on: self.toggle_log_button.setText('收起日志' if on else '显示日志'))
|
||||
buttons = QHBoxLayout()
|
||||
for button in (self.quick_run_button, self.retry_button, self.recover_button, self.stop_queue_button):
|
||||
buttons.addWidget(button)
|
||||
buttons.addStretch()
|
||||
buttons.addWidget(self.toggle_log_button)
|
||||
buttons.addWidget(self.reset_layout_button)
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
layout.addWidget(self.queue_summary)
|
||||
layout.addWidget(self.execution_status)
|
||||
layout.addWidget(self.busy_indicator)
|
||||
layout.addWidget(self.operator_band)
|
||||
layout.addWidget(self.copy_value_check)
|
||||
layout.addLayout(commands)
|
||||
for widget in (self.queue_summary, self.execution_status, self.busy_indicator,
|
||||
self.operator_band, self.copy_value_check):
|
||||
layout.addWidget(widget)
|
||||
layout.addLayout(buttons)
|
||||
layout.addWidget(self.log_view, 1)
|
||||
layout.addWidget(self.log_navigation)
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
APP_STYLESHEET = """
|
||||
QWidget { background: #f4f6f8; color: #17212b; font-size: 13px; }
|
||||
QLabel#taskSectionTitle { color: #5d6873; font-size: 12px; font-weight: 600; padding: 2px 4px; }
|
||||
QWidget#taskNavigation, QWidget#workspace, QTextEdit { background: #ffffff; border: 1px solid #cbd5df; }
|
||||
QPushButton, QComboBox, QLineEdit, QTableWidget { border: 1px solid #aebdca; border-radius: 4px; background: #ffffff; }
|
||||
QPushButton { min-height: 30px; padding: 2px 9px; }
|
||||
@@ -17,7 +18,7 @@ QLineEdit, QComboBox { min-height: 28px; padding: 0 6px; }
|
||||
QTableWidget { gridline-color: #d8e0e7; selection-background-color: #dbeeff; selection-color: #17212b; }
|
||||
QHeaderView::section { background: #e8edf1; border: 0; border-bottom: 1px solid #cbd5df; padding: 5px; font-weight: 600; }
|
||||
QListWidget { background: #ffffff; border: 1px solid #cbd5df; }
|
||||
QListWidget::item { padding: 6px; }
|
||||
QListWidget::item { padding: 8px 10px; border-radius: 6px; margin: 2px 0; }
|
||||
QListWidget::item:selected { background: #dbeeff; color: #17212b; }
|
||||
QLabel#operatorBand { background: #fff8d9; border: 1px solid #dfbf4b; padding: 7px; color: #5a4600; }
|
||||
QLabel#operatorBand[state="success"] { background: #edf8f1; border-color: #71a982; color: #245b35; }
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
"""Model-based editable target plan; filtering never changes saved identities."""
|
||||
from dataclasses import replace
|
||||
from PySide6.QtCore import QAbstractTableModel, QModelIndex, QSortFilterProxyModel, Qt, Signal
|
||||
from PySide6.QtWidgets import QAbstractItemView, QHeaderView, QTableView
|
||||
|
||||
HEADERS = ('替换', '原理图', '图页', '位号', '旧料号', '原 Value', '新料号', '自定义 Value', '新 Value', '同步 NC')
|
||||
CHECK_FIELDS = {0: 'enabled', 7: 'custom_value_enabled', 9: 'sync_nc'}
|
||||
TEXT_FIELDS = {6: 'new_part_number', 8: 'custom_value'}
|
||||
|
||||
class TargetPlanModel(QAbstractTableModel):
|
||||
changed = Signal()
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
self.rows = []
|
||||
self.search_text = []
|
||||
self.editable = True
|
||||
@staticmethod
|
||||
def searchable(row):
|
||||
t = row.target
|
||||
return '\n'.join((t.refdes, t.uid, t.schematic_name, t.sheet_number, t.old_part_number,
|
||||
t.old_value, row.new_part_number, row.custom_value)).casefold()
|
||||
def populate(self, rows):
|
||||
self.beginResetModel()
|
||||
self.rows = list(rows)
|
||||
self.search_text = [self.searchable(row) for row in self.rows]
|
||||
self.endResetModel()
|
||||
def rowCount(self, parent=QModelIndex()):
|
||||
return 0 if parent.isValid() else len(self.rows)
|
||||
def columnCount(self, parent=QModelIndex()):
|
||||
return 0 if parent.isValid() else len(HEADERS)
|
||||
def headerData(self, section, orientation, role=Qt.ItemDataRole.DisplayRole):
|
||||
if role == Qt.ItemDataRole.DisplayRole:
|
||||
return HEADERS[section] if orientation == Qt.Orientation.Horizontal else section + 1
|
||||
def data(self, index, role=Qt.ItemDataRole.DisplayRole):
|
||||
if not index.isValid():
|
||||
return None
|
||||
row = self.rows[index.row()]
|
||||
t = row.target
|
||||
col = index.column()
|
||||
if role == Qt.ItemDataRole.CheckStateRole and col in CHECK_FIELDS:
|
||||
return Qt.CheckState.Checked if getattr(row, CHECK_FIELDS[col]) else Qt.CheckState.Unchecked
|
||||
if role in (Qt.ItemDataRole.DisplayRole, Qt.ItemDataRole.EditRole):
|
||||
return ('', t.schematic_name, t.sheet_number, t.refdes, t.old_part_number,
|
||||
t.old_value, row.new_part_number, '', row.custom_value, '')[col]
|
||||
if role == Qt.ItemDataRole.ToolTipRole:
|
||||
return f'{t.project_path}\n{t.schematic_name}:{t.sheet_number} | {t.refdes} | UID {t.uid}'
|
||||
def flags(self, index):
|
||||
if not index.isValid():
|
||||
return Qt.ItemFlag.NoItemFlags
|
||||
flags = Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsEnabled
|
||||
if self.editable:
|
||||
if index.column() in CHECK_FIELDS:
|
||||
flags |= Qt.ItemFlag.ItemIsUserCheckable
|
||||
elif index.column() in TEXT_FIELDS:
|
||||
flags |= Qt.ItemFlag.ItemIsEditable
|
||||
return flags
|
||||
def setData(self, index, value, role=Qt.ItemDataRole.EditRole):
|
||||
if not self.editable or not index.isValid():
|
||||
return False
|
||||
col = index.column()
|
||||
if role == Qt.ItemDataRole.CheckStateRole and col in CHECK_FIELDS:
|
||||
change = {CHECK_FIELDS[col]: value in (Qt.CheckState.Checked, Qt.CheckState.Checked.value)}
|
||||
elif role == Qt.ItemDataRole.EditRole and col in TEXT_FIELDS:
|
||||
change = {TEXT_FIELDS[col]: str(value).strip()}
|
||||
else:
|
||||
return False
|
||||
number = index.row()
|
||||
updated = replace(self.rows[number], **change)
|
||||
if updated == self.rows[number]:
|
||||
return False
|
||||
self.rows[number] = updated
|
||||
self.search_text[number] = self.searchable(updated)
|
||||
self.dataChanged.emit(index, index, [role, Qt.ItemDataRole.DisplayRole])
|
||||
self.changed.emit()
|
||||
return True
|
||||
|
||||
def apply_changes(self, numbers, column, value, role):
|
||||
"""Notify the view and controller once for a bulk operation."""
|
||||
if not self.editable:
|
||||
return
|
||||
field = CHECK_FIELDS[column] if role == Qt.ItemDataRole.CheckStateRole else TEXT_FIELDS[column]
|
||||
changed = []
|
||||
for number in numbers:
|
||||
updated = replace(self.rows[number], **{field: value})
|
||||
if updated != self.rows[number]:
|
||||
self.rows[number] = updated
|
||||
self.search_text[number] = self.searchable(updated)
|
||||
changed.append(number)
|
||||
if changed:
|
||||
self.dataChanged.emit(self.index(min(changed), column), self.index(max(changed), column),
|
||||
[role, Qt.ItemDataRole.DisplayRole])
|
||||
self.changed.emit()
|
||||
|
||||
class TargetFilter(QSortFilterProxyModel):
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
self.query = ''
|
||||
self.setDynamicSortFilter(False)
|
||||
def filterAcceptsRow(self, row, parent):
|
||||
return not self.query or self.query in self.sourceModel().search_text[row]
|
||||
|
||||
class TargetTable(QTableView):
|
||||
changed = Signal()
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
self.setObjectName('targetPlanTable')
|
||||
self.plan_model = TargetPlanModel(self)
|
||||
self.proxy = TargetFilter(self)
|
||||
self.proxy.setSourceModel(self.plan_model)
|
||||
self.setModel(self.proxy)
|
||||
self.setEditTriggers(QAbstractItemView.EditTrigger.DoubleClicked | QAbstractItemView.EditTrigger.EditKeyPressed)
|
||||
self.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
|
||||
self.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection)
|
||||
self.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Interactive)
|
||||
for col, width in enumerate((55, 90, 50, 70, 160, 130, 160, 90, 130, 75)):
|
||||
self.setColumnWidth(col, width)
|
||||
self.dirty = False
|
||||
self._next_match = -1
|
||||
self.plan_model.changed.connect(self._changed)
|
||||
def _changed(self):
|
||||
self.dirty = True
|
||||
self.changed.emit()
|
||||
def populate(self, rows):
|
||||
self.plan_model.populate(rows)
|
||||
self._next_match = -1
|
||||
self.dirty = False
|
||||
def rows(self):
|
||||
return tuple(self.plan_model.rows)
|
||||
def rowCount(self):
|
||||
return self.proxy.rowCount()
|
||||
|
||||
def item(self, row, column):
|
||||
"""Compatibility cell adapter for the original QTableWidget tests/UI hooks."""
|
||||
index = self.proxy.index(row, column)
|
||||
if not index.isValid():
|
||||
return None
|
||||
return _CellAdapter(self, index)
|
||||
def set_plan_editable(self, editable):
|
||||
if self.plan_model.editable != bool(editable):
|
||||
self.plan_model.editable = bool(editable)
|
||||
self.viewport().update()
|
||||
def set_find_text(self, text):
|
||||
modern = hasattr(self.proxy, 'endFilterChange')
|
||||
if modern:
|
||||
self.proxy.beginFilterChange()
|
||||
self.proxy.query = str(text).strip().casefold()
|
||||
if modern:
|
||||
self.proxy.endFilterChange(QSortFilterProxyModel.Direction.Rows)
|
||||
else:
|
||||
self.proxy.invalidateFilter()
|
||||
self._next_match = -1
|
||||
return self.rowCount()
|
||||
def find_next(self):
|
||||
if not self.rowCount():
|
||||
return None
|
||||
self._next_match = (self._next_match + 1) % self.rowCount()
|
||||
self.selectRow(self._next_match)
|
||||
self.scrollTo(self.proxy.index(self._next_match, 3))
|
||||
return self._next_match
|
||||
def select_all_targets(self, enabled=True):
|
||||
source_rows = [self.proxy.mapToSource(self.proxy.index(row, 0)).row() for row in range(self.rowCount())]
|
||||
self.plan_model.apply_changes(source_rows, 0, bool(enabled), Qt.ItemDataRole.CheckStateRole)
|
||||
def apply_to_selected(self, new_part_number):
|
||||
source_rows = [self.proxy.mapToSource(index).row() for index in self.selectionModel().selectedRows()]
|
||||
self.plan_model.apply_changes(source_rows, 6, str(new_part_number).strip(), Qt.ItemDataRole.EditRole)
|
||||
|
||||
|
||||
class _CellAdapter:
|
||||
def __init__(self, table, index):
|
||||
self.table, self.index = table, index
|
||||
|
||||
def setCheckState(self, state):
|
||||
return self.table.model().setData(self.index, state, Qt.ItemDataRole.CheckStateRole)
|
||||
|
||||
def checkState(self):
|
||||
return self.table.model().data(self.index, Qt.ItemDataRole.CheckStateRole)
|
||||
|
||||
def setText(self, value):
|
||||
return self.table.model().setData(self.index, value, Qt.ItemDataRole.EditRole)
|
||||
|
||||
def text(self):
|
||||
return str(self.table.model().data(self.index, Qt.ItemDataRole.DisplayRole) or '')
|
||||
|
||||
def flags(self):
|
||||
return self.table.model().flags(self.index)
|
||||
@@ -6,7 +6,7 @@ from collections.abc import Callable
|
||||
from typing import Iterable
|
||||
|
||||
from PySide6.QtCore import Qt, QSignalBlocker
|
||||
from PySide6.QtWidgets import QComboBox, QGridLayout, QListWidget, QListWidgetItem, QPushButton, QVBoxLayout, QWidget
|
||||
from PySide6.QtWidgets import QComboBox, QGridLayout, QLabel, QListWidget, QListWidgetItem, QPushButton, QVBoxLayout, QWidget
|
||||
|
||||
|
||||
class TaskList(QWidget):
|
||||
@@ -15,19 +15,27 @@ class TaskList(QWidget):
|
||||
self.setObjectName("taskNavigation")
|
||||
self.filter = QComboBox(objectName="taskFilter")
|
||||
self.filter.addItems(("进行中", "已完成", "已删除"))
|
||||
self.filter.setVisible(False)
|
||||
self.filter.setMaximumHeight(0)
|
||||
self.list = QListWidget(objectName="taskList")
|
||||
self.new_button = QPushButton("新建", objectName="newTaskButton")
|
||||
self.edit_button = QPushButton("编辑", objectName="editTaskButton")
|
||||
self.delete_button = QPushButton("删除", objectName="deleteTaskButton")
|
||||
self.restore_button = QPushButton("恢复", objectName="restoreTaskButton")
|
||||
self.queue_button = QPushButton("顺序执行本批任务", objectName="executeProjectTasks")
|
||||
self.up_button = QPushButton("上移任务", objectName="moveTaskUp")
|
||||
self.down_button = QPushButton("下移任务", objectName="moveTaskDown")
|
||||
actions = QGridLayout()
|
||||
actions.addWidget(self.new_button, 0, 0)
|
||||
actions.addWidget(self.edit_button, 0, 1)
|
||||
actions.addWidget(self.delete_button, 1, 0)
|
||||
actions.addWidget(self.restore_button, 1, 1)
|
||||
actions.addWidget(self.up_button, 2, 0)
|
||||
actions.addWidget(self.down_button, 2, 1)
|
||||
actions.addWidget(self.queue_button, 3, 0, 1, 2)
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(8, 8, 8, 8)
|
||||
layout.addWidget(self.filter)
|
||||
layout.addWidget(QLabel('任务', objectName='taskSectionTitle'))
|
||||
layout.addWidget(self.list, 1)
|
||||
layout.addLayout(actions)
|
||||
self.list.itemSelectionChanged.connect(lambda: on_open(self.current_task_id() or ""))
|
||||
@@ -36,12 +44,17 @@ class TaskList(QWidget):
|
||||
item = self.list.currentItem()
|
||||
return str(item.data(Qt.ItemDataRole.UserRole)) if item is not None else None
|
||||
|
||||
def populate(self, tasks: Iterable[object]) -> None:
|
||||
selected = self.current_task_id()
|
||||
def populate(self, tasks: Iterable[object], *, selected_task_id: str | None = None) -> None:
|
||||
selected = selected_task_id or self.current_task_id()
|
||||
with QSignalBlocker(self.list):
|
||||
self.list.clear()
|
||||
for task in tasks:
|
||||
item = QListWidgetItem(str(getattr(task, "name")))
|
||||
group_id = getattr(task, "group_id", None)
|
||||
prefix = f"{getattr(task, 'group_position', 0) + 1:02d}. " if group_id else ""
|
||||
status = getattr(getattr(task, 'status', None), 'value', '')
|
||||
labels = {'draft': '待配置', 'ready': '待执行', 'running': '执行中', 'paused': '已暂停',
|
||||
'completed': '已完成', 'failed': '失败', 'deleted': '已删除'}
|
||||
item = QListWidgetItem(prefix + str(getattr(task, "name")) + f"\n{labels.get(status, status)}")
|
||||
item.setData(Qt.ItemDataRole.UserRole, str(getattr(task, "task_id")))
|
||||
self.list.addItem(item)
|
||||
if getattr(task, "task_id") == selected:
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Asynchronous paged history and incremental live logs for the selected task."""
|
||||
from PySide6.QtCore import QObject
|
||||
from PySide6.QtGui import QTextCursor
|
||||
|
||||
from .messages import _format_task_log_lines
|
||||
from .queries import LatestQuery
|
||||
|
||||
|
||||
class TaskLogPresenter(QObject):
|
||||
def __init__(self, service, panel, parent=None):
|
||||
super().__init__(parent)
|
||||
self.service, self.panel = service, panel
|
||||
self.query = LatestQuery(self)
|
||||
self.query.settled.connect(self._buttons)
|
||||
self.task_id = None
|
||||
self._requested_task = None
|
||||
self.cursor = self.older_cursor = None
|
||||
self.history = False
|
||||
self.initialized = False
|
||||
self.has_older = False
|
||||
self._displayed_events = 0
|
||||
panel.older_log_button.clicked.connect(self.older)
|
||||
panel.latest_log_button.clicked.connect(self.latest)
|
||||
|
||||
def bind(self, task_id):
|
||||
if task_id == self.task_id:
|
||||
return
|
||||
self.query.invalidate()
|
||||
self.task_id = task_id
|
||||
self.cursor = self.older_cursor = None
|
||||
self.history = self.initialized = self.has_older = False
|
||||
self._displayed_events = 0
|
||||
self.panel.log_view.clear()
|
||||
self._buttons()
|
||||
|
||||
def _buttons(self):
|
||||
self.panel.older_log_button.setEnabled(self.has_older and not self.query.current_busy)
|
||||
self.panel.latest_log_button.setEnabled(bool(self.task_id) and not self.query.current_busy)
|
||||
|
||||
def refresh(self):
|
||||
if not self.task_id or (self.query.current_busy and self._requested_task == self.task_id) or self.history:
|
||||
return
|
||||
# Keep live rendering bounded; older events remain available via paging.
|
||||
self._request('poll' if self.initialized and self._displayed_events < 400 else 'latest')
|
||||
|
||||
def latest(self, *, force=False):
|
||||
if self.task_id and (force or not self.query.current_busy):
|
||||
self.history = False
|
||||
self._request('latest')
|
||||
|
||||
def older(self):
|
||||
if self.task_id and self.has_older and not self.query.current_busy:
|
||||
self.history = True
|
||||
self._request('older')
|
||||
|
||||
def _request(self, mode):
|
||||
task_id = self.task_id
|
||||
self._requested_task = task_id
|
||||
cursor = self.older_cursor if mode == 'older' else self.cursor
|
||||
def read(control):
|
||||
page = self.service.read_task_log(task_id, mode=mode, cursor=cursor, limit=200, read_control=control)
|
||||
control.checkpoint()
|
||||
return page, '\n'.join(_format_task_log_lines(page.lines))
|
||||
def received(result):
|
||||
page, text = result
|
||||
view = self.panel.log_view
|
||||
if mode == 'poll' and not page.reset:
|
||||
if text:
|
||||
scroll = view.verticalScrollBar()
|
||||
follow = scroll.value() >= scroll.maximum() - 2
|
||||
old = scroll.value()
|
||||
position = QTextCursor(view.document())
|
||||
position.movePosition(QTextCursor.MoveOperation.End)
|
||||
position.insertText(('\n' if not view.document().isEmpty() else '') + text)
|
||||
scroll.setValue(scroll.maximum() if follow else old)
|
||||
self._displayed_events += len(page.lines)
|
||||
else:
|
||||
view.setPlainText(text)
|
||||
self.older_cursor = page.older_cursor
|
||||
self.has_older = page.has_older
|
||||
self._displayed_events = len(page.lines)
|
||||
if mode != 'older':
|
||||
view.verticalScrollBar().setValue(view.verticalScrollBar().maximum())
|
||||
if mode != 'older':
|
||||
self.cursor = page.cursor
|
||||
self.initialized = True
|
||||
if page.reset:
|
||||
self.panel.log_page_status.setText('日志已轮转或重建,已加载最近记录')
|
||||
else:
|
||||
self.panel.log_page_status.setText('历史记录 · 每页 200 条' if self.history else '最近记录 · 实时追加')
|
||||
def failed(error):
|
||||
self.panel.log_page_status.setText(f'日志读取失败,可点击最新日志重试:{getattr(error, "message", str(error))}')
|
||||
self.query.request(read, received, failed, cancellable=True)
|
||||
self._buttons()
|
||||
@@ -1 +1 @@
|
||||
VERSION = "1.0.0"
|
||||
VERSION = "1.1.1"
|
||||
@@ -24,6 +24,7 @@ class ProgressWatch:
|
||||
raise ValueError('Idle timeout must be positive')
|
||||
self.token = token
|
||||
self.job_id = job_id
|
||||
self.current_job_id = job_id
|
||||
self.idle_timeout = idle_timeout
|
||||
self.last_progress = started
|
||||
self.sequence = 0
|
||||
@@ -32,11 +33,17 @@ class ProgressWatch:
|
||||
self.done = 0
|
||||
self.total = 0
|
||||
self.safe_stop = True
|
||||
self.started = started
|
||||
self.stage_started = started
|
||||
self.stage_seconds: dict[str, float] = {}
|
||||
|
||||
def accept(self, line: bytes, now: float) -> bool:
|
||||
try:
|
||||
fields = line.decode('ascii').strip().split('\t')
|
||||
if len(fields) != 8 or fields[:3] != ['DX_PROGRESS', self.token, self.job_id]:
|
||||
if len(fields) not in {8, 9} or fields[:3] != ['DX_PROGRESS', self.token, self.job_id]:
|
||||
return False
|
||||
current_job = fields[8] if len(fields) == 9 else self.job_id
|
||||
if not re.fullmatch(r'[A-Za-z0-9_.-]{1,128}', current_job):
|
||||
return False
|
||||
sequence, done, total, safe = (int(fields[index]) for index in (3, 5, 6, 7))
|
||||
if not self.sequence < sequence <= 2**31 - 1 or not re.fullmatch('[a-z_]{1,64}', fields[4]):
|
||||
@@ -45,6 +52,14 @@ class ProgressWatch:
|
||||
return False
|
||||
except (ValueError, UnicodeError):
|
||||
return False
|
||||
if current_job != self.current_job_id:
|
||||
self.current_job_id = current_job
|
||||
self.stage_seconds = {}
|
||||
self.started = self.stage_started = now
|
||||
self.stage = fields[4]
|
||||
if fields[4] != self.stage:
|
||||
self.stage_seconds[self.stage] = self.stage_seconds.get(self.stage, 0.0) + max(0.0, now - self.stage_started)
|
||||
self.stage_started = now
|
||||
self.sequence = sequence
|
||||
self.last_progress = now
|
||||
self.stage, self.done, self.total, self.safe_stop = fields[4], done, total, bool(safe)
|
||||
@@ -59,8 +74,13 @@ class ProgressWatch:
|
||||
return 'unresponsive'
|
||||
return None
|
||||
|
||||
def snapshot(self) -> dict:
|
||||
return {name: getattr(self, name) for name in ('token', 'job_id', 'sequence', 'stage', 'done', 'total', 'safe_stop', 'stop_requested')}
|
||||
def snapshot(self, *, now: float | None = None) -> dict:
|
||||
now = time.monotonic() if now is None else now
|
||||
stages = dict(self.stage_seconds)
|
||||
stages[self.stage] = stages.get(self.stage, 0.0) + max(0.0, now - self.stage_started)
|
||||
return {name: getattr(self, name) for name in ('token', 'sequence', 'stage', 'done', 'total', 'safe_stop', 'stop_requested')} | {
|
||||
'job_id': self.current_job_id,
|
||||
'elapsed_seconds': max(0.0, now - self.started), 'stage_seconds': stages}
|
||||
|
||||
|
||||
def _atomic_text(path: Path, text: str) -> None:
|
||||
@@ -137,7 +157,8 @@ class _OwnedWorkers:
|
||||
self.job.Close()
|
||||
|
||||
|
||||
def run_monitored_process(command: tuple[str, ...], idle_timeout: float) -> subprocess.CompletedProcess[str]:
|
||||
def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abort_event=None,
|
||||
process_factory=None) -> subprocess.CompletedProcess[str]:
|
||||
root = Path(command[3])
|
||||
job_id = command[-1]
|
||||
token = uuid4().hex
|
||||
@@ -175,9 +196,14 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float) -> subp
|
||||
output[channel].extend(line[:1024 * 1024 - len(output[channel])])
|
||||
|
||||
try:
|
||||
process = subprocess.Popen((*command, token), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
owned.assign(process)
|
||||
if process_factory is None:
|
||||
process = subprocess.Popen((*command, token), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
owned.assign(process)
|
||||
else:
|
||||
# PrivateDesktop already assigns its suspended process to an owned
|
||||
# Job before resuming it. Do not reassign it to another Job here.
|
||||
process = process_factory((*command, token), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
for channel, stream in enumerate((process.stdout, process.stderr)):
|
||||
thread = threading.Thread(target=read_stream, args=(stream, channel), daemon=True)
|
||||
thread.start()
|
||||
@@ -185,6 +211,8 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float) -> subp
|
||||
_publish_progress(progress_path, watch.snapshot())
|
||||
_atomic_text(ready, token)
|
||||
while process.poll() is None:
|
||||
if abort_event is not None and abort_event.is_set():
|
||||
raise WorkerMonitorError('project session supervisor requested worker cleanup')
|
||||
try:
|
||||
receive(*messages.get(timeout=min(0.1, idle_timeout / 10)))
|
||||
for pending in range(128):
|
||||
@@ -227,3 +255,5 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float) -> subp
|
||||
for thread in threads:
|
||||
thread.join(0.2)
|
||||
owned.close()
|
||||
if process_factory is not None and process is not None:
|
||||
process.close()
|
||||
+1
-1
@@ -7,7 +7,7 @@ from dx_productivity.part_replace.models import ComponentSnapshot, DesignSnapsho
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def accept_minimal_project_placeholders(monkeypatch: pytest.MonkeyPatch, request: pytest.FixtureRequest) -> None:
|
||||
if request.node.path.name != "test_scanner.py":
|
||||
if "v1_1" not in request.node.path.parts and request.node.path.name != "test_scanner.py":
|
||||
monkeypatch.setattr(
|
||||
"dx_productivity.trial_task_center.scanner._is_schematic_project",
|
||||
lambda _path: True,
|
||||
|
||||
@@ -386,6 +386,12 @@ def test_thousand_item_multisheet_mixed_queue_has_bounded_runtime_and_memory(tmp
|
||||
|
||||
total = project_count * sheet_count * rule_count
|
||||
saved = len(range(0, total, 11))
|
||||
(tmp_path / 'stress-metrics.json').write_text(json.dumps({
|
||||
'mode': 'simulated_worker_with_tracemalloc', 'projects': project_count,
|
||||
'sheets_per_project': sheet_count, 'rules_per_sheet': rule_count,
|
||||
'steps': total, 'saved_steps': saved, 'elapsed_seconds': elapsed,
|
||||
'peak_bytes': peak, 'steps_per_second': total / elapsed,
|
||||
}, indent=2), encoding='utf-8')
|
||||
assert result.progress.queue_complete
|
||||
assert result.progress.total_items == total
|
||||
assert result.progress.saved_items == saved
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
from dx_productivity.trial_task_center.models import ProjectRecord, ProjectStatus, RuleRecord
|
||||
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
|
||||
|
||||
|
||||
def fixture_queue(tmp_path):
|
||||
script = tmp_path / 'runtime.vbs'
|
||||
script.write_text("' fixture", encoding='ascii')
|
||||
preparer = QuickRunPreparer(tmp_path, script_source=script, run_token_factory=lambda: 'snapshot')
|
||||
project = ProjectRecord('project', 'task', 'One', Path('C:/one.prj'), Path('C:/'), True, True, ProjectStatus.PENDING, 0)
|
||||
rule = RuleRecord('rule', 'task', 0, 'OLD', 'NEW', True)
|
||||
handoff = preparer.prepare('task', (project,), (rule,))
|
||||
job = handoff.command_path.read_text(encoding='utf-8').splitlines()[1].split('\t')[1]
|
||||
return preparer, project, rule, handoff, job
|
||||
|
||||
|
||||
def test_snapshot_reads_each_file_once_and_uses_same_status(tmp_path, monkeypatch):
|
||||
preparer, project, rule, handoff, job = fixture_queue(tmp_path)
|
||||
handoff.status_path.write_text(f'job_id\tstate\tcode\tmessage\n{job}\tbatch_saved_unverified\t\tverify\n', encoding='utf-8')
|
||||
opens = []
|
||||
original = Path.open
|
||||
def tracked(path, *args, **kwargs):
|
||||
if path.parent == handoff.command_path.parent:
|
||||
opens.append(path.name)
|
||||
return original(path, *args, **kwargs)
|
||||
monkeypatch.setattr(Path, 'open', tracked)
|
||||
snapshot = preparer.read_snapshot('task', (project,), (rule,))
|
||||
assert opens.count('command.tsv') == opens.count('status.tsv') == 1
|
||||
assert snapshot.evidence_path == handoff.command_path.parent
|
||||
assert snapshot.has_evidence and snapshot.interrupted
|
||||
assert snapshot.progress.saved_items == 0
|
||||
assert snapshot.progress.failed_items == 1
|
||||
|
||||
|
||||
def test_snapshot_cancellation_stops_before_next_file_and_never_writes(tmp_path, monkeypatch):
|
||||
preparer, project, rule, handoff, job = fixture_queue(tmp_path)
|
||||
original = Path.open
|
||||
class Cancelled(Exception):
|
||||
pass
|
||||
class Control:
|
||||
cancelled = False
|
||||
def checkpoint(self):
|
||||
if self.cancelled:
|
||||
raise Cancelled
|
||||
control = Control()
|
||||
opened = []
|
||||
def tracked(path, *args, **kwargs):
|
||||
opened.append(path.name)
|
||||
result = original(path, *args, **kwargs)
|
||||
if path == handoff.command_path:
|
||||
control.cancelled = True
|
||||
return result
|
||||
monkeypatch.setattr(Path, 'open', tracked)
|
||||
with pytest.raises(Cancelled):
|
||||
preparer.read_snapshot('task', (project,), (rule,), read_control=control)
|
||||
assert opened == ['command.tsv']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('state', ['alien_state', 'awaiting_native_replace'])
|
||||
def test_snapshot_unknown_states_do_not_complete_or_save(tmp_path, state):
|
||||
preparer, project, rule, handoff, job = fixture_queue(tmp_path)
|
||||
text = f'job_id\tstate\tcode\tmessage\n{job}\t{state}\t\tunknown\n'
|
||||
handoff.status_path.write_text(text, encoding='utf-8')
|
||||
snapshot = preparer.read_snapshot('task', (project,), (rule,))
|
||||
assert not snapshot.progress.queue_complete
|
||||
assert snapshot.progress.saved_items == 0
|
||||
assert snapshot.interrupted == (state == 'awaiting_native_replace')
|
||||
assert handoff.status_path.read_text(encoding='utf-8') == text
|
||||
|
||||
|
||||
def test_snapshot_corruption_retains_evidence_without_claiming_progress(tmp_path):
|
||||
preparer, project, rule, handoff, job = fixture_queue(tmp_path)
|
||||
handoff.status_path.write_text('corrupt', encoding='utf-8')
|
||||
snapshot = preparer.read_snapshot('task', (project,), (rule,))
|
||||
assert snapshot.has_evidence
|
||||
assert snapshot.progress.completed_items == 0
|
||||
assert snapshot.phase == 'selection'
|
||||
|
||||
|
||||
def test_legacy_phase_wrapper_keeps_terminal_phase_while_snapshot_exposes_retry(tmp_path):
|
||||
preparer, project, rule, handoff, job = fixture_queue(tmp_path)
|
||||
handoff.status_path.write_text(f'job_id\tstate\tcode\tmessage\n{job}\tbatch_failed\t\tfailed\n', encoding='utf-8')
|
||||
assert preparer.read_snapshot('task', (project,), (rule,)).phase == 'retry'
|
||||
assert preparer.current_phase('task', (project,), (rule,)) == 'complete'
|
||||
|
||||
|
||||
def test_snapshot_retries_when_uncertain_flag_is_created_during_status_read(tmp_path, monkeypatch):
|
||||
preparer, project, rule, handoff, job = fixture_queue(tmp_path)
|
||||
original = Path.open
|
||||
injected = False
|
||||
def racing_open(path, *args, **kwargs):
|
||||
nonlocal injected
|
||||
if path == handoff.status_path and args and args[0] == 'r' and not injected:
|
||||
injected = True
|
||||
(path.parent / 'uncertain.flag').write_text('uncertain', encoding='utf-8')
|
||||
return original(path, *args, **kwargs)
|
||||
monkeypatch.setattr(Path, 'open', racing_open)
|
||||
snapshot = preparer.read_snapshot('task', (project,), (rule,))
|
||||
assert snapshot.interrupted
|
||||
assert snapshot.has_evidence
|
||||
|
||||
|
||||
def test_snapshot_retries_command_and_status_as_one_generation(tmp_path, monkeypatch):
|
||||
preparer, project, rule, handoff, job = fixture_queue(tmp_path)
|
||||
original = Path.open
|
||||
command = handoff.command_path.read_text(encoding='utf-8')
|
||||
injected = False
|
||||
def racing_open(path, *args, **kwargs):
|
||||
nonlocal injected
|
||||
if path == handoff.status_path and args and args[0] == 'r' and not injected:
|
||||
injected = True
|
||||
handoff.command_path.write_text(command.replace(job, 'new-generation'), encoding='utf-8')
|
||||
handoff.status_path.write_text('job_id\tstate\tcode\tmessage\nnew-generation\tno_match\t\tno match\n', encoding='utf-8')
|
||||
return original(path, *args, **kwargs)
|
||||
monkeypatch.setattr(Path, 'open', racing_open)
|
||||
snapshot = preparer.read_snapshot('task', (project,), (rule,))
|
||||
assert snapshot.progress.completed_items == 1
|
||||
assert snapshot.progress.queue_complete
|
||||
assert snapshot.progress.no_match_items == 1
|
||||
|
||||
|
||||
def test_snapshot_continuous_changes_block_continuation_after_bounded_retries(tmp_path, monkeypatch):
|
||||
preparer, project, rule, handoff, job = fixture_queue(tmp_path)
|
||||
original = Path.open
|
||||
reads = 0
|
||||
def racing_open(path, *args, **kwargs):
|
||||
nonlocal reads
|
||||
if path == handoff.status_path and args and args[0] == 'r':
|
||||
reads += 1
|
||||
(path.parent / 'changing.txt').write_text('x' * reads, encoding='utf-8')
|
||||
return original(path, *args, **kwargs)
|
||||
monkeypatch.setattr(Path, 'open', racing_open)
|
||||
snapshot = preparer.read_snapshot('task', (project,), (rule,))
|
||||
assert reads == 3
|
||||
assert snapshot.interrupted
|
||||
assert snapshot.progress.next_project_path is None
|
||||
assert snapshot.progress.next_old_part_number is None
|
||||
|
||||
|
||||
def test_context_resolves_facade_from_bundle_without_another_database_read(tmp_path, monkeypatch):
|
||||
from dx_productivity.trial_task_center.logging_setup import configure_logging
|
||||
from dx_productivity.trial_task_center.service import TaskCenterService
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
task = store.create_task('bound')
|
||||
project = store.sync_projects(task.task_id, tmp_path, (tmp_path / 'one.prj',))[0]
|
||||
store.bind_project_task(task.task_id, project.project_id, 'group', 0)
|
||||
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
|
||||
original = store.read_task_bundle
|
||||
def bundle_then_block_rereads(*args, **kwargs):
|
||||
bundle = original(*args, **kwargs)
|
||||
def unexpected(*args, **kwargs):
|
||||
raise AssertionError('context reread task after its database snapshot')
|
||||
for name in ('get_task', 'list_tasks', 'list_projects', 'pending_migration_recoveries',
|
||||
'acknowledge_migration_recoveries', 'recover_interrupted_work'):
|
||||
monkeypatch.setattr(store, name, unexpected)
|
||||
return bundle
|
||||
monkeypatch.setattr(store, 'read_task_bundle', bundle_then_block_rereads)
|
||||
context = service.task_context(task.task_id)
|
||||
assert context.task.primary_project_id == project.project_id
|
||||
assert context.project.project_id == project.project_id
|
||||
|
||||
|
||||
def test_snapshot_cancellation_during_generation_validation_is_not_suppressed(tmp_path, monkeypatch):
|
||||
from dx_productivity.trial_task_center import quick_run_snapshot as module
|
||||
from dx_productivity.trial_task_center.read_control import QueryCancelled, QueryControl
|
||||
preparer, project, rule, handoff, job = fixture_queue(tmp_path)
|
||||
control = QueryControl()
|
||||
original = module._ReadFiles._manifest
|
||||
calls = 0
|
||||
def validating(files, root):
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
if calls == 2:
|
||||
control.cancel()
|
||||
return original(files, root)
|
||||
monkeypatch.setattr(module._ReadFiles, '_manifest', validating)
|
||||
with pytest.raises(QueryCancelled):
|
||||
preparer.read_snapshot('task', (project,), (rule,), read_control=control)
|
||||
@@ -382,7 +382,7 @@ def test_v1_database_migrates_to_attempt_metadata_schema(tmp_path: Path) -> None
|
||||
|
||||
assert migrated.get_task(task.task_id).name == "Trial"
|
||||
with sqlite3.connect(database) as connection:
|
||||
assert connection.execute("SELECT value FROM metadata WHERE key = 'schema_version'").fetchone()[0] == "5"
|
||||
assert connection.execute("SELECT value FROM metadata WHERE key = 'schema_version'").fetchone()[0] == "6"
|
||||
assert connection.execute("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'attempts'").fetchone()
|
||||
assert connection.execute("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'external_requests'").fetchone()
|
||||
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
"""Task bundles retain one database version and release cancelled reads."""
|
||||
from dataclasses import FrozenInstanceError, replace
|
||||
from pathlib import Path
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
from dx_productivity.trial_task_center.target_plan import ComponentTarget
|
||||
|
||||
|
||||
def test_bundle_retains_binding_inventory_and_is_frozen(tmp_path: Path):
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
task = store.create_task('bundle')
|
||||
projects = store.sync_projects(task.task_id, tmp_path, [tmp_path / 'project.prj'])
|
||||
store.bind_project_task(task.task_id, projects[0].project_id, 'group', 2)
|
||||
target = ComponentTarget(projects[0].path, 'main', '1', 'uid', 'R1', 'OLD', 'value')
|
||||
store.record_target_inventory(task.task_id, [target])
|
||||
rule = store.add_rule(task.task_id, 'OLD', 'NEW')
|
||||
before = store._connection.total_changes
|
||||
bundle = store.read_task_bundle(task.task_id)
|
||||
assert bundle.task.primary_project_id == projects[0].project_id
|
||||
assert bundle.task.group_position == 2
|
||||
assert bundle.task.target_plan_mode
|
||||
assert bundle.projects == projects
|
||||
assert bundle.rules == (rule,)
|
||||
assert bundle.targets == store.list_target_plan(task.task_id)
|
||||
assert store._connection.total_changes == before
|
||||
with pytest.raises(FrozenInstanceError):
|
||||
bundle.rules = ()
|
||||
|
||||
|
||||
def test_bundle_uses_sqlite_snapshot_across_external_writer(tmp_path: Path):
|
||||
path = tmp_path / 'tasks.db'
|
||||
store = TaskStore(path)
|
||||
store._connection.execute('PRAGMA journal_mode=WAL')
|
||||
task = store.create_task('before')
|
||||
store.add_rule(task.task_id, 'OLD', 'BEFORE')
|
||||
writer = TaskStore(path)
|
||||
errors = []
|
||||
def edit():
|
||||
try:
|
||||
with writer.transaction():
|
||||
writer.update_task(task.task_id, name='after', note='')
|
||||
rule = writer.list_rules(task.task_id)[0]
|
||||
writer.update_rule(rule.rule_id, old_part_number='OLD', new_part_number='AFTER', enabled=True)
|
||||
except BaseException as error:
|
||||
errors.append(error)
|
||||
class Control:
|
||||
calls = 0
|
||||
def checkpoint(self):
|
||||
self.calls += 1
|
||||
if self.calls == 4: # task SELECT established the SQLite snapshot
|
||||
thread = threading.Thread(target=edit)
|
||||
thread.start()
|
||||
thread.join(timeout=5)
|
||||
assert not thread.is_alive()
|
||||
bundle = store.read_task_bundle(task.task_id, Control())
|
||||
assert not errors
|
||||
assert bundle.task.name == 'before'
|
||||
assert bundle.rules[0].new_part_number == 'BEFORE'
|
||||
assert store.read_task_bundle(task.task_id).task.name == 'after'
|
||||
|
||||
|
||||
def test_cancelled_bundle_releases_transaction_and_preserves_outer_rollback(tmp_path: Path):
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
task = store.create_task('task')
|
||||
class Cancelled(Exception):
|
||||
pass
|
||||
class Control:
|
||||
calls = 0
|
||||
def checkpoint(self):
|
||||
self.calls += 1
|
||||
if self.calls == 4:
|
||||
raise Cancelled()
|
||||
with pytest.raises(Cancelled):
|
||||
store.read_task_bundle(task.task_id, Control())
|
||||
assert not store._connection.in_transaction
|
||||
with pytest.raises(RuntimeError):
|
||||
with store.transaction():
|
||||
store.update_task(task.task_id, name='temporary', note='')
|
||||
with pytest.raises(Cancelled):
|
||||
store.read_task_bundle(task.task_id, Control())
|
||||
assert store._connection.in_transaction
|
||||
assert store.read_task_bundle(task.task_id).task.name == 'temporary'
|
||||
raise RuntimeError('rollback')
|
||||
assert store.read_task_bundle(task.task_id).task.name == 'task'
|
||||
|
||||
@pytest.mark.parametrize('version', [1, 2, 3, 4, 5, 6])
|
||||
def test_migrations_preserve_target_plan(tmp_path: Path, version: int):
|
||||
path = tmp_path / 'tasks.db'
|
||||
store = TaskStore(path)
|
||||
task = store.create_task('retained')
|
||||
project = store.sync_projects(task.task_id, tmp_path, [tmp_path / 'project.prj'])[0]
|
||||
target = ComponentTarget(project.path, 'main', '1', 'uid', 'R1', 'OLD', 'value')
|
||||
inventory = store.record_target_inventory(task.task_id, [target])
|
||||
original = store.replace_target_plan(task.task_id, [replace(inventory[0], enabled=True, new_part_number='NEW')])
|
||||
store._connection.execute("UPDATE metadata SET value = ? WHERE key = 'schema_version'", (str(version),))
|
||||
store.close()
|
||||
migrated = TaskStore(path)
|
||||
assert migrated.read_task_bundle(task.task_id).targets == original
|
||||
assert migrated._connection.execute("SELECT value FROM metadata WHERE key = 'schema_version'").fetchone()[0] == '6'
|
||||
|
||||
|
||||
def test_failed_migration_rolls_back_version_and_schema(tmp_path: Path, monkeypatch):
|
||||
import sqlite3
|
||||
path = tmp_path / 'tasks.db'
|
||||
store = TaskStore(path)
|
||||
store._connection.execute("UPDATE metadata SET value = '5' WHERE key = 'schema_version'")
|
||||
store.close()
|
||||
def fail(self):
|
||||
self._connection.execute('CREATE TABLE should_rollback (value TEXT)')
|
||||
raise RuntimeError('migration failed')
|
||||
monkeypatch.setattr(TaskStore, '_ensure_rule_columns', fail)
|
||||
with pytest.raises(RuntimeError, match='migration failed'):
|
||||
TaskStore(path)
|
||||
with sqlite3.connect(path) as connection:
|
||||
assert connection.execute("SELECT value FROM metadata WHERE key = 'schema_version'").fetchone()[0] == '5'
|
||||
assert connection.execute("SELECT name FROM sqlite_master WHERE name = 'should_rollback'").fetchone() is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('operation', ['bundle', 'tasks'])
|
||||
def test_queries_cancel_while_waiting_for_shared_writer_lock(tmp_path: Path, operation: str):
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
task = store.create_task('task')
|
||||
locked, release = threading.Event(), threading.Event()
|
||||
def hold():
|
||||
with store.transaction():
|
||||
locked.set()
|
||||
release.wait(5)
|
||||
writer = threading.Thread(target=hold)
|
||||
writer.start()
|
||||
assert locked.wait(2)
|
||||
class Cancelled(Exception):
|
||||
pass
|
||||
class Control:
|
||||
calls = 0
|
||||
def checkpoint(self):
|
||||
self.calls += 1
|
||||
if self.calls == 2:
|
||||
raise Cancelled()
|
||||
try:
|
||||
with pytest.raises(Cancelled):
|
||||
if operation == 'bundle':
|
||||
store.read_task_bundle(task.task_id, Control())
|
||||
else:
|
||||
store.list_tasks(read_control=Control())
|
||||
finally:
|
||||
release.set()
|
||||
writer.join(2)
|
||||
assert not writer.is_alive()
|
||||
assert store.read_task_bundle(task.task_id).task == task
|
||||
@@ -0,0 +1,180 @@
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
from dx_productivity.trial_task_center.project_tasks import create_project_tasks
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow, compile_target_rules
|
||||
|
||||
|
||||
def target(uid: str, refdes: str) -> ComponentTarget:
|
||||
return ComponentTarget(Path('board.prj'), 'MAIN', '1', uid, refdes, 'OLD', 'V0')
|
||||
|
||||
|
||||
def test_directory_creates_one_task_per_project_and_deduplicates_active_paths(tmp_path):
|
||||
root = tmp_path / 'projects'
|
||||
for folder in ('left', 'right'):
|
||||
path = root / folder / 'same.prj'
|
||||
path.parent.mkdir(parents=True)
|
||||
path.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n', encoding='ascii')
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
|
||||
created = create_project_tasks(store, root)
|
||||
again = create_project_tasks(store, root)
|
||||
|
||||
assert len(created) == 2
|
||||
assert again == ()
|
||||
assert {task.name for task in created} == {'left/same.prj', 'right/same.prj'}
|
||||
assert all(len(store.list_projects(task.task_id)) == 1 for task in created)
|
||||
store.close()
|
||||
reopened = TaskStore(tmp_path / 'tasks.db')
|
||||
assert len(reopened.list_tasks()) == 2
|
||||
|
||||
|
||||
def test_directory_creation_rolls_back_on_second_project_failure(tmp_path, monkeypatch):
|
||||
root = tmp_path / 'projects'
|
||||
root.mkdir()
|
||||
for name in ('a.prj', 'b.prj'):
|
||||
(root / name).write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n', encoding='ascii')
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
original = store.sync_projects
|
||||
calls = 0
|
||||
|
||||
def fail_second(*args, **kwargs):
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
if calls == 2:
|
||||
raise TaskCenterError('test_failure', 'injected failure')
|
||||
return original(*args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(store, 'sync_projects', fail_second)
|
||||
|
||||
with pytest.raises(TaskCenterError):
|
||||
create_project_tasks(store, root)
|
||||
|
||||
assert store.list_tasks() == ()
|
||||
|
||||
|
||||
def test_completed_project_can_be_created_as_new_task(tmp_path):
|
||||
root = tmp_path / 'projects'
|
||||
root.mkdir()
|
||||
(root / 'a.prj').write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n', encoding='ascii')
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
first = create_project_tasks(store, root)[0]
|
||||
from dx_productivity.trial_task_center.models import TaskStatus
|
||||
store.set_task_status(first.task_id, TaskStatus.READY)
|
||||
store.set_task_status(first.task_id, TaskStatus.RUNNING)
|
||||
store.set_task_status(first.task_id, TaskStatus.COMPLETED)
|
||||
|
||||
second = create_project_tasks(store, root)
|
||||
|
||||
assert len(second) == 1
|
||||
assert second[0].name == 'a.prj (2)'
|
||||
assert second[0].primary_project_id != first.primary_project_id
|
||||
|
||||
|
||||
def test_target_rules_preserve_distinct_subsets_of_same_old_part():
|
||||
rows = (
|
||||
TargetPlanRow(target('u1', 'R1'), True, 'NEW-A'),
|
||||
TargetPlanRow(target('u2', 'R2'), False, ''),
|
||||
TargetPlanRow(target('u3', 'R3'), True, 'NEW-B', True, 'VALUE', False),
|
||||
)
|
||||
|
||||
rules = compile_target_rules(rows)
|
||||
|
||||
assert len(rules) == 2
|
||||
assert {(rule.new_part_number, tuple(item.uid for item in rule.targets)) for rule in rules} == {
|
||||
('NEW-A', ('u1',)), ('NEW-B', ('u3',))
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize('new_part', ['', 'OLD'])
|
||||
def test_enabled_target_requires_valid_replacement(new_part):
|
||||
with pytest.raises(TaskCenterError):
|
||||
compile_target_rules((TargetPlanRow(target('u1', 'R1'), True, new_part),))
|
||||
|
||||
|
||||
def test_empty_target_group_rejected():
|
||||
from dx_productivity.trial_task_center.target_plan import TargetRule
|
||||
|
||||
with pytest.raises(TaskCenterError):
|
||||
TargetRule('OLD', 'NEW', ())
|
||||
|
||||
|
||||
def test_plan_edit_is_atomic_and_survives_reopen(tmp_path):
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
task = store.create_task('board')
|
||||
path = tmp_path / 'board.prj'
|
||||
store.sync_projects(task.task_id, tmp_path, (path,))
|
||||
base = ComponentTarget(path, 'MAIN', '1', 'u1', 'R1', 'OLD', 'V0')
|
||||
store.record_target_inventory(task.task_id, (base,))
|
||||
saved = store.replace_target_plan(task.task_id, (TargetPlanRow(base, True, 'NEW', True, 'V1', False),))
|
||||
assert saved[0].new_part_number == 'NEW'
|
||||
with pytest.raises(TaskCenterError):
|
||||
forged = ComponentTarget(path, 'MAIN', '1', 'u1', 'R1', 'WRONG', 'V0')
|
||||
store.replace_target_plan(task.task_id, (TargetPlanRow(forged, True, 'OTHER'),))
|
||||
assert store.list_target_plan(task.task_id) == saved
|
||||
store.close()
|
||||
reopened = TaskStore(tmp_path / 'tasks.db')
|
||||
assert reopened.list_target_plan(task.task_id) == saved
|
||||
|
||||
|
||||
def test_plan_rejects_duplicate_uid_and_chain(tmp_path):
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
task = store.create_task('board')
|
||||
path = tmp_path / 'board.prj'
|
||||
store.sync_projects(task.task_id, tmp_path, (path,))
|
||||
a = ComponentTarget(path, 'MAIN', '1', 'u1', 'R1', 'OLD', '')
|
||||
b = ComponentTarget(path, 'MAIN', '1', 'u2', 'R2', 'NEW', '')
|
||||
store.record_target_inventory(task.task_id, (a, b))
|
||||
with pytest.raises(TaskCenterError):
|
||||
store.replace_target_plan(task.task_id, (TargetPlanRow(a), TargetPlanRow(a)))
|
||||
with pytest.raises(TaskCenterError):
|
||||
store.replace_target_plan(task.task_id, (TargetPlanRow(a, True, 'NEW'), TargetPlanRow(b, True, 'NEXT')))
|
||||
|
||||
|
||||
def test_forged_initial_plan_cannot_create_inventory(tmp_path):
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
task = store.create_task('board')
|
||||
path = tmp_path / 'board.prj'
|
||||
store.sync_projects(task.task_id, tmp_path, (path,))
|
||||
forged = ComponentTarget(path, 'MAIN', '1', 'forged', 'R1', 'OLD', '')
|
||||
with pytest.raises(TaskCenterError):
|
||||
store.replace_target_plan(task.task_id, (TargetPlanRow(forged, True, 'NEW'),))
|
||||
assert store.get_task(task.task_id).target_plan_mode is False
|
||||
|
||||
|
||||
def test_purge_deletes_target_plan_with_its_task(tmp_path):
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
task = store.create_task('board')
|
||||
path = tmp_path / 'board.prj'
|
||||
store.sync_projects(task.task_id, tmp_path, (path,))
|
||||
store.record_target_inventory(task.task_id, (ComponentTarget(path, 'MAIN', '1', 'u1', 'R1', 'OLD', ''),))
|
||||
store.soft_delete_task(task.task_id)
|
||||
|
||||
assert store.purge_task(task.task_id) == task.task_id
|
||||
assert store.list_tasks() == ()
|
||||
|
||||
|
||||
def test_schema_five_migrates_without_changing_historic_task_and_rules(tmp_path):
|
||||
import sqlite3
|
||||
|
||||
path = tmp_path / 'tasks.db'
|
||||
store = TaskStore(path)
|
||||
task = store.create_task('historic')
|
||||
rule = store.add_rule(task.task_id, 'OLD', 'NEW')
|
||||
store.close()
|
||||
connection = sqlite3.connect(path)
|
||||
connection.execute('DROP TABLE target_plan')
|
||||
for column in ('target_plan_mode', 'primary_project_id', 'group_position', 'group_id'):
|
||||
connection.execute(f'ALTER TABLE tasks DROP COLUMN {column}')
|
||||
connection.execute("UPDATE metadata SET value = '5' WHERE key = 'schema_version'")
|
||||
connection.commit()
|
||||
connection.close()
|
||||
|
||||
migrated = TaskStore(path)
|
||||
|
||||
assert migrated.get_task(task.task_id).name == 'historic'
|
||||
assert migrated.get_task(task.task_id).target_plan_mode is False
|
||||
assert migrated.list_rules(task.task_id) == (rule,)
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Backup coordination keeps durable state independent of CAD execution."""
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
|
||||
|
||||
def test_backup_failure_is_durable_before_propagating(tmp_path):
|
||||
from dx_productivity.trial_task_center.batch_backup import BatchBackupCoordinator
|
||||
project = tmp_path / 'board.prj'
|
||||
project.write_text('project')
|
||||
root = tmp_path / 'queue'
|
||||
session = SimpleNamespace(handoff=SimpleNamespace(command_path=root / 'command.tsv'),
|
||||
commands=(), latest={}, next_index=0)
|
||||
service = SimpleNamespace(_quick_run_preparer=SimpleNamespace(data_root=tmp_path / 'data'),
|
||||
_logging=None)
|
||||
writes = []
|
||||
def fail(*args):
|
||||
raise TaskCenterError('quick_run_backup', 'backup failed')
|
||||
def write(path, task_id, state):
|
||||
writes.append((path, task_id, dict(state)))
|
||||
coordinator = BatchBackupCoordinator(service, 't', session,
|
||||
(SimpleNamespace(path=project),), continue_after_failure=False,
|
||||
backup=fail, write_state=write)
|
||||
coordinator.perform_backup = lambda *args: fail()
|
||||
with coordinator, pytest.raises(TaskCenterError, match='backup failed'):
|
||||
coordinator.prepare(project, SimpleNamespace())
|
||||
assert writes[0][1] == 't'
|
||||
assert next(iter(writes[0][2].values()))['status'] == 'unbacked'
|
||||
@@ -0,0 +1,49 @@
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from openpyxl import Workbook
|
||||
|
||||
from dx_productivity.trial_task_center.bom_plan import BOM_HEADERS, read_bom_plan, write_bom_template
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
from dx_productivity.trial_task_center.target_plan import ComponentTarget
|
||||
|
||||
|
||||
def setup_store(tmp_path):
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
task = store.create_task('board')
|
||||
path = tmp_path / 'board.prj'
|
||||
store.sync_projects(task.task_id, tmp_path, (path,))
|
||||
targets = tuple(ComponentTarget(path, 'MAIN', '1', uid, ref, 'OLD', value)
|
||||
for uid, ref, value in (('u1', 'R1', '10nF'), ('u2', 'R2', '22nF'), ('u3', 'C1', '1uF')))
|
||||
store.record_target_inventory(task.task_id, targets)
|
||||
return store, task, targets
|
||||
|
||||
|
||||
def test_bom_template_expands_one_to_many_refdes_and_preserves_unlisted_targets(tmp_path):
|
||||
store, task, targets = setup_store(tmp_path)
|
||||
path = tmp_path / 'bom.xlsx'
|
||||
write_bom_template(path, (
|
||||
{'old_part_number': 'OLD', 'new_part_number': 'NEW-A', 'refdes': 'R1, R2',
|
||||
'enabled': '是', 'sync_nc': '否', 'custom_value': '10nF'},
|
||||
))
|
||||
rows = read_bom_plan(store, task.task_id, path)
|
||||
by_ref = {row.target.refdes: row for row in rows}
|
||||
assert by_ref['R1'].enabled and by_ref['R2'].enabled
|
||||
assert not by_ref['R1'].sync_nc
|
||||
assert not by_ref['C1'].enabled
|
||||
store.close()
|
||||
|
||||
|
||||
def test_bom_rejects_unknown_or_ambiguous_refdes_and_formulas(tmp_path):
|
||||
store, task, _ = setup_store(tmp_path)
|
||||
path = tmp_path / 'bom.xlsx'
|
||||
write_bom_template(path, ({'old_part_number': 'OLD', 'new_part_number': 'NEW', 'refdes': 'R9'},))
|
||||
with pytest.raises(TaskCenterError, match='R9'):
|
||||
read_bom_plan(store, task.task_id, path)
|
||||
workbook = Workbook(); sheet = workbook.active; sheet.append(BOM_HEADERS)
|
||||
sheet.append(['OLD', '=A2', 'R1', '', '', '', True, '', True])
|
||||
workbook.save(path)
|
||||
with pytest.raises(TaskCenterError, match='公式'):
|
||||
read_bom_plan(store, task.task_id, path)
|
||||
store.close()
|
||||
@@ -0,0 +1,65 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.trial_task_center import cad_identity as identity
|
||||
|
||||
|
||||
def environment(**changes):
|
||||
return {'DXPART_DESKTOP': 'dx-test', 'DXPART_CAD_PID': '123',
|
||||
'DXPART_CAD_GUID': '{owned}', 'DXPART_SESSION_TOKEN': 'a' * 32, **changes}
|
||||
|
||||
|
||||
def test_partial_identity_is_rejected_instead_of_using_interactive_cad():
|
||||
with pytest.raises(ValueError, match='incomplete'):
|
||||
identity.CadBinding.from_environment({'DXPART_DESKTOP': 'dx-test'})
|
||||
|
||||
|
||||
def test_identity_checks_desktop_before_reading_com(monkeypatch):
|
||||
binding = identity.CadBinding.from_environment(environment())
|
||||
monkeypatch.setattr(identity, 'current_desktop_name', lambda: 'Default')
|
||||
with pytest.raises(ValueError, match='desktop'):
|
||||
identity.verify_application(object(), binding)
|
||||
|
||||
|
||||
def test_foreign_com_guid_is_rejected_before_project_access(monkeypatch):
|
||||
binding = identity.CadBinding.from_environment(environment())
|
||||
monkeypatch.setattr(identity, 'current_desktop_name', lambda: 'dx-test')
|
||||
with pytest.raises(ValueError, match='GUID'):
|
||||
identity.verify_application(SimpleNamespace(Guid=lambda: '{foreign}'), binding)
|
||||
|
||||
|
||||
def test_foreign_view_pid_is_rejected(monkeypatch):
|
||||
binding = identity.CadBinding.from_environment(environment())
|
||||
monkeypatch.setattr(identity, 'current_desktop_name', lambda: 'dx-test')
|
||||
monkeypatch.setattr(identity, 'window_pid', lambda _: 456)
|
||||
app = SimpleNamespace(Guid=lambda: '{owned}', ActiveViewHandle=7)
|
||||
with pytest.raises(ValueError, match='PID'):
|
||||
identity.verify_application(app, binding)
|
||||
|
||||
|
||||
def test_owned_app_matches_certificate_and_window_pid(monkeypatch):
|
||||
binding = identity.CadBinding.from_environment(environment())
|
||||
monkeypatch.setattr(identity, 'current_desktop_name', lambda: 'dx-test')
|
||||
monkeypatch.setattr(identity, 'window_pid', lambda _: 123)
|
||||
assert identity.verify_application(SimpleNamespace(Guid=lambda: '{owned}', ActiveViewHandle=7), binding) == binding
|
||||
|
||||
|
||||
def test_no_identity_retains_explicit_legacy_helper_compatibility():
|
||||
assert identity.CadBinding.from_environment({}) is None
|
||||
|
||||
|
||||
def test_closed_project_does_not_treat_stale_view_handle_as_current_pid(monkeypatch):
|
||||
binding = identity.CadBinding.from_environment(environment())
|
||||
monkeypatch.setattr(identity, 'current_desktop_name', lambda: 'dx-test')
|
||||
monkeypatch.setattr(identity, 'window_pid', lambda _: 456)
|
||||
app = SimpleNamespace(Guid=lambda: '{owned}', ActiveViewHandle=7)
|
||||
assert identity.verify_application(app, binding, require_view=False) == binding
|
||||
with pytest.raises(ValueError, match='PID'):
|
||||
identity.verify_application(app, binding)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('pid', ['0', '-1', 'abc'])
|
||||
def test_invalid_pid_cannot_become_an_owned_cad(pid):
|
||||
with pytest.raises(ValueError):
|
||||
identity.CadBinding.from_environment(environment(DXPART_CAD_PID=pid))
|
||||
@@ -0,0 +1,330 @@
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer, _ProjectDiscovery
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
from dx_productivity.trial_task_center.target_plan import ComponentTarget
|
||||
|
||||
|
||||
def prepared(tmp_path):
|
||||
root = tmp_path / 'project'
|
||||
root.mkdir()
|
||||
project = root / 'board.prj'
|
||||
project.write_text('project')
|
||||
(root / 'sch').mkdir()
|
||||
(root / 'sch' / 'MAIN.1').write_text('sheet')
|
||||
preparer = QuickRunPreparer(tmp_path / 'data')
|
||||
calls = []
|
||||
def discover(path, parts, *, collect_components=False):
|
||||
calls.append((parts, collect_components))
|
||||
return _ProjectDiscovery((('MAIN', '1'),), {('MAIN', '1'): frozenset({'old'})}, (ComponentTarget(path, 'MAIN', '1', 'uid', 'R1', 'old', 'value'),) if collect_components else ())
|
||||
preparer._discover_project_sheets = discover
|
||||
return project, preparer, calls
|
||||
|
||||
|
||||
def test_inventory_discovery_reused_by_sheet_discovery(tmp_path):
|
||||
project, preparer, calls = prepared(tmp_path)
|
||||
assert preparer.collect_inventory(project, ('old',))[0].refdes == 'R1'
|
||||
assert preparer.discover_project(project, ('OLD',)).sheets == (('MAIN', '1'),)
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize('change', ['edit', 'add', 'delete', 'replace'])
|
||||
def test_project_content_changes_invalidate_cache(tmp_path, change):
|
||||
project, preparer, calls = prepared(tmp_path)
|
||||
preparer.discover_project(project, ('old',))
|
||||
sheet = project.parent / 'sch' / 'MAIN.1'
|
||||
if change == 'edit':
|
||||
sheet.write_text('changed sheet')
|
||||
elif change == 'add':
|
||||
sheet.with_name('MAIN.2').write_text('new sheet')
|
||||
elif change == 'delete':
|
||||
sheet.unlink()
|
||||
else:
|
||||
replacement = sheet.with_suffix('.new')
|
||||
replacement.write_text('sheet')
|
||||
replacement.replace(sheet)
|
||||
preparer.discover_project(project, ('old',))
|
||||
assert len(calls) == 2
|
||||
|
||||
|
||||
def test_expanded_parts_and_component_request_need_new_discovery(tmp_path):
|
||||
project, preparer, calls = prepared(tmp_path)
|
||||
preparer.discover_project(project, ('old',))
|
||||
preparer.discover_project(project, ('old', 'other'))
|
||||
preparer.collect_inventory(project, ('old', 'other'))
|
||||
assert len(calls) == 3
|
||||
|
||||
|
||||
def test_changed_during_discovery_is_not_cached(tmp_path):
|
||||
project, preparer, calls = prepared(tmp_path)
|
||||
original = preparer._discover_project_sheets
|
||||
def changing(*args, **kwargs):
|
||||
result = original(*args, **kwargs)
|
||||
(project.parent / 'sch' / 'MAIN.1').write_text(str(len(calls)))
|
||||
return result
|
||||
preparer._discover_project_sheets = changing
|
||||
with pytest.raises(TaskCenterError, match='changed'):
|
||||
preparer.discover_project(project, ('old',))
|
||||
with pytest.raises(TaskCenterError, match='changed'):
|
||||
preparer.discover_project(project, ('old',))
|
||||
assert len(calls) == 4
|
||||
|
||||
|
||||
def test_clone_has_independent_cache_and_configuration(tmp_path):
|
||||
project, preparer, calls = prepared(tmp_path)
|
||||
preparer.discover_project(project, ('old',))
|
||||
clone = preparer.for_data_root(tmp_path / 'task-two')
|
||||
assert clone.data_root == tmp_path / 'task-two'
|
||||
clone._discover_project_sheets = preparer._discover_project_sheets
|
||||
clone.discover_project(project, ('old',))
|
||||
assert len(calls) == 2
|
||||
|
||||
|
||||
def test_explicit_invalidation_discards_discovery(tmp_path):
|
||||
project, preparer, calls = prepared(tmp_path)
|
||||
preparer.discover_project(project, ('old',))
|
||||
preparer.invalidate_discovery(project)
|
||||
preparer.discover_project(project, ('old',))
|
||||
assert len(calls) == 2
|
||||
|
||||
|
||||
def queue_records(project):
|
||||
from dx_productivity.trial_task_center.models import ProjectRecord, ProjectStatus, RuleRecord
|
||||
return ((ProjectRecord('p', 't', 'board', project, project.parent, True, True,
|
||||
ProjectStatus.PENDING, 0),),
|
||||
(RuleRecord('r', 't', 0, 'old', 'new', True),))
|
||||
|
||||
|
||||
def test_handoff_reuses_collected_inventory_without_second_cad_open(tmp_path):
|
||||
project, preparer, calls = prepared(tmp_path)
|
||||
projects, rules = queue_records(project)
|
||||
preparer.collect_inventory(project, ('old',))
|
||||
handoff = preparer.ensure_batch_handoff('t', projects, rules)
|
||||
assert 'MAIN' in handoff.command_path.read_text(encoding='utf-8')
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
def test_failed_worker_invalidates_before_it_runs(tmp_path):
|
||||
project, preparer, calls = prepared(tmp_path)
|
||||
projects, rules = queue_records(project)
|
||||
preparer.collect_inventory(project, ('old',))
|
||||
preparer.ensure_batch_handoff('t', projects, rules)
|
||||
preparer._cscript_resolver = lambda: Path('cscript.exe')
|
||||
def fail(command, timeout):
|
||||
preparer.discover_project(project, ('old',))
|
||||
assert len(calls) == 2
|
||||
raise OSError('cannot launch')
|
||||
preparer._process_runner = fail
|
||||
with pytest.raises(TaskCenterError):
|
||||
preparer.execute_step('t', projects, rules, batch_mode=True)
|
||||
assert len(calls) == 2
|
||||
|
||||
|
||||
def test_failed_or_incomplete_discovery_never_cached(tmp_path):
|
||||
project, preparer, calls = prepared(tmp_path)
|
||||
def incomplete(path, parts):
|
||||
calls.append(parts)
|
||||
return _ProjectDiscovery((('MAIN', '1'),), {})
|
||||
preparer._discover_project_sheets = incomplete
|
||||
preparer.discover_project(project, ('old',))
|
||||
preparer.discover_project(project, ('old',))
|
||||
assert len(calls) == 2
|
||||
def fail(path, parts):
|
||||
calls.append(parts)
|
||||
raise TaskCenterError('discovery', 'failed')
|
||||
preparer._discover_project_sheets = fail
|
||||
for _ in range(2):
|
||||
with pytest.raises(TaskCenterError):
|
||||
preparer.discover_project(project, ('old',))
|
||||
assert len(calls) == 4
|
||||
|
||||
|
||||
def test_cached_results_cannot_be_poisoned_by_callers(tmp_path):
|
||||
project, preparer, calls = prepared(tmp_path)
|
||||
result = preparer.discover_project(project, ('old',))
|
||||
result.matched_old_parts.clear()
|
||||
result = preparer.discover_project(project, ('old',))
|
||||
assert result.matched_old_parts == {('MAIN', '1'): frozenset({'old'})}
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
def test_generated_logs_and_tool_evidence_do_not_invalidate(tmp_path):
|
||||
project, preparer, calls = prepared(tmp_path)
|
||||
preparer.discover_project(project, ('old',))
|
||||
(project.parent / 'designer.log').write_text('generated log')
|
||||
preparer.discover_project(project, ('old',))
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
def test_component_collection_filters_cached_superset_to_requested_parts(tmp_path):
|
||||
project, preparer, calls = prepared(tmp_path)
|
||||
def discover(path, parts, *, collect_components=False):
|
||||
calls.append(parts)
|
||||
rows = tuple(ComponentTarget(path, 'MAIN', '1', part, part, part, '') for part in parts)
|
||||
return _ProjectDiscovery((('MAIN', '1'),), {('MAIN', '1'): frozenset(parts)}, rows)
|
||||
preparer._discover_project_sheets = discover
|
||||
preparer.collect_inventory(project, ('old', 'other'))
|
||||
rows = preparer.collect_inventory(project, ('OLD',))
|
||||
assert [row.old_part_number for row in rows] == ['old']
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
def test_tool_evidence_inside_project_tree_is_excluded(tmp_path):
|
||||
project, preparer, calls = prepared(tmp_path)
|
||||
preparer = preparer.for_data_root(project.parent / '.tool-data')
|
||||
def discover(path, parts):
|
||||
calls.append(parts)
|
||||
preparer.data_root.mkdir(exist_ok=True)
|
||||
(preparer.data_root / 'generated.tsv').write_text(str(len(calls)))
|
||||
return _ProjectDiscovery((('MAIN', '1'),), {('MAIN', '1'): frozenset({'old'})})
|
||||
preparer._discover_project_sheets = discover
|
||||
preparer.discover_project(project, ('old',))
|
||||
preparer.discover_project(project, ('old',))
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
def test_same_size_schematic_edit_with_restored_mtime_rechecks_negative_matches(tmp_path):
|
||||
import os
|
||||
project, preparer, calls = prepared(tmp_path)
|
||||
sheet = project.parent / 'sch' / 'MAIN.1'
|
||||
sheet.write_text('nohit', encoding='ascii')
|
||||
def discover(path, parts):
|
||||
calls.append(parts)
|
||||
matches = frozenset({'old'}) if sheet.read_text(encoding='ascii') == 'oldxx' else frozenset()
|
||||
return _ProjectDiscovery((('MAIN', '1'),), {('MAIN', '1'): matches})
|
||||
preparer._discover_project_sheets = discover
|
||||
assert preparer.discover_project(project, ('old',)).matched_old_parts[('MAIN', '1')] == frozenset()
|
||||
original = sheet.stat()
|
||||
sheet.write_text('oldxx', encoding='ascii')
|
||||
os.utime(sheet, ns=(original.st_atime_ns, original.st_mtime_ns))
|
||||
assert sheet.stat().st_size == original.st_size
|
||||
assert sheet.stat().st_mtime_ns == original.st_mtime_ns
|
||||
assert preparer.discover_project(project, ('old',)).matched_old_parts[('MAIN', '1')] == frozenset({'old'})
|
||||
assert len(calls) == 2
|
||||
|
||||
|
||||
def test_file_changed_during_hashing_has_no_reusable_fingerprint(tmp_path, monkeypatch):
|
||||
import hashlib
|
||||
from dx_productivity.trial_task_center.discovery_cache import project_fingerprint
|
||||
project, preparer, _ = prepared(tmp_path)
|
||||
sheet = project.parent / 'sch' / 'MAIN.1'
|
||||
digest = hashlib.file_digest
|
||||
def changing(stream, algorithm):
|
||||
result = digest(stream, algorithm)
|
||||
if Path(stream.name) == sheet:
|
||||
sheet.write_bytes(b'changed while hashing')
|
||||
return result
|
||||
monkeypatch.setattr(hashlib, 'file_digest', changing)
|
||||
assert project_fingerprint(project, preparer.data_root) is None
|
||||
|
||||
|
||||
def test_first_open_normalization_retries_and_caches_only_stable_second_pass(tmp_path):
|
||||
project, preparer, calls = prepared(tmp_path)
|
||||
database = project.parent / 'database'
|
||||
database.mkdir()
|
||||
icdb = database / 'icdb.dat'
|
||||
icdb.write_text('old database')
|
||||
ole = project.parent / 'OLE' / 'sch'
|
||||
ole.mkdir(parents=True)
|
||||
ole_sheet = ole / 'MAIN.1'
|
||||
ole_sheet.write_text('old normalized data')
|
||||
def normalize_once(path, parts, *, collect_components=False):
|
||||
calls.append(parts)
|
||||
if len(calls) == 1:
|
||||
icdb.write_text('normalized database')
|
||||
ole_sheet.write_text('normalized schematic')
|
||||
return _ProjectDiscovery((('MAIN', '1'),), {('MAIN', '1'): frozenset()})
|
||||
return _ProjectDiscovery((('MAIN', '1'),), {('MAIN', '1'): frozenset({'old'})})
|
||||
preparer._discover_project_sheets = normalize_once
|
||||
assert preparer.discover_project(project, ('old',)).matched_old_parts[('MAIN', '1')] == frozenset({'old'})
|
||||
assert len(calls) == 2
|
||||
assert preparer.discover_project(project, ('old',)).matched_old_parts[('MAIN', '1')] == frozenset({'old'})
|
||||
assert len(calls) == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize('directory', ['log', 'plog', 'events'])
|
||||
def test_cdbsvr_audit_churn_does_not_rediscover(tmp_path, directory):
|
||||
project, preparer, calls = prepared(tmp_path)
|
||||
audit = project.parent / 'database' / 'cdbsvr' / directory
|
||||
audit.mkdir(parents=True)
|
||||
audit_file = audit / '000001.dat'
|
||||
audit_file.write_text('audit')
|
||||
original = preparer._discover_project_sheets
|
||||
def audit_during_discovery(*args, **kwargs):
|
||||
result = original(*args, **kwargs)
|
||||
audit_file.write_text('audit grew during native open')
|
||||
return result
|
||||
preparer._discover_project_sheets = audit_during_discovery
|
||||
preparer.discover_project(project, ('old',))
|
||||
audit_file.write_text('audit changed again after native close')
|
||||
(audit / '000002.dat').write_text('new audit')
|
||||
preparer.discover_project(project, ('old',))
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize('relative', ['database/icdb.dat', 'OLE/sch/MAIN.1', 'sch/MAIN.1'])
|
||||
def test_authoritative_same_size_content_changes_are_hashed_despite_restored_timestamps(tmp_path, relative):
|
||||
import os
|
||||
project, preparer, calls = prepared(tmp_path)
|
||||
authoritative = project.parent / relative
|
||||
authoritative.parent.mkdir(parents=True, exist_ok=True)
|
||||
authoritative.write_bytes(b'nohit')
|
||||
def discover(path, parts):
|
||||
calls.append(parts)
|
||||
matches = frozenset({'old'}) if authoritative.read_bytes() == b'oldxx' else frozenset()
|
||||
return _ProjectDiscovery((('MAIN', '1'),), {('MAIN', '1'): matches})
|
||||
preparer._discover_project_sheets = discover
|
||||
assert not preparer.discover_project(project, ('old',)).matched_old_parts[('MAIN', '1')]
|
||||
stamp = authoritative.stat()
|
||||
authoritative.write_bytes(b'oldxx')
|
||||
os.utime(authoritative, ns=(stamp.st_atime_ns, stamp.st_mtime_ns))
|
||||
assert preparer.discover_project(project, ('old',)).matched_old_parts[('MAIN', '1')] == frozenset({'old'})
|
||||
assert len(calls) == 2
|
||||
|
||||
|
||||
def test_unstable_rediscovery_never_falls_back_to_cached_negative_matches(tmp_path):
|
||||
project, preparer, calls = prepared(tmp_path)
|
||||
sheet = project.parent / 'sch' / 'MAIN.1'
|
||||
def negative(path, parts):
|
||||
calls.append(parts)
|
||||
return _ProjectDiscovery((('MAIN', '1'),), {('MAIN', '1'): frozenset()})
|
||||
preparer._discover_project_sheets = negative
|
||||
assert not preparer.discover_project(project, ('old',)).matched_old_parts[('MAIN', '1')]
|
||||
sheet.write_text('externally changed')
|
||||
def unstable(path, parts):
|
||||
calls.append(parts)
|
||||
sheet.write_text('changed during pass ' + str(len(calls)))
|
||||
return _ProjectDiscovery((('MAIN', '1'),), {('MAIN', '1'): frozenset({'old'})})
|
||||
preparer._discover_project_sheets = unstable
|
||||
with pytest.raises(TaskCenterError, match='changed'):
|
||||
preparer.discover_project(project, ('old',))
|
||||
assert len(calls) == 3
|
||||
def stable(path, parts):
|
||||
calls.append(parts)
|
||||
return _ProjectDiscovery((('MAIN', '1'),), {('MAIN', '1'): frozenset({'old'})})
|
||||
preparer._discover_project_sheets = stable
|
||||
assert preparer.discover_project(project, ('old',)).matched_old_parts[('MAIN', '1')] == frozenset({'old'})
|
||||
assert len(calls) == 4
|
||||
|
||||
|
||||
def test_initially_unverifiable_project_uses_fresh_discovery_without_cache(tmp_path):
|
||||
project, preparer, calls = prepared(tmp_path)
|
||||
# A project within the explicit evidence root has no reusable fingerprint.
|
||||
clone = preparer.for_data_root(project.parent)
|
||||
clone._discover_project_sheets = preparer._discover_project_sheets
|
||||
assert clone.discover_project(project, ('old',)).sheets == (('MAIN', '1'),)
|
||||
assert len(calls) == 1
|
||||
assert clone.discover_project(project, ('old',)).sheets == (('MAIN', '1'),)
|
||||
assert len(calls) == 2
|
||||
|
||||
|
||||
def test_unverifiable_retry_after_known_churn_still_fails_closed(tmp_path, monkeypatch):
|
||||
from dx_productivity.trial_task_center import discovery_cache as module
|
||||
project, preparer, calls = prepared(tmp_path)
|
||||
fingerprints = iter([('before',), ('changed',), None, None])
|
||||
monkeypatch.setattr(module, 'project_fingerprint', lambda *args: next(fingerprints))
|
||||
with pytest.raises(TaskCenterError, match='changed'):
|
||||
preparer.discover_project(project, ('old',))
|
||||
assert len(calls) == 2
|
||||
@@ -0,0 +1,37 @@
|
||||
import json
|
||||
from dx_productivity.trial_task_center.logging_setup import configure_logging
|
||||
from dx_productivity.trial_task_center.service import TaskCenterService
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
|
||||
|
||||
def test_feedback_uses_executing_child_and_ignores_previous_run_progress(tmp_path):
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
|
||||
task = service.create_task('board')
|
||||
child = service.for_project_task(task.task_id)
|
||||
child._batch_feedback = (task.task_id, None, '正在执行 board')
|
||||
service._task_queue_feedback = ('queue', task.task_id, 2, 3)
|
||||
path = child._quick_run_preparer.data_root / 'quick-run' / 'worker-progress.json'
|
||||
path.parent.mkdir(parents=True)
|
||||
path.write_text(json.dumps({'stage': 'native_replace', 'stage_seconds': {'native_replace': 1.25}}))
|
||||
value = service.execution_feedback(None, started_after=0)
|
||||
assert value.task_id == task.task_id and (value.position, value.total) == (2, 3)
|
||||
assert value.message == '正在执行 board' and value.stage == 'native_replace'
|
||||
assert value.stage_seconds >= 1.25
|
||||
stale = service.execution_feedback(None, started_after=path.stat().st_mtime + 1)
|
||||
assert stale.stage == ''
|
||||
path.write_text('incomplete JSON')
|
||||
assert service.execution_feedback(None, started_after=0).stage == ''
|
||||
store.close()
|
||||
def test_private_startup_and_shutdown_override_stale_worker_phase(tmp_path):
|
||||
import json
|
||||
from dx_productivity.trial_task_center.execution_feedback import read_feedback
|
||||
root = tmp_path / 'quick-run'
|
||||
root.mkdir()
|
||||
(root / 'worker-progress.json').write_text(json.dumps({'stage': 'capture'}))
|
||||
private = root / 'private-desktop.json'
|
||||
for state, expected in [('starting', 'private_startup'), ('closing', 'private_shutdown')]:
|
||||
private.write_text(json.dumps({'state': state}))
|
||||
assert read_feedback('task', 1, 1, 'running', tmp_path, 0).stage == expected
|
||||
private.write_text(json.dumps({'state': 'released'}))
|
||||
assert read_feedback('task', 1, 1, 'running', tmp_path, 0).stage == 'capture'
|
||||
@@ -0,0 +1,102 @@
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.trial_task_center import worker_monitor
|
||||
from dx_productivity.trial_task_center.logging_setup import configure_logging
|
||||
|
||||
|
||||
def test_phase_timing_records_completed_units_and_failure_without_success(tmp_path, monkeypatch):
|
||||
from dx_productivity.trial_task_center import execution_metrics
|
||||
|
||||
clock = iter((10.0, 12.0, 20.0, 23.0))
|
||||
monkeypatch.setattr(execution_metrics.time, 'perf_counter', lambda: next(clock))
|
||||
logging = configure_logging(tmp_path)
|
||||
with execution_metrics.measure_phase(logging, 'task', 'execute_step', unit='step') as metric:
|
||||
metric['completed_units'] = 1
|
||||
metric['state'] = 'saved_ok'
|
||||
with pytest.raises(RuntimeError, match='worker failed'):
|
||||
with execution_metrics.measure_phase(logging, 'task', 'execute_step', unit='step'):
|
||||
raise RuntimeError('worker failed')
|
||||
events = [json.loads(line) for line in (tmp_path / 'tasks/task/events.jsonl').read_text().splitlines()]
|
||||
assert events[0]['details']['elapsed_seconds'] == 2
|
||||
assert events[0]['details']['units_per_minute'] == 30
|
||||
assert events[0]['details']['state'] == 'saved_ok'
|
||||
assert events[1]['details']['elapsed_seconds'] == 3
|
||||
assert events[1]['details']['state'] == 'error'
|
||||
assert events[1]['details']['completed_units'] == 0
|
||||
|
||||
|
||||
def test_worker_stages_include_repeated_stages_without_double_counting():
|
||||
watch = worker_monitor.ProgressWatch('token', 'job', 150, 0)
|
||||
def frame(n, stage):
|
||||
return f'DX_PROGRESS\ttoken\tjob\t{n}\t{stage}\t0\t1\t1\n'.encode()
|
||||
assert watch.accept(frame(1, 'capture'), 2)
|
||||
assert watch.accept(frame(2, 'native_replace'), 5)
|
||||
assert not watch.accept(frame(2, 'ignored'), 100)
|
||||
assert watch.accept(frame(3, 'capture'), 9)
|
||||
snapshot = watch.snapshot(now=12)
|
||||
assert snapshot['elapsed_seconds'] == 12
|
||||
assert snapshot['stage_seconds'] == {'starting': 2, 'capture': 6, 'native_replace': 4}
|
||||
assert sum(snapshot['stage_seconds'].values()) == snapshot['elapsed_seconds']
|
||||
assert watch.snapshot(now=12) == snapshot
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != 'nt', reason='Windows Script Host path compatibility')
|
||||
def test_long_evidence_path_remains_visible_to_real_vbs(tmp_path):
|
||||
from dx_productivity.trial_task_center.quick_run import _vbs_worker_paths, _resolve_cscript
|
||||
|
||||
root = tmp_path / ('evidence-' + 'x' * 80) / ('discovery-' + 'y' * 60)
|
||||
root.mkdir(parents=True)
|
||||
script = root / 'QuickPartReplace.vbs'
|
||||
script.write_text("Set f=CreateObject(\"Scripting.FileSystemObject\")\n"
|
||||
"WScript.Echo CStr(f.FileExists(f.BuildPath(WScript.Arguments(0), WScript.Arguments(1))))\n")
|
||||
marker = 'monitor-' + 'a' * 32 + '.ready'
|
||||
(root / marker).write_text('token')
|
||||
assert len(str(root / marker)) > 259
|
||||
script_arg, root_arg = _vbs_worker_paths(script, root)
|
||||
result = subprocess.run((str(_resolve_cscript()), '//nologo', script_arg, root_arg, marker),
|
||||
capture_output=True, text=True, timeout=10)
|
||||
assert result.returncode == 0 and result.stdout.strip() == 'True'
|
||||
|
||||
|
||||
def test_external_status_append_blocks_next_worker_before_cad_write(tmp_path):
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
|
||||
from dx_productivity.trial_task_center.service import TaskCenterService
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
|
||||
root = tmp_path / 'projects'; root.mkdir()
|
||||
(root / 'board.prj').write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
|
||||
data = tmp_path / 'data'; calls = []
|
||||
def worker(command, timeout):
|
||||
calls.append(command[-1])
|
||||
with (Path(command[3]) / 'status.tsv').open('a', encoding='utf-8') as stream:
|
||||
stream.write(f'{command[-1]}\tno_match\tbatch_closed\tnot found\n')
|
||||
return subprocess.CompletedProcess(command, 0, '', '')
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
preparer = QuickRunPreparer(data, process_runner=worker, cscript_resolver=lambda: Path('cscript'),
|
||||
sheet_discoverer=lambda _: (('MAIN', '1'),))
|
||||
service = TaskCenterService(store, configure_logging(data), quick_run_preparer=preparer)
|
||||
task = service.create_project_tasks(root)[0]
|
||||
service.add_rule(task.task_id, 'A', 'B'); service.add_rule(task.task_id, 'C', 'D')
|
||||
child = service.for_project_task(task.task_id)._quick_run_preparer
|
||||
original = child.execute_step
|
||||
def inject(*args, **kwargs):
|
||||
result = original(*args, **kwargs)
|
||||
if len(calls) == 1:
|
||||
with result.status_path.open('a', encoding='utf-8') as stream:
|
||||
stream.write('foreign_job\tno_match\tbatch_closed\tchanged externally\n')
|
||||
return result
|
||||
child.execute_step = inject
|
||||
progress = service.quick_run_progress(task.task_id)
|
||||
with pytest.raises(TaskCenterError):
|
||||
service.execute_quick_run_queue(task.task_id,
|
||||
expected_item=(str(progress.next_project_path), 'A', 'B', 'preserve'), stop_event=Event())
|
||||
assert len(calls) == 1
|
||||
assert (child._data_root / 'quick-run/uncertain.flag').exists()
|
||||
store.close()
|
||||
@@ -0,0 +1,36 @@
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
from dx_productivity.trial_task_center.inventory import read_component_inventory
|
||||
|
||||
|
||||
def test_inventory_reads_distinct_uids_on_same_sheet(tmp_path):
|
||||
project = tmp_path / 'board.prj'
|
||||
inventory = tmp_path / 'components.tsv'
|
||||
inventory.write_text(
|
||||
'project_path\tschematic_name\tsheet_number\tuid\trefdes\told_part\told_value\n'
|
||||
f'{project}\tMAIN\t1\tu1\tR1\tOLD\tV1\n'
|
||||
f'{project}\tMAIN\t1\tu2\tR2\tOLD\tV2\n', encoding='utf-8')
|
||||
|
||||
rows = read_component_inventory(inventory, project, (('MAIN', '1'),))
|
||||
|
||||
assert [(row.uid, row.refdes, row.old_value) for row in rows] == [
|
||||
('u1', 'R1', 'V1'), ('u2', 'R2', 'V2')]
|
||||
|
||||
|
||||
def test_inventory_rejects_forged_sheet_or_duplicate_uid(tmp_path):
|
||||
project = tmp_path / 'board.prj'
|
||||
inventory = tmp_path / 'components.tsv'
|
||||
inventory.write_text(
|
||||
'project_path\tschematic_name\tsheet_number\tuid\trefdes\told_part\told_value\n'
|
||||
f'{project}\tOTHER\t1\tu1\tR1\tOLD\tV1\n', encoding='utf-8')
|
||||
with pytest.raises(TaskCenterError):
|
||||
read_component_inventory(inventory, project, (('MAIN', '1'),))
|
||||
inventory.write_text(
|
||||
'project_path\tschematic_name\tsheet_number\tuid\trefdes\told_part\told_value\n'
|
||||
f'{project}\tMAIN\t1\tu1\tR1\tOLD\tV1\n'
|
||||
f'{project}\tMAIN\t1\tu1\tR1\tOLD\tV1\n', encoding='utf-8')
|
||||
with pytest.raises(TaskCenterError):
|
||||
read_component_inventory(inventory, project, (('MAIN', '1'),))
|
||||
@@ -0,0 +1,200 @@
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
from threading import Timer
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.trial_task_center import isolated_cad as runtime
|
||||
from dx_productivity.trial_task_center.worker_monitor import WorkerMonitorError
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != 'nt', reason='Windows state-file sharing semantics')
|
||||
def test_private_record_survives_a_reader_temporarily_denying_replacement(tmp_path):
|
||||
import win32con
|
||||
import win32file
|
||||
session = runtime.IsolatedCadSession(tmp_path)
|
||||
session._record(state='starting')
|
||||
held = win32file.CreateFile(str(tmp_path / 'private-desktop.json'), win32con.GENERIC_READ,
|
||||
win32con.FILE_SHARE_READ, None, win32con.OPEN_EXISTING, 0, None)
|
||||
reader_done = Timer(0.1, held.Close)
|
||||
reader_done.start()
|
||||
try:
|
||||
session._record(state='released', clean=True)
|
||||
finally:
|
||||
reader_done.join()
|
||||
current = json.loads((tmp_path / 'private-desktop.json').read_text())
|
||||
archived = json.loads((tmp_path / 'private-desktop-sessions' / (session.token + '.json')).read_text())
|
||||
assert current == archived and current['state'] == 'released' and current['clean']
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != 'nt', reason='Windows state-file sharing semantics')
|
||||
def test_private_record_reports_persistent_denial_and_keeps_previous_record(tmp_path):
|
||||
import win32con
|
||||
import win32file
|
||||
session = runtime.IsolatedCadSession(tmp_path)
|
||||
session._record(state='starting')
|
||||
held = win32file.CreateFile(str(tmp_path / 'private-desktop.json'), win32con.GENERIC_READ,
|
||||
win32con.FILE_SHARE_READ, None, win32con.OPEN_EXISTING, 0, None)
|
||||
try:
|
||||
with pytest.raises(PermissionError):
|
||||
session._record(state='released', clean=True)
|
||||
assert json.loads((tmp_path / 'private-desktop.json').read_text())['state'] == 'starting'
|
||||
finally:
|
||||
held.Close()
|
||||
|
||||
|
||||
def fake_desktop(monkeypatch, tmp_path, *, abort=None, quit_code=0, cad_exit_code=0):
|
||||
events = []
|
||||
cad = SimpleNamespace(pid=123, returncode=None)
|
||||
cad.poll = lambda: cad.returncode
|
||||
cad.wait = lambda timeout: cad.returncode
|
||||
class Desktop:
|
||||
def __init__(self, name, **kwargs):
|
||||
self.name = name
|
||||
def __enter__(self):
|
||||
events.append('create')
|
||||
return self
|
||||
def start_process(self, command, **kwargs):
|
||||
events.append(command[0])
|
||||
if command[0] == 'cad.exe':
|
||||
return cad
|
||||
action, path, pid = command
|
||||
if action == 'probe':
|
||||
Path(path).write_text(json.dumps({'desktop': self.name, 'pid': pid,
|
||||
'guid': '{owned}', 'token': kwargs['env']['DXPART_SESSION_TOKEN']}))
|
||||
if abort is not None:
|
||||
abort.set()
|
||||
else:
|
||||
cad.returncode = cad_exit_code
|
||||
return SimpleNamespace(poll=lambda: None if abort is not None else 0,
|
||||
wait=lambda timeout: quit_code, close=lambda: events.append('close-helper'),
|
||||
stderr=io.BytesIO(b'project still open'))
|
||||
def close(self):
|
||||
events.append(('release', (tmp_path / 'uncertain.flag').exists()))
|
||||
cad.returncode = 1 if cad.returncode is None else cad.returncode
|
||||
monkeypatch.setattr(runtime, 'PrivateDesktop', Desktop)
|
||||
monkeypatch.setattr(runtime, '_designer_executable', lambda: 'cad.exe')
|
||||
monkeypatch.setattr(runtime, '_helper_command', lambda action, path, pid: (action, str(path), pid))
|
||||
return events, cad
|
||||
|
||||
|
||||
def test_success_quits_owned_cad_before_releasing_desktop(monkeypatch, tmp_path):
|
||||
events, cad = fake_desktop(monkeypatch, tmp_path)
|
||||
with runtime.IsolatedCadSession(tmp_path):
|
||||
assert cad.poll() is None
|
||||
assert events.index('quit') < events.index(('release', False))
|
||||
record = json.loads((tmp_path / 'private-desktop.json').read_text())
|
||||
assert record['state'] == 'released' and record['clean']
|
||||
|
||||
|
||||
def test_repeated_session_preserves_prior_release_evidence(monkeypatch, tmp_path):
|
||||
fake_desktop(monkeypatch, tmp_path)
|
||||
with runtime.IsolatedCadSession(tmp_path) as first:
|
||||
first_token = first.token
|
||||
fake_desktop(monkeypatch, tmp_path)
|
||||
with runtime.IsolatedCadSession(tmp_path):
|
||||
pass
|
||||
records = [json.loads(path.read_text()) for path in (tmp_path / 'private-desktop-sessions').glob('*.json')]
|
||||
assert len(records) == 2 and first_token in {row['token'] for row in records}
|
||||
assert all(row['state'] == 'released' and row['clean'] for row in records)
|
||||
|
||||
|
||||
def test_hidden_private_action_dispatches_without_opening_gui(monkeypatch, tmp_path):
|
||||
from dx_productivity.trial_task_center import application
|
||||
def forbidden(*args, **kwargs):
|
||||
pytest.fail('private CAD helper must not initialize the GUI')
|
||||
monkeypatch.setattr(application, 'QApplication', forbidden)
|
||||
calls = []
|
||||
monkeypatch.setattr(runtime, 'native_action', lambda *args: calls.append(args) or 0)
|
||||
path = tmp_path / 'evidence.json'
|
||||
assert application.main(['--private-cad-action', 'probe', '--private-cad-evidence', str(path),
|
||||
'--private-cad-pid', '123']) == 0
|
||||
assert calls == [('probe', path, 123)]
|
||||
assert application.main(['--private-cad-action', 'probe']) == 2
|
||||
|
||||
|
||||
def test_private_helper_works_when_application_is_the_executable_entry_script(monkeypatch, tmp_path):
|
||||
import runpy
|
||||
import sys
|
||||
from dx_productivity.trial_task_center import application
|
||||
calls = []
|
||||
monkeypatch.setattr(runtime, 'native_action', lambda *args: calls.append(args) or 0)
|
||||
evidence = tmp_path / 'binding.json'
|
||||
monkeypatch.setattr(sys, 'argv', [application.__file__, '--private-cad-action', 'probe',
|
||||
'--private-cad-evidence', str(evidence), '--private-cad-pid', '123'])
|
||||
with pytest.raises(SystemExit) as result:
|
||||
runpy.run_path(application.__file__, run_name='__main__')
|
||||
assert result.value.code == 0
|
||||
assert calls == [('probe', evidence, 123)]
|
||||
|
||||
|
||||
def test_startup_cancellation_releases_without_waiting_for_com_timeout(monkeypatch, tmp_path):
|
||||
abort = Event()
|
||||
events, _ = fake_desktop(monkeypatch, tmp_path, abort=abort)
|
||||
with pytest.raises(WorkerMonitorError, match='cancelled'):
|
||||
with runtime.IsolatedCadSession(tmp_path, abort_event=abort):
|
||||
pytest.fail('cancelled startup entered replacement body')
|
||||
assert 'quit' not in events
|
||||
assert ('release', False) in events
|
||||
|
||||
|
||||
def test_startup_cleanup_failure_keeps_uncertain_lock(monkeypatch, tmp_path):
|
||||
abort = Event()
|
||||
fake_desktop(monkeypatch, tmp_path, abort=abort)
|
||||
session = runtime.IsolatedCadSession(tmp_path, abort_event=abort)
|
||||
def failure():
|
||||
raise OSError('owned process did not exit')
|
||||
session.desktop.close = failure
|
||||
with pytest.raises(WorkerMonitorError, match='cleanup requires reconciliation'):
|
||||
session.__enter__()
|
||||
assert (tmp_path / 'uncertain.flag').exists()
|
||||
|
||||
|
||||
def test_released_startup_failure_returns_retryable_pre_mutation_code(monkeypatch, tmp_path):
|
||||
class FailedStartup:
|
||||
def __init__(self, *args, **kwargs):
|
||||
pass
|
||||
def __enter__(self):
|
||||
raise runtime.PrivateCadStartupError('startup cancelled before project launch')
|
||||
def __exit__(self, *args):
|
||||
pytest.fail('failed enter must not enter execution')
|
||||
monkeypatch.setattr(runtime, 'IsolatedCadSession', FailedStartup)
|
||||
result = runtime.run_isolated_process(('cscript.exe', '//nologo', 'helper.vbs', str(tmp_path)), 1)
|
||||
assert result.returncode == 2
|
||||
assert 'before project launch' in result.stderr
|
||||
assert not (tmp_path / 'uncertain.flag').exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure', ['quit', 'cad_exit', 'unexpected_exit'])
|
||||
def test_uncertain_cleanup_is_durable_before_forced_owned_release(monkeypatch, tmp_path, failure):
|
||||
events, cad = fake_desktop(monkeypatch, tmp_path,
|
||||
quit_code=1 if failure == 'quit' else 0,
|
||||
cad_exit_code=7 if failure == 'cad_exit' else 0)
|
||||
with pytest.raises(WorkerMonitorError, match='reconciliation'):
|
||||
with runtime.IsolatedCadSession(tmp_path):
|
||||
if failure == 'unexpected_exit':
|
||||
cad.returncode = 9
|
||||
assert ('release', True) in events
|
||||
assert not json.loads((tmp_path / 'private-desktop.json').read_text())['clean']
|
||||
|
||||
|
||||
def test_single_step_backup_precedes_discovery_and_failure_blocks_discovery(monkeypatch, tmp_path):
|
||||
from dx_productivity.trial_task_center import single_step
|
||||
events = []
|
||||
preparer = SimpleNamespace(data_root=tmp_path,
|
||||
progress=lambda *args, **kwargs: SimpleNamespace(queue_complete=False, next_project_path=tmp_path / 'one.prj'),
|
||||
ensure_batch_handoff=lambda *args, **kwargs: events.append('discover'))
|
||||
monkeypatch.setattr(single_step, 'create_schematic_backup', lambda *args: events.append('backup'))
|
||||
single_step.prepare_private_single_step(preparer, 'task', (), (), False)
|
||||
assert events == ['backup', 'discover']
|
||||
def failed_backup(*args):
|
||||
raise OSError('backup failed')
|
||||
monkeypatch.setattr(single_step, 'create_schematic_backup', failed_backup)
|
||||
events.clear()
|
||||
with pytest.raises(OSError, match='backup failed'):
|
||||
single_step.prepare_private_single_step(preparer, 'task', (), (), False)
|
||||
assert not events
|
||||
@@ -0,0 +1,330 @@
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import os
|
||||
import sys
|
||||
from uuid import uuid4
|
||||
from types import SimpleNamespace
|
||||
import pytest
|
||||
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
from dx_productivity.trial_task_center.isolated_desktop import PrivateDesktop, build_startup_info
|
||||
from dx_productivity.trial_task_center.isolated_desktop import _Win32Api, _Win32Process
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != 'nt', reason='native Windows desktop lifetime')
|
||||
def test_release_does_not_report_success_while_another_handle_keeps_desktop_alive():
|
||||
desktop = PrivateDesktop('dx-test-' + uuid4().hex, enabled=True)
|
||||
desktop.__enter__()
|
||||
retained = subprocess.Popen((sys.executable, '-u', '-c',
|
||||
'import win32service,sys,time; h=win32service.OpenDesktop(sys.argv[1],0,False,1); print("ready",flush=True); time.sleep(30)',
|
||||
desktop.name), stdout=subprocess.PIPE)
|
||||
try:
|
||||
assert retained.stdout.readline() == b'ready\r\n'
|
||||
with pytest.raises(TaskCenterError, match='still exists'):
|
||||
desktop.close()
|
||||
finally:
|
||||
retained.terminate()
|
||||
retained.wait(timeout=5)
|
||||
retained.stdout.close()
|
||||
desktop.close()
|
||||
|
||||
|
||||
def test_startup_info_always_targets_private_desktop():
|
||||
info = build_startup_info('dx-private-test')
|
||||
assert info.lpDesktop == 'winsta0\\dx-private-test'
|
||||
|
||||
|
||||
def test_private_desktop_never_falls_back_to_input_desktop(monkeypatch):
|
||||
desktop = PrivateDesktop('dx-private-test', enabled=True)
|
||||
monkeypatch.setattr(desktop, '_create', lambda: None)
|
||||
monkeypatch.setattr(desktop, '_handle', None)
|
||||
with pytest.raises(TaskCenterError, match='private desktop'):
|
||||
desktop.start_process(('cad.exe',))
|
||||
|
||||
|
||||
class Handle:
|
||||
def __init__(self, name, events, fail_once=False):
|
||||
self.name, self.events, self.fail_once = name, events, fail_once
|
||||
self.closed = False
|
||||
|
||||
def Close(self):
|
||||
self.events.append(('close', self.name))
|
||||
if self.fail_once:
|
||||
self.fail_once = False
|
||||
raise OSError('close failed')
|
||||
self.closed = True
|
||||
|
||||
|
||||
def native_api(*, assign_error=False):
|
||||
events = []
|
||||
process_handle = Handle('process', events)
|
||||
thread = Handle('thread', events)
|
||||
job = Handle('job', events)
|
||||
state = {'running': True, 'code': 259}
|
||||
def create(*args):
|
||||
events.append(('create', args[5]))
|
||||
return process_handle, thread, 42, 43
|
||||
def assign(*_args):
|
||||
events.append(('assign',))
|
||||
if assign_error:
|
||||
raise OSError('assign failed')
|
||||
def terminate(*_args):
|
||||
events.append(('terminate',))
|
||||
state['running'] = False
|
||||
def wait(_handle, timeout):
|
||||
events.append(('wait', timeout))
|
||||
return 258 if state['running'] else 0
|
||||
api = _Win32Api.__new__(_Win32Api)
|
||||
api.con = SimpleNamespace(CREATE_NO_WINDOW=0x8000000, CREATE_SUSPENDED=4)
|
||||
api.process = SimpleNamespace(
|
||||
STARTUPINFO=lambda: SimpleNamespace(), CreateProcess=create,
|
||||
ResumeThread=lambda _thread: events.append(('resume',)),
|
||||
GetExitCodeProcess=lambda _handle: state['code'], TerminateProcess=terminate,
|
||||
)
|
||||
api.job = SimpleNamespace(
|
||||
CreateJobObject=lambda *_args: job,
|
||||
QueryInformationJobObject=lambda _job, kind: (
|
||||
{'BasicLimitInformation': {'LimitFlags': 0}} if kind == 9 else {'ActiveProcesses': int(state['running'])}),
|
||||
SetInformationJobObject=lambda *_args: events.append(('limits',)),
|
||||
AssignProcessToJobObject=assign, TerminateJobObject=terminate,
|
||||
JobObjectExtendedLimitInformation=9, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE=0x2000,
|
||||
JobObjectBasicAccountingInformation=1,
|
||||
)
|
||||
api.event = SimpleNamespace(WaitForSingleObject=wait)
|
||||
return api, events, state, process_handle, job
|
||||
|
||||
|
||||
def test_process_is_suspended_until_job_assignment():
|
||||
api, events, *_ = native_api()
|
||||
process = api.create_process(('python.exe',), 'winsta0\\private', None, None)
|
||||
assert process.pid == 42
|
||||
assert ('create', 0x8000004) in events
|
||||
assert events.index(('assign',)) < events.index(('resume',))
|
||||
|
||||
|
||||
def test_failed_job_assignment_terminates_and_reaps_owned_process():
|
||||
api, events, state, process_handle, job = native_api(assign_error=True)
|
||||
with pytest.raises(Exception, match='assign failed'):
|
||||
api.create_process(('python.exe',), 'winsta0\\private', None, None)
|
||||
assert not state['running']
|
||||
assert events.index(('wait', 0)) < events.index(('close', 'process'))
|
||||
assert process_handle.closed and job.closed
|
||||
assert ('resume',) not in events
|
||||
|
||||
|
||||
def test_wait_uses_signal_and_accepts_real_exit_code_259():
|
||||
api, events, state, *_ = native_api()
|
||||
process = api.create_process(('python.exe',), 'winsta0\\private', None, None)
|
||||
with pytest.raises(subprocess.TimeoutExpired):
|
||||
process.wait(timeout=0.025)
|
||||
assert ('wait', 25) in events
|
||||
assert process.poll() is None
|
||||
state['running'] = False
|
||||
assert process.poll() == 259
|
||||
assert process.wait(timeout=0) == 259
|
||||
|
||||
|
||||
def test_process_close_attempts_all_handles_and_retries_failed_handle():
|
||||
api, events, state, process_handle, job = native_api()
|
||||
process = api.create_process(('python.exe',), 'winsta0\\private', None, None)
|
||||
process_handle.fail_once = True
|
||||
with pytest.raises(TaskCenterError, match='close failed'):
|
||||
process.close()
|
||||
assert job.closed
|
||||
assert not state['running']
|
||||
process.close()
|
||||
assert process_handle.closed
|
||||
process.close()
|
||||
assert events.count(('close', 'job')) == 1
|
||||
|
||||
|
||||
def test_desktop_cleanup_continues_after_process_error_and_retries():
|
||||
events = []
|
||||
class OwnedProcess:
|
||||
def __init__(self, failing=False):
|
||||
self.failing = failing
|
||||
def poll(self):
|
||||
return None
|
||||
def terminate(self):
|
||||
events.append('terminate')
|
||||
def wait(self, timeout):
|
||||
events.append(('wait', timeout))
|
||||
def close(self):
|
||||
events.append('process-close')
|
||||
if self.failing:
|
||||
self.failing = False
|
||||
raise OSError('process close failed')
|
||||
class DesktopHandle:
|
||||
def CloseDesktop(self):
|
||||
events.append('desktop-close')
|
||||
desktop = PrivateDesktop('private', enabled=True)
|
||||
desktop._handle = DesktopHandle()
|
||||
desktop._processes = [OwnedProcess(), OwnedProcess(failing=True)]
|
||||
with pytest.raises(TaskCenterError, match='process close failed'):
|
||||
desktop.close()
|
||||
assert events.count('process-close') == 2
|
||||
assert events[-1] == 'desktop-close'
|
||||
assert ('wait', 5.0) in events
|
||||
desktop.close()
|
||||
assert events.count('process-close') == 3
|
||||
|
||||
|
||||
def test_desktop_close_reports_bounded_process_timeout_and_closes_handles():
|
||||
events = []
|
||||
process = SimpleNamespace(
|
||||
poll=lambda: None, terminate=lambda: events.append('terminate'),
|
||||
wait=lambda timeout: (_ for _ in ()).throw(subprocess.TimeoutExpired('owned', timeout)),
|
||||
close=lambda: events.append('process-close'),
|
||||
)
|
||||
desktop = PrivateDesktop('private', enabled=True)
|
||||
desktop._handle = SimpleNamespace(CloseDesktop=lambda: events.append('desktop-close'))
|
||||
desktop._processes = [process]
|
||||
with pytest.raises(TaskCenterError, match='timed out'):
|
||||
desktop.close()
|
||||
assert events == ['terminate', 'process-close', 'desktop-close']
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != 'nt', reason='native Windows desktop/process boundary')
|
||||
def test_native_private_process_has_captured_output_and_real_exit_259():
|
||||
with PrivateDesktop('dx-test-' + uuid4().hex, enabled=True) as desktop:
|
||||
process = desktop.start_process(
|
||||
(sys.executable, '-c', "import sys,os; print('private-out',flush=True); print('private-err',file=sys.stderr,flush=True); os._exit(259)"),
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
)
|
||||
assert process.stdout.readline() == b'private-out\r\n'
|
||||
assert process.stderr.readline() == b'private-err\r\n'
|
||||
assert process.wait(timeout=5) == 259
|
||||
assert process.poll() == 259
|
||||
|
||||
|
||||
def test_failed_rollback_termination_still_releases_owned_handles():
|
||||
api, events, state, process_handle, job = native_api(assign_error=True)
|
||||
api.process.TerminateProcess = lambda *_args: (_ for _ in ()).throw(OSError('terminate failed'))
|
||||
with pytest.raises(Exception, match='assign failed'):
|
||||
api.create_process(('python.exe',), 'winsta0\\private', None, None)
|
||||
assert job.closed
|
||||
assert ('close', 'thread') in events
|
||||
# A process outside the job still needs its handle for a cleanup retry.
|
||||
assert not process_handle.closed
|
||||
def terminate(*_args):
|
||||
state['running'] = False
|
||||
api.process.TerminateProcess = terminate
|
||||
api.close_pending()
|
||||
assert process_handle.closed
|
||||
|
||||
|
||||
def test_poll_failure_does_not_skip_termination_or_bounded_wait():
|
||||
events = []
|
||||
def failed_poll():
|
||||
raise OSError('poll failed')
|
||||
process = SimpleNamespace(
|
||||
poll=failed_poll, terminate=lambda: events.append('terminate'),
|
||||
wait=lambda timeout: events.append(('wait', timeout)),
|
||||
close=lambda: events.append('close'),
|
||||
)
|
||||
desktop = PrivateDesktop('private', enabled=True)
|
||||
desktop._processes = [process]
|
||||
with pytest.raises(TaskCenterError, match='poll failed'):
|
||||
desktop.close()
|
||||
assert events == ['terminate', ('wait', 5.0), 'close']
|
||||
|
||||
|
||||
def test_desktop_handle_close_failure_is_retried():
|
||||
events = []
|
||||
handle = Handle('desktop', events, fail_once=True)
|
||||
handle.CloseDesktop = handle.Close
|
||||
desktop = PrivateDesktop('private', enabled=True)
|
||||
desktop._handle = handle
|
||||
with pytest.raises(TaskCenterError, match='close failed'):
|
||||
desktop.close()
|
||||
assert desktop._handle is handle
|
||||
desktop.close()
|
||||
assert handle.closed and desktop._handle is None
|
||||
|
||||
|
||||
def test_descendant_handles_are_owned_before_terminating_the_job():
|
||||
api, events, _state, *_ = native_api()
|
||||
api.job.JobObjectBasicProcessIdList = 3
|
||||
query = api.job.QueryInformationJobObject
|
||||
api.job.QueryInformationJobObject = lambda job, kind: [42, 43] if kind == 3 else query(job, kind)
|
||||
def open_child(_access, _inherit, pid):
|
||||
events.append(('open-child', pid))
|
||||
return Handle('child', events)
|
||||
api.open_process = open_child
|
||||
process = api.create_process(('python.exe',), 'winsta0\\private', None, None)
|
||||
desktop = PrivateDesktop('private', enabled=True)
|
||||
desktop._processes = [process]
|
||||
desktop.close()
|
||||
assert events.index(('open-child', 43)) < events.index(('terminate',))
|
||||
assert ('close', 'child') in events
|
||||
|
||||
|
||||
@pytest.mark.parametrize('error_code', [87, 5])
|
||||
def test_native_descendant_open_error_only_ignores_already_exited_process(error_code):
|
||||
# pywintypes.error derives directly from Exception, rather than OSError.
|
||||
class NativeError(Exception):
|
||||
pass
|
||||
|
||||
error = NativeError(error_code, 'OpenProcess', 'native process open failed')
|
||||
api, events, _state, *_ = native_api()
|
||||
api.job.JobObjectBasicProcessIdList = 3
|
||||
query = api.job.QueryInformationJobObject
|
||||
api.job.QueryInformationJobObject = lambda job, kind: [43] if kind == 3 else query(job, kind)
|
||||
def open_child(*_args):
|
||||
raise error
|
||||
api.open_process = open_child
|
||||
process = api.create_process(('python.exe',), 'winsta0\\private', None, None)
|
||||
if error_code == 87:
|
||||
process._remember_descendants()
|
||||
assert process._descendant_handles == []
|
||||
else:
|
||||
with pytest.raises(NativeError) as caught:
|
||||
process._remember_descendants()
|
||||
assert caught.value is error
|
||||
|
||||
|
||||
def test_unconfirmed_descendant_exit_retains_handle_for_cleanup_retry():
|
||||
api, events, state, *_ = native_api()
|
||||
process = api.create_process(('python.exe',), 'winsta0\\private', None, None)
|
||||
child = Handle('child', events)
|
||||
process._descendant_handles = [child]
|
||||
original_wait = api.event.WaitForSingleObject
|
||||
pending = {'child': True}
|
||||
api.event.WaitForSingleObject = lambda handle, timeout: (
|
||||
258 if handle is child and pending['child'] else original_wait(handle, timeout))
|
||||
with pytest.raises(TaskCenterError, match='descendant exit'):
|
||||
process.close()
|
||||
assert not child.closed
|
||||
pending['child'] = False
|
||||
process.close()
|
||||
assert child.closed
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != 'nt', reason='native Windows job descendant cleanup')
|
||||
@pytest.mark.parametrize('parent_exits', [True, False])
|
||||
def test_native_private_job_kills_descendant_after_root_exit(parent_exits):
|
||||
import win32api
|
||||
import win32event
|
||||
import win32service
|
||||
import pywintypes
|
||||
|
||||
name = 'dx-test-' + uuid4().hex
|
||||
child_handle = None
|
||||
try:
|
||||
with PrivateDesktop(name, enabled=True) as desktop:
|
||||
process = desktop.start_process((
|
||||
sys.executable, '-c',
|
||||
"import subprocess,sys,time; p=subprocess.Popen([sys.executable,'-c','import time;time.sleep(60)']); print(p.pid,flush=True)"
|
||||
+ ('' if parent_exits else '; time.sleep(60)'),
|
||||
), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
child_pid = int(process.stdout.readline())
|
||||
child_handle = win32api.OpenProcess(0x100000, False, child_pid)
|
||||
if parent_exits:
|
||||
assert process.wait(timeout=5) == 0
|
||||
assert win32event.WaitForSingleObject(child_handle, 0) == 0
|
||||
with pytest.raises(pywintypes.error):
|
||||
unexpected = win32service.OpenDesktop(name, 0, False, 1)
|
||||
unexpected.CloseDesktop()
|
||||
finally:
|
||||
if child_handle is not None:
|
||||
child_handle.Close()
|
||||
@@ -0,0 +1,117 @@
|
||||
"""Catch lost/duplicated events across pagination, partial writes and rotation."""
|
||||
from pathlib import Path
|
||||
from threading import RLock
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.trial_task_center.task_logs import TaskLogReader
|
||||
from dx_productivity.trial_task_center.read_control import QueryCancelled, QueryControl
|
||||
|
||||
|
||||
def test_pages_cover_rotated_history_without_duplicates(tmp_path):
|
||||
path = tmp_path / 'events.jsonl'
|
||||
path.with_name(path.name + '.1').write_text('旧一\n旧二\n', encoding='utf-8')
|
||||
path.write_text('新一\n新二\n新三\n', encoding='utf-8')
|
||||
reader = TaskLogReader(path, RLock(), backup_count=5)
|
||||
latest = reader.latest(limit=2)
|
||||
assert latest.lines == ('新二', '新三') and latest.has_older
|
||||
previous = reader.older(latest.older_cursor, limit=2)
|
||||
assert previous.lines == ('旧二', '新一') and previous.has_older
|
||||
first = reader.older(previous.older_cursor, limit=2)
|
||||
assert first.lines == ('旧一',) and not first.has_older
|
||||
assert reader.poll(latest.cursor).lines == ()
|
||||
|
||||
|
||||
def test_incremental_poll_handles_partial_utf8_and_rotation(tmp_path):
|
||||
path = tmp_path / 'events.jsonl'
|
||||
path.write_bytes('first\n'.encode())
|
||||
reader = TaskLogReader(path, RLock(), backup_count=5)
|
||||
cursor = reader.latest().cursor
|
||||
payload = '位号 R1\n'.encode('utf-8')
|
||||
with path.open('ab') as stream:
|
||||
stream.write(payload[:2])
|
||||
incomplete = reader.poll(cursor)
|
||||
assert incomplete.lines == () and incomplete.cursor == cursor
|
||||
with path.open('ab') as stream:
|
||||
stream.write(payload[2:])
|
||||
path.rename(path.with_name(path.name + '.1'))
|
||||
path.write_text('next\n', encoding='utf-8')
|
||||
page = reader.poll(cursor)
|
||||
assert page.lines == ('位号 R1', 'next') and not page.reset
|
||||
assert reader.poll(page.cursor).lines == ()
|
||||
|
||||
|
||||
def test_truncated_log_resets_and_empty_log_can_later_be_created(tmp_path):
|
||||
path = tmp_path / 'events.jsonl'
|
||||
reader = TaskLogReader(path, RLock(), backup_count=5)
|
||||
empty = reader.latest()
|
||||
assert not empty.lines
|
||||
path.write_text('abcdef\n', encoding='utf-8')
|
||||
first = reader.poll(empty.cursor)
|
||||
assert first.lines == ('abcdef',)
|
||||
path.write_text('xy\n', encoding='utf-8')
|
||||
reset = reader.poll(first.cursor)
|
||||
assert reset.reset and reset.lines == ('xy',)
|
||||
|
||||
|
||||
def test_poll_is_bounded_and_retains_unread_events(tmp_path):
|
||||
path = tmp_path / 'events.jsonl'
|
||||
path.touch()
|
||||
reader = TaskLogReader(path, RLock(), backup_count=5)
|
||||
cursor = reader.latest().cursor
|
||||
path.write_text('1\n2\n3\n4\n5\n', encoding='utf-8')
|
||||
a = reader.poll(cursor, limit=2)
|
||||
b = reader.poll(a.cursor, limit=2)
|
||||
c = reader.poll(b.cursor, limit=2)
|
||||
assert (a.lines, b.lines, c.lines) == (('1', '2'), ('3', '4'), ('5',))
|
||||
|
||||
|
||||
def test_cancelled_read_releases_while_another_thread_holds_log_lock(tmp_path):
|
||||
from threading import Event, Thread
|
||||
lock, entered, release, finished = RLock(), Event(), Event(), Event()
|
||||
control = QueryControl()
|
||||
failures = []
|
||||
def holder():
|
||||
with lock:
|
||||
entered.set()
|
||||
release.wait(5)
|
||||
def read():
|
||||
try:
|
||||
TaskLogReader(tmp_path / 'events.jsonl', lock, read_control=control).latest()
|
||||
except Exception as error:
|
||||
failures.append(error)
|
||||
finally:
|
||||
finished.set()
|
||||
writer = Thread(target=holder)
|
||||
reader = Thread(target=read)
|
||||
writer.start()
|
||||
try:
|
||||
assert entered.wait(2)
|
||||
reader.start()
|
||||
control.cancel()
|
||||
assert finished.wait(1)
|
||||
assert len(failures) == 1 and isinstance(failures[0], QueryCancelled)
|
||||
assert not release.is_set()
|
||||
finally:
|
||||
release.set()
|
||||
writer.join(2)
|
||||
if reader.ident:
|
||||
reader.join(2)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('mode', ['latest', 'poll'])
|
||||
def test_large_single_log_line_can_be_cancelled_between_chunks(tmp_path, mode):
|
||||
path = tmp_path / 'events.jsonl'
|
||||
path.touch()
|
||||
reader = TaskLogReader(path, RLock())
|
||||
cursor = reader.latest().cursor
|
||||
path.write_text('x' * (1024 * 1024) + '\n', encoding='utf-8')
|
||||
class CancelAfterSegments:
|
||||
calls = 0
|
||||
def checkpoint(self):
|
||||
self.calls += 1
|
||||
if self.calls == 8:
|
||||
raise QueryCancelled()
|
||||
reader.read_control = CancelAfterSegments()
|
||||
with pytest.raises(QueryCancelled):
|
||||
reader.latest() if mode == 'latest' else reader.poll(cursor)
|
||||
@@ -0,0 +1,17 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.parametrize('behavior', ['success', 'failure_continue', 'uncertain_stop', 'pause_resume'])
|
||||
def test_multiple_projects_preserve_task_order_scope_results_and_measurements(tmp_path, behavior):
|
||||
path = Path(__file__).resolve().parents[2] / 'tools/measure_task_queue.py'
|
||||
spec = importlib.util.spec_from_file_location('measure_task_queue', path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
report = module.run_scenario(tmp_path / behavior, projects=3, sheets=2, rules=2, behavior=behavior)
|
||||
assert report['checks'] == 'passed'
|
||||
timings = report['timings']
|
||||
assert len([row for row in timings if row['phase'] == 'execute_step']) == report['executed_steps']
|
||||
assert all(row['elapsed_seconds'] >= 0 for row in timings)
|
||||
@@ -0,0 +1,183 @@
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.trial_task_center.models import TaskStatus
|
||||
from dx_productivity.trial_task_center.logging_setup import configure_logging
|
||||
from dx_productivity.trial_task_center.service import TaskCenterService
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
|
||||
|
||||
def make_service(tmp_path):
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
logging = configure_logging(tmp_path / 'data')
|
||||
return TaskCenterService(store, logging), store
|
||||
|
||||
|
||||
@pytest.mark.parametrize('mode', ['log', 'feedback'])
|
||||
def test_auxiliary_queries_cancel_while_database_writer_holds_lock(tmp_path, mode):
|
||||
from threading import Event, Thread
|
||||
from dx_productivity.trial_task_center.read_control import QueryControl, QueryCancelled
|
||||
service, store = make_service(tmp_path)
|
||||
task = store.create_task('one')
|
||||
control, entered, finished = QueryControl(), Event(), Event()
|
||||
errors = []
|
||||
def read():
|
||||
entered.set()
|
||||
try:
|
||||
if mode == 'log':
|
||||
service.read_task_log(task.task_id, read_control=control)
|
||||
else:
|
||||
service.execution_feedback(task.task_id, started_after=0, read_control=control)
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
finally:
|
||||
finished.set()
|
||||
worker = Thread(target=read)
|
||||
try:
|
||||
with store._lock:
|
||||
worker.start()
|
||||
assert entered.wait(2)
|
||||
control.cancel()
|
||||
assert finished.wait(1), 'obsolete query remained blocked behind writer'
|
||||
assert len(errors) == 1 and isinstance(errors[0], QueryCancelled)
|
||||
finally:
|
||||
if worker.ident:
|
||||
worker.join(2)
|
||||
store.close()
|
||||
|
||||
|
||||
def test_task_context_is_frozen_single_bound_project_and_cached(tmp_path):
|
||||
service, store = make_service(tmp_path)
|
||||
task = store.create_task('one')
|
||||
path = tmp_path / 'one.prj'; path.touch()
|
||||
project = store.sync_projects(task.task_id, tmp_path, (path,))[0]
|
||||
project = store.set_project_selected(project.project_id, True)
|
||||
store.bind_project_task(task.task_id, project.project_id, 'g', 0)
|
||||
target = ComponentTarget(path, 'MAIN', '1', 'u1', 'R1', 'OLD', 'V')
|
||||
store.record_target_inventory(task.task_id, (target,))
|
||||
store.replace_target_plan(task.task_id, (TargetPlanRow(target, False, 'NEW'),))
|
||||
|
||||
first = service.task_context(task.task_id)
|
||||
second = service.task_context(task.task_id)
|
||||
|
||||
assert first == second
|
||||
assert first.project == project
|
||||
assert first.targets[0].target.uid == 'u1'
|
||||
with pytest.raises(Exception):
|
||||
first.targets += ()
|
||||
|
||||
|
||||
def test_task_context_empty_disabled_plan_does_not_fallback_to_rules(tmp_path):
|
||||
service, store = make_service(tmp_path)
|
||||
task = store.create_task('one')
|
||||
path = tmp_path / 'one.prj'; path.touch()
|
||||
project = store.sync_projects(task.task_id, tmp_path, (path,))[0]
|
||||
store.bind_project_task(task.task_id, project.project_id, 'g', 0)
|
||||
store.add_rule(task.task_id, 'OLD', 'NEW')
|
||||
store.record_target_inventory(task.task_id, ())
|
||||
|
||||
context = service.refresh_bound_project(task.task_id)
|
||||
|
||||
assert context.targets == ()
|
||||
assert context.progress.total_items == 0
|
||||
assert context.legacy is False
|
||||
|
||||
|
||||
def test_multi_project_legacy_context_is_read_only(tmp_path):
|
||||
service, store = make_service(tmp_path)
|
||||
task = store.create_task('legacy')
|
||||
paths = (tmp_path / 'a.prj', tmp_path / 'b.prj')
|
||||
for path in paths: path.touch()
|
||||
store.sync_projects(task.task_id, tmp_path, paths)
|
||||
|
||||
context = service.task_context(task.task_id)
|
||||
|
||||
assert context.legacy is True
|
||||
assert context.project is None
|
||||
with pytest.raises(TaskCenterError):
|
||||
service.refresh_bound_project(task.task_id)
|
||||
|
||||
|
||||
def test_private_desktop_worker_is_opt_in_and_never_falls_back():
|
||||
from dx_productivity.trial_task_center.isolated_worker import IsolatedDesktopWorker, IsolatedWorkerRequest
|
||||
|
||||
request = IsolatedWorkerRequest('1', 'task', Path('C:/board.prj'), ('u1',), 'sha256:x')
|
||||
worker = IsolatedDesktopWorker(enabled=False)
|
||||
with pytest.raises(TaskCenterError, match='opt-in'):
|
||||
worker.run(request)
|
||||
|
||||
|
||||
def test_private_worker_read_only_probe_requires_matching_pid_and_project(tmp_path):
|
||||
from dx_productivity.trial_task_center.isolated_worker import CadIdentity, IsolatedDesktopWorker, IsolatedWorkerRequest
|
||||
|
||||
project = tmp_path / 'board.prj'; project.write_text('x', encoding='utf-8')
|
||||
request = IsolatedWorkerRequest('1', 'task', project, ('u1',), 'sha256:x')
|
||||
class FakeDesktop:
|
||||
def __enter__(self): return self
|
||||
def __exit__(self, *_args): return None
|
||||
worker = IsolatedDesktopWorker(enabled=True, desktop_factory=lambda _name: FakeDesktop(), existing_cad_validator=lambda _path: False)
|
||||
result = worker.read_only_probe(request, lambda _path: CadIdentity(42, project), evidence_root=tmp_path / 'evidence')
|
||||
assert result.state == 'read_only_verified'
|
||||
assert result.cad_pid == 42
|
||||
with pytest.raises(TaskCenterError, match='identity'):
|
||||
worker.read_only_probe(request, lambda _path: CadIdentity(0, project))
|
||||
|
||||
|
||||
def bound_task(tmp_path):
|
||||
service, store = make_service(tmp_path)
|
||||
task = store.create_task('bound')
|
||||
path = tmp_path / 'bound.prj'
|
||||
path.write_text('[Project]\n', encoding='utf-8')
|
||||
project = store.sync_projects(task.task_id, tmp_path, (path,))[0]
|
||||
store.set_project_selected(project.project_id, True)
|
||||
task = store.bind_project_task(task.task_id, project.project_id, 'g', 0)
|
||||
return service, store, task, project, path
|
||||
|
||||
|
||||
def test_bound_membership_cannot_be_changed_by_old_service_apis(tmp_path):
|
||||
service, store, task, project, path = bound_task(tmp_path)
|
||||
for operation in (
|
||||
lambda: service.scan_projects(task.task_id, tmp_path),
|
||||
lambda: service.clear_project_selection(task.task_id),
|
||||
lambda: service.select_all_projects(task.task_id),
|
||||
lambda: service.set_project_selected(project.project_id, False),
|
||||
):
|
||||
with pytest.raises(TaskCenterError) as caught:
|
||||
operation()
|
||||
assert caught.value.code == 'project_binding'
|
||||
assert store.list_projects(task.task_id)[0].selected
|
||||
|
||||
|
||||
def test_context_uses_one_cached_task_facade_and_sees_service_edits(tmp_path):
|
||||
service, store, task, project, path = bound_task(tmp_path)
|
||||
first = service.for_project_task(task.task_id)
|
||||
assert service.for_project_task(task.task_id) is first
|
||||
service.task_context(task.task_id)
|
||||
service.add_rule(task.task_id, 'OLD', 'NEW')
|
||||
assert service.task_context(task.task_id).rules[0].new_part_number == 'NEW'
|
||||
|
||||
|
||||
def test_context_enabled_target_plan_is_counted_with_uid_scope(tmp_path):
|
||||
service, store, task, project, path = bound_task(tmp_path)
|
||||
target = ComponentTarget(path, 'MAIN', '1', 'u1', 'R1', 'OLD', 'V')
|
||||
store.record_target_inventory(task.task_id, (target,))
|
||||
store.replace_target_plan(task.task_id, (TargetPlanRow(target, True, 'NEW'),))
|
||||
context = service.task_context(task.task_id)
|
||||
assert context.progress.total_items == 1
|
||||
assert context.phase == 'selection'
|
||||
|
||||
|
||||
def test_bound_refresh_checks_only_existing_path_and_retains_membership(tmp_path, monkeypatch):
|
||||
service, store, task, project, path = bound_task(tmp_path)
|
||||
monkeypatch.setattr('dx_productivity.trial_task_center.service.scan_projects',
|
||||
lambda *_args, **_kwargs: pytest.fail('directory scan is forbidden'))
|
||||
path.unlink()
|
||||
context = service.refresh_bound_project(task.task_id)
|
||||
assert context.project.project_id == project.project_id
|
||||
assert context.project.selected
|
||||
assert not context.project.available
|
||||
assert len(store.list_projects(task.task_id)) == 1
|
||||
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user