Compare commits
51
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
392ae365da | ||
|
|
0b7f3e5c4a | ||
|
|
f80127e7bd | ||
|
|
ec2591ac75 | ||
|
|
22442e03ae | ||
|
|
9d9b316634 | ||
|
|
6d45ea1fa0 | ||
|
|
d0bbc73da3 | ||
|
|
4fb715507e | ||
|
|
c114db9f31 | ||
|
|
7d4f6bde0b | ||
|
|
ad3ee4151c | ||
|
|
650dfd5491 | ||
|
|
ba69f86628 | ||
|
|
8ccc9716de | ||
|
|
3187b304c6 | ||
|
|
29b40a5370 | ||
|
|
315d2e85b3 | ||
|
|
d954b527f5 | ||
|
|
63999b7bfd | ||
|
|
46deb9cec8 | ||
|
|
488bf027cc | ||
|
|
bd80f86357 | ||
|
|
0540a1e3bb | ||
|
|
846c4b92e9 | ||
|
|
b2a84404d8 | ||
|
|
7597e98eef | ||
|
|
b038951cc4 | ||
|
|
d9bfc57900 | ||
|
|
e65bed0408 | ||
|
|
a74b810786 | ||
|
|
de16bbdfa1 | ||
|
|
eda9403d94 | ||
|
|
9ccf99bd8f | ||
|
|
f91b4deb5e | ||
|
|
fe8765beec | ||
|
|
a606ed9179 | ||
|
|
6175bdb254 | ||
|
|
211d139653 | ||
|
|
ec677a2864 | ||
|
|
b9712ed651 | ||
|
|
e6e9b6906d | ||
|
|
f25dd228fd | ||
|
|
deaf8c3ab4 | ||
|
|
de486a9c6b | ||
|
|
4da211d5d2 | ||
|
|
b3c8c9c126 | ||
|
|
76074f8d11 | ||
|
|
f5d39f6261 | ||
|
|
0406028a02 | ||
|
|
dbb264f679 |
No files matched your search
@@ -49,8 +49,9 @@ jobs:
|
||||
npm install --prefix /opt/ci-node --no-audit --no-fund node@24.11.1
|
||||
node --version
|
||||
npm ci --prefix integration/dsh --no-audit --no-fund
|
||||
- name: Read-only model availability (real Harness, no remote model calls)
|
||||
- name: Runtime and model availability (real Harness, no remote model calls)
|
||||
run: |
|
||||
node tools/verify_dsh_runtime.mjs
|
||||
node tools/verify_dsh_model_availability.mjs
|
||||
node --test tests/integration/test_dsh_standard_compat.mjs
|
||||
node tools/verify_dsh_incident_restart.mjs
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
# 引脚字段读取范围
|
||||
|
||||
FREEFORM / FLAT BLOCKS 原生文本中的 `Pin 名称\tnum 编号\ttype 类型码` 可以与已解析图的实例、位号、物理脚号核对。适配器保留文件 SHA256 和行号,重复或无法绑定的字段不进入已证明清单。类型码按原文展示,不臆造类型语义。
|
||||
|
||||
自建格式夹具验证了逻辑名和电气类型码。另对已有工程的两份已保存副本执行了真实原生只读导出:前后各 57 个器件,83 个物理引脚取得了名称和类型码的原文证明。验收记录在本机 `D:/dx-vfy-native-final/acceptance.json`;原始客户工程和网表不提交 Git。
|
||||
|
||||
引脚级 Value 尚未在该格式中证明,保持 unknown;器件 Value 不能代替它。确切库版本内部的引脚到焊盘映射尚未支持,保持未覆盖。若检查计划要求这些未证明字段,结论必须为 INCOMPLETE(已有明确硬异常时仍为 DIFFERENT)。
|
||||
|
||||
探针:`python tools/probe_verification_pin_metadata.py <受管导出/netlist.json>`,只读已有输出,不调用 CAD、不修改工程。
|
||||
@@ -0,0 +1,107 @@
|
||||
# Issue #44 整批任务整改方案审查
|
||||
|
||||
日期:2026-11-27。方式:当前会话逐层代码核对与方案自审;没有委托独立代理,不将本记录称作独立代码审查。审查对象是设计和实施计划,尚无业务修复代码。
|
||||
|
||||
设计:`docs/superpowers/specs/2026-11-27-issue44-batch-remediation-design.md`。
|
||||
|
||||
计划:`docs/superpowers/plans/2026-11-27-issue44-batch-remediation.md`。
|
||||
|
||||
## 1. 审查结论
|
||||
|
||||
方案可作为后续实施的依据,前提是执行时保留三项已经由用户确定的规则:确认清单后只执行可执行子集;isolated/unknown 阻断新写入;写入不确定暂停整批,核验原工程并重新确认后继续。
|
||||
|
||||
工单中的“执行器缺失”“handler 空实现”等根因表述不能直接当作实现规格。主线已存在相应模块,本轮应补契约和复现真实断点。设计已据此避免增加新的队列或恢复执行器。
|
||||
|
||||
没有发现需要用户继续补充的业务取舍。现场原始数据、CAD 复现与冻结包验收是实施阶段的证据门槛,不能由本次方案自审替代。
|
||||
|
||||
## 2. 发现的问题及方案中的处理
|
||||
|
||||
| 级别 | 问题 | 若不处理的后果 | 方案处理及验收 |
|
||||
| --- | --- | --- | --- |
|
||||
| P0 | #33 允许证据完整的 isolated 非阻塞,#44 和本次决定要求阻断 | UI 灰化但 Agent/运行时仍可写入 | Task 1 统一所有入口;测试旧 blocking=False 仍阻断 |
|
||||
| P0 | 原 D8 可隔离不确定工程后推进独立工程 | 与用户本次“暂停整批”决定冲突 | Task 3 收紧 UI、queue、runtime、workspace 恢复;资源 released 也不能自动推进 |
|
||||
| P0 | OpenProcess 拒绝访问若视作 gone,或继续向上抛 | 前者可能误放行,后者可能启动崩溃 | gone/alive/unknown 三态;unknown 受限启动、保持保护、无误杀 |
|
||||
| P0 | 确认时展示范围与执行时解析范围各算一次 | 扩大范围或把旧确认用于新计划 | manifest 摘要覆盖候选/顺序/裁决/计划;租约内复核,变化零派发 |
|
||||
| P0 | 单纯 try/finally 下一项忽略写入事实 | 原 CAD 仍写入时处理下一工程,或重放保存项 | 沿用证据认证的失败策略;保存未知整批停;终止前持久化保护 |
|
||||
| P0 | 每个工程前要求所有资源消失,误把本代健康资源当残留 | 共享 CAD 自锁,正常批次也跑不完 | 新代次和异常恢复按物理释放准入;健康代次仅验证本代所有权与关闭检查点,旧代次残留仍阻断 |
|
||||
| P1 | 改共享 preflight 的 all() 为 any() | Agent/排期也会静默局部执行 | 保持严格接口,新增显式批量裁决层 |
|
||||
| P1 | 每步重比确认前的可变任务指纹 | 第一个工程完成或 BOM 正常解析后就被误判为陈旧计划 | 初始指纹只用于确认边界;运行中核对冻结计划及认证的单调进度,manifest 与进展分开 |
|
||||
| P1 | 工单建议把所有未运行任务永久改 skipped | 预检跳过后无法就地修改,任务配置被业务终态污染 | skipped 为本次批次条目状态,原 TaskStatus 不扩张;UI 清楚显示范围 |
|
||||
| P1 | 任务数、作业数、目标数混算,pending_save 被遗漏 | 23 个待核验目标被显示为 1 个问题或 0 个已保存而无解释 | 当前轮次单一投影,三个量分开,pending_save 单列,未知不填 0 |
|
||||
| P1 | 跨 task-center.db、dsh-state.sqlite3 和文件承诺原子提交 | 崩溃后出现虚假成功或自动重替换补报表 | 明确可恢复的持久化顺序和 revision;只重建报告,不重放替换 |
|
||||
| P1 | 错把 supervisor ok 或成功保存当整体成功 | 桌面隔离、网表失败被成功文案覆盖 | execution/resource/acceptance 三轴;保留保存成功事实但整体不计完成 |
|
||||
| P1 | “PID 集合=1”无条件应用于故障回收 | 为满足分数而保留错误 CAD,或错误否定正常重建 | 仅正常批次验证 CAD 根 PID=1;异常按代次、原因和唯一派发验证 |
|
||||
| P1 | 超时被解释为 target_not_found | 库故障被误诊,跳过可能存在的料号 | 确定性查库证据才给不存在;超时/不可用单列 |
|
||||
| P1 | 整个数据根直接打包诊断 | 导出原工程、库或凭据;包无限增长 | 扩展现有白名单、脱敏、限额,遗漏可见 |
|
||||
| P2 | 列表焦点、列表多选、projects.selected、group_id 混用 | 选两项却跑整批、按搜索顺序执行 | “本批”与“所选”两个明确动作,持久化顺序唯一 |
|
||||
|
||||
上述为审查中发现并纳入方案的风险,不是已经修复的代码缺陷清单。新增接口的具体实现仍需代码审查。
|
||||
|
||||
## 3. 需要替换的历史验收假设
|
||||
|
||||
1. `test_resource_queue_resume.py` 及 D8 的旧证据允许原不确定工程隔离后继续;本次将有意停止这种自动推进。必须新增“资源释放后仍不继续,核验并确认后才继续”的替代验收。
|
||||
2. `resource_blockers` 对 verified isolation 的非阻塞行为不再是目标;保留桌面/Job/身份观察技术,改变准入结论。
|
||||
3. `execution_rounds` 是逐任务轮次,不是天然的批次主表。8 工程不强制改为一条 execution_rounds;用 manifest/run_id 绑定多个任务和现有队列。新一轮是否增加轮次按现有生命周期确认,不能为了断言直接插行。
|
||||
4. #44 最小回归中的“pending_save 卡住后下一工程开始”只适用于已证明无写入或保存结果已核验的安全结论。真正 pending_save 未核验时,按用户决定整批暂停,不能以达成该字面期望为由放宽保护。
|
||||
5. 预检跳过成员不实际开始执行,因此不创建假执行轮次。其 skipped 结论持久化到本次批次范围,原任务仍可编辑。
|
||||
6. 不要求真实 CAD 的整批、故障恢复、网表 CLI 和监督 helper 全部共用同一个 PID。PID=1 的检查只统计正常代次的 CAD 根进程。
|
||||
|
||||
## 4. 验证事实
|
||||
|
||||
基线为 `f80127e7bd0b098dfe3ef34823a3c13f2f9c5982`,不是旧工作区的 `4a438e0`。受测 beta.1 分支只比基线增加版本和发行说明,因此可以用本基线定位执行逻辑。
|
||||
|
||||
本次运行:
|
||||
|
||||
```text
|
||||
tests/v1_1/test_task_queue.py
|
||||
tests/v1_1/test_resource_queue_resume.py
|
||||
tests/v1_1/test_batch_supervisor.py
|
||||
tests/ui/test_pr27_confirmation_admission.py
|
||||
58 passed in 70.93s
|
||||
```
|
||||
|
||||
该结果只说明既有队列、监督、恢复及确认保护测试在当前环境通过。它没有验证本设计拟新增行为,也没有复现 BOB/ETHERNET_1G 的现场问题。
|
||||
|
||||
实施计划逐项覆盖工单 A4、B1/B2/B3/B6/B7/B8、C1/C3/C7/C8、D1/D2/D4/D7/D8、E2/E4/E5/E6,共 20 项。涉及等待和恢复的用例必须同时断言零错误派发,而非只看按钮亮起或最终状态字符串。
|
||||
|
||||
## 5. 还需获取或生成的现场证据
|
||||
|
||||
| 证据 | 要回答的问题 | 获取阶段 |
|
||||
| --- | --- | --- |
|
||||
| paper4*_data 的原始副本、BOB status/事件与保存证据 | 23 pending_save 卡在 CAD 保存、关闭、源绑定还是回读阶段 | Task 3/7 实施复现前 |
|
||||
| 启动崩溃 traceback 和旧 supervisor 身份记录 | 权限异常从哪个观察入口穿透,PID 是否已复用 | Task 1;先用故障注入覆盖,再补现场复核 |
|
||||
| ETHERNET_1G 原生展开和属性报告 | 位号冲突属于采集身份规则、层次门还是旧数据 | Task 6 |
|
||||
| 实测所选两项与整批确认窗口、对应数据库快照 | 范围问题发生在入口、绑定刷新还是裁决阶段 | Task 2/7 |
|
||||
| 同一候选冻结包的构建身份、8/100 工程终态与资源记录 | 修复是否真实进入 EXE,源码与实测是否同版 | Task 7 |
|
||||
|
||||
现有摘要附件未包含完整上述现场运行目录。可以先完成自动化和合成 Windows 复现;没有对应证据不能把“未复现”写成“已修复”。
|
||||
|
||||
## 6. 方案审查通过条件
|
||||
|
||||
- 三项用户决定在设计、计划、测试与日志口径一致。
|
||||
- 所有 20 项都映射到实施任务,并明确真实 CAD 与模拟测试边界。
|
||||
- 新增功能不破坏现有租约、保存提交、防重放和历史检查点。
|
||||
- 不以清 uncertain、伪造 released、自动跳过未知结果、降低采集完整性换取高分。
|
||||
- 代码实施后再进行实际代码审查;冻结包卷四 >=90 分及无保护违规之后,才建议关闭 #44。
|
||||
|
||||
本轮仅完成方案准备与审查,没有执行以上整改或宣称达到关闭条件。
|
||||
|
||||
## 7. 实施后的独立代码审查(2026-11-27 更新)
|
||||
|
||||
用户批准实施后,另行委托独立只读代码审查,覆盖本轮业务代码和生产调用链;这里补记实际结果,不改变前文方案阶段的历史事实。
|
||||
|
||||
审查发现并整改:
|
||||
|
||||
- 将“资源暂停只接受 blocked”改为识别绑定当前批次、业务已确定的 completed/failed 暂停,保留原业务状态。
|
||||
- 确认返回后重新规范化列表选集,按持久化顺序比较,不因显示倒序误拒绝,也不允许旧选集偷偷派发;可见确认范围只使用冻结候选。
|
||||
- 事件重试在预约、意图落盘和实际派发前校验整个原批次,包括未被选中的同组待核验成员;已清标记但原批次仍须重新确认的情形不自动继续。
|
||||
- 手动续跑及每一次自动资源接续均在派发租约内校验清单、成员顺序、计划和工程 iCDBDir 写入源,保留原始摘要,允许合法单调进度。
|
||||
- 已知带 manifest_digest 的运行丢失冻结清单时不退回旧版兼容路径。
|
||||
- 原生 BOM 核验后无须替换的 skipped 正确进入摘要;pending_save、整批保护、查库错误代码与资源结论正确区分。
|
||||
- 正常清理失败后的资源原因规范化;稍后物理释放会更新回执,不抹掉已验证替换。
|
||||
- 崩溃恢复同时处理首次回执尚未落库,以及续跑后仍留有上一版暂停回执两种情况,使用本次绑定的最终监督结果与检查点。
|
||||
- 事件重试成功或异常均重新发布同一批次的回执并携带本次资源证据;兼容工作区保留 completed_result 的网表验收。
|
||||
|
||||
相关反例均按增量范围验证;最后四处遗留生产路径的独立复核通过。没有重复全量测试或执行真实 CAD 换料。
|
||||
|
||||
详细命令范围、结果和未复现现场问题见 `docs/testing/2026-11-27-issue44-incremental-acceptance.md`。ETHERNET_1G 身份冲突及客户库确定性不存在仍缺对应现场证据,本轮不关闭工单。
|
||||
@@ -0,0 +1,324 @@
|
||||
# 独立校验新增功能 Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use `superpowers:executing-plans` to implement task-by-task. N01–N12 implementation and local development-package acceptance are complete. Continuous full-suite stability remains a release gate; see the acceptance record. Do not start implementation from the UI image alone or dispatch agents without user authorization.
|
||||
|
||||
**Goal:** 新增可独立创建、接收成功结果、执行并让人复核的工程校验任务,交付 A 工作台及完整判断/失败处理。
|
||||
|
||||
**Architecture:** 在现有原生捕获、导出、图比较、回执证明之上增加校验领域包;任务、工程项、不可变输入版本、执行尝试与本次运行范围各有身份。界面只查持久事实和证据;统一输入接口不包含来源分类,批量与未来增量共用接口。
|
||||
|
||||
**Tech Stack:** Python 3.12、SQLite、PySide6、pytest/pytest-qt、已有 Native CLI/OwnedCliScope/ServiceWorker/LatestQuery;标准库 JSON/HTML,无新运行时依赖。
|
||||
|
||||
**Spec:** [业务、流程、状态、数据与失败处理](../specs/2026-11-17-independent-verification-business-design.md)。对应用户最终选择的 A 图片入口,不采用此前带来源或流水线横条的旧草案。
|
||||
|
||||
用户已确认业务方向,开发阶段、工作区隔离、跨任务接口和交付门槛统一从[开发与交付入口](2026-11-17-verification-development.md)读取。本文件是该入口下的逐任务清单,N01~N12 已实施并完成本地开发包验收;既有连续全量回归的时序波动保留为发布门槛,详见验收记录。
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- 只开发当前没有的功能;不接手 issue29 收尾、既有任务列表或其他并行修复。
|
||||
- 原始捕获、原生导出、覆盖核验与绑定实际回执的预期解析直接复用;不重写旧替换状态机。
|
||||
- 独立任务始终可创建;资源忙只影响执行领取,不影响新建和输入登记。
|
||||
- 无 source/type/mode 来路字段或来源筛选;没有预期清单不等于所有变化均被允许。
|
||||
- 当前只在已落盘结果后批量交接;增量接口和乱序规则先做好,不修改替换侧实时刷新。
|
||||
- 所有工作只读固定输入;禁止重新换料、自动换脚、修改库或把当前工程补造为旧 before。
|
||||
- 位号/物理脚号/连接严格;引脚文字变化与器件 Value、网络名分开;未知字段不能冒充一致。
|
||||
- “执行成功”与“工程结论”分开;必查未知不能通过,已知异常不被警告或未知覆盖。
|
||||
- 同一输入版本只允许一个活动尝试;新版本不替换在跑输入,迟到结果不能覆盖当前结论。
|
||||
- GUI 不进行 CAD/CLI/磁盘全图扫描;延用既有风格、980×700 最小窗口与1280×880默认窗口。
|
||||
- 新增原生进程只使用现有 OwnedCliScope;退出无法确认时暂停该执行器,不触发旧 CAD 退出/恢复动作。
|
||||
- 清理不能删除活动/当前引用的快照、证明和报告;Git不接收客户工程、原始网表或厂商二进制。
|
||||
- 每个任务独立测试/审阅/提交;只暂存其明确文件,保护工作区并行修改。实现前按最新主线重新定位接口。
|
||||
|
||||
## 0. 文件划分与依赖
|
||||
|
||||
领域包新建于 `src/dx_productivity/trial_task_center/verification/`,以下缩写 `V/` 指该目录;`UI/` 指既有 `src/dx_productivity/trial_task_center/ui/`。测试使用完整仓库相对路径。
|
||||
|
||||
| 文件 | 职责 | 首次任务 |
|
||||
| --- | --- | --- |
|
||||
| `V/__init__.py`、`V/contracts.py` | 输入/检查/状态合同,结果汇总 | N01 |
|
||||
| `V/store.py` | 校验任务、工程、版本、尝试、运行、命令去重事务 | N02 |
|
||||
| `V/service.py` | 本域公开接口,接收/查询/执行薄编排 | N03 |
|
||||
| `V/intake.py` | 稳定导入、版本接收、成功交接适配 | N03 |
|
||||
| `V/queries.py` | 当前版本投影、分页与统计 | N04 |
|
||||
| `V/runner.py` | 独立只读执行器、资源准入与发布 | N05 |
|
||||
| `V/control.py`、`V/ownership.py` | 冻结运行范围、持久停止、跨窗口进程归属和恢复证明 | N10 |
|
||||
| `V/rules.py` | J01~J13 分维度判断与事实差异 | N06 |
|
||||
| `V/pin_metadata.py` | 已验证原生字段适配、能力与未覆盖清单 | N07 |
|
||||
| `V/evidence.py` | issue 定位、端点差异与确定性图数据 | N08 |
|
||||
| `UI/verification_workspace.py` | 页面、任务选择、工程表、底栏 | N09 |
|
||||
| `UI/verification_controller.py` | 异步查询、选择代次和用户命令 | N09 |
|
||||
| `UI/verification_inspector.py` | 逐脚对照、事实表、范围与证据入口 | N09 |
|
||||
| `V/report.py` | 同一证据包的HTML/JSON和整任务导出 | N11 |
|
||||
| `tools/verify_independent_verification.py` | 受控/真实只读验收CLI,明确区分两种证据 | N12 |
|
||||
|
||||
新增 schema 由现有 `store_schema.py` 的版本升级入口调用 `V/store.py`,原服务 `service.py` 只暴露本域服务引用,不继续堆叠校验业务。
|
||||
|
||||
依赖:N01→N02→N03→N04;N02/N03→N05;N01→N06;N05/N06→N07→N08;N04/N05/N08→N09;N05/N09→N10→N11→N12。
|
||||
|
||||
N05 可以先用已有比较器返回原始事实和明确覆盖,N06 增加分级,N07 丰富引脚元数据;能力未验证的阶段必须产生 unknown,不为界面测试假造通过。
|
||||
|
||||
## N01:固定输入、执行状态与结论合同
|
||||
|
||||
**Files:** Create `V/__init__.py`、`V/contracts.py`;Test `tests/v1_1/test_independent_verification_contracts.py`。
|
||||
|
||||
**Interfaces:** `validate_input(value: dict) -> dict`;`rollup_results(checks: tuple[dict, ...], *, required_checks: tuple[str, ...], optional_checks: tuple[str, ...] = ()) -> dict`。返回 verdict、coverage、warnings/errors/unknown计数及 scope。missing required check 等同 unknown;空检查不能一致,空required_checks拒绝为非法检查计划。`CheckResult` 用字典并严格校验 check_id/state/issues/evidence_refs,不新增泛型框架。
|
||||
|
||||
检查ID固定:inputs(J01)、coverage(J02)、components(J03)、physical_pins(J04)、connections(J05/J06)、net_names(J07)、declared_attributes(J08)、attribute_changes(J09)、pin_text(J10)、pin_semantics(J11)、footprint_mapping(J12)、export_identity(J13)。同一check有多个issue,不重复check_id;无expectation时declared_attributes不能伪装已检查,attribute_changes仍输出变化事实。
|
||||
|
||||
- [x] 写空结果、缺必查、错误与未知并存、警告、可选未知、无预期清单的失败测试:
|
||||
|
||||
```python
|
||||
def test_empty_checks_do_not_prove_consistency():
|
||||
from dx_productivity.trial_task_center.verification.contracts import rollup_results
|
||||
result = rollup_results((), required_checks=('connections',))
|
||||
assert result['verdict'] == 'INCOMPLETE'
|
||||
assert result['coverage'] == 'partial'
|
||||
```
|
||||
|
||||
- [x] Run `.venv/Scripts/python.exe -m pytest tests/v1_1/test_independent_verification_contracts.py -q`,确认新合同尚不存在而失败。
|
||||
- [x] 实现严格字段、枚举、摘要、整数版本与受管引用结构校验;拒绝外部任意输出路径,UI不传来源字段。输入字段按规范4.1,check_plan明确 required/optional/excluded。
|
||||
- [x] 实现纯汇总优先级,核心逻辑固定为:
|
||||
|
||||
```python
|
||||
if any(row['state'] == 'error' for row in checks):
|
||||
verdict = 'DIFFERENT'
|
||||
elif any(states.get(key, 'unknown') not in {'equal', 'expected_change', 'warning'}
|
||||
for key in required_checks):
|
||||
verdict = 'INCOMPLETE'
|
||||
elif any(row['state'] == 'warning' for row in checks):
|
||||
verdict = 'WARNING'
|
||||
else:
|
||||
verdict = 'CONSISTENT'
|
||||
```
|
||||
|
||||
`states` 在同函数中由唯一 check_id 建立;重复check_id拒绝,不用后值覆盖前值。必查项被标not_requested同样不能通过;空required_checks在该分支前抛出TaskCenterError。覆盖清单独立计算。
|
||||
|
||||
- [x] 重跑本组,补 actual属性值不能反推expected、not_requested不计已检查、没有规则时scope文字不能“换料符合”的断言。
|
||||
- [x] 对照规范J01~J13与状态表自审字段;保留原始文字及证据引用,不在合同层猜测引脚功能。
|
||||
- [x] Commit `feat: define independent verification contracts and verdicts`。
|
||||
|
||||
## N02:任务、版本、尝试与去重事务
|
||||
|
||||
**Files:** Create `V/store.py`;Modify `src/dx_productivity/trial_task_center/store_schema.py`;Test `tests/v1_1/test_independent_verification_store.py`。
|
||||
|
||||
**Interfaces:** `VerificationRepository(task_store)`:`create_task(name: str, *, request_id: str) -> dict`、`publish(task_id: str, inputs: tuple[dict, ...], *, submission_id: str) -> dict`、`create_attempt(item_id: str, version: int, *, request_id: str) -> dict`、`claim(attempt_id: str, *, owner_id: str) -> dict`、`finish(attempt_id: str, *, generation: int, result: dict) -> bool`。这些只操作已验证的领域记录;原生I/O由服务完成。
|
||||
|
||||
- [x] 写旧DB升级、创建去重、同版不同正文、乱序、唯一活动尝试、迟到finish与并发claim测试。测试内创建真实临时TaskStore:
|
||||
|
||||
```python
|
||||
def test_new_task_does_not_require_replacement_task(tmp_path):
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
from dx_productivity.trial_task_center.verification.store import VerificationRepository
|
||||
with_store = TaskStore(tmp_path / 'tasks.db')
|
||||
try:
|
||||
repo = VerificationRepository(with_store)
|
||||
first = repo.create_task('电源板核对', request_id='create-1')
|
||||
again = repo.create_task('电源板核对', request_id='create-1')
|
||||
assert first['task_id'] == again['task_id']
|
||||
finally:
|
||||
with_store.close()
|
||||
```
|
||||
|
||||
- [x] Run `.venv/Scripts/python.exe -m pytest tests/v1_1/test_independent_verification_store.py -q`,确认失败。
|
||||
- [x] 建 verification_tasks/items/input_revisions/attempts/runs/requests 表,状态只属于本域;给版本和请求去重键唯一索引。至少固定:
|
||||
|
||||
```sql
|
||||
CREATE UNIQUE INDEX verification_input_identity
|
||||
ON verification_input_revisions(item_id, input_version);
|
||||
CREATE UNIQUE INDEX verification_active_attempt
|
||||
ON verification_attempts(item_id, input_version)
|
||||
WHERE state IN ('queued','running','publishing','stopping');
|
||||
```
|
||||
|
||||
- [x] 实现事务内版本指针移动、逐条接收和CAS generation;批量外层错误全拒绝,逐项错误返回原因,已接收其他项不回滚。保存request摘要,拒绝同request_id异文。
|
||||
- [x] 用真实临时SQLite跑本组及既有schema/store回归;核对旧execution_operations与重试额度字节/行值未被新操作改写。
|
||||
- [x] 故障注入提交前/提交后;返回值在事务内准备,不能因COMMIT后的额外尾读失败误报未接收;记录同一 before 新after与新before分项的区别。
|
||||
- [x] Commit `feat: persist verification tasks inputs and attempts`。
|
||||
|
||||
## N03:统一接收、独立导入与成功结果交接
|
||||
|
||||
**Files:** Create `V/service.py`、`V/intake.py`;Modify `src/dx_productivity/trial_task_center/service.py` 仅暴露 `verification` 服务;接入 `dsh/execution_runs.py` 的已持久结果通知,不修改其执行/恢复合同;Test `tests/v1_1/test_independent_verification_intake.py`。
|
||||
|
||||
**Interfaces:** `VerificationService(task_store, data_root: Path)`;`create_task(name, *, request_id)`;`publish_inputs(task_id, inputs, *, submission_id)`;`import_pair(task_id, before: Path, after: Path, *, request_id: str, stop_event) -> dict`;`receive_successful_results(result_ref: dict, *, submission_id: str) -> dict`;`reconcile_deliveries(*, limit: int = 100) -> dict`。两种操作最终发布同一种inputs,无来路枚举。默认自动接收容器名为“校验任务”,以持久交接关联键去重,用户可改名。
|
||||
|
||||
- [x] 写两份工程同文件/数据库别名、捕获时变化、成功交接缺before、未成功结果拒绝、重复交接、一次批量和分次输入等价的测试。自建文件只用于事务/捕获测试,不假称可打开CAD工程。
|
||||
- [x] Run `.venv/Scripts/python.exe -m pytest tests/v1_1/test_independent_verification_intake.py -q`,确认失败。
|
||||
- [x] 复用capture_project,受管目录外输入先检查稳定性;两个文件最终数据库同源也要拒绝。已冻结交接只核验引用,不打开原CAD或重新捕获旧before。
|
||||
- [x] 对已落盘成功范围建规范inputs;expectation_ref来自冻结清单/有效回执,不用after反推。补有界交接对账:首次接收和重启/进入校验页重扫未确认通知都用同submission键,落库回执作为完成依据。
|
||||
- [x] 重跑本组;让导入/发布期间的替换和恢复入口抛AssertionError,证明只创建校验记录。成功工程缺证据仍可见,错误输入不能将旧baseline换成当前工程。
|
||||
- [x] 对照接口确认当前能批量传、未来能乱序增量传;输入接收不创建queued尝试,不强制切走用户正在看的任务。
|
||||
- [x] Commit `feat: receive verification inputs and import project pairs`。
|
||||
|
||||
## N04:当前版本查询、任务统计与历史投影
|
||||
|
||||
**Files:** Create `V/queries.py`;Modify `V/service.py`;Test `tests/v1_1/test_independent_verification_queries.py`。
|
||||
|
||||
**Interfaces:** `list_tasks(*, query='', cursor=None, limit=50, read_control=None)`;`read_task(task_id, *, state='', query='', cursor=None, limit=100, read_control=None)`;`read_item(item_id, *, version: int | None = None, read_control=None)`;`read_issues(attempt_id, *, kind='', cursor=None, limit=100, read_control=None)`。返回task view_revision、当前input_version、attempt身份、结论、范围、动作门禁、分页cursor。`summarize_items(rows)`只统计当前版本。
|
||||
|
||||
- [x] 写24项计数、旧版不重复计数、重校验转排队后旧绿灯退出当前、同名不同身份、筛选与整任务操作范围分离的测试。
|
||||
- [x] Run `.venv/Scripts/python.exe -m pytest tests/v1_1/test_independent_verification_queries.py -q`,确认失败。
|
||||
- [x] 实现“输入→当前尝试→结论→可执行动作”的单一投影;执行succeeded且verdictDIFFERENT必须显示异常,而非通过。空任务可新建/加工程,活动任务不禁用创建其他任务。
|
||||
- [x] 参数化查询实现50任务/100工程/100问题上限,搜索名称、路径及已有issue位号/料号;转义LIKE的百分号/下划线。分页cursor绑定过滤、排序和view_revision,身份不从行号推断。
|
||||
- [x] 跑本组与既有任务只读查询测试,核对“24=16一致+2警告+1异常+1无法校验+4待校验,已处理20”;暂停/中断单列不当一致。
|
||||
- [x] 用并发读/新版本发布验证快照计数一致;旧attempt结果只进入历史,不刷新当前绿色。
|
||||
- [x] Commit `feat: query current verification results and task summaries`。
|
||||
|
||||
## N05:独立只读执行器与原生后端适配
|
||||
|
||||
**Files:** Create `V/runner.py`;Modify `netlist_verification.py` 仅暴露固定输入导出缓存适配,原调用保持;Modify `V/service.py`、`V/store.py`;Test `tests/v1_1/test_independent_verification_runner.py`;Regression `test_netlist_execution.py`、`test_pr27_netlist_pause.py`。
|
||||
|
||||
**Interfaces:** `run_attempt(service, attempt_id: str, *, stop_event) -> dict`;`export_inputs(before_ref: dict, after_ref: dict, *, output: Path, stop_event) -> tuple[dict, dict]`;`can_start_native_export(service) -> dict` 返回allowed/reason,不占用新建入口。N06前本适配可返回已有比较事实并显式缺少扩展检查,不能编造完整结论。
|
||||
|
||||
- [x] 写任意独立任务可运行、原输入不变、缺工具不启动CAD、旧缓存损坏重导出、并发领取唯一、资源忙排队的测试。runner用受控OwnedCliScope/现有graph夹具,实际持久库和文件发布链不替换为固定成功值。
|
||||
- [x] Run `.venv/Scripts/python.exe -m pytest tests/v1_1/test_independent_verification_runner.py -q`,确认失败。
|
||||
- [x] 依照E03~E07核验固定引用;捕获/导出只走既有native_netlist。首版独立runner一次领取一个工程对,前后导出顺序运行,避免复制旧批次pool再叠加并发。若原生资源准入不可证明可并行,则留队列等待;不以该等待禁用新建。
|
||||
- [x] 组织比较调用与暂存产物;先按E10确认自有CLI退出,再按E11发布结果及CAS finish。原异步导出/旧finish行为不被替换为新全局队列,接收既有完整证据时可以只复核/复用而不额外开进程。
|
||||
- [x] 跑新组及两个旧网表组;断言替换派发数、CAD启动数、execution_operations写次数均为0,旧入口的暂停与缓存合同不退化。
|
||||
- [x] 注入导出失败和发布中断;确认旧结果不覆盖、迟到attempt不更新当前。记录新执行器与旧资源修复的责任边界,不用本任务修退出helper。
|
||||
- [x] Commit `feat: execute independent verification on immutable inputs`。
|
||||
|
||||
## N06:结构、属性、警告与未知的逐项判断
|
||||
|
||||
**Files:** Create `V/rules.py`;Modify `V/runner.py`;Test `tests/v1_1/test_independent_verification_rules.py`。
|
||||
|
||||
**Interfaces:** `evaluate(before: dict, after: dict, *, expectations: dict | None, check_plan: dict, pin_metadata: dict | None = None) -> dict` 返回checks、issues和N01汇总;`match_components(before_graph, after_graph) -> dict`返回可证明对应及歧义,不改原图。没有expectations与有意声明空变化清单须区分。
|
||||
|
||||
- [x] 用真实最小graph夹具写J01~J13反例:断线、短接、交换物理脚、位号增删、用户网名、无清单属性、正常目标变化、非目标变化、命名警告、必查unknown。固定脚号互换测试独立于名称相似度。
|
||||
- [x] Run `.venv/Scripts/python.exe -m pytest tests/v1_1/test_independent_verification_rules.py -q`,确认失败。
|
||||
- [x] 复用已有完整图/物理端点语义,建立只读对应视图;延用最新实例范围+生效位号唯一绑定,UID仅保留原始证据,其缺失/重复/变化不得否定已证明的位号对应。真实位号/实例歧义仍unknown。连接按完整端点集合比较,单端网络与未连接不混用。
|
||||
- [x] 按check输出事实,不直接复用旧verified作为新最终结论;对允许改名的原比较结果补warning。关键边界为:
|
||||
|
||||
```python
|
||||
if numbers_equal is False or connections_equal is False:
|
||||
pin_text_state = 'error'
|
||||
elif numbers_equal is not True or connections_equal is not True or pin_text_changed is None:
|
||||
pin_text_state = 'unknown'
|
||||
elif pin_text_changed:
|
||||
pin_text_state = 'warning'
|
||||
else:
|
||||
pin_text_state = 'equal'
|
||||
```
|
||||
|
||||
该片段只在物理脚已建立对应后运行;结构或连接已证明改变仍按硬异常处理,未证明的比较结果不会被Python的假值语义误判为“已证实改变”。unknown字段不由空字符串补齐,GND/VCC语义不由模型判断。
|
||||
|
||||
- [x] 跑本组及现有physical pin/逻辑改名测试;证明默认旧比较器结果不被全局放宽,网名变化不会套入引脚名称规则。
|
||||
- [x] 检查错误优先、未知必查、警告、范围一致四类;有已知反脚加缺失属性时仍DIFFERENT,同时保留unknown列表。
|
||||
- [x] Commit `feat: classify verification checks with explicit evidence and coverage`。
|
||||
|
||||
## N07:引脚级字段与封装映射能力探测
|
||||
|
||||
**Files:** Create `V/pin_metadata.py`、`tools/probe_verification_pin_metadata.py`、`docs/research/2026-11-17-pin-metadata-capability.md`;Test `tests/v1_1/test_verification_pin_metadata.py`;Modify `V/runner.py`。
|
||||
|
||||
**Interfaces:** `inspect_pin_metadata(export: dict, *, evidence_root: Path) -> dict` 返回每物理脚的logical_name/pin_value/electrical_type字段、存在性、原始定位、confidence为proven/unknown;`inspect_footprint_mapping(binding: dict) -> dict` 首版只接纳真实可证适配,未支持返回unknown及原因,不用空字典代表映射相同。
|
||||
|
||||
- [x] 写引脚Value与器件Value不同、原字段缺失、引脚类型变化、逻辑名对齐物理号、库映射未知的测试。缺证据边界:
|
||||
|
||||
```python
|
||||
def test_missing_mapping_is_unknown(tmp_path):
|
||||
from dx_productivity.trial_task_center.verification.pin_metadata import inspect_footprint_mapping
|
||||
result = inspect_footprint_mapping({'symbol': 'example', 'cell': 'example', 'evidence': None})
|
||||
assert result['state'] == 'unknown'
|
||||
assert result['mapping'] is None
|
||||
```
|
||||
|
||||
- [x] Run `.venv/Scripts/python.exe -m pytest tests/v1_1/test_verification_pin_metadata.py -q`,确认失败。
|
||||
- [x] 探针只在用户工程已保存副本/受管导出上读取现有原生输出,记录确切字段、版本、存在性和物理脚绑定。先确认能否读出,不能凭类型名发明COM方法或回退CAD采集;探针不直接进入生产导入链。
|
||||
- [x] 只有已证明的字段进入最小解析适配;无引脚Value就保留unknown,不用逻辑名或器件Value代替。库内映射默认未覆盖,只有取得真实版本/符号/Cell/脚号证据才实现对应分支。
|
||||
- [x] 运行本组及N06,使用自建可提交fixture覆盖loop/outloop、同号不同文字、同名不同脚和已证实映射交换;客户报告只本地保存,仓库仅自建摘录。
|
||||
- [x] 写能力报告:已验证字段/格式、未覆盖项、真实读取或纯夹具证据;无法验证的能力不阻止A基础页交付,但必查请求该能力时必须INCOMPLETE。
|
||||
- [x] Commit `feat: expose proven pin metadata and unsupported mapping coverage`。
|
||||
|
||||
## N08:可人工复核的证据模型与连接图
|
||||
|
||||
**Files:** Create `V/evidence.py`;Modify `V/runner.py`;Test `tests/v1_1/test_verification_evidence.py`。
|
||||
|
||||
**Interfaces:** `build_evidence(before_graph: dict, after_graph: dict, issues: tuple[dict, ...], *, binding: dict) -> dict` 返回issue稳定ID、前后物理脚位置、连接对端、差异表和raw定位。`connection_view(evidence: dict, issue_id: str) -> dict` 只生成确定性绘图数据,不调用图片/语言模型。
|
||||
|
||||
- [x] 写R12 1/2互换、短接多对端、纯改名不画红断线、未知映射、图页未知与证据摘要损坏测试。前后pin1的绘制顺序必须相同,不能自动互换位置使图看起来一致。
|
||||
- [x] Run `.venv/Scripts/python.exe -m pytest tests/v1_1/test_verification_evidence.py -q`,确认失败。
|
||||
- [x] 从N06事实产生唯一issue_id;图和表共享同一数据结构,不分别拼判断。端点按固定脚号排列,变化线给出added/removed及原网络名,保留多gate与实例身份。
|
||||
- [x] 将issue绑定不可变raw文件、摘要与可定位段落/对象键;图页无法确定则明确未定位。图标注“由网表生成”,不画伪原理图截图,不用生成模型解释电气正确性。
|
||||
- [x] 跑本组与N06;反例断言每条红色连线都有对应连接error/差异,纯文字warning没有虚构接线变化。
|
||||
- [x] 检查独立输入无expectation时证据仍可读;原生身份列差异与有效料号显示分开,不改写raw以统一数值。
|
||||
- [x] Commit `feat: build traceable pin and network comparison evidence`。
|
||||
|
||||
## N09:A工作台、独立新建与证据检查器
|
||||
|
||||
**Files:** Create `UI/verification_workspace.py`、`UI/verification_controller.py`、`UI/verification_inspector.py`;Modify `UI/main_window.py`、`UI/icons.py`,样式仅加本页控件选择器;Test `tests/ui/test_verification_workspace.py`、`test_verification_inspector.py`。
|
||||
|
||||
**Interfaces:** `VerificationWorkspace(service, parent=None)`;`open_task(task_id, item_id=None)`、`set_active(active)`、`shutdown()`、`busy`、`busy_changed`;`VerificationInspector.set_evidence(evidence)`。controller通过N04查询,未来增量输入仅更新结果查询,不重新设计来路入口。
|
||||
|
||||
- [x] 写四导航映射、始终可新建、已有任务时独立导入、无来源横条、选择保持、不同任务延迟回调、DIFFERENT不显示通过的Qt测试。沿用既有`ui` fixture,但不更改其修复逻辑。
|
||||
- [x] Run `.venv/Scripts/python.exe -m pytest tests/ui/test_verification_workspace.py tests/ui/test_verification_inspector.py -q`,确认失败。
|
||||
- [x] 按最终图建立任务列表/状态筛选/工程表/右证据/固定底栏;main_window按页面对象明确映射四导航,DSH懒加载不被触发。新建对话框只含名称与可选前后工程,不要求来源选择。
|
||||
- [x] QPainter或Qt原生控件渲染N08确定性图,表格同源;保持8–12px圆角、白色数据面、已有亚克力外框和减少透明度设置。980宽改可展开详情,不遮住开始/停止按钮。
|
||||
- [x] 跑本组、现有history/DSH导航与样式测试;无后台run时点击导航或选工程只查询,不隐式导出。
|
||||
- [x] 人工看1280×880、980×700及125/150%缩放;右侧R12对照保持1/2位置,警告/未知文字可读。静态图片仅视觉参考,不算功能验收。
|
||||
- [x] Commit `feat: add the independent verification workspace and evidence inspector`。
|
||||
|
||||
## N10:开始、停止、重校验、崩溃恢复与版本竞争
|
||||
|
||||
**Files:** Modify `V/service.py`、`V/store.py`、`V/runner.py`、`UI/verification_controller.py`、`UI/main_window.py` 仅校验生命周期;Test `tests/v1_1/test_verification_control.py`、`tests/ui/test_verification_control.py`。
|
||||
|
||||
**Interfaces:** `start(task_id, *, selection: tuple[tuple[str,int], ...] | None, request_id)`,None表示服务端冻结当前全部ready;`stop(run_id, *, request_id)`;`rerun(item_id, version, *, request_id)`;`recover() -> dict`;`begin_shutdown()`。停止/恢复均不调用替换停止/准备重试/核验恢复函数。
|
||||
|
||||
- [x] 写重复点击、冻结范围不吞新项、当前v2不被v1完成覆盖、取消与提交竞争、进程退出未知、重启不自动执行的测试。queued取消保留历史;整run停止前从未派发项投影回待校验,用户单项取消显示已停止。
|
||||
- [x] Run `.venv/Scripts/python.exe -m pytest tests/v1_1/test_verification_control.py tests/ui/test_verification_control.py -q`,确认失败。
|
||||
- [x] 实现命令幂等与持久stop_requested;领取前/后、原生导出阶段和发布CAS前检查。终态提交先发生时保留真实结果;取消先发生时旧callback不能提交当前结果。
|
||||
- [x] 实现重启核实OwnedCli身份/退出、F15产物补提交和interrupted;归属核对使用原owner/token/进程创建身份,不仅凭PID,以免PID复用误杀外部进程。未知资源留stopping,禁止盲目新导出。新attempt递增generation,旧terminal不改回running。
|
||||
- [x] 跑本组及旧网表暂停组;在全部校验控制测试中将既有替换动作设为抛AssertionError,证明不会触发。GUI关闭不join/wait原生进程,通知安全结束后再关闭。
|
||||
- [x] 受控慢导出期间切页、建新任务和停止,验证事件循环可响应;新工程后到保持待校验,不无限扩展当前run范围。
|
||||
- [x] Commit `feat: control and recover independent verification attempts`。
|
||||
|
||||
## N11:完整报告、历史与证据保留
|
||||
|
||||
**Files:** Create `V/report.py`;Modify `V/service.py`、`UI/verification_controller.py`、`retention.py` 仅保护校验引用,复用HistoryRepository;Test `tests/v1_1/test_verification_reports.py`、`tests/ui/test_verification_report_actions.py`;Create `docs/user/independent-verification.md`。
|
||||
|
||||
**Interfaces:** `render_item_report(result_ref: dict, destination: Path) -> Path`;`export_task(task_id, destination: Path, *, request_id)`;`open_evidence(attempt_id, artifact_id)`只接受受管artifact标识。导出冻结view_revision,可在运行中生成并明确未完成项。
|
||||
|
||||
- [x] 写同版本报告/图表一致、HTML转义、原证据损坏、导出重名、运行中快照、清历史不删证据、缓存不可伪装新结果的测试。
|
||||
- [x] Run `.venv/Scripts/python.exe -m pytest tests/v1_1/test_verification_reports.py tests/ui/test_verification_report_actions.py -q`,确认失败。
|
||||
- [x] 从N08证据包渲染HTML/JSON,字段转义,原始文件只引用或用户明确选择后打包;默认不复制整个工程。报告固定输入/策略/工具/attempt摘要与检查范围。
|
||||
- [x] 暂存→完整性核验→原子发布,重名目录明确错误不混写;HistoryRepository用稳定source_key防重复记录校验事件,此source_key为事件去重而非UI来源类型。
|
||||
- [x] 跑本组与retention/history回归,核对当前/活动引用不可被普通日志清空删除,失去证据时显示不可用而非缓存绿灯。
|
||||
- [x] 写用户说明:新建/自动接收无需来源、开始范围、警告/异常/未知、版本更新、停止重启、对照图与证据查看;不宣称ERC/PCB已检查。
|
||||
- [x] Commit `feat: export verification evidence and preserve result history`。
|
||||
|
||||
## N12:集成、真实只读输入、包内入口与发布门禁
|
||||
|
||||
**Files:** Create `tools/verify_independent_verification.py`、`tests/v1_1/test_independent_verification_acceptance.py`、`tests/ui/test_verification_acceptance.py`、`docs/testing/2026-11-17-independent-verification-acceptance.md`;Modify `packaging/DxPartReplace.spec`及打包测试只在确有静态遗漏时,保护现有本地变更。
|
||||
|
||||
**Interfaces:** CLI `--fixture-root ... --output ...` 与 `--native-before ... --native-after ... --output ...` 明确分开;后者只读两份合法已保存工程,不执行换料。原有真实新换料闭环由已有执行器/验收工具交接,本任务只验证新校验任务能接收和复核,不重做其他任务的修复。
|
||||
|
||||
- [x] 用真实临时SQLite、受控CLI和完整文件发布链建立端到端用例:两份工程创建、批量成功交接、增量乱序、24工程计数、命名警告、反脚、缺基线、停止、重启、v1/v2竞争、报告。每用例记录实际派发与原工程摘要,不用单纯固定绿灯填页面。
|
||||
- [x] Run `.venv/Scripts/python.exe -m pytest tests/v1_1/test_independent_verification_acceptance.py tests/ui/test_verification_acceptance.py -q`,确认缺口;前置已全部实现时允许首跑通过,不为制造red破坏实现。
|
||||
- [x] 实现验收CLI串联公开接口并非零退出失败,记录模型图片仅参考、新功能真实证据另存。真实只读副本上复核引脚字段与层级范围;未知范围保持未知,不修改源工程制造反例。
|
||||
- [x] 运行全部新增组、现有网表/BOM/导航/关闭/DSH及打包回归;再按仓库默认配置运行默认suite一次。记录当前分支并行修复是否已合入,不能冒用旧108项或旧EXE结果。
|
||||
- [x] 在实际包中验证四导航、缺CAD工具仍可新建/导入记录/看已有报告、正确unavailable、正常关闭;不携带厂商exe和客户fixture。若可用真实本次成功回执,验证自动交接与手工独立输入共存且零重复换料。
|
||||
- [x] 输出验收矩阵每项结果、通过数量、精确构建/输入/策略摘要、失败现场和未测范围;未取得真实引脚Value/映射证明时保留未覆盖声明。
|
||||
- [x] Commit `test: accept independent verification tasks and evidence workflows`,功能完成后再走集成/发布决策;本计划不授权发布。
|
||||
|
||||
## 1. 场景到任务的验收映射
|
||||
|
||||
| 场景 | 必须满足 | 任务 |
|
||||
| --- | --- | --- |
|
||||
| 前面已有替换任务,仍新建独立校验 | 新建不依赖或覆盖换料任务,不要求来源 | N02/N03/N09 |
|
||||
| 成功结果批量与分次传入 | 当前数据相同,重复与旧版不派发 | N02/N03 |
|
||||
| 校验运行时收到新版本 | 旧输入固定,旧结果历史,新版待校验 | N02/N04/N10 |
|
||||
| R12 1/2连接互换 | DIFFERENT,固定脚号图与逐脚表同源 | N06/N08/N09 |
|
||||
| loop→outloop且结构不变 | WARNING,不能直接无提示通过 | N06/N07 |
|
||||
| 缺引脚字段或库内映射 | unknown/未覆盖,必查未知不通过 | N01/N07 |
|
||||
| 只有网名变 | 拓扑与名称分别显示,不套引脚改名放行 | N06 |
|
||||
| 无清单两份工程 | 可比较,不能说换料规则符合 | N01/N03/N06 |
|
||||
| CLI/解析/证据失败 | 明确原因,安全收尾后继续,未知资源暂停 | N05/N10/N11 |
|
||||
| 关闭/崩溃/迟到回调 | 不重做换料、不污染新尝试,重启不自运行 | N10 |
|
||||
| 图、表、报告、raw | 同一输入/issue/attempt,能追溯 | N08/N11 |
|
||||
| 24项及1000工程规模 | 当前版本计数正确,100行有界读取,事件循环可响应 | N04/N09/N12 |
|
||||
|
||||
## 2. 分段交付与未实现边界
|
||||
|
||||
1. N01~N04:可以创建、接收和查询独立任务,先不宣称校验完成。
|
||||
2. N05~N08:可独立执行、输出分级结论与人工证据;无法读取的字段保留unknown。
|
||||
3. N09~N11:最终A页面、控制、报告与历史完整可用。
|
||||
4. N12:真实输入、包内入口与回归结果已留证,交付本地开发包;默认回归仍有既有时序波动,不据此发布。
|
||||
|
||||
共12个新增功能任务、84个复选步骤已逐项实施和执行验证;测试波动及未覆盖能力见验收记录,勾选不表示已满足发布门槛。本文不是把旧计划未完成项全部重做:原生后端、非阻塞换料和当前修复仍沿用已有成果。未来替换实时推送、自动启动开关、未知电气语义字典、库映射扩展和自动修复均不作为首版暗含承诺。
|
||||
@@ -0,0 +1,158 @@
|
||||
# 工程校验功能开发与交付计划
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use `superpowers:executing-plans` with the linked N01~N12 detailed plan. This is the delivery entry point, not authorization to begin application changes. N01–N12 implementation and local development-package acceptance are complete; continuous full-suite stability remains a release gate.
|
||||
|
||||
**Goal:** 开发独立校验任务、可信判断和可人工复核的 A 工作台,复用现有能力,只增加缺失功能。
|
||||
|
||||
**Architecture:** 按“任务数据 → 独立校验 → 人工证据 → 页面与操作 → 验收”顺序交付。任务、工程输入版本、执行尝试分开持久化;统一接收接口适配当前批量交接和未来增量推送;判断、图、表和报告共享一份事实。
|
||||
|
||||
**Tech Stack:** Python 3.12、SQLite、PySide6、现有原生网表CLI与进程归属机制、pytest/pytest-qt;不新增运行时依赖。
|
||||
|
||||
**Spec:** [已确认业务设计及六张流程/状态图](../specs/2026-11-17-independent-verification-business-design.md)。逐文件接口、测试命令和提交步骤见 [N01~N12 开发清单](2026-11-17-independent-verification-new-features.md)。
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- 只做新增功能,不接手其他任务的退出、资源回收、工程统一提交或任务徽标修复。
|
||||
- 任何时候可新建校验,不展示或要求选择来源,不加换料流水线横条。
|
||||
- 当前接收已提交成功结果;增量、去重和版本接口做好,但本轮不开发替换实时刷新。
|
||||
- 使用固定前后副本;不自动换脚、不重新换料、不写原工程或库。
|
||||
- 位号/物理脚号/连接严格;引脚文字变化单独警告;缺证据明确未知。
|
||||
- 工具判断、人工接线图、事实表、报告绑定同一工程版本和同一次尝试。
|
||||
- 每任务先验证失败用例、最小实现、相关回归、自审和单独提交。功能完成前不发布。
|
||||
|
||||
## 1. 开工前处理
|
||||
|
||||
现在共享工作区的公共执行模块正在由其他任务修改,包括回执、工程统一保存、身份关联、资源隔离和 UI 状态。不得复制或清理这些未提交修改,也不得在其上混入本功能实现。
|
||||
|
||||
实施时使用独立开发分支 `codex/independent-verification` 和独立工作目录,按 `superpowers:using-git-worktrees` 流程准备。先核对已有分支是否存在并保留工作;不重置用户分支。基础纯逻辑和新增文件可基于已提交主线开发;接线前将其他任务的已合入修复同步进来,再复核接口。
|
||||
|
||||
| 接口边界 | 我们需要什么 | 处理原则 |
|
||||
| --- | --- | --- |
|
||||
| 工程身份 | 实例范围、生效位号、物理脚号及可靠对应证据 | 延用最新位号唯一关联规则;UID 为证据,不因UID缺失/变化一律拒绝 |
|
||||
| 成功交接 | 真正已保存、关闭/重开回读的工程提交证明 | 待保存或只完成内存替换的项不得交接为成功 |
|
||||
| 输入副本 | 本次 before、after、范围与摘要 | 缺失就登记无法校验,不能补造历史before |
|
||||
| 预期变化 | 相对同一before的累计已成功修改及固定规则 | 不只传最后一条改动,不从after实际值反推预期 |
|
||||
| 自有资源 | 当前本域CLI的归属和退出证明 | 复用既有接口,不修CAD退出;隔离桌面不被错误等同未退出CLI |
|
||||
| UI公共文件 | 四导航插入点、关闭协作、主服务引用 | 窄范围接线,不覆盖其他任务实时刷新或状态投影改动 |
|
||||
|
||||
接线不满足时仍可完成本域数据/规则测试;不得用虚构成功回执凑出可演示闭环。若同名类/方法已经被新版本增加,应先复用,不按旧文件清单重复建设。
|
||||
|
||||
## 2. 四个开发阶段
|
||||
|
||||
| 阶段 | 任务 | 完成后能做什么 | 阶段验收条件 |
|
||||
| --- | --- | --- | --- |
|
||||
| 第一阶段:校验任务与数据 | N01~N04 | 创建空任务、导入两份工程、接收成功项、保存版本和查询状态 | 重复/乱序不重复建项;新版本不覆盖旧输入;无来源限制;缺证据可见 |
|
||||
| 第二阶段:独立校验与人工证据 | N05~N08 | 独立导出、逐项判断、警告分级,生成前后接线图所需数据 | 反脚检出;改名有警告;未知不通过;图和表能定位到原始证据 |
|
||||
| 第三阶段:A 页面与完整操作 | N09~N11 | 第四页、任务选择、开始/停止/重校验、前后对照、报告和历史 | 有其他任务仍可新建;控制操作不换料;关闭重启安全;报告可独立复核 |
|
||||
| 第四阶段:集成与交付验收 | N12 | 在实际应用包中完成两种输入路径和混合批次 | 相关/默认回归、真实只读输入、产物身份、正常关闭全部留证 |
|
||||
|
||||
前三个阶段是内部可测交付,不等同发布版本。每阶段更新同一进度记录,注明实际完成的任务、提交、测试和能力缺口,不依据图片或测试数量推断已经支持的业务范围。
|
||||
|
||||
## 3. 十二个任务的工作量边界
|
||||
|
||||
| ID | 要实现的最小完整内容 | 依赖 | 做完怎么判断 |
|
||||
| --- | --- | --- | --- |
|
||||
| N01 | 输入、逐项检查、执行状态、结论和覆盖合同 | 无 | 空检查/缺必查不一致,错误优先,警告与未知分别保留 |
|
||||
| N02 | SQLite校验任务、工程、不可变版本、尝试、运行与去重 | N01 | 同版同文幂等,同版异文拒绝,只有一个活动尝试,旧DB正常打开 |
|
||||
| N03 | 独立导入、统一发布、成功交接和有界补交 | N02 | 一次批量和分次发布结果相同;只交接提交成功范围;创建不派发 |
|
||||
| N04 | 当前版本投影、计数、分页、筛选、历史 | N03 | 24项计数正确,旧结果不重复,筛选不改变批量命令范围 |
|
||||
| N05 | 复用原生导出的独立只读runner | N02、N03 | 不调用替换/CAD写入,工作副本隔离,资源忙只排队 |
|
||||
| N06 | 器件/物理脚/连接/属性/名称的判断分级 | N01、N05 | 断线短接反脚、错属性均定位;允许改名给警告;缺证据未知 |
|
||||
| N07 | 引脚Value、逻辑名、电气类型能力验证与适配 | N05、N06 | 证明字段来源与脚号对应;拿不到就unknown,不替代字段 |
|
||||
| N08 | 同源issue、接线图数据、对照表和raw定位 | N06、N07 | 1/2脚前后位置固定,红线有对应事实,文字警告不画成接错线 |
|
||||
| N09 | A页面、独立新建、四导航、工程表与检查器 | N04、N05、N08 | 与整体UI一致,已有任务时仍可新建,无来源/流水线横条 |
|
||||
| N10 | 开始/停止/继续/重校验、关闭重启与版本竞争 | N05、N09 | 停止未派发项保留待校验,迟到结果不串版本,零重复换料 |
|
||||
| N11 | 单项/整任务HTML/JSON、证据打开、历史和引用保留 | N08、N10 | 图表报告对应同一证据包,运行中报告标未完成,清历史不删证明 |
|
||||
| N12 | 服务/Qt/真实只读输入/实际包验收 | N01~N11 | 全链路证据可复查,失败现场保留,支持范围写明 |
|
||||
|
||||
顺序执行即可,不需要同时派多个代理。每项具体文件、接口签名、用例和7步清单在[N01~N12详细清单](2026-11-17-independent-verification-new-features.md)中;共84步,不在此重复创建另一套进度复选框。
|
||||
|
||||
## 4. 最早验证的两个能力点
|
||||
|
||||
N01~N04开发期间可以提前做N07的只读探针,尽早知道业务边界;只读探索结果不等于N07任务已完成。
|
||||
|
||||
| 能力点 | 成功时 | 无法取得时 |
|
||||
| --- | --- | --- |
|
||||
| 引脚级Value/名称/类型 | 保存准确字段、存在性、原始定位,与物理脚绑定后比较 | 明确标该字段未覆盖;用户必查时INCOMPLETE;不得用器件Value代替 |
|
||||
| 库内引脚到焊盘映射 | 只有确切库版本和绑定证明才启用检查 | 首版显示未覆盖,不承诺能发现网表未体现的库内反脚 |
|
||||
|
||||
已确认的工程接线反脚检查不能因为扩展映射拿不到就不做;也不能因为基础网表一致而宣称库内部映射通过。GND/VCC文字变化的语义字典和自动严重性仍沿用业务稿的保留决定,不在开发时临时让模型判断。
|
||||
|
||||
## 5. 开发时固定的接口载荷
|
||||
|
||||
这里固定形状,摘要、ID和受管路径由服务生成,示例是结构说明,不是可跳过验证的真实输入。
|
||||
|
||||
```python
|
||||
input_record = {
|
||||
'item_key': 'stable-project-comparison-key',
|
||||
'project_key': 'stable-project-identity',
|
||||
'input_version': 1,
|
||||
'before_ref': {'manifest_id': 'before-id', 'sha256': 'a' * 64},
|
||||
'after_ref': {'manifest_id': 'after-id', 'sha256': 'b' * 64},
|
||||
'expectation_ref': None,
|
||||
'check_plan': {
|
||||
'policy_version': 'verification-v1',
|
||||
'required_checks': ['inputs', 'coverage', 'components', 'physical_pins', 'connections', 'net_names'],
|
||||
'optional_checks': ['pin_text'],
|
||||
'excluded_checks': ['footprint_mapping'],
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
校验task_id与submission_id为外层命令参数;没有 source 字段。expectation_ref=None仅说明未核对换料规则;若后来提供规则,要发布新版本,不能修改原检查上下文。check_plan的id与N01实际定义保持一致,类型/枚举/摘要长度在边界拒绝非法值。
|
||||
|
||||
结果包至少分开保存:输入版本、attempt/generation、执行state、verdict、coverage、checks、issues、artifacts、resource_state。界面不得把attempt succeeded当成verdict CONSISTENT。
|
||||
|
||||
## 6. 每个提交的验证流程
|
||||
|
||||
1. 写本任务明确反例,运行该测试确认失败原因属于本功能缺失。
|
||||
2. 实现最小完整逻辑;同步所有调用方、必要fixture、序列化和导出。
|
||||
3. 运行该任务测试和与公共边界相关的既有回归,失败则定位根因,不通过跳过/放宽断言凑绿。
|
||||
4. 对照业务稿检查状态、图表数据、证据绑定和失败路径;确认未调用换料/恢复入口。
|
||||
5. 只提交本任务文件,记录提交SHA、实际命令、通过数量和未测范围,再进入下一项。
|
||||
|
||||
本仓库默认测试路径在 `pyproject.toml` 中为 `tests/v1_1` 与 `tests/ui`;只运行裸pytest不能声称DSH/打包组已测。N12需显式执行相关扩展组后,再跑默认suite。
|
||||
|
||||
```text
|
||||
.venv/Scripts/python.exe -m pytest tests/v1_1/test_native_cli_netlist.py tests/v1_1/test_netlist_execution.py tests/v1_1/test_pr27_netlist_pause.py -q
|
||||
.venv/Scripts/python.exe -m pytest tests/ui tests/dsh tests/packaging -q
|
||||
.venv/Scripts/python.exe -m pytest -q
|
||||
```
|
||||
|
||||
第一条是旧原生网表边界回归;第二条涵盖UI、DSH、打包;第三条按项目默认配置验证。具体新增测试文件由N01~N12逐项命令执行,不能只跑以上旧测试声称新功能完成。进程级测试使用新的短路径basetemp,环境变量仅对测试进程设置,不改系统用户环境。
|
||||
|
||||
## 7. 最终交付门槛
|
||||
|
||||
| 验收面 | 必须提供的证据 |
|
||||
| --- | --- |
|
||||
| 功能路径 | 已有换料成功数据交接与用户独立两份工程均可创建、运行、查看、重校验,且可共存 |
|
||||
| 业务正确性 | 反脚/断线/短接/错属性/命名警告/缺证据均给出对应事实与范围 |
|
||||
| 人工说服力 | 同一R12反脚在图、逐脚表、HTML报告、raw证据四处一致,能看出为什么异常 |
|
||||
| 版本与幂等 | 重复接收零重复项;v1结果不覆盖v2;同版异文拒绝;旧attempt不能覆盖新结果 |
|
||||
| 非阻塞与失败 | 单项问题保留后继续其他可运行项;资源/存储不确定时暂停正确范围,不假报通过 |
|
||||
| 使用体验 | 980×700、1280×880和125%/150%可读;慢查询可导航和停止;新建按钮始终可用 |
|
||||
| 生命周期 | 正常关闭、崩溃恢复、停止继续、证据丢失、历史清理均不损坏输入或重复换料 |
|
||||
| 包与范围 | 实际包启动/入口/关闭、工具缺失原因、精确产物与输入摘要;未覆盖能力明确列出 |
|
||||
|
||||
开发不设虚假的固定天数。每阶段通过验收出口后再推进;引脚字段/封装映射的探索结果影响能承诺的检查范围,不影响先交付可信基础校验和证据页面。
|
||||
|
||||
## 8. 交接状态
|
||||
|
||||
### N12 后续闭环标准(2026-11-18)
|
||||
|
||||
所有后续任务按[闭环标准 v1](../../testing/verification-closed-loop-standard.md)留证;不再用“导入成功”“文件已生成”或历史分组通过数量单独宣布闭环完成。批量添加见[验收记录](../../testing/2026-11-18-verification-batch-import.md)。
|
||||
|
||||
- [x] C01~C05:开始前冻结名单/输入/策略,核对实际运行成员、预期结论、同源图表与报告、原文和退出证明;源文件不变、新增换料操作为0。
|
||||
- [x] C06:实际包正常关闭后重启,证据可回读,尝试数不增加。
|
||||
- [x] C07:实际包单项重校验,新attempt及generation递增,旧结果/报告不被覆盖。
|
||||
- [x] C08受控回归:反脚、命名警告、必查未知、停止/资源未知、版本竞争和单项失败后继续的服务/Qt反例。
|
||||
- [x] C08实际包补充:原生导出失败项先运行,后续正常项仍完成;混合批次的报告、重启和重校验均通过,见[本轮闭环验收](../../testing/2026-11-18-verification-closed-loop.md)。
|
||||
- [x] C08实际包停止与资源未知:已有各自独立现场,见[剩余闭环执行记录](2026-11-18-verification-remaining-closure.md);三工程停止/继续和自有实例异常退出后资源未知保护分别通过。
|
||||
- [x] 真实已保存换料回执触发的自动交接实际包闭环:新临时副本真实换料1项,自动交接后校验、报告、重启和重校验通过,校验期间换料增量0;见同一执行记录。
|
||||
- [x] 连续默认全量:两轮2276 passed,固定提交上的最终运行0失败/0错误,631个产品/测试/工具文件运行前后不变;扩展120 passed、1 skipped(缺7-Zip)。未改旧时序断言,完整结果见[最终闭环验收](../../testing/2026-11-18-verification-final-closure.md)。
|
||||
|
||||
单次只读验收入口为 `tools/verify_independent_verification.py --expect-verdict ...`,明确只覆盖 C01~C05;实际包入口为 `tools/accept_verification_closed_loop.py`,覆盖独立输入 C01~C07,并可用 `--fault-batch` 增加原生失败隔离反例。未测项在JSON里保留not_run。测试失败或标准不符均非零退出;已有换料历史采用执行前基线,不能要求历史总数为0。
|
||||
|
||||
用户授权的 N01~N12 已顺序实现、分步提交并完成本地开发包验收。11月18日后续批量导入及四项剩余闭环均已完成:独立输入和真实换料保存交接两条实际包路径通过,停止与资源未知保护通过,固定版本的默认全量2276项通过。历史波动记录保留,不宣称修复其全部根因。未合并、推送或发布,本分支没有复制另一修复任务的未提交修改。
|
||||
|
||||
实施进度及验证结果见 docs/testing/2026-11-17-independent-verification-acceptance.md。后续开发以本入口和[N01~N12清单](2026-11-17-independent-verification-new-features.md)共同为准,11月6日的V/U旧计划保留为历史参考,不能再并行照旧重建后端或来源界面。
|
||||
@@ -0,0 +1,16 @@
|
||||
# 剩余四项闭环执行计划
|
||||
|
||||
用户确认顺序实施并允许在工具新建的临时副本中执行真实换料。使用 `codex/independent-verification` 工作区,不修改另一修复工作区,不合并/推送/发布。
|
||||
|
||||
- [x] 实际包停止、重启不重跑、继续未派发项、明确重校验已停止项。三工程现场:`D:/dx-vfy-stop-three-20261118/acceptance.json`,两项未派发均保持待校验,继续和重校验的报告绑定通过。
|
||||
- [x] 本工具自有实例异常退出,按PID和创建时间证明后才中断;重启保留资源未知,不派发后续原生导出,仍能新建校验。现场:`D:/dx-vfy-owner-exit-20261118/acceptance.json`。不为闭环伪造退出证明,不终止其他进程。
|
||||
- [x] 真实换料交接:临时副本 RV05 从4100-CA0000-T7替换至4100-CA0000-T0,RV11保持;真实保存回执自动登记,校验/报告/重启/重校验不新增换料。新现场 `D:/dx-vfy-real-handoff-20261118-v2/acceptance.json` 和其 `verification-loop/acceptance.json` 均通过;替换操作1条且verified,校验阶段增量0,声明属性检查为expected_change,原始样例及库LMC摘要未变。
|
||||
- [x] 最终回归:两轮完整默认suite均为2276 passed;最终固定提交XML `D:/dx-vfy-fixed-default-20261118.xml`,运行前后631个产品/测试/工具文件摘要不变。执行恢复与打包扩展120 passed、1 skipped(缺官方7-Zip),最终包运行时和资源释放复核通过。没有用分组复核替代连续通过,也未放宽旧断言。
|
||||
|
||||
验收工具新增 `--control-scenario stop|owner-exit`、`--handoff-data`,真实换料入口为 `tools/accept_verification_saved_handoff.py`。后者只接受全新外部输出目录,先原生导出证明固定RV05/RV11前提,使用已有BOM/执行器和实际EXE运行;不通过直接修改SQLite制造回执。
|
||||
|
||||
交接场景的before来自不可变历史捕获,不能要求它的源文件在真实替换后仍保留旧字节;`freeze_inputs(..., historical_before=True)`要求冻结预期清单,核验历史副本完整性,以已保存after的源摘要建立校验只读基线。默认独立导入仍要求两个源与导入时摘要相同。
|
||||
|
||||
每项完成需:输入名单/摘要和预期在执行前固定;运行及报告身份一致;原始样例/共享库不变;测试副本仅发生一次授权替换;校验阶段新增换料为0;停止/异常状态不能被显示为一致。按[闭环标准](../../testing/verification-closed-loop-standard.md)逐项留passed/failed/not_run。
|
||||
|
||||
最终四项记录见[剩余闭环验收](../../testing/2026-11-18-verification-final-closure.md)。保留分支与独立工作目录;未合并、推送或发布。Value/库内部映射仍属于明确未覆盖的能力边界。
|
||||
@@ -0,0 +1,250 @@
|
||||
# Issue #44 整批任务整改 Implementation Plan
|
||||
|
||||
2026-11-27 更新:用户已批准实施,并将验收范围收敛为“本地、增量代码的实际功能、不重复验收”。该最新指令覆盖下文原规划阶段的授权边界和 Task 7 全量发布验收安排。实际整改、增量结果及未复现项见 `docs/testing/2026-11-27-issue44-incremental-acceptance.md`;未执行全量/100 工程/冻结包复测。
|
||||
|
||||
> **For agentic workers:** 使用 `superpowers:executing-plans` 按任务执行;本次仅编写与审查方案,未授权自动启动实施。用户另行要求并行代理时才选择 `superpowers:subagent-driven-development`。
|
||||
|
||||
**Goal:** 让整批任务按确认范围运行,安全失败可继续,写入不确定整批暂停,资源真实释放后才允许新写入,并输出可对账的批次回执。
|
||||
|
||||
**Architecture:** 复用 `task_queue`、`BatchCadRuntime`、`RunJournal` 和诊断导出。新增批次裁决与汇总两个小模块,服务、UI 和导出消费同一范围及结果。历史队列保留兼容读取,不新增执行器。
|
||||
|
||||
**Tech Stack:** Windows、Python >=3.12,<3.13、PySide6/Qt6、pywin32、SQLite、pytest/pytest-qt,真实 CAD 使用 Mentor 7.9.5。
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-11-27-issue44-batch-remediation-design.md`。本计划为待用户评审的实施草案;示例是拟新增接口的验收契约,不是已经存在或通过的实现。
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- 基线 `f80127e7bd0b098dfe3ef34823a3c13f2f9c5982`;分支 `codex/issue44-batch-remediation-plan`。
|
||||
- 整批中存在缺计划、工程不可访问等不可执行任务时,在执行确认中列出可执行项和跳过原因,确认后只执行可执行项。写入结果不确定的任务仍停止保护。
|
||||
- 即使已证明自有写进程退出、租约归还,只要原桌面仍被外部句柄持有,仍阻断新写入;物理释放核验通过后再继续。不能把隔离记作资源释放成功。
|
||||
- 某工程已可能写入、但保存核验结果不确定时,暂停整批;即使资源已经释放,也必须先核验该工程,再重新确认继续。不能自动隔离该工程后推进其他独立工程。
|
||||
- 不改变单任务/Agent 现有严格 preflight 契约;批量容错必须显式选择,不能蔓延到排期工具。
|
||||
- 新写入前在租约内复核范围摘要、计划和实时资源事实;仅 UI 禁用不构成保护。
|
||||
- 不新增运行依赖,不删除 uncertain 标记换取通过,不按错误码证明无写入,不终止身份不明或外部进程。
|
||||
- 按当前轮次与操作身份防重放;报表/导出失败不导致替换重试。
|
||||
- 真实 CAD 验收使用完整独立副本;源码回归与冻结包实测分开报告。
|
||||
|
||||
## 0. 工作区与已有基线
|
||||
|
||||
工作区:`F:/Sync Tool Skyworth/Work Maps/dxdesigner-part-replacement/.worktrees/issue44-plan`。
|
||||
|
||||
原仓库的 `.venv` 已存在,可直接复用;只在当前进程设置环境,不修改 Windows 用户环境变量:
|
||||
|
||||
```powershell
|
||||
$env:PYTHONPATH = (Resolve-Path src).Path
|
||||
$env:QT_QPA_PLATFORM = 'offscreen'
|
||||
$taskPython = 'F:/Sync Tool Skyworth/Work Maps/dxdesigner-part-replacement/.venv/Scripts/python.exe'
|
||||
& $taskPython -X utf8 -m pytest tests/v1_1/test_task_queue.py tests/v1_1/test_resource_queue_resume.py tests/v1_1/test_batch_supervisor.py tests/ui/test_pr27_confirmation_admission.py -q --tb=short
|
||||
```
|
||||
|
||||
2026-11-27 已执行:58 passed,70.93 秒。实施后的行为会有意改变部分 D8 隔离后自动续跑测试;必须替换为本次确认的安全策略,不能只删除失败断言。
|
||||
|
||||
## 1. 文件职责与拟定接口
|
||||
|
||||
以下均为拟新增或调整的接口,任务之间以这些名字和字典字段对接。
|
||||
|
||||
| 文件 | 职责与接口 |
|
||||
| --- | --- |
|
||||
| 新增 `trial_task_center/batch_admission.py` | `resolve_batch_task_ids(tasks, group_id: str, *, selected_ids: tuple[str, ...] | None = None) -> tuple[str, ...]`;`build_batch_admission(service, task_ids: tuple[str, ...], *, scope_kind: str) -> dict`;`validate_batch_admission(service, admission: dict) -> dict` 返回重新核对的可执行子集原生报告或抛出 TaskCenterError |
|
||||
| 新增 `trial_task_center/batch_summary.py` | `summarize_batch(manifest: dict, queue: dict, operation_rows: list[dict], resource_snapshot: dict, *, elapsed_seconds: float) -> dict`,纯函数,输入为已验证身份的当前轮次快照 |
|
||||
| `trial_task_center/batch_resources.py` | 新增 `observe_process_identity(identity: dict) -> dict`,state 为 gone/alive/unknown;保留 `_process_gone(identity) -> bool` 包装,只在 gone 返回 True;统一 `resource_blockers` |
|
||||
| `ui/task_list.py` | 新增 `selected_task_ids() -> tuple[str, ...]` 返回当前显式选集;新增所选执行动作,保留本批动作 |
|
||||
| `ui/main_window.py` | 解析动作意图、异步预检、显示裁决、确认后复核;展示统一摘要;不在 GUI 线程扫描全部工程 |
|
||||
| `dsh/execution_runs.py`、`dsh/run_journal.py` | 持久化 manifest 绑定、原执行回执和汇总;恢复不改变原执行子集;兼容缺少 manifest 的历史记录 |
|
||||
| `task_queue.py`、`batch_runtime.py`、`batch_supervisor.py` | 执行/资源/停滞的真实事实;不再隔离不确定工程后自动推进其他工程 |
|
||||
| `workspace_execution.py` | 只保留旧检查点恢复,同样应用严格资源与不确定暂停策略 |
|
||||
| `execution_problems.py`、`ui/resource_status.py` | 从同一操作/资源快照派生计数和准入 |
|
||||
| `diagnostics_bundle.py` | 在原白名单和限额下导出 manifest、receipt 及关联证据 |
|
||||
|
||||
`build_batch_admission` 返回字段:`schema_version=1`、`policy_version='issue44-strict-v1'`、`scope_kind`、`candidate_task_ids`、`decisions`、`runnable_task_ids`、`plan_hashes`、`candidate_fingerprint`、`manifest_digest`、`global_blockers`、`ready`、`execution_report`。每条 decision 含 task_id、order、project、classification、reason_code、message、enabled_scope、component_count、verification_pending;明确不存在的值用 null,不用未知的 0。
|
||||
|
||||
`summarize_batch` 输出 `task_counts`、`operation_counts`、`execution_status`、`resource_state`、`acceptance_status`、`status`、`retry_selection`。工程分类固定为 completed/failed/blocked/skipped/already_completed/pending/paused/running。操作输入每行含 task_id、round_id、operation_key、generation、state、target_keys、verified、superseded、current_round;target_keys 为稳定目标身份数组,未知则为 null。同一操作和目标只取当前有效代次,旧轮次或 superseded 不计。
|
||||
|
||||
## Task 1: 先统一资源身份与写入准入
|
||||
|
||||
**Files:** Modify `batch_resources.py`、`batch_supervisor.py`、`batch_runtime.py`、`service.py`、`workspace_execution.py`、`ui/resource_status.py`;Test 新增 `tests/v1_1/test_issue44_resource_admission.py`、`tests/ui/test_issue44_startup.py`,调整现有资源测试。
|
||||
|
||||
**Consumes:** 现有进程/Job 身份、桌面租约证明、session/supervisor 记录。
|
||||
|
||||
**Produces:** 不抛出权限异常的进程观察结果;所有入口一致的严格资源准入。
|
||||
|
||||
- [ ] 编写失败测试:隔离记录即使带旧 `blocking=False` 也阻断。
|
||||
|
||||
```python
|
||||
def test_old_nonblocking_isolation_cannot_admit_a_new_write():
|
||||
from dx_productivity.trial_task_center.batch_resources import resource_blockers
|
||||
record = {'state': 'isolated', 'blocking': False}
|
||||
assert resource_blockers((record,)) == (record,)
|
||||
```
|
||||
|
||||
- [ ] 补身份测试:OpenProcess 返回错误 5 时 observe_process_identity 返回 state=unknown、error_code=5;`_process_gone` 为 False;错误 87 为 gone;创建时间不匹配为 gone;匹配的存活句柄为 alive;每个打开的查询句柄恰好关闭一次。
|
||||
- [ ] 运行新测试确认失败:`python -m pytest tests/v1_1/test_issue44_resource_admission.py -q`。
|
||||
- [ ] 实现最小权限观察和 unknown 诊断,启动读取历史记录时保留阻断而不传播异常到窗口初始化。未知记录不触发终止或清标记。
|
||||
- [ ] 统一 `resource_blockers`,逐一搜索并修正 `owned_writers_exited`、`blocking=False`、`state in {'released','isolated'}` 的放行分支。物理 released 必须继续验证写进程、代次、租约及桌面事实。
|
||||
- [ ] 补 UI 启动集成:旧 supervisor 记录访问拒绝时主窗口可打开,写入不可用,重查和诊断可用;已恢复的旧 PID 不被杀死。
|
||||
- [ ] 运行新测试与 `test_nonblocking_resources.py`、`test_resource_status.py`、`test_batch_supervisor.py`、`test_resource_queue_resume.py`;记录新策略导致的预期断言调整及替代用例。
|
||||
- [ ] 单独提交:`fix: enforce proven resource release for batch admission (#44)`。
|
||||
|
||||
## Task 2: 冻结本批/所选范围及逐任务裁决
|
||||
|
||||
**Files:** Create `batch_admission.py`;Modify `ui/task_list.py`、`ui/main_window.py`、`dsh/execution_runs.py`、`dsh/run_journal.py`;Test 新增 `tests/v1_1/test_issue44_batch_admission.py`、`tests/ui/test_issue44_batch_scope.py`。
|
||||
|
||||
**Consumes:** Task 1 的资源准入,现有严格 preflight、影响报告、计划哈希。
|
||||
|
||||
**Produces:** 批量裁决字典和不可变 manifest;实际执行范围为 runnable_task_ids。
|
||||
|
||||
- [ ] 编写所选范围的失败测试,验证显示排序不会改变执行顺序。
|
||||
|
||||
```python
|
||||
from types import SimpleNamespace
|
||||
from dx_productivity.trial_task_center.models import TaskStatus
|
||||
|
||||
def test_selected_scope_uses_persisted_batch_order():
|
||||
from dx_productivity.trial_task_center.batch_admission import resolve_batch_task_ids
|
||||
tasks = [SimpleNamespace(task_id=key, group_id='g', group_position=pos,
|
||||
status=TaskStatus.READY)
|
||||
for key, pos in [('C', 2), ('A', 0), ('B', 1)]]
|
||||
assert resolve_batch_task_ids(tasks, 'g', selected_ids=('C', 'A')) == ('A', 'C')
|
||||
```
|
||||
|
||||
- [ ] 补空选集、跨批、已删除、候选重复、当前焦点变化用例;全批动作不读取列表多选来缩小范围,所选动作不回退成全批。
|
||||
- [ ] 集成构造 8 个真实服务任务:5 个有合法计划,1 个无启用计划、1 个路径缺失、1 个确定性配置错误;预览含 8 项,runnable=5、skipped=3,执行只收到这 5 个 ID。
|
||||
- [ ] 运行新测试确认失败,然后实现 resolver 与批量裁决。任一任务的上下文读取错误须分类,不因一项异常丢掉整个清单;证据/所有权未知仍 global_blocker。
|
||||
- [ ] 对单任务 preflight 和 Agent 工具运行原测试,证明它们没有被静默改成局部执行。
|
||||
- [ ] 区分确认前候选指纹与执行中进度:A 完成、BOM 合法解析后 B 仍可运行;用户改计划或加入 C 则原确认失效。复用既有计划别名与单调核验进度检查,不在每步重比初始 mutable context 指纹。
|
||||
- [ ] 异步收集预检,确认窗口展示完整裁决和准确计数;manifest 摘要覆盖候选、顺序、计划、裁决、写入源和策略。
|
||||
- [ ] 确认后在租约内重算摘要;分别注入任务切换、计划改变、成员新增、资源变脏、已有 worker、关闭窗口,断言零新派发、旧 StopControl 不被替换。
|
||||
- [ ] `ready=False` 或用户取消时导出零派发的 rejected/cancelled 预检回执;不创建空 RunJournal,也不伪造执行轮次。
|
||||
- [ ] 运行新测试与 `tests/ui/test_pr27_confirmation_admission.py`、`tests/v1_1/test_ui_batch_retry.py`、`tests/dsh/test_run_journal.py`。
|
||||
- [ ] 单独提交:`fix: confirm and execute the same eligible batch scope (#44)`。
|
||||
|
||||
## Task 3: 停滞后真实收尾,不确定结果整批暂停
|
||||
|
||||
**Files:** Modify `batch_supervisor.py`、`worker_monitor.py`、`task_queue.py`、`batch_runtime.py`、`workspace_execution.py`、`ui/main_window.py`;Test 新增 `tests/v1_1/test_issue44_stall_policy.py`,调整 `test_resource_queue_resume.py` 和 `test_project_isolation_queue.py`。
|
||||
|
||||
**Consumes:** Task 1 的严格释放事实、Task 2 的冻结范围,现有 ProgressWatch、StopControl 和失败证据。
|
||||
|
||||
**Produces:** 明确 stop_reason 的暂停/失败结果;无写入或已核验结果与 pending_save/uncertain 分开。
|
||||
|
||||
- [ ] 用可控时钟编写失败用例:连续心跳/重复状态超过 150 秒只发出一次协作停止;真实位号/阶段推进重置计时;同一轮询读取不算推进。
|
||||
- [ ] 编写队列用例:A 完成,B 在保存前确定失败且无写入证明完整,C 执行;另一个用例 B 有 pending_save/uncertain,即使资源已 released,C 的派发次数仍为 0,队列 paused=True。
|
||||
- [ ] 编写保护顺序断言:保护记录写成功时间 < 自有 Job 终止时间 < 物理释放核验时间;写保护失败、所有权未知或原写进程存活均不得进入 C。
|
||||
- [ ] 先运行新测试确认失败,再把外层停滞动作接入现有停止控制;记录 150 秒外层阈值与实际 worker 阶段预算,不新增独立定时线程。
|
||||
- [ ] 收紧 `isolate_project` 后继续、resource_pause_admitted、UI 自动恢复和 workspace 兼容路径:业务未知一律等原工程核验及重新确认。
|
||||
- [ ] 对业务结果已确定的资源暂停保留 D8 原范围与一次消费校验;物理 released 后免重启接续。主动暂停、取消、范围变化都不得自动接续。
|
||||
- [ ] 运行新测试和 `test_task_queue.py`、`test_resource_queue_resume.py`、`test_project_isolation_queue.py`、`test_nonblocking_resources.py`。原“未知工程隔离后继续”断言替换成“整批暂停且原证据保留”。
|
||||
- [ ] 单独提交:`fix: stop uncertain batches and reconcile stalled work safely (#44)`。
|
||||
|
||||
## Task 4: 汇总工程与目标操作的单一投影
|
||||
|
||||
**Files:** Create `batch_summary.py`;Modify `execution_problems.py`、`dsh/execution_runs.py`、`dsh/live_state.py`、`ui/main_window.py`;Test 新增 `tests/v1_1/test_issue44_batch_summary.py`、`tests/ui/test_issue44_summary_ui.py`。
|
||||
|
||||
**Consumes:** manifest、同轮次操作行、队列检查点和已验证资源快照。
|
||||
|
||||
**Produces:** 所有展示共用的 summary;未知与待核验不会被折算成成功。
|
||||
|
||||
- [ ] 编写核心纯函数失败用例。
|
||||
|
||||
```python
|
||||
def test_pending_save_is_visible_and_is_never_saved_success():
|
||||
from dx_productivity.trial_task_center.batch_summary import summarize_batch
|
||||
manifest = {'candidate_task_ids': ['A'], 'decisions': [
|
||||
{'task_id': 'A', 'classification': 'executable'}]}
|
||||
queue = {'entries': {'A': {'state': 'blocked', 'message': 'save unverified'}}}
|
||||
rows = [dict(task_id='A', round_id='r', operation_key=str(i), generation=1,
|
||||
state='pending_save', target_keys=[f'uid:{i}'], verified=False,
|
||||
superseded=False, current_round=True) for i in range(23)]
|
||||
summary = summarize_batch(manifest, queue, rows,
|
||||
{'state': 'released'}, elapsed_seconds=301)
|
||||
assert summary['operation_counts']['pending_save'] == 23
|
||||
assert summary['operation_counts']['saved'] == 0
|
||||
assert summary['task_counts']['blocked'] == 1
|
||||
assert summary['status'] != 'completed'
|
||||
```
|
||||
|
||||
- [ ] 补互斥守恒用例:5 可执行+3 跳过的候选总数为 8;历史轮次、superseded 和重复代次只计一次;单作业含多 UID 时目标数正确;规则未解析目标数为 null;verified 结果不被报表失败抹掉。
|
||||
- [ ] 运行新测试确认失败,再实现纯投影;从 SQLite 读取 round/operation 快照并比较源版本,变化重读一次仍不稳定则显示 unknown。
|
||||
- [ ] UI 运行条、批次问题摘要、日志、回执引用相同 revision;逐任务问题清单继续保留自己的工程范围,不与批次目标总数硬比较。
|
||||
- [ ] 预检 skipped 只写批次条目,任务全局状态仍可编辑;真实运行状态通过原 record_task_outcome 收口;暂停未派发项保持 pending。
|
||||
- [ ] 运行新测试与 `tests/ui/test_ui_execution_feedback.py`、`tests/v1_1/test_execution_journal.py`;以“同一 revision 的同一范围”断言 UI/DB/日志一致。
|
||||
- [ ] 单独提交:`fix: reconcile batch and target counts from durable evidence (#44)`。
|
||||
|
||||
## Task 5: 回执完整性与批次诊断导出
|
||||
|
||||
**Files:** Modify `dsh/execution_runs.py`、`dsh/run_journal.py`、`diagnostics_bundle.py`;Test 新增 `tests/dsh/test_issue44_batch_receipt.py`、`tests/v1_1/test_issue44_batch_bundle.py`。
|
||||
|
||||
**Consumes:** Tasks 2/4 的 manifest 与 summary,既有 RunJournal、原子文件写入和诊断白名单。
|
||||
|
||||
**Produces:** `batch-runs/<run_id>/manifest.json` 和 `batch-receipt.json`;正常、拒绝、取消、异常和暂停均有可读记录。
|
||||
|
||||
- [ ] 编写资源与业务分离的失败测试:业务 saved/verified 保留但资源 isolated 时 status 不能 completed;原 supervisor status=ok 不被解释为资源已释放。
|
||||
- [ ] 覆盖七种出口:正常、部分安全失败、全跳过拒绝、用户取消、写入不确定暂停、资源暂停、报表写入失败;每种检查 run/queue/manifest 绑定和零重放。
|
||||
- [ ] 运行新测试确认失败,再按“manifest→运行记录/检查点→同 revision 摘要→JSON”持久化;任何导出失败留 reporting_errors,不回滚已保存替换。
|
||||
- [ ] 注入 SQLite 提交成功后 JSON 写失败、检查点成功后汇总写失败;重启仅重建回执,native_replace 调用数不变。
|
||||
- [ ] 旧运行没有 manifest 时按旧冻结 task_ids 和计划哈希显示历史证据,无法重建的候选清单注明 unavailable,不补造跳过原因或扩大范围。
|
||||
- [ ] 扩展白名单,诊断包含所选 run 的 manifest/receipt、检查点、资源代次与脱敏保存/网表证据;超出既有限额写 omission 清单。
|
||||
- [ ] 运行新测试、`tests/dsh/test_run_journal.py`、`tests/v1_1/test_diagnostics_bundle.py`,检查凭据、原工程和中心库未混入。
|
||||
- [ ] 单独提交:`fix: persist complete batch receipts and bounded diagnostics (#44)`。
|
||||
|
||||
## Task 6: 重试、新一轮及采集/目标不存在的交界
|
||||
|
||||
**Files:** Modify `ui/main_window.py`、`ui/project_plan.py`、`new_round.py`、`execution_problems.py`;仅按复现证据修改 `native_inventory_reader.py` 或现有库查询适配层。Test 新增 `tests/ui/test_issue44_round_retry.py`,扩展 `tests/v1_1/test_new_round.py`、`test_native_inventory_reader.py`。
|
||||
|
||||
**Consumes:** 当前轮次操作键、代次、工程提交证明、Tasks 1–5 的准入和汇总。
|
||||
|
||||
**Produces:** 可见且有证据的重试准备、新一轮和失败原因;成功项零重放。
|
||||
|
||||
- [ ] 编写真实 UI 点击测试:从已完成任务点击新一轮,归档成功后旧 round 与证据保留、当前位号基线清空、计划面板重新绑定;失败显示原因且旧配置不丢失。
|
||||
- [ ] 混合 verified/no_match/failed/pending_save/uncertain 计划只允许策略认证的 failed 进入 retry_selection;确认后 generation 或 round 改变则零派发。
|
||||
- [ ] 先运行新测试确认失败,再沿已有 handler 修复不可达/无反馈;不另建恢复执行器。资源未释放时提供资源处理入口,CAD 恢复写入仍不可执行。
|
||||
- [ ] 用 ETHERNET_1G 的原生报告与副本复现 DXT-20261126-B19CC4B3,保留展开前后 UID/refdes/属性差异;按原生身份规则修采集冲突,不降低完整性校验。
|
||||
- [ ] 对目标不存在只接受确定性只读库证据;超时单列不可用。若接口无法可靠查询,维持既有加载前无写入保护并记录该接口限制,不伪造 target_not_found。
|
||||
- [ ] 运行新测试与 `test_new_round.py`、`test_retry_recovery_transactions.py`、`test_native_inventory_reader.py`,重复点击不能产生重复轮次或替换派发。
|
||||
- [ ] 单独提交:`fix: make batch retry and round transitions observable (#44)`。
|
||||
|
||||
## Task 7: 源码、Windows 故障注入和冻结包验收
|
||||
|
||||
**Files:** 新增 `tools/verify_issue44_batch.py`、`docs/testing/2026-11-27-issue44-batch-acceptance.md`;证据目录 `docs/testing/evidence/2026-11-27-issue44/`。复用现有打包脚本,不在计划阶段变更版本。
|
||||
|
||||
**Consumes:** Tasks 1–6 的候选提交、已有六套试卷及独立工程副本。
|
||||
|
||||
**Produces:** 逐场景日志、数据库/回执对账、原件哈希及冻结包构建标识,才能判断是否达到工单关闭门槛。
|
||||
|
||||
- [ ] 验收脚本先跑 8 工程夹具:5 合法+3 可跳过,验证确认清单与 native_dispatch ID 顺序一致;再跑 100 工程服务集成,不把 CAD 模拟回执当真实换料。
|
||||
- [ ] Windows 实际创建自有 Job/桌面,注入晚退出与外部桌面持有句柄;证明 isolated 时无下一派发,外部持有者存活,释放后按策略恢复。
|
||||
- [ ] 在失败工程已写入但未核验的夹具中释放全部资源,证明仍整批暂停;核验原工程并重新确认后才派发后续项,已保存目标各一次。
|
||||
- [ ] 运行源码定向集后跑配置默认集 `python -m pytest`,以及本计划列出的 `tests/dsh` 专项。真实 Windows/CAD 专项分别记结果,不用统一 passed 掩盖 skip。
|
||||
- [ ] 完整复制 8 个受测工程和必要库,计算原件哈希,真实 Mentor 跑正常、缺目标、安全失败、保存待核验、资源暂停、新一轮场景,逐一核对派发、保存、网表与资源事实。
|
||||
- [ ] 正常批次 CAD 根 PID/代次=1;异常回收可新代次,但每个成功操作键唯一派发。100 工程需每项进入明确终态或明确暂停原因,回执与 UI 同 revision 对账。
|
||||
- [ ] 用同一源码构建冻结包,记录 commit、EXE/包 SHA256、依赖清单;重新执行 #44 最小回归与卷四评分,目标 >=90 分且无保护违规。
|
||||
- [ ] 记录未通过项与证据缺口。未通过不关闭工单、不声称无人值守可用;本次计划不授权推送、发布或发送工单消息。
|
||||
- [ ] 单独提交验收资料:`test: document batch remediation evidence for issue 44`。
|
||||
|
||||
## 2. Issue #44 的 20 项覆盖映射
|
||||
|
||||
| 工单项 | 实施任务 | 必须保留的断言 |
|
||||
| --- | --- | --- |
|
||||
| A4 | 2 | 确认候选/执行子集/实际派发一致 |
|
||||
| B1 | 2 | 所选两项可达,混合批次明确跳过 |
|
||||
| B2 | 2、3 | 以冻结顺序逐工程执行 |
|
||||
| B3 | 3、7 | 正常共享 CAD;异常代次可解释 |
|
||||
| B6 | 3 | 心跳不能掩盖停滞,停止与保护有序 |
|
||||
| B7 | 3 | 仅证据认证的安全失败可继续 |
|
||||
| B8 | 3、6 | 成功提交不重放,未知结果整批暂停 |
|
||||
| C1 | 6、7 | 原生采集完整性;不存在与查询失败分开 |
|
||||
| C3 | 3 | 失败语义决定续跑,不能无条件 finally 下一项 |
|
||||
| C7 | 4、6 | 可编辑失败选集绑定操作键与代次 |
|
||||
| C8 | 6 | verified/no_match/pending_save/uncertain 不重试 |
|
||||
| D1 | 4、5 | 批次条目收口;未派发与预检跳过不混淆 |
|
||||
| D2 | 4 | 23 pending_save 可见,任务数与目标数分开 |
|
||||
| D4 | 5 | 所有出口都有带身份的批次回执 |
|
||||
| D7 | 4、5 | 同范围同 revision 的 UI/DB/日志相等 |
|
||||
| D8 | 5 | 批次诊断白名单、脱敏与 omission 清单 |
|
||||
| E2 | 1、7 | 权限未知不崩溃、不放行、不误杀 |
|
||||
| E4 | 1、3、7 | 资源释放后无需重启;不绕过未核验写入 |
|
||||
| E5 | 1、5 | isolated/unknown 不冒充整体成功 |
|
||||
| E6 | 1、5、6 | 启动容错、处理入口和可读诊断 |
|
||||
|
||||
## 3. 本次规划阶段交付界限
|
||||
|
||||
本计划及配套设计/审查文档完成后,工作停在可评审的方案。正式实施需要用户确定方案;不会因文档内的复选框或提交建议自动开始代码修改。方案审查属于本次工作,未调用其他代理;后续代码评审与实机验收需要单独记录实际执行结果。
|
||||
@@ -0,0 +1,402 @@
|
||||
# 独立工程校验:判断、执行、状态与失败处理
|
||||
|
||||
日期:2026-11-17。状态:业务细化稿,尚未实现新增功能。本文落实本次对话已确定的校验任务与 A 界面;未回答的引脚语义问题明确列为待人工确认,不擅自变成自动放行规则。
|
||||
|
||||
## 1. 用户使用方式与本轮范围
|
||||
|
||||
用户可以随时创建校验任务,选择修改前、修改后的工程。前面的替换成功结果也可以自动交接到校验任务;校验页不展示或要求选择来源,不把当前换料任务作为新建校验的前置条件。
|
||||
|
||||
当前先在已有替换执行结果落盘后一次性交接。接收接口支持批量、增量、去重和版本更新,为后续实时交接留接口;本轮不改替换任务的实时刷新机制。
|
||||
|
||||
用户在工程表里先看结论,再点开同一物理脚号的前后连接图、差异表和原始证据,能够独立复核。校验不修改工程,不自动换脚、不重新换料;发现的问题集中记录。
|
||||
|
||||
本轮新增:校验任务与输入接收、独立只读运行与恢复、判断分级、引脚元数据能力探测、可复核证据、A 工作台和报告。其他任务正在处理的退出/收尾修复、任务列表修复、既有替换状态机和性能优化不纳入本轮。
|
||||
|
||||
## 2. 现有能力怎样复用
|
||||
|
||||
检查基线:`main/v1.3.1@b19afc6`。工作区有并行进行的 issue29 修改;实施前再次核对实际主线,不能覆盖其改动。
|
||||
|
||||
| 已有模块 | 直接复用 | 新增边界 |
|
||||
| --- | --- | --- |
|
||||
| `native_netlist.py` | 固定副本、HIER/effective ASCII/Keyin 导出、层级/实例/gate 与物理连接交叉核验 | 新增领域层调用已有公开捕获/导出接口;不重写原生导出器 |
|
||||
| `netlist_verification.py` | 完整导出缓存、原生库回执绑定、原计划/实际成功证据 | 提取或暴露接收固定输入的薄适配;原有队列入口保持兼容 |
|
||||
| `native_cli.OwnedCliScope` | 隐藏进程、归属和退出证明 | 独立校验只拥有自己的 CLI,不接管替换 CAD |
|
||||
| `batch_resources.write_record` | 原子文件发布 | 新报告先完整发布再提交数据库引用 |
|
||||
| `TaskStore`、schema、事务锁 | 持久化与升级 | 只新增校验表,不写 execution_operations 终态或重试预算 |
|
||||
| `LatestQuery`、`ServiceWorker` | 异步读取、旧回调隔离 | UI 不同步跑导出或遍历全工程 |
|
||||
| `HistoryRepository`、现有样式 | 事件与窗口视觉 | 四导航、任务列表、工程表和证据检查器 |
|
||||
|
||||
现有比较器已能拒绝物理脚号/连接变化,并在已证明的目标符号替换中允许逻辑脚名变化;该变化目前没有警告。ASCII 引脚记录中的类型、引脚级 Value、库内焊盘映射不能因现有物理图通过而视为已覆盖。新增功能补充这些事实和范围,不全局放宽旧比较器。
|
||||
|
||||
## 3. 四种业务对象与身份
|
||||
|
||||
| 对象 | 是什么 | 身份与生命周期 |
|
||||
| --- | --- | --- |
|
||||
| 校验任务 task | 左侧一个名称,例如“电源板核对”;可以含多个工程 | 独立 task_id,随时新建;既有任务或排队不禁用新建 |
|
||||
| 工程项 item | 中间表里的一行比较对象 | item_id;绑定 project_key、基线 before_id 和检查配置,不按名称猜测合并 |
|
||||
| 输入版本 revision | 一对固定 before/after、预期变化及检查配置 | item_id + input_version;发布后不可修改 |
|
||||
| 执行尝试 attempt | 对某个版本真正运行一次校验 | attempt_id + generation;重新校验增加尝试,不更改旧报告 |
|
||||
|
||||
另有批量命令 run:只冻结本次选择的 item/revision 集合、派发顺序和停止意图,不建立第二套工程结论。任务的状态与统计由当前工程版本推导,不另造会与工程行矛盾的通过标记。
|
||||
|
||||
同名工程不自动合并。同一个工程更换了 before 基线,建立新的工程项;不能把另一轮 before 覆盖到原项上。相同基线下的新 after 与累计预期变化才是新 input_version。
|
||||
|
||||
## 4. 统一输入与未来增量交接
|
||||
|
||||
### 4.1 统一接收合同
|
||||
|
||||
UI、文件导入和成功交接最终调用同一个 `publish_inputs(task_id, inputs, submission_id)`。没有 source/type/mode 等按来路分流的字段。
|
||||
|
||||
| 字段 | 必需 | 含义与校验 |
|
||||
| --- | --- | --- |
|
||||
| task_id | 是 | 已存在的校验任务;创建独立任务不要求换料任务存在 |
|
||||
| submission_id | 是 | 请求去重键;相同键与不同正文冲突时拒绝 |
|
||||
| item_key / project_key | 是 | 发布者持久身份;独立导入由服务生成,不使用显示名作为身份 |
|
||||
| input_version | 是 | 同工程项内递增整数;较旧版本不得夺回当前版本 |
|
||||
| before_ref / after_ref | 是 | 受管快照引用及 manifest 摘要;缺失证据可登记不可用工程项,不能伪造输入 |
|
||||
| expectation_ref | 可空 | 已确认的预期属性变化与适用器件、证据引用;空表示未提供换料规则,不等于确认所有属性都应不变 |
|
||||
| check_plan | 是 | 本次要求核对的维度、必查/可选范围和固定策略版本 |
|
||||
| payload_digest | 服务生成 | 规范化内容摘要,绑定输入、预期和检查计划 |
|
||||
|
||||
内部证据仍保留真实执行回执、文件摘要和版本以供追溯,但它们不是 UI 的任务来源字段。不得以“没有换料任务”拒绝独立输入。
|
||||
|
||||
### 4.2 接收规则
|
||||
|
||||
1. task 不存在、外层结构不合法:整个请求拒绝,不修改任何任务。
|
||||
2. 外层有效后逐条处理;一条坏输入不会撤销其他条已接收的输入。返回 accepted、duplicates、stale_ignored、rejected 以及逐条原因。
|
||||
3. 相同 item_key/version/digest:幂等返回原记录,不加行、不重复排队。
|
||||
4. 相同 item_key/version、不同 digest:记输入冲突,不覆盖。
|
||||
5. 较旧版本:只返回旧记录或忽略,不成为当前版本。版本跳号允许,不能依据到达顺序推断修改顺序。
|
||||
6. 新版本:原子发布新 revision,然后移动 current_revision 指针;旧输入、运行和结果保留。
|
||||
7. 新工程/新版本默认待校验,接收本身不自动执行。正在运行的批量命令不自动吞入后来到达的项,避免未来持续流入导致命令永不结束。
|
||||
8. 当前一次性交接与未来逐条交接具有相同语义;未来是否自动开始是独立运行设置,首版默认手动。
|
||||
|
||||
### 4.3 成功交接与独立输入
|
||||
|
||||
- 成功交接从已落盘、已保存回读且归属准确的回执读取成功范围,引用已冻结前后副本;失败、不确定或未执行项不冒充成功工程。工程内部分成功时只能交接有完整检查范围和可靠 after 的成功集合,明确预期范围;不能宣称整个替换计划完成。
|
||||
- 若替换成功但附加校验副本缺失,仍登记该项并显示“缺少校验证据”,不撤销替换成功,也不从当前盘上补造旧 before。
|
||||
- 当前已有网表报告可以作为证据导入,但只有输入、工具、解析器、检查策略和输出摘要均匹配时才复用;不能用旧 verified 字段直接点亮新任务。
|
||||
- 独立新建填写任务名和前后工程;服务后台验证不同工程文件/数据库别名、源稳定性及可读性,冻结受管副本后发布同一种输入。没有预期清单时只比较结构和列出属性变化,不声称换料规则已符合。
|
||||
- 交接失败不影响已保存换料结果。接收去重和已有回执扫描允许重新交接;UI 不在结束回调里等待全部捕获或导出。首版进入校验页或重启时扫描有界、尚未交接的已完成结果,且不为缺失 before 创建替代基线。
|
||||
|
||||
## 5. 判断规则:先证明能检查,再判断结果
|
||||
|
||||
每个检查返回 `check_id`、`state`、`required`、`issues`、`evidence_refs`、`coverage_reason`。state 为 equal / expected_change / warning / error / unknown / not_requested。所有异常都有明确事实;警告不能抵消异常,未知不能冒充相同。
|
||||
|
||||
### 5.1 输入与范围
|
||||
|
||||
| 编号 | 判断内容 | 具体逻辑 | 结果 |
|
||||
| --- | --- | --- | --- |
|
||||
| J01 | 前后输入可信 | manifest 存在、摘要匹配、数据库和配置属于声明对象,源在捕获时稳定 | 缺失/损坏则 unknown,停止依赖该输入的检查 |
|
||||
| J02 | 能完整读出 | HIER 实例集合、effective 器件/脚/网络互反覆盖与 Keyin 物理端点覆盖一致 | 部分/截断/不支持配置则 unknown,不能比较两个不完整图判通过 |
|
||||
| J03 | 器件身份 | 延用最新实例范围+生效位号唯一对应;UID保留为证据,缺失、重复、变化不得否定已证明的位号对应 | 缺件、多件或位号改变为 error;真实位号/实例对应歧义为 unknown,不做相似匹配 |
|
||||
|
||||
多 gate 使用工程实例范围+生效位号+物理脚作为对应依据,不能将同一位号的不同 gate 误报为重复器件;同一物理脚重叠仍为异常或无法完整核对。跨工程不合并身份。
|
||||
|
||||
### 5.2 脚号、连接和网名
|
||||
|
||||
| 编号 | 判断内容 | 具体逻辑 | 结果 |
|
||||
| --- | --- | --- | --- |
|
||||
| J04 | 物理脚号和集合 | 对应器件的物理脚号集合和占用次数必须相同,包括已知未连接脚 | 增减、重复或编号改变为 error;不能交换脚号消除差异 |
|
||||
| J05 | 固定脚号的连接 | 每个端点 `(实例范围, 位号, 物理脚号)` 对应网络的完整端点集合前后相同 | 分组变化为 error;给出新增/丢失对端及网络分裂/合并 |
|
||||
| J06 | 单连接端与未连接 | 有明确完整名册时区分“单端网络”“明确未连接”“导出未覆盖” | 已连接变未连接为 error,未覆盖为 unknown |
|
||||
| J07 | 网名 | 连接分组相同后再比较名称 | 已识别自动生成名称变化保留说明;用户/未知网名变化保持 error,不能套用引脚文字警告 |
|
||||
|
||||
R12.1 原连 NET_LOOP/U1.3、R12.2 原连 GND/C5.2,修改后两者互换:J05 必须报错。器件数、脚数、网络总数相同不能抵消此错误。
|
||||
|
||||
比较本质是端点分组,不能因为另一个脚仍写 GND 就推断整个器件接线正确;两个网络同名也不能替代端点集合证明。
|
||||
|
||||
### 5.3 预期属性与引脚文字
|
||||
|
||||
| 编号 | 判断内容 | 具体逻辑 | 结果 |
|
||||
| --- | --- | --- | --- |
|
||||
| J08 | 有清单的器件属性 | 只允许固定 expectation_ref 声明的目标 UID/位号及字段按精确目标变化;其余字段保持原值 | 已声明且符合为 expected_change;漏换/错值/非目标变化为 error |
|
||||
| J09 | 没有预期清单 | 仍列出全部属性变化,区分器件 Value、引脚 Value 和网络名 | 属性变更为 warning,标“未核对换料规则”;不得显示规则符合。无变化也只证明一致,不证明某个换料目标已完成 |
|
||||
| J10 | 引脚 Value/名称 | 先按固定物理脚号对应;保留原始文字,单独记录变化;不能把器件 Value 充当引脚 Value | 文字相同为 equal。用户确认的 loop→outloop 且结构/连接保持时为 warning;其他名称变化为 warning 并提示功能需确认,不自动宣称功能等价 |
|
||||
| J11 | 功能位置疑点 | 若 GND/VCC 等文字变化或原两脚文字对调,保留原始值和结构证据 | 输出高关注 warning“疑似功能变化,需人工确认”;是否升级 error 尚未由用户确认。若 J04/J05 或可靠库映射已证明互换,直接 error,不依赖名称猜测 |
|
||||
| J12 | 库内映射 | 已有可靠方法能读取并绑定确切库版本、symbol/Cell 和引脚→焊盘映射时再核对 | 明确反脚为 error;未实现/拿不到为 unknown 或 not_requested,显式显示未覆盖 |
|
||||
| J13 | 原生身份表 | Keyin Part 表与 effective Part Number 各自保留 | 旧身份列与有效料号不一致单列 warning/限制说明,不改写原始输出,不据此推导 PCB 已验证 |
|
||||
|
||||
J10 的“其他名称变化为 warning”只表示需要复核,不能解释为所有改名均安全。不能采用字符串相似度、模型猜测或全局 loop 替换来自动放行。引脚电气类型变更在可读取时与原值一起提示;其自动严重性字典首版不臆造。
|
||||
|
||||
预期值来自用户确认的清单、固定策略与可靠事务/库证据;不得从待校验 after 的实际字段倒推“预期就是这个值”。旧策略的特殊保留/NC 语义由已有函数解释并保留证据,本轮不另写一套换料策略。
|
||||
|
||||
### 5.4 首版检查范围
|
||||
|
||||
核心必查:可信输入、完整图、器件/位号、物理脚号、端点连接与名称;有 expectation_ref 时该范围内的预期属性也为必查。没有清单时属性检查为“只展示变化”,不能冒充目标检查。
|
||||
|
||||
引脚 Value/电气类型先做原生字段能力探测。探测未完成或字段缺失,报告明确 unknown;用户请求该项时不得算完整通过。库内部焊盘映射首版默认不请求,UI 固定披露“未覆盖:封装库内部映射”;有可靠适配器后才能启用为必查项。
|
||||
|
||||
检查计划记录 required_checks、optional_checks、excluded_checks 和策略摘要。未请求项不能被写成已检查;用户不能通过“一键忽略异常”改写原报告。只对当前输入和明确范围下结论。
|
||||
|
||||
## 6. 结论与执行状态必须分开
|
||||
|
||||
### 6.1 业务结论
|
||||
|
||||
```text
|
||||
存在任何已证明 error → DIFFERENT(发现异常)
|
||||
否则有必查 unknown → INCOMPLETE(无法完整校验)
|
||||
否则有 warning → WARNING(检查完成,有警告)
|
||||
否则全部必查 equal / expected_change → CONSISTENT(本次检查范围一致)
|
||||
```
|
||||
|
||||
可选 unknown 使 coverage=partial 并显示未覆盖项;允许核心范围一致,但显示“核心检查一致,扩展项未覆盖”,不能笼统写全工程全部通过。必查 unknown 优先于警告,已经证明的异常优先于 unknown,两类事实都保留。
|
||||
|
||||
J08 未请求时,结论文字始终附“未核对换料规则”。人工作出“已查看/备注”的行为不改变机器结论;真正消除异常需要修改工程后发布新输入版本。
|
||||
|
||||
### 6.2 三组独立字段
|
||||
|
||||
| 字段 | 值 | 含义 |
|
||||
| --- | --- | --- |
|
||||
| input_state | receiving / ready / unavailable | 前后副本是否已可信发布 |
|
||||
| attempt_state | queued / running / publishing / stopping / succeeded / failed / cancelled / interrupted | 校验程序是否完成执行;succeeded 可以对应 DIFFERENT |
|
||||
| verdict | CONSISTENT / WARNING / DIFFERENT / INCOMPLETE / 空 | 工程内容结论;尚未得到结果时为空 |
|
||||
|
||||
另存 resource_state=not_started/owned/released/unknown 与 currentness=current/historical。资源未知只影响归属的校验执行器准入,不改写已有换料回执,也不发出全局 CAD 退出命令。
|
||||
|
||||
## 7. 每个工程怎样执行
|
||||
|
||||
| 步骤 | 动作 | 发布物 / 下一步条件 |
|
||||
| --- | --- | --- |
|
||||
| E01 | 接收工程或导入两份文件 | 建 item 与不可变输入版本,登记缺证据原因 |
|
||||
| E02 | 固定当前点击范围 | 全部待校验或明确所选 item/revision;提交后不跟随新版本漂移 |
|
||||
| E03 | 入队与领取 | 事务内去重与 CAS;同一版本只允许一个活动尝试 |
|
||||
| E04 | 复核固定输入 | 校验 manifest/摘要、工具与配置支持;原文件变化不偷偷换输入 |
|
||||
| E05 | 准备工作副本 | 从受管冻结输入复制;原生工具不写原工程或冻结原件 |
|
||||
| E06 | 导出前/后图和属性 | 复用已有 HIER/effective/Keyin;保存命令、版本、输出摘要和清理结果 |
|
||||
| E07 | 核对覆盖 | 先执行 J01/J02;某维度缺数据就记录 unknown,不以空集合相同通过 |
|
||||
| E08 | 执行判断 | J03~J13 只读取本版本输入和预期;检查之间按依赖分组继续,不因一个可定位差异跳过其他可检查维度 |
|
||||
| E09 | 组织人工证据 | 生成逐脚差异、网络端点增删、前后示意和原始证据定位 |
|
||||
| E10 | 确认资源退出 | 自有 CLI 收尾得到证明后才能提交执行完成并继续派发;不以“报告已写完”代替资源确认 |
|
||||
| E11 | 发布结果 | 暂存→摘要与资源证明核对→原子发布产物→数据库 CAS 完成;迟到尝试不可覆盖新尝试 |
|
||||
| E12 | 更新当前任务 | 更新工程行/计数;下一个工程继续,最后导出本命令汇总 |
|
||||
|
||||
首版一个独立校验工程对处于运行中,新runner前后顺序导出,同时最多一个本域CLI;复用已有单次导出能力,不另建一个双线程批次池叠加并发。资源实际许可/系统准入继续生效,不能证明可并行时保留排队,不通过新建任务动作抢占替换资源。只增加任务和排队不占原工程写入租约;原有批次内部导出并发不由本功能改写。
|
||||
|
||||
发生差异不会立即弹模态框要求处理,不自动重新运行相同输入。只读工具异常首版由用户点击重校验;不借用、消耗或重置换料的一次自动重试额度。
|
||||
|
||||
## 8. 总流程图
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A[新建校验或接收已成功结果] --> B[统一接收接口与去重]
|
||||
B --> C{固定前后输入可用}
|
||||
C -->|否| D[登记无法校验及原因]
|
||||
C -->|是| E[待校验]
|
||||
E --> F[用户开始当前待校验或所选]
|
||||
F --> G[冻结本次范围并入队]
|
||||
G --> H[领取一个工程版本]
|
||||
H --> I[复核输入并在工作副本导出]
|
||||
I --> J{覆盖和格式可判断}
|
||||
J -->|完整或部分可判断| K[逐项判断并保存未知范围]
|
||||
J -->|无有效输入| L[记录执行失败或无法判断]
|
||||
K --> M[生成前后对照与事实证据]
|
||||
M --> O{自有资源已确认释放}
|
||||
L --> O
|
||||
D --> V[更新任务列表与原因]
|
||||
O -->|是| N[原子发布结果并更新状态]
|
||||
N --> P{本次范围还有待执行项}
|
||||
P -->|有| H
|
||||
P -->|无| V
|
||||
O -->|否| Q[暂停该校验执行器并保留队列]
|
||||
Q --> R[等待安全收尾或人工处理]
|
||||
R -->|确认释放后用户继续| N
|
||||
```
|
||||
|
||||
## 9. 状态图
|
||||
|
||||
### 9.1 单次执行尝试
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> Queued: 用户明确提交
|
||||
Queued --> Running: CAS领取且资源准入通过
|
||||
Queued --> Cancelled: 派发前取消
|
||||
Running --> Publishing: 证据与资源退出证明齐备
|
||||
Publishing --> Succeeded: 产物与数据库引用提交成功
|
||||
Running --> Failed: 工具或解析失败且资源已释放
|
||||
Publishing --> Failed: 结果发布失败且可确认落盘状态
|
||||
Running --> Stopping: 记录停止意图
|
||||
Publishing --> Stopping: 完成提交前请求停止
|
||||
Stopping --> Cancelled: 自有资源退出确认
|
||||
Queued --> Interrupted: 重启后冻结原队列
|
||||
Running --> Interrupted: 崩溃后核实旧进程退出
|
||||
Publishing --> Interrupted: 提交结果未能证明完整
|
||||
Stopping --> Interrupted: 重启后核实收尾状态
|
||||
Succeeded --> [*]
|
||||
Failed --> [*]
|
||||
Cancelled --> [*]
|
||||
Interrupted --> [*]
|
||||
```
|
||||
|
||||
Stopping 的 resource_state=unknown 时保持等待,不直接迁移 Cancelled。Succeeded 只表示比较处理完成,仍须读取 verdict;停止与发布竞争以数据库提交先后为准,完整终态已提交就保留真实结果,不改成“取消”。恢复/重校验建立新 attempt,旧终态不原地改回 running。
|
||||
|
||||
整run停止时,尚未实际派发的queued尝试记录cancelled及`run_stopped_before_dispatch`原因,释放队列预留;工程行恢复“待校验”,继续时创建新queued尝试。用户明确取消单个工程或已经启动的工程显示“已停止”;不能因两种行为都留下cancelled尝试就混淆行状态。
|
||||
|
||||
### 9.2 任务状态由工程当前版本推导
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> Empty: 创建任务
|
||||
Empty --> Ready: 收到可运行输入
|
||||
Empty --> Attention: 只有不可用输入
|
||||
Ready --> Active: 用户开始校验
|
||||
Active --> Stopping: 用户停止当前运行范围
|
||||
Stopping --> Paused: 归属资源已释放
|
||||
Paused --> Active: 用户继续尚未开始项
|
||||
Active --> Attention: 本次完成且有异常或缺证据
|
||||
Active --> Finished: 当前范围完成
|
||||
Attention --> Ready: 补充合法新输入或手动重校验
|
||||
Finished --> Ready: 收到新工程或新版本
|
||||
Paused --> Ready: 收到新输入且无活动派发
|
||||
```
|
||||
|
||||
队列尚未执行的行存在时,任务不得标“所有工程已完成”。任务可继续接收新输入;Finished 不是禁止接收的永久关闭状态。Attention 与 Finished 的详情仍显示准确计数,警告不导致自动重试。
|
||||
|
||||
## 10. 数据流向与版本更新
|
||||
|
||||
### 10.1 数据流图
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A[已落盘的成功结果] --> C[统一输入接收服务]
|
||||
B[用户选择两份工程] --> D[稳定性检查与冻结副本]
|
||||
D --> C
|
||||
C --> S[(SQLite任务/工程/版本/尝试)]
|
||||
C --> M[(受管快照及manifest)]
|
||||
S --> Q[独立校验调度器]
|
||||
Q --> M
|
||||
M --> W[一次性工作副本]
|
||||
W --> N[已有原生导出与覆盖核验]
|
||||
N --> G[标准图与逐项判断]
|
||||
E[(固定预期变化与策略版本)] --> G
|
||||
G --> R[(不可变结果包和原始证据)]
|
||||
R --> S
|
||||
S --> U[A工作台查询投影]
|
||||
R --> U
|
||||
U --> H[人查看前后图/差异表/原始证据]
|
||||
R --> X[导出HTML与JSON]
|
||||
```
|
||||
|
||||
没有从校验服务回到替换执行器的写入箭头。GUI 不直接读原工程数据库,示意图与差异表来自同一个标准图和 issue 记录,不使用生图模型或语言模型生成工程判定。
|
||||
|
||||
### 10.2 新版本到来时
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant P as 输入发布者
|
||||
participant S as 校验服务
|
||||
participant DB as 持久库
|
||||
participant W as 校验执行器
|
||||
participant UI as A工作台
|
||||
P->>S: 发布工程A v1和去重键
|
||||
S->>DB: 原子发布v1并设为当前
|
||||
S-->>P: 返回接收回执
|
||||
UI->>S: 开始工程A v1
|
||||
S->>DB: 建立queued尝试
|
||||
W->>DB: CAS领取v1
|
||||
P->>S: 发布工程A v2
|
||||
S->>DB: 新增v2并更新当前指针
|
||||
S-->>UI: v2待校验,v1正在处理历史版本
|
||||
W->>DB: 提交v1结果,绑定v1尝试
|
||||
DB-->>UI: v1结果归档,v2仍待校验
|
||||
P->>S: 重复v2或迟到v1
|
||||
S-->>P: 去重或忽略旧版,不新增派发
|
||||
```
|
||||
|
||||
同一 before 下,v2 的预期集合必须覆盖该 before 到 v2 after 的全部累计成功变化,不能只携带最后一条改动;否则其他合法变化会被误判。新一轮 before 不同则新建工程项。当前只做接收和版本管理,不在本轮实现替换侧实时推送。
|
||||
|
||||
## 11. 结果包:让人能够复核
|
||||
|
||||
每个 issue 必须有:稳定 issue_id、check_id、严重性、工程/版本、位号/实例、物理脚号、前值、后值、预期或保持规则、关联证据及定位、检查范围。没有足够定位时说明“图页未定位”,不编造图页或 CAD 截图。
|
||||
|
||||
| 产物 | 内容与约束 |
|
||||
| --- | --- |
|
||||
| `result.json` | 身份、attempt/generation、输入/工具/策略摘要、逐项结论、覆盖、问题与资源证明 |
|
||||
| 标准图 | 物理脚、网络端点、有效属性、实例/多 gate、字段来源;原值不被正常化覆盖 |
|
||||
| 原始导出 | HIER/effective/Keyin 和完整工具输出,保持原样 |
|
||||
| 连接对照 | 前后相同脚号相同位置;只高亮变化连接,列新增/丢失对端 |
|
||||
| 事实表 | 引脚/字段、替换前、替换后、判断、证据入口;与示意图共享同一 issue 数据 |
|
||||
| 覆盖清单 | 已检查、未知、未请求;封装内部映射不能被工程网表结果隐含覆盖 |
|
||||
| HTML/JSON报告 | 相同结果包渲染;明确任务、版本、生成时间和未完成项 |
|
||||
|
||||
例如 R12 反脚:左右两张图均保持 1 脚在上、2 脚在下;前后网络/对端不同处标红。明确标“连接关系示意(由网表生成)”,不伪装原理图截图。命名警告用 amber,不能用红色导线假装发生实际断接。
|
||||
|
||||
UI 的原始证据入口只能打开受管、摘要匹配的文本/报告,不接受工程字符串或模型输出指定任意可执行路径。所有 HTML 字段转义,客户数据和原始网表不写入 Git。
|
||||
|
||||
## 12. 失败处理矩阵
|
||||
|
||||
| 编号 | 失败或变化 | 当前工程怎样处理 | 其他工程 / 后续 |
|
||||
| --- | --- | --- | --- |
|
||||
| F01 | 缺 before/after | input unavailable,指出缺哪个副本 | 继续其他可运行项;补合法记录,不补造 before |
|
||||
| F02 | 独立导入源正在写入或复制中变化 | 不发布可信 revision,保留导入原因 | 可重新选择/捕获;其他任务可新建 |
|
||||
| F03 | 相同版本不同内容 | 输入冲突,拒绝覆盖 | 返回逐条原因,其他已接收项保留 |
|
||||
| F04 | 旧版本迟到/重复通知 | 幂等或 stale_ignored | 不再导出、不改当前结果 |
|
||||
| F05 | 缺工具/不支持配置 | 明确能力原因,必查为 unknown | 其他支持项继续;不回退 CAD 读取 |
|
||||
| F06 | CLI 超时/异常退出 | 保存诊断,自有进程安全收尾 | 确认 released 后继续下一项;用户可单项重校验 |
|
||||
| F07 | CLI 无输出/空图/截断/覆盖不足 | 无法完整检查;保留可定位事实 | 不显示通过,其他工程继续 |
|
||||
| F08 | 发现反脚/漏换/非目标改动 | succeeded + DIFFERENT,保存事实与证据 | 继续后续项,不自动修改或重试 |
|
||||
| F09 | 只有符合条件的文字变化 | succeeded + WARNING | 继续,留待集中查看 |
|
||||
| F10 | 引脚属性/库映射读取不支持 | 对应 check unknown/not_requested | 必查未知则 INCOMPLETE;未请求项始终披露 |
|
||||
| F11 | 用户停止 | 先存停止意图,停止当前自有只读导出 | 未派发项回到待校验;当前 cancelled 后用户可重校验 |
|
||||
| F12 | 自有资源退出不确定 | 保持 stopping + resource unknown | 暂停该校验执行器,不盲目开启下一导出,不杀用户 CAD |
|
||||
| F13 | 应用关闭或崩溃 | 正常关闭先收尾;异常重启核实旧进程和产物 | interrupted 后等用户继续,不自动重复换料或开始校验 |
|
||||
| F14 | 结果文件或数据库提交失败 | 不显示完成;旧结果保持 | 优先停止受影响发布/执行范围;存储故障不能保证后续落盘,不承诺其他项仍可持久化 |
|
||||
| F15 | 保存文件后DB提交前崩溃 | 扫描已发布结果包并核对输入/attempt/token | 仅有完整不可变包、released证明且无更新尝试才可补提交;否则 interrupted |
|
||||
| F16 | 迟到 worker 回调 | CAS拒绝当前终态覆盖,保留诊断 | 新尝试/新版本不受污染 |
|
||||
| F17 | 当前工程文件后来变化 | 已固定版本仍能比较,其结果标“对应已保存副本” | 不偷偷替换 after;要核对新状态须新输入版本 |
|
||||
| F18 | 报告丢失/摘要不符 | UI显示证据不可用,保留原记录 | 可对原固定输入重校验;不能用残留绿灯代替证据 |
|
||||
|
||||
一般异常不弹阻塞对话框。需要用户选择路径、确认停止或操作外部文件时才交互。资源/存储归属异常属于无法安全继续的边界,不用“非阻塞”掩盖它。
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A[步骤异常或用户停止] --> B{已有完整提交的终态}
|
||||
B -->|有| C[保留真实结论与证据]
|
||||
B -->|无| D[记录失败或停止意图]
|
||||
D --> E[收尾本次自有只读进程]
|
||||
E --> F{资源退出是否有证明}
|
||||
F -->|有且存储可用| G[当前项终态,其他待执行项继续]
|
||||
F -->|无| H[保持停止中,暂停该执行器]
|
||||
H --> I[继续收尾或人工处理资源]
|
||||
I -->|确认退出后用户继续| G
|
||||
D -->|持久化不可用| J[显示存储故障,暂停结果发布]
|
||||
```
|
||||
|
||||
## 13. A 工作台与数量口径
|
||||
|
||||
- 四导航保持一致;上方只有“工程校验”和始终可用的“新建校验”。无来源、流水线或返回替换任务横条。
|
||||
- 左侧先选择校验任务,再筛选当前任务工程;中间表与右侧证据随同一个 item/revision 切换。
|
||||
- 新建任务只需名称;选择两份工程可在新建对话框完成,也可先建空任务后加工程。校验侧不要求用户先创建替换任务。
|
||||
- “开始待校验”仅对当前任务所有 ready、未提交的当前版本生效,不受表格筛选暗中缩小范围;“校验所选”只对显式勾选版本生效。勾选随切任务/分页/筛选清空并提示,避免隐藏提交。
|
||||
- “重新校验此工程”默认当前选中版本;历史版本只能从历史详情显式重校验并始终标历史,不能把其结果挂到当前版本。
|
||||
- 表格每页100项,差异每页100项;250ms搜索防抖,后台查询代次隔离旧回调;不在GUI扫描全部网表。
|
||||
- 统计只取每个 item 的 current_revision。已处理 = 一致 + 有警告 + 有异常 + 无法完整校验;排队/执行中/待校验/已停止/中断分别列出。失败且无有效业务结果计入无法校验,并保留“执行失败”原因,不计一致。
|
||||
- 旧版结果和旧尝试不重复计入当前计数。重校验排队后该行显示排队中,旧结果可展开查看但不继续充当当前已处理结论。
|
||||
- 没有完整证据的“处理结束”不显示绿色通过;只有 scoped 一致可使用绿色,并带检查范围。
|
||||
|
||||
## 14. 持久化、接口与发布顺序
|
||||
|
||||
新增校验 task/item/input_revision/attempt/run 与命令去重记录,复用当前 SQLite 事务和日志模式。文件内容保存在受管目录,数据库存身份、状态、摘要与引用;不在新表复制原 execution_operations 状态。运行去重/停止命令可使用校验域自己的 request 表;不复用专用于 AI 创建任务的请求语义。
|
||||
|
||||
```text
|
||||
verification/<task_id>/<item_id>/inputs/<version>/manifest.json
|
||||
verification/<task_id>/<item_id>/attempts/<attempt_id>/raw/...
|
||||
verification/<task_id>/<item_id>/attempts/<attempt_id>/result.json
|
||||
verification/<task_id>/<item_id>/attempts/<attempt_id>/report.html
|
||||
```
|
||||
|
||||
输入版本、尝试、产物路径均由服务生成并验证归属,不允许外部命令在受管目录之外指定输出位置。清历史不删除校验结果;活动/当前引用的快照、原生证明和结果包不得按普通日志保留期清掉。首版不新增“一键删除证据”入口。
|
||||
|
||||
发布顺序固定:完整暂存文件 → 原子发布 manifest/结果包 → DB事务验证身份与generation并引用 → 通知UI。目录与DB不能跨资源真原子,使用上述顺序和 F15 恢复规则;拒绝“先更新成功状态,再尝试写报告”。
|
||||
|
||||
## 15. 能力门禁和未确认事项
|
||||
|
||||
1. 引脚级 Value 的实际字段、端点逻辑名与物理脚号对应、可读电气类型需用真实导出确认;缺失不以器件属性替代。
|
||||
2. 库内脚→焊盘读取尚未证明,首版可先交付工程物理连接校验与明确未覆盖项,不宣称封装制造验证。
|
||||
3. GND→VCC 或纯功能文字对调的自动严重性尚未由用户确认,首版保留高关注警告,不让模型推断电气等价或改工程。
|
||||
4. 用户网名变化暂不放宽为普通命名警告;后续若要放宽,独立规则与反例确认。
|
||||
5. 多层级/多 gate 当前已有读取能力;直接换料的子实例范围不是本轮新增任务。独立比较若不能唯一建立前后对应,返回 unknown,不强行比对。
|
||||
6. 旧 before 缺失不会因为新增页面而变得可恢复;真实新副本验收与图像原型分开。
|
||||
|
||||
实施从[开发与交付入口](../plans/2026-11-17-verification-development.md)进入,逐项步骤见[独立校验新增功能计划](../plans/2026-11-17-independent-verification-new-features.md)。本文及计划不授权开始 CAD 写入、改动其他任务的修复或发布程序。
|
||||
@@ -0,0 +1,201 @@
|
||||
# Issue #44 整批任务整改设计
|
||||
|
||||
日期:2026-11-27。状态:方案草案,已进行代码核对和方案自审,尚未实施。
|
||||
|
||||
实施更新:用户随后批准本地整改,并要求只验收增量实际功能。设计阶段的“尚未实施”保留为当时的记录;当前实现及剩余现场缺口以 `docs/testing/2026-11-27-issue44-incremental-acceptance.md` 为准。原全量发布验收不在本次执行范围。
|
||||
|
||||
关联:[Issue #44](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/issues/44),交叉关联 #33 D7/D8、#43、#46。
|
||||
|
||||
分支:`codex/issue44-batch-remediation-plan`。基线:`origin/main` 的 `f80127e7bd0b098dfe3ef34823a3c13f2f9c5982`。受测 `1.3.3-beta.1` 的 `818fb9a` 相对该基线仅调整版本及发行说明,执行逻辑一致。
|
||||
|
||||
## 1. 目标与已确认的业务规则
|
||||
|
||||
目标是让已确认的整批范围按持久化顺序运行,安全失败不会吞掉后续独立工程;不能继续时有真实的暂停原因、检查点和结果汇总,资源释放后可以核对原授权范围再接续。
|
||||
|
||||
用户已在本次对话确认:
|
||||
|
||||
1. 整批中存在缺计划、工程不可访问等不可执行任务时,在执行确认中列出可执行项和跳过原因,确认后只执行可执行项。写入结果不确定的任务仍停止保护。
|
||||
2. 即使已证明自有写进程退出、租约归还,只要原桌面仍被外部句柄持有,仍阻断新写入;物理释放核验通过后再继续。不能把隔离记作资源释放成功。
|
||||
3. 某工程已可能写入、但保存核验结果不确定时,暂停整批;即使资源已经释放,也必须先核验该工程,再重新确认继续。不能自动隔离该工程后推进其他独立工程。
|
||||
|
||||
第二、三条有意收紧 #33 D7/D8 的历史行为,需要同步修改所有使用 `blocking=False` 放行隔离资源或隔离不确定工程后自动推进的入口及相应测试。不能只改 UI 文案。
|
||||
|
||||
本轮输出为设计、实施计划及审查记录;没有业务代码修改、安装包构建或实机 CAD 换料。
|
||||
|
||||
## 2. 现状证据与判断边界
|
||||
|
||||
工单记录 50/100 分、20 项失败,分为范围准入、停滞推进、计数终态、资源生命周期、重试入口五组。附件交付包 SHA256 已核对为 `e1f4988b245a3c8f9eb5b850b80322bbbdacb5392336a90cb148ec3edba716ca`。交付包中的分析、试卷和评分不能替代原始现场数据根与进程证据。
|
||||
|
||||
以下行号以本设计基线为准:
|
||||
|
||||
| 核对位置 | 已查到的事实 | 对整改的影响 |
|
||||
| --- | --- | --- |
|
||||
| `ui/main_window.py:905` | 批量入口已调用预检、执行确认和 `execute_confirmed_run` | 复用入口,不能据“无执行器”的描述重建调度器 |
|
||||
| `ui/execution_state.py:14`、`ui/main_window.py:633` | 本批范围来自 `group_id/group_position`,列表多选没有进入本批范围解析 | 明确“本批”与“所选”语义,消除列表选中、工程 selected、当前任务之间的歧义 |
|
||||
| `dsh/task_lifecycle.py:47` | 逐任务有 blockers,但总 ready 用 `all()` | 新增批量裁决层;保留单任务和既有 Agent 工具的原有严格契约 |
|
||||
| `ui/main_window.py:816` | 预检失败只合并原因,不保留清晰的逐任务裁决清单 | 预览与执行必须引用同一份裁决 |
|
||||
| `task_queue.py:253`、`batch_runtime.py` | 顺序执行、工程检查点、同批 CAD 复用、问题轮次和资源暂停均已存在 | 修接线、事实传递与收口,不新增第三套队列 |
|
||||
| `task_queue.py:253` | 新批次走共享监督进程;已有 workspace-queue 检查点走兼容路径 | 保留旧检查点读取和身份核验;新批次统一走现有共享运行时 |
|
||||
| `batch_resources.py:143` | `isolated + blocking=False` 可以绕过资源门禁 | 与本次用户决定冲突,必须统一收紧 |
|
||||
| `batch_resources.py:240` | `_process_gone()` 仅把 Win32 87 作为已退出,其他异常向上抛 | 访问拒绝可能影响启动;不能改为把访问拒绝视作进程已退出 |
|
||||
| `batch_supervisor.py:349` | 业务结果、资源 blockers 和 warnings 分开计算;无 blockers 可使 outcome 保持 ok | 输出必须同时表达业务结论与资源结论,隔离不能成为整体成功 |
|
||||
| `batch_supervisor.py:517` 附近 | 外层 business stall 目前主要写告警 | 与底层 `worker_monitor.ProgressWatch` 的停止/收尾能力衔接,避免另加相互打架的计时器 |
|
||||
| `execution_problems.py:112` | 问题列表按部分操作状态筛选,未穷尽保存待核验的展示 | 按当前操作行投影统计,不能拿“问题条数”冒充目标数 |
|
||||
| `dsh/execution_runs.py`、`dsh/run_journal.py` | 回执已存入 `dsh-state.sqlite3`,不是完全没有回执 | 增补批次范围、汇总和资源事实,并提供稳定的 JSON 导出 |
|
||||
| `ui/main_window.py:1239/1271`、`new_round.py` | 新一轮、核验恢复已有 handler 和服务实现 | 查不可达、陈旧绑定、状态与反馈;不能按“空实现”重复新增 |
|
||||
| `diagnostics_bundle.py` | 已有白名单、脱敏和限额的诊断导出 | 扩展现有导出器,不直接压缩整个数据根 |
|
||||
|
||||
基线定向验证:2026-11-27,58 passed,70.93 秒。范围为 `test_task_queue.py`、`test_resource_queue_resume.py`、`test_batch_supervisor.py`、`test_pr27_confirmation_admission.py`。这些既有测试验证现有行为,不代表 #44 新验收已通过。
|
||||
|
||||
仍需现场复现:仅选两项时的按钮行为、BOB 的 23 项 `pending_save` 停滞、ETHERNET_1G 采集冲突,以及旧 supervisor PID 复用触发访问拒绝的完整启动路径。当前静态证据只支持对应代码风险,不支持声称所有现场根因已确定。
|
||||
|
||||
## 3. 方案比较与选择
|
||||
|
||||
| 方案 | 收益 | 代价与问题 | 结论 |
|
||||
| --- | --- | --- | --- |
|
||||
| 补齐现有链的范围、裁决、资源和汇总契约 | 保留保存核验、防重放、D7/D8 与历史检查点;改造可以逐段验收 | 必须同时检查 UI、Agent、监督进程和兼容路径 | 采用 |
|
||||
| 新建一套批处理执行器和资源池 | 新接口表面统一 | 重复租约、检查点、保存核验和重试规则,容易重放已保存操作 | 不采用 |
|
||||
| 只放开按钮、遇错继续 | 改动少 | 仍有范围错配,无法证明无写入或释放,违反用户确认的资源规则 | 不采用 |
|
||||
|
||||
## 4. 批次范围与执行前裁决
|
||||
|
||||
### 4.1 两个明确的操作
|
||||
|
||||
保留“顺序执行本批任务”,范围为当前批次全部未删除成员,按持久化 `group_position` 排序;已完成、待核验、缺配置等成员也进入预览,给出处理结论。
|
||||
|
||||
增加“顺序执行所选任务”动作,来源为列表明确选中的同批任务。它与当前用于展示详情的焦点任务分开;仅选两项时只确认和执行两项。跨批选择明确拒绝并提示分批操作,不静默合并。搜索和显示排序不改变实际执行顺序,不扩大用户选集。
|
||||
|
||||
独立单任务继续沿用“执行当前任务”。工程表的 `projects.selected` 不再被解释为跨任务选集;它只属于对应任务内部的工程选择语义。
|
||||
|
||||
### 4.2 裁决分类
|
||||
|
||||
| 分类 | 示例 | 批次行为 |
|
||||
| --- | --- | --- |
|
||||
| executable | 工程存在、已保存计划有效、无未核验结果 | 加入冻结执行子集 |
|
||||
| skipped | 无启用计划、工程不存在或不可访问、确定性配置错误 | 逐任务列原因;不写 CAD、不消耗替换尝试 |
|
||||
| already_completed | 同轮次已保存且核验通过 | 列为已完成不重放,保留原回执引用 |
|
||||
| held | 原任务写入不确定、共享该写入源、重试证据未核对 | 保留待核验保护,不自动跳过成成功;本批存在未核验写入时阻断本批启动或继续 |
|
||||
| global_blocker | 资源未释放、运行租约占用、资源状态读取失败、裁决所需证据损坏 | 整批不启动,仍可查看原因与导出诊断 |
|
||||
|
||||
确定性配置问题可以局部跳过。无法确认的所有权、写入源或证据读取失败不能归入普通 skipped。原不确定工程及共享源保留 held,本批整体暂停;不能借助“执行所选任务”绕过同一原批次的未核验保护。原工程核验完成后重新确认继续。未知写入源也停止本批。
|
||||
|
||||
只有执行子集非空且无全局阻断时可确认启动。全不可执行时显示完整裁决清单,不建立空的 RunJournal 执行记录;生成 `rejected` 预检回执。用户取消生成 `cancelled` 预检回执,两者均证明零派发,不创建执行轮次。
|
||||
|
||||
### 4.3 冻结与确认
|
||||
|
||||
新增仅负责批量范围和裁决的 `trial_task_center/batch_admission.py`。既有 `task_lifecycle.preflight` 的 ready 契约保持不变;批量层逐任务收集报告,汇总可执行子集,生成该子集的原生执行报告。
|
||||
|
||||
确认窗口显示:候选 N 个工程、可执行 K 个工程、启用目标/规则数、待原生核验数量、跳过/待核验/已完成清单及原因。只有位号级计划才能给准确器件数;规则模式显示“规则数,命中器件数待执行核验”,不能把规则数冒充目标数。
|
||||
|
||||
保存候选顺序、分组、每项裁决、可执行顺序、可执行计划哈希、候选状态指纹、共享写入源和资源策略版本,得到 `manifest_digest`。候选成员、顺序、计划、裁决理由、资源事实任一变化,旧确认失效。
|
||||
|
||||
候选状态指纹用于“确认前后”的比较;运行开始后,程序自身产生的 running/completed 状态、原生 BOM 核验和已认证保存进度不能与初始指纹硬比较,否则第二个工程会被误判为陈旧授权。执行中和恢复时沿用 RunJournal 的原范围、计划哈希/合法 BOM 解析别名、单调已核验进度检查;用户修改计划、增加成员或无法证明的状态变化仍使授权失效。manifest 原始裁决保持不可变,运行进展写在检查点和回执。
|
||||
|
||||
模态确认关闭后,先执行现有 `_confirmed_execution_allowed` 检查,再在服务租约内重新裁决和比较摘要。新出现的可执行项不能被追加;需要重新确认。资源仅在确认时已释放还不够,新运行时代次准入及异常后恢复时仍复核;健康共享代次内逐工程验证本代所有权、关闭检查点与授权,不要求把本代正在正常复用的桌面先销毁。
|
||||
|
||||
## 5. 执行、停滞与安全续跑
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A[解析本批或所选候选] --> B[逐任务裁决并展示清单]
|
||||
B --> C{资源已核验释放且有可执行项}
|
||||
C -->|否| D[拒绝回执与诊断入口]
|
||||
C -->|是| E[确认冻结范围并持久化清单]
|
||||
E --> F[租约内复核摘要与资源事实]
|
||||
F --> G[取得或复核健康共享运行时代次]
|
||||
G --> H{工程结果}
|
||||
H -->|保存并核验| I[保存真实回执并推进]
|
||||
H -->|证明无写入的安全失败| I
|
||||
H -->|写入不确定或资源未释放| J[先持久化保护与检查点]
|
||||
J --> K[限次清理并核验物理释放]
|
||||
K -->|未释放或写入结果不确定| L[暂停本批并保留可读报告]
|
||||
K -->|资源已释放且业务结果已确定| I
|
||||
L --> M[核验原工程并重新确认原范围]
|
||||
M --> F
|
||||
I --> N{剩余工程}
|
||||
N -->|有| F
|
||||
N -->|无| O[批次收口与统一汇总]
|
||||
```
|
||||
|
||||
正常批次沿用共享 `BatchCadRuntime`,同工程只开、保存、关闭一次,正常代次同批复用 CAD。发生确需回收的异常时允许新代次和新 PID;回执记录代次变化及原因。不能同时要求“异常后物理释放”与“异常后仍永远只有一个 CAD PID”。
|
||||
|
||||
正常代次内部的 ready 记录表示当前执行者持有的健康资源,不等于待清理残留。内部复用检查必须核对相同 session/generation/租约及工程已关闭证明;不能把自己的 ready 记录纳入历史残留门禁而形成自锁,也不能用“属于本批”跳过旧代次的 isolated/unknown。新的外部执行入口仍须等待原运行结束,不能共享在途写租约。
|
||||
|
||||
复用 `execution_problems.classify_execution_failure`,由身份绑定的无写入/保存核验/资源释放证据决定能否继续,不由错误码或 try/except 单独决定。
|
||||
|
||||
停滞以单工程/操作的业务进展为准:位号完成、阶段实际推进、保存或回读证明才重置;心跳、相同状态帧、轮询读取和耗时增长都不能重置。保留 worker 的既有分阶段预算;外层监督看门狗在 150 秒业务无进展时仅发出一次协作停止,记录实际采用的超时参数。worker 已发出停止时不重复申请另一套停止流程。
|
||||
|
||||
不可安全中断阶段继续使用底层的安全收尾等待和 30 秒故障收尾宽限;最终需要强退时,必须先持久化 uncertain 保护,再结束仅属于本代的 Job/句柄。无法持久化保护或无法证明所有权时停止自动终止,明确显示需人工接管。不能因为超过 300 秒就直接把 `pending_save` 改成 failed 或成功,也不能在原写进程存活时派发下一工程。
|
||||
|
||||
用户主动暂停、写入不确定和单纯资源暂停分开:主动暂停不被资源清理成功自动恢复;写入不确定必须核验原工程并重新确认,D8 的“隔离后推进独立工程”不再自动适用。只有业务结果已确定的单纯资源暂停,且原 queue_id、顺序、摘要、计划哈希和共享源证据未变、资源物理释放、用户未暂停/取消时,才允许原范围自动接续。保留 D8 的身份绑定和一次消费保护。
|
||||
|
||||
## 6. 资源身份、启动容错与统一准入
|
||||
|
||||
进程观察区分“已退出/身份已复用”“仍存活”“无法确认”。Win32 87 或已核验的创建时间不匹配可以证明原进程已不在;Win32 5、身份缺失、枚举失败均为无法确认,绝不能按已退出处理。
|
||||
|
||||
已有持有句柄时优先观察原句柄与 Job。仅有历史 PID 时,以最小必要查询权限尝试身份观察;拒绝访问后写入可诊断的阻断记录,让主窗口以受限状态打开,保留资源重查入口。未知历史记录不得驱动终止任意 PID,不移走记录假装修复,不清 uncertain 标记。
|
||||
|
||||
资源记录只有同时证明以下事实才发布 released:自有写进程及后代退出、原租约已归还、本代句柄已关闭、该代桌面已物理消失;复核受管理桌面时绑定代次与槽位锁,不能将新的同名租约误认作旧桌面残留。桌面不再出现但写进程或租约证据缺失也不能放行。
|
||||
|
||||
沿用现有最多三次 0.5/1/2 秒复核,不在周期轮询中无限重试。自动复核耗尽则保持暂停,提供“重试释放资源”和“导出诊断”;外部句柄只观察,不结束外部进程。物理释放后通过原范围校验恢复,无需重启。
|
||||
|
||||
`resource_blockers()`、监督回执、运行时新代次准入、失败工程释放、D8 恢复、workspace 旧队列兼容路径、Agent/排期入口、UI 的 ResourceStatus 必须同源。历史 `blocking=False` 不能覆盖新策略;物理状态未知同样阻断新写入。
|
||||
|
||||
“标记已处理”只能写审计备注,不得改变准入事实;不提供可绕过物理核验的解锁按钮。只读查看回执、导出诊断和操作资源清理入口在资源阻断时仍可用。需要 CAD 的恢复写入依旧受资源门禁约束;#46 的完整恢复工作台不在本轮重建。
|
||||
|
||||
## 7. 统一状态、计数与回执
|
||||
|
||||
### 7.1 分清三个层级
|
||||
|
||||
| 层级 | 唯一事实来源 | 展示规则 |
|
||||
| --- | --- | --- |
|
||||
| 批次工程条目 | 冻结裁决与 task-queue 检查点 | completed / failed / blocked / skipped / already_completed / pending / paused / running |
|
||||
| 当前轮次目标操作 | 当前 `execution_rounds` 对应的有效 `execution_operations` 及保存核验证据 | pending、准备/在途、pending_save、verified、no_match、failed、uncertain 等逐类计数 |
|
||||
| 批次资源 | 本代 session/supervisor/租约与物理观察 | released / pending / isolated / unknown;只有 released 可准入新写入 |
|
||||
|
||||
新增轻量投影模块 `batch_summary.py`,同时供 UI、问题列表的批次汇总、日志摘要和回执使用。任务数与操作数永不混加。一个 job 若携带多个位号选择器,要按规范化后的目标身份展开目标数;另列作业数。规则模式尚未原生解析时目标总数为 unknown,不填 0。
|
||||
|
||||
`pending_save` 单列为“已执行、保存/核验尚未确认”,计入待核验而非已保存。`superseded` 和历史轮次不进入当前计数;同一操作以最新有效代次计算,已有 verified 提交保留成功事实,后续报表或资源失败不能抹掉它。
|
||||
|
||||
批次总数必须守恒:候选总数 = 当前八类批次条目数之和。`already_completed` 与本次新完成分开。目标总数已知时也按互斥分类守恒,缺证据则显示 unknown 并列缺口。
|
||||
|
||||
预检 skipped 写入本次批次条目,不把可编辑任务永久改成全局 skipped,也不伪造执行轮次。原 `TaskStatus` 无 skipped,因此本轮不为预检跳过新增全局任务枚举;UI 对该批次显示“本批已跳过,任务可修改”。运行过的工程通过既有 `record_task_outcome` 收口其真实状态。因暂停尚未派发的成员保留 pending,不能写成 skipped。
|
||||
|
||||
### 7.2 回执与持久化
|
||||
|
||||
在 `data_root/batch-runs/<run_id>/` 增加两类可导出证据:
|
||||
|
||||
- `manifest.json`:不可变确认快照,含 schema_version、policy_version、候选范围、裁决、执行子集、摘要和确认时间。RunJournal 中仍仅绑定实际执行子集及计划哈希。
|
||||
- `batch-receipt.json`:批次摘要快照,包含 revision、manifest_digest、run_id、queue_id、状态、停止原因、工程及操作计数、资源结论、独立网表验收、elapsed_seconds、retry_selection、reporting_errors 和证据引用。
|
||||
|
||||
状态轴分开保存 `execution_status`、`resource_state`、`acceptance_status`。全局 `status=completed` 需要业务收口、所需核验通过且资源 released;业务已核验但资源 pending/isolated 时显示“替换结果已核验,资源尚未释放”,保留原 saved 计数。
|
||||
|
||||
复用 `RunJournal` 与现有原子文件写入,不承诺 SQLite 与 JSON 跨存储的原子事务。顺序为:不可变 manifest → 既有运行记录/检查点 → 相同 revision 的汇总持久化 → JSON 导出。中途失败写 reporting_errors,启动以检查点和已保存提交重建 JSON,不派发替换来补报表。预检拒绝或取消没有执行记录,单独生成零派发回执。
|
||||
|
||||
不能要求跨数据库读取“瞬间绝对一致”;聚合器记录当前 round_id、检查点摘要及每个来源的版本,读前读后检查版本,变化则重读一次,仍变化返回“读取中/未知”。UI、日志、JSON 比较同一个 summary_revision。
|
||||
|
||||
诊断导出复用现有白名单、脱敏及文件/大小上限,新增 batch-runs 的 manifest/receipt,关联原任务、资源代次、原队列、保存核验和网表证据。导出清单记录遗漏及原因,不包含完整原工程、中心库或凭据。
|
||||
|
||||
## 8. 失败重试、新一轮与交叉问题
|
||||
|
||||
retry_selection 只收集原范围中失败且经现有重试策略允许的操作键、round_id、generation。重试准备和执行前再次核对;verified、no_match、已有工程提交、uncertain、prepared、pending_save 都不能直接重放。已成功目标与失败目标混在一个旧命令时,必须沿用既有逐目标拆分及回执核验,不整条重放。
|
||||
|
||||
先接通现有 `_start_new_round`、`_recover_quick_run` 与任务绑定刷新链,增加每次点击的可见反馈和证据路径,复核失败不清缓存假装成功。新一轮归档成功后按当前工程料号重采集,不能复用旧轮次位号身份。
|
||||
|
||||
ETHERNET_1G 采集报告冲突和目标料号不存在列为独立复现任务。若原生只读接口能确定目标不存在,则在派发写入前返回 `target_not_found`;查库超时只能记 lookup_unavailable/timeout,不能冒充不存在。没有可靠只读存在性接口时复用现有加载前无写入证明和分级超时,不引入另一套 CAD 读取回退。两类结果均进入本批汇总。
|
||||
|
||||
#43 的 Value/NC/封装写入正确性、#45 的整体 UI 体验、#46 的完整恢复流程由对应工作负责;本轮覆盖其与范围、资源门禁、计数和入口反馈的交界,不悄然扩展为重写全部功能。
|
||||
|
||||
## 9. 验收口径与分阶段交付
|
||||
|
||||
实施顺序:资源身份/准入契约 → 范围裁决/确认 → 停滞与接续 → 汇总/回执/诊断 → 重试/新一轮/交叉复现 → 源码和冻结包实机验收。资源规则先统一,避免后续在旧的非阻塞隔离语义上继续开发。
|
||||
|
||||
必须通过:两项所选范围准确;8 项中跳过 3 项并按序执行 5 项;确认后范围变化零派发;安全失败继续;不确定保存先保护且整批暂停、资源释放也不自动继续;隔离或 unknown 零新写入;确定结果的资源暂停释放后免重启接续;原暂停授权不被自动恢复;pending_save 计数一致;拒绝/取消/异常均可导出真实回执;新一轮归档与旧检查点兼容。
|
||||
|
||||
“PID 集合=1”仅用于正常共享 CAD 批次的 CAD 根进程,不包含监督进程、CLI 网表读取器和诊断 helper。异常回收用代次、唯一派发和保存次数验收。
|
||||
|
||||
自动化包括纯函数、生产服务及 SQLite 集成、Qt 按钮/模态确认、Windows 真实 Job/桌面故障注入;CAD 模拟器通过不能替代真实 Mentor。实机先 8 工程混合批次,再 100 工程终态与回执对账,均使用完整独立副本。卷四同一版本冻结包复测达到 90 分以上且无上述保护违规后才建议关闭 #44;本方案不预填修复后分数。
|
||||
|
||||
## 10. 评审结论
|
||||
|
||||
建议采用“复用执行链、统一范围和事实契约”的方案。三项核心业务取舍已由用户确定,没有以绕过安全门禁提升通过率。实施前必须把本设计中的提议接口、兼容读取及故障注入用例一起纳入首个代码评审;本次没有声称故障已修复。
|
||||
@@ -0,0 +1,94 @@
|
||||
# 独立工程校验验收记录
|
||||
|
||||
2026-11-18 已追加批量添加工程对,见[本轮验收](2026-11-18-verification-batch-import.md)。同一路径的本地开发包已更新;下文为11月17日历史结果,原EXE和证明保留在 `D:/dx-vfy-history-20261117/`。
|
||||
|
||||
开发分支:`codex/independent-verification`。独立工作目录:`.worktrees/independent-verification`。基础主线:`origin/main@b19afc6`;重新 fetch 后未出现更新提交。原工作区另一项修复仍有未提交修改,本分支没有复制它们。
|
||||
|
||||
## 已实现范围
|
||||
|
||||
| 阶段 | 结果 |
|
||||
| --- | --- |
|
||||
| N01~N04 | 独立任务、不可变输入版本、幂等交接、独立导入、当前版本投影、筛选/分页/计数 |
|
||||
| N05~N08 | 原生只读导出、固定物理脚号判断、名称/属性警告、未知覆盖、同源接线图和逐脚事实 |
|
||||
| N09~N11 | 第四导航、随时新建、开始/停止/重校验、历史版本与尝试、异步关闭、HTML/JSON报告、证据摘要与保留 |
|
||||
| N12 | 混合批次、验收 CLI、真实原生导出已验证;最终默认回归、扩展回归和安装包结果见下方完成记录 |
|
||||
|
||||
## 验收路径
|
||||
|
||||
受控格式路径:`python tools/verify_independent_verification.py --fixture-root <目录> --output <新目录>`。夹具目录中 `before/after` 各含合法捕获配置 `.prj` 与数据库、`effective.txt` 和 `design.kyn`。该路径明确标记 `controlled-format-fixture`,不能冒充真实 CAD 导出。
|
||||
|
||||
真实只读路径:`python tools/verify_independent_verification.py --native-before <前工程.prj> --native-after <后工程.prj> --output <新目录>`。非零退出区分异常、缺覆盖和执行失败;警告结果保留给人工确认。
|
||||
|
||||
实际执行输出:`D:/dx-vfy-native-final/acceptance.json`。前后各 57 个器件、83 个有原文定位的引脚,结论 WARNING(器件属性变化且没有固定换料清单;原生身份表另有提示)。两个工程文件及两个数据库的 SHA256 前后不变,`replacement_operations=0`。JSON、HTML、网表原文及输入摘要保留于该本地目录,Git不收录工程和厂商二进制。
|
||||
|
||||
## 验证过的关键反例
|
||||
|
||||
- R12.1/2 互换:DIFFERENT;前后图位置不随名称交换,表和报告来自相同证据。
|
||||
- loop→outloop、拓扑不变:WARNING;不伪造红色接错线。
|
||||
- 断线、短接、位号变化、物理脚号/占用次数变化、用户网名变化:硬异常。
|
||||
- 有固定清单时精确核对目标属性;无清单时列出变化并注明“未核对换料规则”。
|
||||
- 缺必查字段/库映射:INCOMPLETE;硬异常与未知同时存在时仍为 DIFFERENT。
|
||||
- 重复/乱序交接不重复创建;旧版本结果只留历史;重校验不会沿用旧绿灯。
|
||||
- 持久停止先于提交时取消获胜;终态先提交时保留真实结果;未派发项回到待校验。
|
||||
- 原始证据损坏取消绿色结论并拒绝有效报告;清历史不删除证据;存储失败暂停执行器。
|
||||
- 慢证据核验不占住数据库事务,新建任务可继续;同一尝试仅一个领取者。
|
||||
- 关闭可重复调用;重启不自动重跑;退出缺证明保留现场,不按 PID 误杀其他进程。
|
||||
|
||||
## 视觉检查
|
||||
|
||||
实际 Qt 截图而非生图:本机 `F:/dx-vfy-preview-20261117/`。1280×880、980×700,以及 1.25/1.5 缩放均已生成检查。接线图使用自建 R12 反脚夹具演示,不能冒充真实工程错误。完整事实另有逐脚表和原文定位。
|
||||
|
||||
## 验证环境与限制
|
||||
|
||||
共享 `.venv` 的基础 Python 路径异常,导致 `-E/-I` 的旧进程边界测试失败;Windows 默认 GBK 还影响旧测试中未声明编码的读取。没有修改产品旧执行器或用户环境变量。独立验证环境为 `D:/dx-vfy-python-20261117`,基于本机已安装 Python 3.12.10,复用已安装依赖;测试使用进程级 `-X utf8`。
|
||||
|
||||
首次默认回归:2221 passed、6 failed、6 errors;其中关闭重复调用的本功能回归已修复,环境相关项在独立环境的相关 66 项测试中通过。首次扩展回归 818 passed、4 failed、4 skipped;本功能首选问题定位已修正,GBK 相关的 28 项复核通过。不能把首轮失败记录解释为最终全绿结果。
|
||||
|
||||
F 盘空间不足使第一次构建未完成;仅清理了本工作目录本次生成的失败构建目录,构建和后续测试转到 D 盘。没有清理原工作区、客户工程或其他任务输出。引脚级 Value、确切库内部引脚到焊盘映射、ERC/PCB 正确性仍未覆盖。
|
||||
|
||||
## 最终完成记录
|
||||
|
||||
N01~N12 的新增功能已完成并提交到独立分支,本次交付本地开发包,不合并、不推送、不发布。原工作区另一任务的未提交修复未改动。
|
||||
|
||||
### 测试结果
|
||||
|
||||
| 范围 | 实际结果与证据 |
|
||||
| --- | --- |
|
||||
| 全部新增服务/Qt/验收组(16 个测试文件) | **81 passed**,`D:/dx-vfy-new-final81.xml`;包含慢读取不饿死、100行分页保持、刷新保留问题选择 |
|
||||
| DSH 与打包扩展组 | **476 passed, 1 skipped**;跳过项是未配置官方 7-Zip 的自解压验证 |
|
||||
| 默认范围分段及相关复核 | 当前收集 **2250** 项,均能在通过的分组记录中找到,`missing=[]`;`D:/dx-vfy-regression-coverage.json` |
|
||||
| 一次连续默认全量稳定全绿 | **未取得**;不能用分组覆盖替代。此前运行及复核记录保留如下 |
|
||||
|
||||
新增组命令:使用 `D:/dx-vfy-python-20261117/Scripts/python.exe -X utf8 -m pytest`,逐项传入 `tests/v1_1/test_independent_verification_{contracts,store,intake,queries,runner,rules,acceptance}.py`、`tests/v1_1/test_verification_{pin_metadata,evidence,control,reports}.py`、`tests/ui/test_verification_{workspace,inspector,control,report_actions,acceptance}.py`(花括号表示文件集合,实际使用完整文件名),参数 `-q --basetemp D:/dx-vfy-tests-final81 --junitxml D:/dx-vfy-new-final81.xml`。扩展组命令为同一解释器执行 `-m pytest tests/dsh tests/packaging -q`。
|
||||
|
||||
默认范围证据:`D:/dx-vfy-default-complete.xml`(1496 passed、1 failed)、`D:/dx-vfy-default-tail.xml`(746 passed、1 failed、1 teardown error)。失败分别涉及既有 safe-user-stop 的真实 supervisor 启动见证超时,以及 history 搜索精确 250ms 的定时边界;相应文件未改,独立复核 `D:/dx-vfy-legacy-stop.xml` 为 **34 passed**。既有 VBS 超时组单独复核 **5 passed**。这些波动仍是发布前需要处理的事项,不在本次新增功能中改写旧逻辑或放宽断言。
|
||||
|
||||
覆盖审计只收集当前默认用例、与各 XML 的实际 passed 节点集合比较,不运行或跳过测试;证据集合为上述两份默认记录、新增81项及34项复核,`continuous_full_run_green=false`。审计脚本 `D:/vfy_audit_coverage.py`。
|
||||
|
||||
### 实际包验收
|
||||
|
||||
开发包:`D:/dx-vfy-release-20261117/DxPartReplace/DxPartReplace.exe`(须保留同目录完整 `_internal`)。源码提交 `f91b4de`;EXE SHA256:`9aeea5d8fb1263b1da32d5d0363a2f9cd6310d884c41a45c44debb4bf3fb8fb3`。随后只更新验收文档,不改变包内源码。
|
||||
|
||||
完整运行时由仓库标准 spec 构建。最终 Python 修改通过官方 PyInstaller PYZ/EXE API 重新编译并原子替换 EXE,复用该次已完成且未改变的原生/Node运行时,未修改厂商内容。可复核脚本为 `D:/verification-code-refresh.spec`;`D:/vfy_verify_archive.py` 实际逐个比较归一化路径后的 Python 代码对象,**22 个变更源码模块与最终包完全一致**,无 mismatch,证明保存在 `D:/dx-vfy-package-proof.json`。
|
||||
|
||||
| 实际操作 | 结果与现场 |
|
||||
| --- | --- |
|
||||
| 四导航、连续新建两个独立任务 | 通过,`D:/dx-vfy-package-ui-v2/acceptance.json` |
|
||||
| 使用真实系统文件选择器添加前后工程并开始 | 原生导出完成、WARNING、输入四文件摘要不变、换料操作数0、正常退出,`D:/dx-vfy-package-pair-v5/acceptance.json` |
|
||||
| 包内重校验 | generation 2、WARNING;PID+进程创建时间归属证明成立、换料操作数0、正常退出,`D:/dx-vfy-package-final-rerun/acceptance.json` |
|
||||
| 最终包重启并查看已有结果 | 右侧真实接线图与“input · 需关注”加载完成;attempt数仍为2、不自动执行、换料操作数0、退出码0,`D:/dx-vfy-package-final-view/acceptance.json` |
|
||||
| 最终包运行时/正常关闭 | frozen supervisor、win32timezone、创建时间读取及资源释放均通过;`tools/verify_packaged_runtime.py` 对新数据根 `D:/dx-vfy-package-smoke-delivery` 的实际结果 |
|
||||
|
||||
最终包截图:`D:/dx-vfy-package-final-view/native-result-final.png`。该图使用真实导出的工程结果,不能把较早在读取完成前抓到的待校验画面当成最终证据。反脚效果仍使用明确标注的自建 R12 夹具;没有改写客户工程制造错误。
|
||||
|
||||
### 操作与恢复细节
|
||||
|
||||
工程表每页100项,“下一页”有界读取;周期刷新保留当前页,筛选回第一页,开始全部不受分页影响。周期刷新等待当前查询完成,保留多选、问题选择和事实滚动位置,用户显式切换仍使用代际取消。切任务清空旧检查器,关闭先失效旧查询。
|
||||
|
||||
`verification/ownership.py` 用 PID 和创建时间证明校验窗口归属,保护另一窗口仍活跃的执行;调度仅处理本实例运行,停止请求持久化。进程已经退出但缺少原生CLI退出证明时仍保持资源未知;不猜测退出、不按PID杀进程、不自动重跑。资源失败原因随尝试保存。
|
||||
|
||||
成功交接与增量接口已通过受控真实SQLite/服务集成测试;本次包内真实验证走独立两份工程路径,没有为制造新回执再执行客户换料。未来替换实时推送不在本轮范围。
|
||||
|
||||
### 保留边界
|
||||
|
||||
引脚级 Value、确切封装库内部脚位到焊盘映射未得到来源证明,明确未覆盖;ERC/PCB及自动修复不属于本功能。默认连续全量时序稳定性尚未满足发布门槛。以上限制不以网表一致或执行完成掩盖。
|
||||
@@ -0,0 +1,41 @@
|
||||
# 批量添加工程对验收
|
||||
|
||||
分支 `codex/independent-verification`,功能提交 `eda9403`,拒收回执修正 `de16bbd`。2026-11-18 重新 fetch 后,主线仍为 `b19afc6`。本轮只补批量导入,不修改另一任务的既有执行器修复。
|
||||
|
||||
## 已实现
|
||||
|
||||
- 第四页新增“批量添加”,打开非模态窗口,仍能新建其他校验任务。
|
||||
- 读取两个独立根目录,沿用已有只读目录扫描规则,按相对路径精确配对;不按同名文件猜测对应关系。缺失、不唯一的项列出且不能勾选。
|
||||
- 勾选后逐对建立冻结副本,列表与报告保留相对路径名称;同名工程可区分。导入不会启动网表校验或换料。
|
||||
- 单项失败后继续,取消保留已导入项;同一批请求可续传且不重复建项。请求取消后仍绑定原始输入,不允许用相同请求标识替换内容。
|
||||
- 磁盘/存储故障中断整批;任务库拒收单项时明确显示失败,不把函数返回等同于导入成功。超过256字符的批量名称提示缩短层级或逐对添加。
|
||||
- 扫描、复制在后台执行;关闭窗口取消操作,晚到结果不回写已关闭界面,应用关闭协作沿用现有控制器。
|
||||
|
||||
## 自动化验证
|
||||
|
||||
| 范围 | 实际结果 |
|
||||
| --- | --- |
|
||||
| 原独立校验组与本轮两份新测试文件,共18文件 | **92 passed**,`D:/dx-vfy-batch-final.xml` |
|
||||
| 既有关闭生命周期 `tests/ui/test_deferred_close_lifetime.py` | **2 passed**,`D:/dx-vfy-batch-close.xml` |
|
||||
| 最终包运行时、supervisor、创建时间、关闭与资源释放 | 通过;`tools/verify_packaged_runtime.py`,数据根 `D:/dx-vfy-batch-smoke-20261118` |
|
||||
|
||||
本轮新增11项测试覆盖相对路径/缺失、根目录重叠、失败后继续、重复请求、取消续传、存储耗尽、输入绑定、拒收回执,以及Qt勾选导入、并行新建和关闭读取。先确认缺失接口、请求复用及误报成功的反例失败,再实现并复跑。
|
||||
|
||||
解释器为 `D:/dx-vfy-python-20261117/Scripts/python.exe -X utf8`。新文件为 `tests/v1_1/test_verification_batch_import.py` 与 `tests/ui/test_verification_batch_import.py`,与[前轮验收](2026-11-17-independent-verification-acceptance.md)的16文件校验组一起执行,使用独立D盘临时目录,没有放宽旧断言。
|
||||
|
||||
本轮未重新执行全部默认测试。当前默认收集2261项,在已留存的分组通过记录中均有覆盖,`missing=[]`,`D:/dx-vfy-batch-regression-coverage.json`。这属于历史分组覆盖审计,不代表新取得一次连续全量全绿;前轮记录的既有时序波动仍保留。
|
||||
|
||||
## 实际开发包
|
||||
|
||||
更新包:`D:/dx-vfy-release-20261117/DxPartReplace/DxPartReplace.exe`,保留同目录 `_internal`。EXE SHA256:`56ba31c71f61aafed0bdeab88026112adc7362c4a037d94a783cfddb5959a24f`。仍使用前轮完整标准构建的原生运行时,通过官方PyInstaller API重新编译Python代码;`D:/verification-code-refresh.spec` 显式包含新增两个模块。
|
||||
|
||||
实际解包与源码代码对象比较:**24个变更模块匹配,无 mismatch**;`D:/dx-vfy-package-proof.json`,复核脚本 `D:/vfy_verify_archive.py`。前轮EXE及证明另存 `D:/dx-vfy-history-20261117/`,避免覆盖历史证据。
|
||||
|
||||
通过外部Windows UI操作实际EXE,新建任务、点击“批量添加”、填写前后目录、读取配对、导入所选、返回任务、正常关闭。输入是既有已保存工程的复制件,包含两个同名工程对及一项缺失:
|
||||
|
||||
- `A/input.prj`、`B/input.prj` 正确导入,`orphan/input.prj` 因缺少修改后工程未导入。
|
||||
- 校验尝试数0、换料操作数0,所有输入文件摘要不变,退出码0。
|
||||
- 实际操作证明 `D:/dx-vfy-batch-package-20261118/acceptance.json`;预览截图 `batch-preview.png`、完成截图 `batch-imported.png`、任务截图 `batch-workspace.png` 在同目录。
|
||||
- 测试脚本 `D:/vfy_packaged_batch.py` 只通过Windows可访问性接口操作应用窗口,再查询持久结果;没有直接注入任务状态。主窗口PrintWindow截图的灰底来自默认透明材质捕获,不据此改动既有全局UI。
|
||||
|
||||
批量导入仅覆盖目录结构对应的输入登记;本轮未重新执行真实原生网表导出。引脚级Value、确切库内脚到焊盘映射仍按前轮明确未覆盖。未合并、推送或发布。
|
||||
@@ -0,0 +1,53 @@
|
||||
# 工程校验闭环验收(2026-11-18)
|
||||
|
||||
后续剩余四项已完成,最新状态见[最终闭环验收](2026-11-18-verification-final-closure.md)。本文保留当时的原始范围与未测记录,不作为最新缺口清单。
|
||||
|
||||
按[闭环标准 v1](verification-closed-loop-standard.md)补齐 N12。代码与工具提交 `e65bed0`,分支 `codex/independent-verification`。本次没有修改另一修复任务的旧执行器,没有合并、推送或发布。
|
||||
|
||||
## 实现与标准
|
||||
|
||||
新增 `tools/verification_closed_loop.py`:开始前冻结范围、源文件摘要和换料操作基线,逐项检查实际运行成员、终态、预期结论、输入/尝试/策略绑定、原文摘要、资源退出证明与报告。空任务、漏项、停止/中断、错误预期、旧报告或源文件变化不能通过。
|
||||
|
||||
HTML报告增加 item、attempt、generation、输入版本/摘要和证据摘要的可核对绑定。已有换料历史允许保留;只读标准检查运行前后计数不变,而非历史总数必须为0。整任务报告中只验证选定项时必须明确指定范围,其余项不冒充已验证。
|
||||
|
||||
单次服务验收入口 `tools/verify_independent_verification.py` 增加 `--expect-verdict`,默认 CONSISTENT;预期警告应事先传 WARNING。输出 `frozen-scope.json` 和 `closed-loop.json`,检查不通过非零退出。它明确只覆盖 C01~C05,C06~C08 保留 not_run。
|
||||
|
||||
实际包入口 `tools/accept_verification_closed_loop.py` 通过Windows可访问性操作EXE,公开服务和SQLite用于读取及核对,不直接注入执行状态。必须事先给出预期名单和结论;`--fault-batch` 在私有复制件中加入明确无效的数据库反例,原输入目录不改写。
|
||||
|
||||
## 实际通过范围
|
||||
|
||||
| 场景 | 结果 | 证据 |
|
||||
| --- | --- | --- |
|
||||
| 两份真实保存副本批量导入、原生执行、查看、报告、重启、重校验 | C01~C07通过,两个 WARNING 符合事先指定的预期;重校验后尝试为1、1、2,旧结果和报告不变 | `D:/dx-vfy-loop-package-20261118-v2/acceptance.json`,16条检查通过 |
|
||||
| 首项原生失败,后续两个真实保存副本继续 | 00-invalid 为 failed/INCOMPLETE,随后 A、B 均完成 WARNING;混合报告、重启和A单项重校验通过 | `D:/dx-vfy-loop-faults-20261118-v2/acceptance.json`,17条检查通过 |
|
||||
| 只读与正常关闭 | 两个现场的所有记录输入摘要不变,换料操作数0;所有测试实例正常关闭,未按PID杀进程 | 各现场 JSON、应用正常退出日志和资源退出证明 |
|
||||
| 校验功能组 | 104 passed,19个测试文件 | `D:/dx-vfy-loop-final.xml` |
|
||||
| 闭环选定范围补充复核 | 19 passed,覆盖本轮验收器、CLI和报告 | `D:/dx-vfy-loop-scope.xml` |
|
||||
|
||||
第二现场的失败项是自建无效数据库,证据类型 `native-real-copies-and-invalid-database-fixture`。它证明真实原生导出失败后的隔离行为,不能冒充真实客户工程反脚。物理脚互换、断线、短接、loop→outloop、必查未知等判断仍由明确标注的受控服务/Qt反例验证。
|
||||
|
||||
各现场保存 `01-pairs.png`、`02-result.png`、`03-restart.png`、`frozen-scope.json`、`first-run.json`、`restart-readback.json`、`rerun.json` 和两个不可覆盖的报告目录。重校验报告绑定新attempt,原报告摘要未变。
|
||||
|
||||
## 可复现命令
|
||||
|
||||
使用本机独立验证环境,下面的输入目录是前轮保存副本,不是源工程;输出必须为新目录。
|
||||
|
||||
```powershell
|
||||
& 'D:/dx-vfy-python-20261117/Scripts/python.exe' -X utf8 tools/accept_verification_closed_loop.py --exe D:/dx-vfy-release-20261117/DxPartReplace/DxPartReplace.exe --before-root D:/dx-vfy-batch-package-20261118/before --after-root D:/dx-vfy-batch-package-20261118/after --expected-items A/input.prj B/input.prj --expect-verdict WARNING --output D:/NEW-normal-loop
|
||||
```
|
||||
|
||||
加入 `--fault-batch` 并换用新输出目录,可重复故障隔离场景。工具只在自己的输出目录复制输入并生成 `00-invalid`,该名称为反例保留名。
|
||||
|
||||
测试使用同一解释器 `-X utf8 -m pytest`,原18文件校验组增加 `tests/v1_1/test_verification_closed_loop.py`,参数 `-q --basetemp D:/dx-vfy-loop-delta-final --junitxml D:/dx-vfy-loop-final.xml`。补充复核为 `tests/v1_1/test_verification_closed_loop.py tests/v1_1/test_independent_verification_acceptance.py tests/v1_1/test_verification_reports.py`,输出 `D:/dx-vfy-loop-scope.xml`。
|
||||
|
||||
## 包身份与失败现场
|
||||
|
||||
本地开发包仍位于 `D:/dx-vfy-release-20261117/DxPartReplace/DxPartReplace.exe`,须保留同目录 `_internal`。本轮EXE SHA256为 `c52c43d8b4a864b85f0a39b92a5b3aab2bc36095240d42968d2d34971c270a91`。复用此前标准构建的未变原生运行时,通过官方PyInstaller API重新编译Python;`D:/vfy_verify_archive.py` 对本分支24个变更模块逐个比较代码对象,全部一致,记录 `D:/dx-vfy-package-proof.json`。上一批量版EXE和证明保留在 `D:/dx-vfy-history-20261118-batch/`。
|
||||
|
||||
失败记录保留:首个正常现场因自动化误用文件选择器而无法操作目录选择器;首个故障现场在重启等待中触发驱动内部15秒超时。已依据真实控件ID修正目录选择器,并让外层90秒等待正确处理内部超时;没有改产品文件对话框或伪造结果。旧现场分别为 `D:/dx-vfy-loop-package-20261118/`、`D:/dx-vfy-loop-faults-20261118/`,测试实例均正常关闭。通过结果来自修正后的全新目录,不是改写旧失败记录。
|
||||
|
||||
## 未测与发布门槛
|
||||
|
||||
仍未取得实际包中停止/资源未知的独立故障现场;其服务/Qt受控回归已通过。真实成功换料回执触发自动交接的包内闭环尚未测,不能用独立输入替代;本轮没有为此重新执行客户换料。连续默认全量没有重跑,前轮既有时序波动仍未解决。因此本次只证明上表范围,未达到发布门槛。
|
||||
|
||||
引脚级Value、确切封装库内部脚位到焊盘映射仍未覆盖,不能从网表校验推断这些能力通过。后续按计划中未勾选项推进。
|
||||
@@ -0,0 +1,59 @@
|
||||
# 剩余四项闭环验收
|
||||
|
||||
执行分支 `codex/independent-verification`,验收工具与回归提交 `b038951`。按[确认的剩余计划](../superpowers/plans/2026-11-18-verification-remaining-closure.md)顺序执行,未修改其他修复工作区,未合并、推送或发布。
|
||||
|
||||
**剩余四项均已取得对应闭环证据。** 停止/恢复、资源未知保护、真实已保存回执自动交接,以及固定提交上的连续默认全量均通过;此前历史记录中的未测状态以本文更新为准。
|
||||
|
||||
## 业务闭环现场
|
||||
|
||||
| 项目 | 已验证的实际行为 | 现场 |
|
||||
| --- | --- | --- |
|
||||
| 三工程停止与继续 | 第一项运行时点击停止;两项未派发保持待校验;重启不自动运行;开始全部只继续这两项,已停止项明确重校验;最终三项均WARNING,旧停止记录保留 | `D:/dx-vfy-stop-three-20261118/acceptance.json` |
|
||||
| 自有实例异常退出 | 核对PID、创建时间与owner后仅中断本工具启动的实例;没有原生退出证明时重启保留stopping/unknown,不显示有效结论、不给后续项创建导出目录 | `D:/dx-vfy-owner-exit-register-20261118/acceptance.json` |
|
||||
| 资源未知下可用性 | 可新建另一任务并导入两项;共4输入、仍只有原来的2次尝试;暂停原因在“检查与范围”中实际可见,应用正常关闭 | 同目录 `reason-visible.json`、`resource-unknown-reason.png` |
|
||||
| 真实保存回执自动交接 | 临时副本RV05从4100-CA0000-T7到4100-CA0000-T0,RV11保持;恰好一条verified换料记录,自动交接只有一个工程项 | `D:/dx-vfy-real-handoff-20261118-v2/acceptance.json` |
|
||||
| 交接后校验、报告、重启与重校验 | 两次尝试generation 1/2,均WARNING;声明属性为expected_change,物理脚/连接/位号/覆盖/网名等必查equal;14条闭环检查通过,换料记录完整内容未变,重复交接未重复建项 | 同目录 `verification-loop/acceptance.json` |
|
||||
|
||||
所有只读校验现场的输入摘要再次核对未变。真实换料只发生于新测试副本,原始样例及共享库LMC摘要仍与执行前一致。资源未知现场按设计保留,不补造退出证明;测试应用实例均已退出。
|
||||
|
||||
预期在开始前保存:停止/异常场景的 `frozen-scope.json`,真实换料的 `predeclared.json`。后者先真实原生导出证明RV05/RV11前提,再准备BOM并通过实际EXE点击确认执行;无直接SQLite写入来伪造换料结果。
|
||||
|
||||
停止现场有 `continued.json`、`stopped-item-rerun.json` 和各自报告。真实交接有确认截图、自动交接截图、原生before/after、不可变快照、实际运行回执、报告以及重启截图。未知资源场景有本工具记录的owner身份和界面截图,未终止其他进程。
|
||||
|
||||
## 实现与验证边界
|
||||
|
||||
新增控制场景验收检查器和真实交接验收工具;`accept_verification_closed_loop.py` 增加 `--control-scenario stop|owner-exit`、`--handoff-data`。产品没有新增故障开关,也没有更改旧换料执行器。
|
||||
|
||||
真实交接的before是历史不可变快照,替换保存后,其原路径自然已有新内容。验收器仅在明确的 `historical_before=True` 且存在预期清单时使用历史快照证明before,以after源摘要作为后续校验只读基线,不重新捕获旧before。普通独立导入仍检查源文件未偏离导入版本。
|
||||
|
||||
只读检查增加执行日志摘要,除了记录数不变,还要求原有command、receipt和generation不变;相应反例已先失败再修正。真实实际包外层另外比较校验前后全部换料记录,证明不会原地重放已有操作。
|
||||
|
||||
针对验收器/控制/CLI/报告的相关回归:**22 passed**,`D:/dx-vfy-final-closure-related.xml`。
|
||||
|
||||
第一次连续默认全量:**2276 passed,0 failures,0 errors**,`D:/dx-vfy-continuous-default-20261118.xml`,耗时1214.45秒。此轮启动后补充过验收器的日志摘要反例,因此仍追加在固定提交 `b038951` 上的最终全量运行,不把首轮当作最终固定测试版本的全部证据。
|
||||
|
||||
执行恢复/回执及打包扩展:**120 passed,1 skipped**,`D:/dx-vfy-final-closure-extended.xml`。范围为 `tests/dsh/test_execution_recovery.py`、`test_run_journal.py`、`test_large_execution_scope.py` 和 `tests/packaging`;跳过的是未配置官方7-Zip的自解压验证。
|
||||
|
||||
固定提交上的最终默认全量:**2276 passed,0 failures,0 errors,0 skipped**,输出 `D:/dx-vfy-fixed-default-20261118.xml`,耗时1271.60秒。启动前记录631个已跟踪产品/测试/工具文件的SHA256:`D:/dx-vfy-fixed-default-20261118-manifest.json`;结束后实际复核全部不变。它与第一轮分开留证,不能用历史分组覆盖代替。
|
||||
|
||||
两轮均只有pywinauto的STA COM线程模式提示,没有失败或错误。本轮未改写旧测试的时序断言;当前完整回归通过不等于声称根治所有环境中的历史时序波动。
|
||||
|
||||
第一次真实交接现场 `D:/dx-vfy-real-handoff-20261118` 因自动化尚未选择任务导致执行按钮不可用,记录失败并正常关闭,换料操作数0。修正测试驱动为先选择任务,再使用全新v2副本完成实际执行;没有对已替换副本重复派发。
|
||||
|
||||
## 包身份
|
||||
|
||||
仍使用 `D:/dx-vfy-release-20261117/DxPartReplace/DxPartReplace.exe` 和完整 `_internal`。EXE SHA256:`c52c43d8b4a864b85f0a39b92a5b3aab2bc36095240d42968d2d34971c270a91`。本轮只改验收工具、测试和文档,产品代码没有改变,无需重新构建。
|
||||
|
||||
`D:/vfy_verify_archive.py` 已对本分支24个变更产品模块逐个比较最终包代码对象,全部匹配。身份记录 `D:/dx-vfy-package-proof.json`。校验源码与包的一致性不能替代厂商工具或库内部能力验证。
|
||||
|
||||
最终运行时复核通过:`tools/verify_packaged_runtime.py` 对全新数据根 `D:/dx-vfy-final-closure-runtime-20261118` 验证frozen supervisor、win32timezone、进程创建时间、正常退出和资源释放,均为true。开发包保持原SHA256。
|
||||
|
||||
## 复现入口
|
||||
|
||||
使用 `D:/dx-vfy-python-20261117/Scripts/python.exe -X utf8`,工作目录为本分支。所有输出目录必须新建且不能位于源工程/库内。
|
||||
|
||||
- 停止/异常退出:`tools/accept_verification_closed_loop.py --exe <EXE> --before-root <前目录> --after-root <后目录> --expected-items A/input.prj B/input.prj C/input.prj --expect-verdict WARNING --control-scenario stop --output <新目录>`;未知资源用 `owner-exit`,至少保留两项供未派发检查。
|
||||
- 真实交接:`tools/accept_verification_saved_handoff.py --source <原始已保存工程.prj> --library <已安装库.lmc> --exe <EXE> --output <新目录>`;固定RV05/RV11和料号前提不满足时失败,不临时换测试目标。
|
||||
- 连续默认全量:`-m pytest -q --basetemp D:/dx-vfy-fixed-default-20261118-long-temporary-root --junitxml D:/dx-vfy-fixed-default-20261118.xml`;重复执行须换用全新临时根和XML文件,保留本次原始记录。
|
||||
|
||||
引脚级Value和确切封装库内部映射仍未覆盖,不属于四项验收缺口,也未宣称完成ERC/PCB验证。官方7-Zip缺失导致的自解压安装包检查仍为skip;本轮交付已验证的本地开发包,没有制作、合并或发布新安装包。
|
||||
@@ -0,0 +1,37 @@
|
||||
# Issue 33 D2 · 工程路径错误提示验收
|
||||
|
||||
工程读取和任务创建的路径检查直接调用 `lstat()`。目录不存在或扫描后工程移走时,文件系统异常进入统一兜底,现场报告仅能看到“发生未处理异常”。目录存在且能读取属性时,`scandir()` 仍可能因缺少列目录权限失败。
|
||||
|
||||
修复在路径检查和读取处分类处理这些预期错误。读取对话框和创建任务的错误提示均显示完整路径、分类代码、处理建议和可关联日志的 `DXT` 编号。预期错误写入一条应用日志。未知异常保留 traceback。
|
||||
|
||||
## Windows 11 实测
|
||||
|
||||
使用 Qt 按钮启动读取、真实文件系统与任务库。第五例在成功扫描两个候选工程后重命名其中一个文件,从实际服务入口创建选定任务并检查主窗口所用的错误格式和任务数据库。
|
||||
|
||||
| 输入 | 基线 `46deb9c` | 修复后代码 | 修复后错误编号 |
|
||||
| --- | --- | --- | --- |
|
||||
| 不存在的目录 | 通用兜底 | `path_missing` | `DXT-20261125-3EE8F667` |
|
||||
| 普通文件作为目录 | 英文非目录文案 | `path_not_directory` | `DXT-20261125-92876D74` |
|
||||
| 路径中途遇到普通文件 | 通用兜底 | `path_not_directory` | `DXT-20261125-0C615FE8` |
|
||||
| ACL 拒绝列目录 | 通用兜底 | `path_denied` | `DXT-20261125-ED64EEA9` |
|
||||
| 工程在扫描后被移走 | 通用兜底 | `path_missing` | `DXT-20261125-CA48D2FF` |
|
||||
|
||||
ACL 测试对临时目录中的当前用户拒绝 `FILE_LIST_DIRECTORY`,两个版本的文件系统操作均触发原生 `WinError 5`。创建任务失败后库中仍有 0 条任务。五个路径输入的通用兜底率从 4/5 降到 0/5。额外注入的 `RuntimeError` 对照组仍触发一次 `unhandled_exception`,并保留 traceback。
|
||||
|
||||
## 复跑
|
||||
|
||||
在仓库根目录运行。使用未占用的临时目录保存测试日志。
|
||||
|
||||
```powershell
|
||||
$env:PYTHONUTF8 = '1'
|
||||
python -m pytest -q -s tests/v1_1/test_project_path_errors.py tests/v1_1/test_scan_responsiveness.py tests/v1_1/test_project_long_paths.py tests/v1_1/test_path_access.py tests/trial_task_center/test_logging_setup.py --basetemp build/issue33-d2
|
||||
```
|
||||
|
||||
实测 35 项通过。以下命令按错误记录统计扫描和创建任务的通用兜底率。路径用例与故障对照分别统计时,从相应测试目录读取日志。
|
||||
|
||||
```powershell
|
||||
$rows = Get-ChildItem build/issue33-d2 -Recurse -Filter application.log |
|
||||
Select-String 'error_id=\S+ operation=(scan_project_directory|create_project_tasks) (code=\S+ )?message='
|
||||
$generic = $rows | Where-Object { $_.Line -match 'code=unhandled_exception |message=发生未处理异常$' }
|
||||
'{0}/{1}' -f @($generic).Count, @($rows).Count
|
||||
```
|
||||
@@ -0,0 +1,31 @@
|
||||
# Issue 33 D5 · BOM 未知列验收
|
||||
|
||||
现场 B3 的 `INVALID_C1_bad_header_extra_col.xlsx` 带有 `extra_column`。名称归一化将未知列映射为空,后续只复制模板定义的列。导入成功时,工作区原先只报告保存行数与失败行数。
|
||||
|
||||
现在 BOM 导入保留模板列的精确映射,并为每个被忽略的具名列显示来源文件、原始列名与警告计数。详情和任务事件同时记录这些警告。缺失必需列时,导入停止,错误详情列出具体缺失项并对相近列名给出改名建议。
|
||||
|
||||
## Windows 11 重放
|
||||
|
||||
通过 Qt 工作区的“导入 BOM”按钮和真实任务服务运行,测试替换的是文件选择对话框的返回值。现场文件复制到临时目录,仅把第一条记录的工程名称与路径绑定到临时工程,保留了原始表头和替换字段。
|
||||
|
||||
| 工作簿 | 结果 |
|
||||
| --- | --- |
|
||||
| 两个额外列「供应商」「备注」 | 保存 1 行、失败 0 行、警告 2 项。详情逐列列名,任务事件记录同一组警告 |
|
||||
| 现场 B3 `extra_column` | 保存 1 行、失败 0 行、警告 1 项。详情保留该列名 |
|
||||
| 用「新料号编码」替换必需的「新料号」 | 指出缺少「新料号」,并建议将「新料号编码」改为「新料号」 |
|
||||
| 缺少「新料号」 | 指出具体缺失项 |
|
||||
| 表头公式与额外列中的数据公式 | 分别拒绝表头公式和第 2 行公式 |
|
||||
| 原模板 | 保存 1 行、失败 0 行,无警告 |
|
||||
|
||||
BOM 草稿导入时未启动工程位号采集。回归还检查了由监督子进程返回的真实预览报告能携带同样的警告。包含现场工作簿重放的定向回归共通过 110 项。
|
||||
|
||||
## 复跑
|
||||
|
||||
在仓库根目录运行。现场文件从工单附件 `05_实测证据/paper2_bom` 解出。普通回归可省略 `DX_ISSUE33_D5_FIELD`,此时跳过现场文件重放。
|
||||
|
||||
```powershell
|
||||
$env:PYTHONUTF8 = '1'
|
||||
$env:PYTHONPATH = (Resolve-Path src).Path
|
||||
$env:DX_ISSUE33_D5_FIELD = 'C:/path/to/INVALID_C1_bad_header_extra_col.xlsx'
|
||||
python -m pytest -q -s tests/v1_1/test_bom_header_feedback.py tests/v1_1/test_bom_import_report.py tests/v1_1/test_bom_pending.py tests/v1_1/test_bom_sources_supervision.py tests/trial_task_center/test_bom_import_review.py tests/trial_task_center/test_item_value_and_bom_sources.py
|
||||
```
|
||||
@@ -0,0 +1,26 @@
|
||||
# Issue #33 D6 · DxDataBook 加载失败验证
|
||||
|
||||
现场 `WIFI_RTL8723DU` 的 `LWB01` 在加载目标 `4885-S018D0-M220` 时超时。原报告记录了可见列表窗口,阶段为 `preflight`,本项写入凭据为 `prepared`。同代次此前的项已有写入凭据,项目进入保留和对账流程。类似的失败也出现在 `BOB` 与 `BOB_SHIELD` 的目标 `4885-S033D0-M220` 上。现场空标题窗口 `10750260` 属于同批后续 `WIFI_RTL8192FC` 会话的启动阶段。它与 `LWB01` 超时分属不同 CAD 进程和代次。现场日志能定位超时阶段及保留原因,库服务状态和窗口复建情况仍待同代次采样。
|
||||
|
||||
加载阶段根据 DxDataBook 控件是否已存在采用 45 秒或 20 秒窗口。加载过程重新发现同一窗口下的列表与筛选器,控件重建后重发筛选并重新验证行稳定性。超时前写下本项凭据状态,超时后至多重试一次。重试要求本项仍有身份匹配的 `prepared` 凭据。空窗口处理进一步要求窗口在本次浏览后出现,属于同一 CAD 进程、线程和替换对话框,且替换对话框已被禁用。窗口和子控件证据先写盘,随后才发送关闭消息并观察结果。替换提交、属性恢复和保存继续使用既有的写入凭据与关闭检查点。
|
||||
|
||||
## Windows 验证
|
||||
|
||||
| 场景 | 观测结果 |
|
||||
| --- | --- |
|
||||
| 冷加载列表重建注入 | 原列表 `10` 更新为 `20`,筛选器从 `11` 切换到 `21`,稳定性窗口重新计时,最终使用新列表。 |
|
||||
| 控件枚举与访问之间发生重建 | 筛选消息返回 Win32 `1400`,或列表读取返回 UIA `0x80040201`。两种故障都在当前加载时限内重取控件,访问新筛选器并选中正确的行。 |
|
||||
| 真实 Win32 空窗口,凭据 `prepared` | 私有桌面创建的 HWND `19728876` 属于替换对话框,保存窗口树后只关闭该窗口。加载重试一次后返回目标,原有同 PID 无关窗口仍打开,凭据仍为 `prepared`。 |
|
||||
| 真实 Win32 空窗口,凭据 `mutation_possible` | 窗口 `1183362` 具备同样的结构和归属,仅留下诊断。未重试,窗口与写入凭据均保留。 |
|
||||
| 先前已有暂存写入,当前项失败 | Windows `cscript.exe` 执行生产 VBS 清理过程。当前未写且无暂存项时经过原始状态核验并以 `SaveChanges=False` 关闭。已有前项暂存写入、当前项写入状态无法确认或保存已请求时,保留工程供对账。 |
|
||||
|
||||
真实 HWND 注入运行生产窗口检查和加载重试代码,测试用 Win32 窗口模拟 DxDataBook 的无按钮提示。测试将等待时间缩短到 1.5 秒,筛选响应由测试控制。原始诊断见 [prepared.json](evidence/2026-11-25-issue33-d6/prepared.json) 和 [mutation_possible.json](evidence/2026-11-25-issue33-d6/mutation_possible.json)。
|
||||
|
||||
另一组注入使用原生 ListView、Edit、UIA 行读取和消息驱动生产 `run_native`,CAD COM 属性与菜单资源由替身提供。先销毁筛选框触发 Win32 `1400`,再销毁列表触发 UIA `0x80040201`。程序复取新列表和筛选器,扫描两行后命中精确料号。提交回调只触发一次并读到持久化状态 `mutation_possible`。只有相似料号的对照执行两次筛选后超时,提交数为零,凭据仍为 `prepared`。 [精确命中](evidence/2026-11-25-issue33-d6/native-controls-positive.json) [没有精确命中](evidence/2026-11-25-issue33-d6/native-controls-negative.json)
|
||||
|
||||
定向回归 114 项通过,包含加载、窗口归属、写入凭据、VBS 失败收尾和现有目标 Cell 路径。另执行扩展集成测试时,丢失 UID 的旧测试出现保存回读证明缺失,用 `origin/main` 的原始 VBS 同例复现。
|
||||
|
||||
## 真实工程副本
|
||||
|
||||
- 现场备份 `WIFI_RTL8723DU` 使用本机 `Skyworth_Lib` 中央库替代现场 `S:\mentor_lib.lmc`,BOM 核验找到 `LWB01` 并确认 UID。执行停在 `open_project` 249 秒,回到 `open_sheet` 安全边界时停止,关闭检查点仍观测到工程打开。写入凭据为 `prepared`,工程保护标记保留。此次在进入 DxDataBook 前结束,现场目标件换料及保存回读尚待验证。 [现场副本记录](evidence/2026-11-25-issue33-d6/field-copy.json)
|
||||
- `Audio_D2128` 副本上,`RV05` 从 `4100-CA0000-T7` 换为 `4100-CA0000-T0`。已存在的 DxDataBook 控件在 2.703 秒内返回目标。原生替换报告成功,保存请求和返回各一次,工程完成关闭及重新读取,状态为 `saved_ok/project_committed`,独立网表比对为 `verified`。关闭整个 CAD 进程时超出 15 秒并触发资源释放保护标记,任务目录未产生业务不确定标记。 [正常副本记录](evidence/2026-11-25-issue33-d6/normal-copy.json)
|
||||
@@ -0,0 +1,14 @@
|
||||
# Issue #33 D7 · 已保存工程的资源收尾验证
|
||||
|
||||
Audio_D2128 历史副本的 `RV05` 换料已保存并通过独立网表核验。Quit 助手退出码为 0,CAD 根进程 15 秒内未退出。执行自有 Job 强退后,Job 活动进程数降到 0,两条后代进程的退出句柄已核验,根进程句柄在随后 5 秒内仍未发出信号。批次保留了根进程的创建时间和强退记录,桌面还未进入关闭阶段。首次失败后,运行时缺少自动复核这一迟到的退出结果的路径。
|
||||
|
||||
运行时在已请求强退的收尾失败后等待 0.5、1、2 秒,最多复核三次原有进程树。进程树仍活跃时保留原句柄与阻塞,确认退出时再收尾该代桌面。Windows 进程已收到强退请求后只等待原句柄。已保存工程的任务状态和独立网表回执继续作为业务证据。
|
||||
|
||||
历史记录通过 PID 和创建时间确认写进程退出,还要求自有清理记录或绑定到该代 CAD 的空 Job 证明。桌面存在性通过枚举核验。同名受管理桌面经槽位互斥锁检查,新的活动租约在观察期间保持运行。资源记录和业务保护独立持久化。启动和批次收尾的自动观察耗尽后保留已有保护,下一次资源清理可重新取证。
|
||||
|
||||
## Windows 证据
|
||||
|
||||
- 用原始受阻历史数据的独立副本运行资源清理。槽位锁内确认桌面已经消失,六个已绑定进程均退出,批次由 `blocked` 更新为 `released`。比较前后 SHA-256,任务状态、保存回读、独立网表、关闭检查点和原有 `uncertain.flag` 保持逐字节一致。 [历史副本记录](evidence/2026-11-25-issue33-d7/historical.json)
|
||||
- 用真实 Win32 私有桌面和独立 Job 验证晚退出。故障注入使 CAD 收尾在子进程实际退出前返回异常,之后自动等待并证明原进程退出,随后退还同一租约。原异常和注入的强退诊断均保留。外部持有者场景确认外部进程存活,桌面先保持隔离,外部持有者退出后复核到物理释放。 [晚退出](evidence/2026-11-25-issue33-d7/delayed-owned-exit.json) [外部持有](evidence/2026-11-25-issue33-d7/external-reference.json)
|
||||
- 真实 Mentor 7.9.5 空闲会话运行正常退出。Quit 助手和 CAD 根进程的退出码均为 0,约 4.375 秒完成关停,桌面释放后资源待处理数为 0。 [正常退出](evidence/2026-11-25-issue33-d7/mentor-idle.json)
|
||||
- 新建的 Audio_D2128 真实 Mentor 对照在本机完成 BOM 位号核验,执行时停在 `open_project` 276 秒,到 `open_sheet` 安全检查点才返回。工程仍打开,任务保持保护。本轮未在该副本复现保存后的 Mentor 退出,保存侧证据来自上述真实历史数据。
|
||||
@@ -0,0 +1,21 @@
|
||||
# Issue #33 D8 · 原批次资源恢复验证
|
||||
|
||||
现场 100 工程按同一个任务队列执行。第 10 项已经隔离,第 11 项留下业务阻断回执,原队列仍有 89 项待派发。后台资源复核完成后,应用界面更新了资源状态,队列执行入口未再次读取原检查点。现场归档队列编号为 `55e1032ac965453b8adf307da1400511`。
|
||||
|
||||
候选在延续执行前核对监督进程与结束回执、原始请求摘要、队列编号、有序任务范围和计划哈希。现有写入资源和监督进程须通过释放核验。新暂停记录保存每个工程的写入源,恢复时重新读取工程声明,源不明确或变更时保留暂停。已经出具结果待核验回执的工程与共享其写入源的后续工程继续隔离。队列租约内消费原暂停记录并保存隔离状态,防止重复接续。同一用户授权运行可在资源释放后继续,用户主动暂停仍走原确认流程。
|
||||
|
||||
| Windows 场景 | 验证结果 |
|
||||
| --- | --- |
|
||||
| D7 基线,100 工程 | Windows 写进程退出后,首次返回 9 项完成、2 项阻断、89 项待执行。 [基线记录](evidence/2026-11-25-issue33-d8/baseline-100.json) |
|
||||
| D8 候选,100 工程 | 写进程存活时,89 项仍待执行。退出后原队列自动继续,最终 97 项完成、3 项阻断。第 10、11 项各保留一条待核验回执,第 12 项共享数据库且零次替换派发。成功项各保存一次。 [候选记录](evidence/2026-11-25-issue33-d8/candidate-100.json) |
|
||||
| D8 候选,8 工程 | 人工在第 3 项保存后暂停,保留 5 项待执行。启动不同 PID 的 Python 进程,以同一队列及冻结计划恢复到 8 项完成。每个作业 ID 仅派发一次。 [重启记录](evidence/2026-11-25-issue33-d8/candidate-8-restart.json) |
|
||||
|
||||
夹具使用生产任务服务、队列、SQLite、监督协议和 Windows 进程退出检查。CAD 替换与保存结果使用故障注入回执。验收覆盖调度和恢复路径,真实 Mentor 批量替换另有实机环境依赖。
|
||||
|
||||
```powershell
|
||||
$env:PYTHONPATH = (Resolve-Path src).Path
|
||||
py -3.12 tools/verify_issue33_queue.py --projects 100 --output <新候选目录>
|
||||
py -3.12 tools/verify_issue33_queue.py --projects 8 --output <新暂停目录>
|
||||
```
|
||||
|
||||
将 `PYTHONPATH` 指向 D7 基线源码,并在 100 项命令追加 `--expect-baseline`,即可复跑基线。输出目录首次运行时应当不存在。
|
||||
@@ -0,0 +1,63 @@
|
||||
# Issue #44 本地增量功能验收
|
||||
|
||||
日期:2026-11-27。分支:`codex/issue44-batch-remediation-plan`。本次从 `0b7f3e5` 开始实施。状态:本轮可验证的增量已整改并通过本地验收;原生工程采集冲突仍缺现场资料,不据此关闭 #44。
|
||||
|
||||
用户要求:以修复完成为目标,只验收增量代码的实际功能,不重复验收。此前 58 项基线结果保留,不重跑整套基线、六套试卷或 100 工程发布验收;不重新构建安装包。以下记录每项增量的首次失败、修改后结果及受影响的必要回归。仅当新改动影响已通过功能,才重验对应项。
|
||||
|
||||
| 编号 | 实际增量功能 | 验收方式 | 状态/证据 |
|
||||
| --- | --- | --- | --- |
|
||||
| L1 | 历史 PID 查询拒绝访问不崩溃、不误判退出 | Win32 错误 5/87 注入;真实查询接口的关闭/复用语义 | 通过;未知保持阻断,历史记录不被删除或改成成功 |
|
||||
| L2 | isolated 即使旧 blocking=False 也阻断新写入 | 生产资源门禁;真实自有 Windows 桌面的外部句柄生命周期 | 通过;外部句柄未释放时不放行;健康本代租约可复用 |
|
||||
| L3 | 本批/所选范围准确且按持久化顺序 | 生产任务服务 + Qt 动作;列表倒序但按原顺序派发 | 通过;确认窗口实际文字也不含未选中的工程 |
|
||||
| L4 | 混合配置只确认并执行可执行子集 | 8 个服务任务的裁决、确认和实际执行器派发记录 | 通过;5 项进入原队列,3 项 skipped;UI/JSON 同一摘要 |
|
||||
| L5 | 确认后计划或选集变化零派发 | 模态确认变更注入 + 服务派发锁内重核验 | 通过;新增可执行成员、改变 Value、改变所选范围均不能偷用旧确认 |
|
||||
| L6 | 停滞协作停止有正确来源、不确定写入整批停 | 监督 IPC 子进程;实际队列副作用和保护写入顺序 | 通过;inactivity 与 user_pause 分开;资源释放不能自动越过未核验写入 |
|
||||
| L7 | 23 pending_save 进入同一摘要,不能计成功 | 当前轮次 SQLite 操作记录及返回/JSON 摘要 | 通过;目标、作业、工程分开,旧轮次和 superseded 不混入 |
|
||||
| L8 | 所有出口留回执,报表失败不重放 | 生产执行服务、SQLite/JSON 故障注入、启动恢复及资源重查 | 通过;正常、取消、拒绝、暂停、异常、重试均有实际结论;丢 JSON 不重派发 |
|
||||
| L9 | 诊断包含批次清单和回执且遵守白名单 | 实际 ZIP 导出内容及原有脱敏限额 | 通过;原工程与密钥不混入,遗漏可见 |
|
||||
| L10 | 新一轮/绑定与重试边界 | 原有 handler/归档/重绑实现核对;增量仅验收重试的整批保护 | 重试保护通过;新一轮和完整任务绑定未修改,按要求不重复验收 |
|
||||
| L11 | 查库超时不冒充目标不存在 | 真正超时分支、准备态一次重载、真实 cscript/VBScript 回执链 | 5 项通过;输出 lookup_unavailable,未经无写入认证不得自动重试 |
|
||||
| L12 | 暂停后数据库声明变化不能沿旧授权写入 | Qt 实际暂停、修改下一工程 iCDBDir、手动继续 | RED 复现第二次错误派发;GREEN 保持一次派发并报写入源变化 |
|
||||
| L13 | 同批待核验不能借事件重试绕过 | 预约前、RunJournal 重试意图、实际派发锁内三处生产校验 | 通过;包括未选中的同批待核验成员和已清标记但仍须重新确认的旧回执 |
|
||||
| L14 | 资源交接每次继续仍核对原范围 | 监督进程交接租约内调用;初次 begin 与后续验证区分 | 通过;原范围/源变更或新待核验成员阻断下一监督进程 |
|
||||
| L15 | 续跑结束但新回执未写入时重启 | 原暂停回执非空、本次结果已落盘、应用退出注入 | 通过;SQLite/JSON 使用新结果及新 revision,零 CAD 重放 |
|
||||
| L16 | 冻结清单损坏/丢失不能退为旧队列 | SQLite 汇总或检查点仍有 manifest_digest 的缺文件场景 | 通过;明确 batch_manifest 错误,未再次派发 |
|
||||
|
||||
模拟 CAD 的测试只证明服务/队列行为,不作为真实 Mentor 换料证明。真实 Windows 资源测试只操作自行创建的 Job/桌面和进程,绝不杀外部持有者。验收结束时逐项更新本表,未执行、受阻和未修复均如实单列。
|
||||
|
||||
## 执行记录
|
||||
|
||||
以下集合有相交与因代码修改而重验的用例,不累加为互不重复的验收总数。测试先验证新增失败分支,再验证对应修复;不重复运行已经通过且未受新修改影响的全套场景。
|
||||
|
||||
| 范围 | 结果 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| 原方案阶段 58 项基线 | 沿用历史记录 | 本次未重跑该命令或全量套件 |
|
||||
| 资源/停滞及直接受影响的旧策略断言 | 68 passed,38.51 秒 | 含真实 Windows 外部桌面句柄与监督子进程停止;旧非阻塞隔离断言被严格策略替换 |
|
||||
| RunJournal 资源暂停与相邻安全失败 | 3 passed,3.37 秒 | 新 completed/failed 资源暂停的真实持久化检查点可被识别 |
|
||||
| 摘要/回执/导出及直接存储回归 | 52 passed,20.86 秒 | `test_issue44_batch_summary`、`test_issue44_batch_bundle`、`test_issue44_batch_receipt` 与相关三组存储/导出回归 |
|
||||
| 最终清理后恢复资源结论 | 1 passed,2.37 秒 | 只重跑新增的 isolated→released 回执修复用例 |
|
||||
| 第一轮审查后的回执专项 | 8 项新增用例最终通过 | native no-op skipped、整批重试抑制、故障结果恢复、查库代码、主动/停滞暂停 |
|
||||
| 续跑后的新监督结果恢复 | 1 passed,1.96 秒 | 旧暂停 summary 不能遮住本次已完成结果 |
|
||||
| 事件重试保护及兼容回执 | 6 passed,16.91 秒 | 5 个新增反例与一个正常重试邻接用例 |
|
||||
| 每次继续复核、缺失清单及重试异常回执 | 3 passed,7.17 秒 | 只验证第二轮审查新增的缺口 |
|
||||
| 原生查库错误及 VBScript 传播 | 5 passed | 4 个新语义用例与一个 cscript 集成用例;未调用真实 CAD |
|
||||
| Qt 批次入口 | 首轮 6 例各自修复后通过 | 明确所选、缺计划跳过、确认失效、整批待核验、取消回执 |
|
||||
| Qt 混合 8 工程 / 模态改计划 | 均通过 | 执行器只收到已确认的 5 个 ID,JSON/界面计数一致;改计划零派发 |
|
||||
| Qt 启动补报表 / 确认改选集 | 2 passed,6.56 秒 | 使用生产监督启动分支;报告修复不增加派发 |
|
||||
| 恢复不比较可变进度 / 同批未选成员保护 | 2 passed,2.54 秒 | 严格复核不可变源,正常进度不会失效 |
|
||||
| Qt 真正手动恢复源变更 / 异步确认读通道 | 2 passed,3.71 秒 | 恢复前写入源变化被锁内阻断;健康后台读不占写通道 |
|
||||
| Qt 倒序显示的所选执行 | 1 passed,3.75 秒 | 倒序显示不改变冻结的 A→B 顺序 |
|
||||
| 已知清单运行缺失 manifest 的继续入口 | 1 passed,1.81 秒 | 明确报告 batch_manifest,拒绝旧版兼容回退 |
|
||||
| 确认可见文字和直接受影响入口 | 4 passed,9.39 秒 | 可见确认范围、异步预检错误、已完成成员与 21 工程确认 |
|
||||
| 修改文件语法及差异检查 | 通过 | 40 个修改/新增 Python 文件 AST 可解析;`git diff --check` 无错误 |
|
||||
|
||||
最终独立代码复核对已发现的范围、资源续跑、事件重试、源变更和崩溃回执问题完成复查;四项最后遗留路径复核通过。复查未重复执行测试,也未操作真实 CAD。
|
||||
|
||||
## 未验收与剩余现场问题
|
||||
|
||||
- 未执行真实 Mentor 换料、六卷评分、100 工程整批或冻结包复测;本次结果不声称卷四达到 90 分,也不关闭 #44。
|
||||
- ETHERNET_1G 的 DXT-20261126-B19CC4B3:仓库、已知本地资料及附件中缺原工程与配对的 scope/effective 报告,尚不能复现该身份冲突。原检查保留,未通过忽略位号属性冲突换取通过。
|
||||
- 客户库未提供可确定目标不存在的只读证据,未声称修复所有 `target_not_found` 场景。本次已完成的是把查库不可用与不存在分开,避免错误成功或未经认证的自动重试。
|
||||
- 新一轮和完整恢复工作台的既有功能没有因本轮重复重写。其跨 #43/#46 的现场缺陷仍需原现场证据;本轮仅处理共同的整批准入、写入保护、入口反馈与回执。
|
||||
|
||||
本地分支保留,可继续定位剩余现场问题。没有推送、合并、发布或向远端工单发送消息。
|
||||
@@ -0,0 +1,17 @@
|
||||
# Issue #33 D1 同数据目录单实例
|
||||
|
||||
`application.main` 原先直接配置日志、打开 `task-center.db` 并执行启动恢复。现场 `data_lock` 日志有两次同根 `application_start`,两实例均成功读取任务列表。现有执行租约只在执行操作中生效。
|
||||
|
||||
GUI 现在先取得 `.gui-instance.lock` 的内核文件锁,再打开日志和数据库。第二次启动经 Qt 本地套接字请求激活现有窗口,该窗口写入 `instance_conflict` 并在状态栏提示。锁保持到 SQLite 和后台读线程关闭,进程强制结束时由操作系统回收。启动参数中的工作进程和 CLI 在 GUI 文件锁之前分流。
|
||||
|
||||
## Windows 复测
|
||||
|
||||
```powershell
|
||||
$env:QT_QPA_PLATFORM = 'offscreen'
|
||||
python -m pytest -q tests/v1_1/test_single_instance.py
|
||||
```
|
||||
|
||||
- 四个真实 GUI 子进程并发打开同一目录,其中两个使用大写路径。日志有一次 `application_start`、一次启动恢复和三次 `instance_conflict`,三个转发进程均返回 0。
|
||||
- 另一个数据目录的窗口与持锁窗口同时存活。同根 `--native-helper` 执行自身参数校验并返回 2,冲突计数仍为三次。
|
||||
- 强制结束持锁进程后,同根 `--smoke-test` 成功启动并正常关闭,预先写入的任务 ID 仍在 SQLite。另一数据目录的进程继续运行。
|
||||
- 修改前运行同一并发场景时,三个竞争进程没有退出,测试失败。测试使用 Qt offscreen,验证激活请求已处理。Windows 桌面前台切换和实际 CAD 写入需通过交互式验收复核。
|
||||
@@ -0,0 +1,21 @@
|
||||
# Issue #33 D3 主窗口布局恢复
|
||||
|
||||
原来的 `ui-layout.ini` 只保存分栏、表头与排序,`TrialTaskCenterWindow` 每次启动都会重用默认窗口尺寸。复现时,保存进程关闭前的普通窗口为 `(45, 55, 1200, 760)` 且已最大化,重启后普通窗口变为 `(2, 2, 1280, 880)` 且未最大化。
|
||||
|
||||
正常接受关闭后,现通过 Qt `saveGeometry()` 持久化普通窗口几何和最大化状态。启动时调用 `restoreGeometry()`。若配置损坏、DPI 改变导致 Qt 拒绝恢复,或普通窗口超出当前可用屏幕,窗口会在当前可用屏幕内重新定位,并保留产品定义的最小尺寸。
|
||||
|
||||
## Windows 原生窗口实测
|
||||
|
||||
```powershell
|
||||
$env:QT_QPA_PLATFORM = 'windows'
|
||||
python -m pytest -q -s tests/v1_1/test_window_geometry.py
|
||||
```
|
||||
|
||||
| 场景 | 结果 |
|
||||
| --- | --- |
|
||||
| 正常退出并启动新进程 | 普通窗口几何保持 `(45, 55, 1200, 760)`,最大化状态保持为真 |
|
||||
| 新进程设 `QT_SCALE_FACTOR=1.5` | 普通窗口回退为 `(8, 36, 1008, 700)`,窗口位于可用屏幕,采用普通状态 |
|
||||
| 配置值为错误类型或截断的字节 | 窗口仍能打开,普通窗口位置可达 |
|
||||
| 配置保存位置为 `(50000, 50000)` | 窗口回到可用屏幕 |
|
||||
|
||||
测试通过 4 项。屏外场景用坐标模拟显示器移除,DPI 变化由 Qt 环境设置触发。
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"mode": "field",
|
||||
"environment": "Windows, DxDesigner 7.9.5, source runtime",
|
||||
"library_mapping": "Skyworth_Lib",
|
||||
"library_lmc_unchanged": true,
|
||||
"project": "WIFI_RTL8723DU.prj",
|
||||
"request_old_new_refdes": [
|
||||
"483C-S018D0-M210",
|
||||
"4885-S018D0-M220",
|
||||
"LWB01"
|
||||
],
|
||||
"attempt": {
|
||||
"session_id": "bf846ff076254e5fbb3bc7ccf1ee859d",
|
||||
"generation": 1,
|
||||
"attempt_id": "44a747ec3c5d440fb60d5a2a407b8037",
|
||||
"job_id": "08d6ebdc6cc540f7b2296a2ef737947a_0",
|
||||
"state": "prepared"
|
||||
},
|
||||
"native": [],
|
||||
"status_log": [
|
||||
"job_id\tstate\tcode\tmessage"
|
||||
],
|
||||
"operation_log_excerpt": [
|
||||
"2026/11/25 9:57:21\tINFO\tstage=open_project target=<copy-root>\\project\\WIFI_RTL8723DU.prj",
|
||||
"2026/11/25 10:01:30\tERROR\tstage=open_sheet number=-2147220644 source=QuickPartReplace.SafeStop description=stopped at a safe boundary before native mutation after inactivity; prewrite pause closure was not proven: %7F3A%5C11%5BF9%8C61",
|
||||
"quick_run_uncertain monitor_failure error=project close checkpoint failed: owned CAD still has a project open; no implicit save or discard\\r\\n"
|
||||
],
|
||||
"independent_verification": [
|
||||
"not_completed"
|
||||
],
|
||||
"uncertain_flags_relative_to_data_root": [
|
||||
"batch-resources/bf846ff076254e5fbb3bc7ccf1ee859d/generation-1/uncertain.flag",
|
||||
"tasks/546160ef-0e8f-4b15-8394-e35f8c562366/quick-run/uncertain.flag"
|
||||
],
|
||||
"queue_outcome": "project remained open at the close checkpoint"
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
[
|
||||
{
|
||||
"stage": "preflight",
|
||||
"databook": {
|
||||
"loads": [
|
||||
{
|
||||
"mode": "warm",
|
||||
"timeout_seconds": 20,
|
||||
"attempt_state_before_load": "mutation_possible",
|
||||
"list_handle": 17,
|
||||
"filter_handle": 18,
|
||||
"error": "Native DxDataBook did not finish loading target part: NEW",
|
||||
"elapsed_seconds": 1.594,
|
||||
"dialogs": [
|
||||
{
|
||||
"hwnd": 1183362,
|
||||
"owner": 200514,
|
||||
"pid": 56180,
|
||||
"title": "",
|
||||
"children": [],
|
||||
"browser": false,
|
||||
"dismissible": true
|
||||
}
|
||||
],
|
||||
"attempt_state": "mutation_possible",
|
||||
"retry": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"window_closed": [],
|
||||
"marker_state": "mutation_possible"
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,91 @@
|
||||
{
|
||||
"attempt": "prepared",
|
||||
"events": [
|
||||
{
|
||||
"controls": [
|
||||
21630720,
|
||||
528470
|
||||
]
|
||||
},
|
||||
{
|
||||
"edit_hwnd": 528470,
|
||||
"text": "NEW"
|
||||
},
|
||||
{
|
||||
"read_list": 21630720,
|
||||
"row_count": 1
|
||||
},
|
||||
{
|
||||
"read_list": 21630720,
|
||||
"row_count": 1
|
||||
},
|
||||
{
|
||||
"edit_hwnd": 528470,
|
||||
"text": "NEW"
|
||||
},
|
||||
{
|
||||
"read_list": 21630720,
|
||||
"row_count": 1
|
||||
},
|
||||
{
|
||||
"read_list": 21630720,
|
||||
"row_count": 1
|
||||
}
|
||||
],
|
||||
"report": {
|
||||
"native_command": {
|
||||
"id": 33977,
|
||||
"executable": "C:\\Users\\ABS_Windows\\AppData\\Local\\Programs\\Python\\Python312\\python.exe",
|
||||
"trigger": "resource_command"
|
||||
},
|
||||
"native_options": {
|
||||
"1704": {
|
||||
"text": "Option",
|
||||
"checked": true
|
||||
},
|
||||
"1105": {
|
||||
"text": "Option",
|
||||
"checked": true
|
||||
},
|
||||
"1697": {
|
||||
"text": "Option",
|
||||
"checked": true
|
||||
},
|
||||
"1700": {
|
||||
"text": "Option",
|
||||
"checked": true
|
||||
}
|
||||
},
|
||||
"databook": {
|
||||
"main_visible_before_browse": true,
|
||||
"browse_button": 3017658,
|
||||
"loads": [
|
||||
{
|
||||
"mode": "cold",
|
||||
"timeout_seconds": 45,
|
||||
"attempt_state_before_load": "prepared",
|
||||
"list_handle": 21630720,
|
||||
"filter_handle": 528470,
|
||||
"error": "Native DxDataBook did not finish loading target part: NEW",
|
||||
"elapsed_seconds": 3.437,
|
||||
"dialogs": [],
|
||||
"attempt_state": "prepared",
|
||||
"retry": true
|
||||
},
|
||||
{
|
||||
"mode": "warm",
|
||||
"timeout_seconds": 20,
|
||||
"attempt_state_before_load": "prepared",
|
||||
"list_handle": 21630720,
|
||||
"filter_handle": 528470,
|
||||
"error": "Native DxDataBook did not finish loading target part: NEW",
|
||||
"elapsed_seconds": 3.344,
|
||||
"dialogs": [],
|
||||
"attempt_state": "prepared",
|
||||
"retry": false
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"error": "TimeoutError('Native DxDataBook did not finish loading target part: NEW')"
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
{
|
||||
"attempt": "mutation_possible",
|
||||
"events": [
|
||||
{
|
||||
"controls": [
|
||||
21696256,
|
||||
594006
|
||||
]
|
||||
},
|
||||
{
|
||||
"controls": [
|
||||
21761792,
|
||||
659542
|
||||
]
|
||||
},
|
||||
{
|
||||
"dead_edit": 594006,
|
||||
"winerror": 1400
|
||||
},
|
||||
{
|
||||
"edit_hwnd": 659542,
|
||||
"text": "NEW"
|
||||
},
|
||||
{
|
||||
"read_list": 21761792,
|
||||
"row_count": 2
|
||||
},
|
||||
{
|
||||
"controls": [
|
||||
21827328,
|
||||
725078
|
||||
]
|
||||
},
|
||||
{
|
||||
"dead_ui_list": 21761792,
|
||||
"hresult": -2147220991,
|
||||
"exception": "COMError(-2147220991, '\u4e8b\u4ef6\u65e0\u6cd5\u8c03\u7528\u4efb\u4f55\u8ba2\u6237', (None, None, None, 0, None))"
|
||||
},
|
||||
{
|
||||
"edit_hwnd": 725078,
|
||||
"text": "NEW"
|
||||
},
|
||||
{
|
||||
"read_list": 21827328,
|
||||
"row_count": 2
|
||||
},
|
||||
{
|
||||
"read_list": 21827328,
|
||||
"row_count": 2
|
||||
},
|
||||
{
|
||||
"submit": "mutation_possible"
|
||||
}
|
||||
],
|
||||
"report": {
|
||||
"native_command": {
|
||||
"id": 33977,
|
||||
"executable": "C:\\Users\\ABS_Windows\\AppData\\Local\\Programs\\Python\\Python312\\python.exe",
|
||||
"trigger": "resource_command"
|
||||
},
|
||||
"native_options": {
|
||||
"1704": {
|
||||
"text": "Option",
|
||||
"checked": true
|
||||
},
|
||||
"1105": {
|
||||
"text": "Option",
|
||||
"checked": true
|
||||
},
|
||||
"1697": {
|
||||
"text": "Option",
|
||||
"checked": true
|
||||
},
|
||||
"1700": {
|
||||
"text": "Option",
|
||||
"checked": true
|
||||
}
|
||||
},
|
||||
"databook": {
|
||||
"main_visible_before_browse": true,
|
||||
"browse_button": 3017658,
|
||||
"loads": [
|
||||
{
|
||||
"mode": "warm",
|
||||
"timeout_seconds": 20,
|
||||
"attempt_state_before_load": "prepared",
|
||||
"list_handle": 21827328,
|
||||
"filter_handle": 725078,
|
||||
"elapsed_seconds": 6.125
|
||||
}
|
||||
],
|
||||
"list_handle": 21827328,
|
||||
"list_visible": true,
|
||||
"main_visible_after_load": true
|
||||
},
|
||||
"library_row": [
|
||||
"DATA",
|
||||
"NEW",
|
||||
"LIB:EXACT",
|
||||
"",
|
||||
"Exact",
|
||||
"Target"
|
||||
],
|
||||
"slot_count": 1,
|
||||
"row_rectangle": [
|
||||
157,
|
||||
398,
|
||||
769,
|
||||
422
|
||||
],
|
||||
"list_handle": 21827328,
|
||||
"target_text": "NEW",
|
||||
"symbol_text": "LIB:EXACT",
|
||||
"target_submit_enabled": true,
|
||||
"transaction": {
|
||||
"snapshot_sha256": "d36e0c485331eac7b3c0d25de6dbfc5e915b761dd7eb738caf49b69d89640daa",
|
||||
"project_path": "g:\\dx33\\acceptance\\d6-native-controls-03\\positive\\synthetic.prj",
|
||||
"sheet_identity": "MAIN:1",
|
||||
"old_part_number": "OLD",
|
||||
"new_part_number": "NEW",
|
||||
"source_uids": [
|
||||
"uid"
|
||||
],
|
||||
"target_selectors": null,
|
||||
"library_row": [
|
||||
"DATA",
|
||||
"NEW",
|
||||
"LIB:EXACT",
|
||||
"",
|
||||
"Exact",
|
||||
"Target"
|
||||
],
|
||||
"target_symbol": "LIB:EXACT",
|
||||
"slot_count": 1
|
||||
},
|
||||
"stage": "native_replace_verified",
|
||||
"replaced_uids": [
|
||||
"uid"
|
||||
],
|
||||
"promoted_pins": []
|
||||
},
|
||||
"error": null
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
{
|
||||
"mode": "normal",
|
||||
"environment": "Windows, DxDesigner 7.9.5, source runtime",
|
||||
"library_mapping": "Skyworth_CBB_Lib",
|
||||
"library_lmc_unchanged": true,
|
||||
"project": "Audio_D2128.prj",
|
||||
"request_old_new_refdes": [
|
||||
"4100-CA0000-T7",
|
||||
"4100-CA0000-T0",
|
||||
"RV05"
|
||||
],
|
||||
"attempt": {
|
||||
"session_id": "588db35caf664589a499f02800559ff0",
|
||||
"generation": 1,
|
||||
"attempt_id": "65d0375a0a3e4e02a0e0225f5cd7da1d",
|
||||
"job_id": "3fd4cca09997419cbf0850fe2907f1b5_0",
|
||||
"state": "mutation_possible"
|
||||
},
|
||||
"native": [
|
||||
{
|
||||
"ok": true,
|
||||
"stage": "native_replace_applied",
|
||||
"databook": {
|
||||
"main_visible_before_browse": true,
|
||||
"browse_button": 1577092,
|
||||
"loads": [
|
||||
{
|
||||
"mode": "warm",
|
||||
"timeout_seconds": 20,
|
||||
"attempt_state_before_load": "prepared",
|
||||
"list_handle": 266464,
|
||||
"filter_handle": 266532,
|
||||
"elapsed_seconds": 2.703
|
||||
}
|
||||
],
|
||||
"list_handle": 266464,
|
||||
"list_visible": true,
|
||||
"main_visible_after_load": true
|
||||
},
|
||||
"library_row": [
|
||||
"RESISTOR",
|
||||
"4100-CA0000-T0",
|
||||
"skyworth:res01",
|
||||
"unassigned",
|
||||
"RESC1608N",
|
||||
"0R",
|
||||
""
|
||||
],
|
||||
"replaced_uids": [
|
||||
"$2I2014"
|
||||
],
|
||||
"pin_promotion_phase": "promotion_complete"
|
||||
}
|
||||
],
|
||||
"status_log": [
|
||||
"job_id\tstate\tcode\tmessage",
|
||||
"3fd4cca09997419cbf0850fe2907f1b5_0\tawaiting_native_replace\t\tSnapshot captured; automatic native replacement is starting.",
|
||||
"3fd4cca09997419cbf0850fe2907f1b5_0\tpending_save\tsession_staged\tWrites staged; awaiting engineering project save and saved native data verification.",
|
||||
"3fd4cca09997419cbf0850fe2907f1b5_0\tpending_save\tproject_saved\tEngineering project saved and closed; awaiting saved native data verification.",
|
||||
"3fd4cca09997419cbf0850fe2907f1b5_0\tsaved_ok\tproject_committed\t%5DE5%7A0B%7EDF%4E00%4FDD%5B58%FF0C%539F%751F%6570%636E%6838%9A8C%901A%8FC7%3002"
|
||||
],
|
||||
"operation_log_excerpt": [
|
||||
"2026/11/25 10:03:45\tINFO\tstage=open_project target=<copy-root>\\project\\Audio_D2128.prj",
|
||||
"2026/11/25 10:03:59\tINFO\tstage=open_sheet schematic=Audio-D2128 sheet=S905L CVBS-LR",
|
||||
"2026/11/25 10:04:49\tINFO\tnative_helper_exit code=0",
|
||||
"2026/11/25 10:05:16\tINFO\treplacement RV05 4100-CA0000-T7 -> 4100-CA0000-T0",
|
||||
"2026/11/25 10:05:17\tINFO\tsave_requested job=3fd4cca09997419cbf0850fe2907f1b5_0",
|
||||
"2026/11/25 10:05:17\tINFO\tsave_returned job=3fd4cca09997419cbf0850fe2907f1b5_0",
|
||||
"2026/11/25 10:05:22\tINFO\tproject_closed job=3fd4cca09997419cbf0850fe2907f1b5_0"
|
||||
],
|
||||
"independent_verification": [
|
||||
"verified"
|
||||
],
|
||||
"uncertain_flags_relative_to_data_root": [
|
||||
"batch-resources/588db35caf664589a499f02800559ff0/generation-1/uncertain.flag"
|
||||
],
|
||||
"queue_outcome": "CAD exit exceeded 15 seconds during batch resource cleanup after the saved business receipt"
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
[
|
||||
{
|
||||
"stage": "preflight",
|
||||
"databook": {
|
||||
"loads": [
|
||||
{
|
||||
"mode": "warm",
|
||||
"timeout_seconds": 20,
|
||||
"attempt_state_before_load": "prepared",
|
||||
"list_handle": 17,
|
||||
"filter_handle": 18,
|
||||
"error": "Native DxDataBook did not finish loading target part: NEW",
|
||||
"elapsed_seconds": 1.547,
|
||||
"dialogs": [
|
||||
{
|
||||
"hwnd": 19728876,
|
||||
"owner": 134972,
|
||||
"pid": 5004,
|
||||
"title": "",
|
||||
"children": [],
|
||||
"browser": false,
|
||||
"dismissible": true
|
||||
}
|
||||
],
|
||||
"attempt_state": "prepared",
|
||||
"retry": true,
|
||||
"closed_dialog": 19728876
|
||||
},
|
||||
{
|
||||
"mode": "warm",
|
||||
"timeout_seconds": 20,
|
||||
"attempt_state_before_load": "prepared",
|
||||
"list_handle": 17,
|
||||
"filter_handle": 18,
|
||||
"elapsed_seconds": 0.187
|
||||
}
|
||||
]
|
||||
},
|
||||
"window_closed": [
|
||||
19728876
|
||||
],
|
||||
"marker_state": "prepared"
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,74 @@
|
||||
{
|
||||
"state": "released",
|
||||
"generation": 1,
|
||||
"desktop": "dx-7f3f2f5227fc2de985373cc53acedcd9",
|
||||
"release_proof": {
|
||||
"session_id": "61c734f3d79d42579ca635bbdb996673",
|
||||
"generation": 1,
|
||||
"desktop": "dx-7f3f2f5227fc2de985373cc53acedcd9",
|
||||
"desktop_handle_closed": true,
|
||||
"desktop_released": true,
|
||||
"processes_exited": true,
|
||||
"processes": [
|
||||
{
|
||||
"pid": 11236,
|
||||
"creation_time": "2026-11-25 02:26:52.007000+00:00"
|
||||
}
|
||||
],
|
||||
"observed_at": 1795573613.951475,
|
||||
"method": "owned_cleanup"
|
||||
},
|
||||
"release_rechecks": [
|
||||
{
|
||||
"attempt": 1,
|
||||
"delay_seconds": 0.5
|
||||
},
|
||||
{
|
||||
"attempt": 2,
|
||||
"delay_seconds": 1
|
||||
}
|
||||
],
|
||||
"event_timeline": [
|
||||
{
|
||||
"phase": "releasing",
|
||||
"desktop_disappeared": null,
|
||||
"release_rechecks": []
|
||||
},
|
||||
{
|
||||
"phase": "blocked",
|
||||
"desktop_disappeared": null,
|
||||
"release_rechecks": []
|
||||
},
|
||||
{
|
||||
"phase": "releasing",
|
||||
"desktop_disappeared": null,
|
||||
"release_rechecks": [
|
||||
{
|
||||
"attempt": 1,
|
||||
"delay_seconds": 0.5
|
||||
},
|
||||
{
|
||||
"attempt": 2,
|
||||
"delay_seconds": 1
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"phase": "released",
|
||||
"desktop_disappeared": true,
|
||||
"release_rechecks": [
|
||||
{
|
||||
"attempt": 1,
|
||||
"delay_seconds": 0.5
|
||||
},
|
||||
{
|
||||
"attempt": 2,
|
||||
"delay_seconds": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"shutdown": {
|
||||
"forced_termination": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"state": "released",
|
||||
"generation": 1,
|
||||
"desktop": "dx-7f3f2f5227fc2de985373cc53acedcd9",
|
||||
"release_proof": {
|
||||
"generation": 1,
|
||||
"desktop_released": true,
|
||||
"processes_exited": true,
|
||||
"processes": [],
|
||||
"method": "restart_observation"
|
||||
},
|
||||
"release_rechecks": [],
|
||||
"event_timeline": [
|
||||
{
|
||||
"phase": "releasing",
|
||||
"desktop_disappeared": null,
|
||||
"release_rechecks": []
|
||||
},
|
||||
{
|
||||
"phase": "isolated",
|
||||
"desktop_disappeared": false,
|
||||
"release_rechecks": []
|
||||
},
|
||||
{
|
||||
"phase": "releasing",
|
||||
"desktop_disappeared": false,
|
||||
"release_rechecks": []
|
||||
},
|
||||
{
|
||||
"phase": "released",
|
||||
"desktop_disappeared": true,
|
||||
"release_rechecks": []
|
||||
}
|
||||
],
|
||||
"shutdown": null
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
{
|
||||
"original_state": "blocked",
|
||||
"confirmed_state": "released",
|
||||
"desktop": "dx-7f3f2f5227fc2de985373cc53acedcd9",
|
||||
"desktop_absent_under_slot_mutex": true,
|
||||
"owned_root_observations": [
|
||||
{
|
||||
"pid": 62180,
|
||||
"creation_time": "2026-11-25 02:02:37.882000+00:00",
|
||||
"gone": true
|
||||
},
|
||||
{
|
||||
"pid": 59508,
|
||||
"creation_time": "2026-11-25 02:02:38.250000+00:00",
|
||||
"gone": true
|
||||
},
|
||||
{
|
||||
"pid": 58980,
|
||||
"creation_time": "2026-11-25 02:03:40.779000+00:00",
|
||||
"gone": true
|
||||
},
|
||||
{
|
||||
"pid": 60628,
|
||||
"creation_time": "2026-11-25 02:03:43.660000+00:00",
|
||||
"gone": true
|
||||
},
|
||||
{
|
||||
"pid": 23736,
|
||||
"creation_time": "2026-11-25 02:05:22.446000+00:00",
|
||||
"gone": true
|
||||
},
|
||||
{
|
||||
"pid": 54872,
|
||||
"creation_time": "2026-11-25 02:05:44.928000+00:00",
|
||||
"gone": true
|
||||
}
|
||||
],
|
||||
"original_shutdown": {
|
||||
"orderly_shutdown": false,
|
||||
"forced_termination": true,
|
||||
"forced_root_termination": true,
|
||||
"forced_descendant_pids": [
|
||||
5216,
|
||||
51620
|
||||
],
|
||||
"quit_helper_exit_code": 0
|
||||
},
|
||||
"release_proof": {
|
||||
"generation": 1,
|
||||
"desktop_released": true,
|
||||
"processes_exited": true,
|
||||
"processes": [
|
||||
{
|
||||
"pid": 62180,
|
||||
"creation_time": "2026-11-25 02:02:37.882000+00:00"
|
||||
},
|
||||
{
|
||||
"pid": 59508,
|
||||
"creation_time": "2026-11-25 02:02:38.250000+00:00"
|
||||
},
|
||||
{
|
||||
"pid": 58980,
|
||||
"creation_time": "2026-11-25 02:03:40.779000+00:00"
|
||||
},
|
||||
{
|
||||
"pid": 60628,
|
||||
"creation_time": "2026-11-25 02:03:43.660000+00:00"
|
||||
},
|
||||
{
|
||||
"pid": 23736,
|
||||
"creation_time": "2026-11-25 02:05:22.446000+00:00"
|
||||
},
|
||||
{
|
||||
"pid": 54872,
|
||||
"creation_time": "2026-11-25 02:05:44.928000+00:00"
|
||||
}
|
||||
],
|
||||
"method": "restart_observation"
|
||||
},
|
||||
"preserved_sha256": {
|
||||
"batch-resources/588db35caf664589a499f02800559ff0/generation-1/uncertain.flag": "4a131c344827d0bbe9667dc5534af3d52e472737ec1d1c1c44a792c1ac66f360",
|
||||
"tasks/d5810026-3117-4b2e-9eca-c16b22396dc3/quick-run/status.tsv": "2afdeacd43812445f616f89da425efe6adf565ff75052e7f587e332b70066338",
|
||||
"tasks/d5810026-3117-4b2e-9eca-c16b22396dc3/execution-proof/saved-netlist-6f55dbc86cc94adeb3561dfedd30e44a/export/verification.json": "3579e55e5987f9aababe167801c127f4404511f96cc0334de663fc449990b955",
|
||||
"tasks/d5810026-3117-4b2e-9eca-c16b22396dc3/netlist-checks/2af39a6d4d6143afa3352b8cbe4e4180/verification.json": "f0ed2209fa9de4c97a01da3079da1097e8ab2dc091631c625440a299e23728e3",
|
||||
"tasks/d5810026-3117-4b2e-9eca-c16b22396dc3/quick-run/project-checkpoint.json": "04d6b04e85b23671b2ce92dd2adc64d673b8c3209813a148214a7322bf0e7e4a"
|
||||
},
|
||||
"project_descriptor_sha256_unchanged": true
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"state": "released",
|
||||
"desktop": "dx-7f3f2f5227fc2de985373cc53acedcd9",
|
||||
"shutdown": {
|
||||
"state": "session_closed",
|
||||
"clean": true,
|
||||
"cad_exit_code": 0,
|
||||
"quit_helper_exit_code": 0,
|
||||
"cleanup_errors": [],
|
||||
"shutdown_seconds": 4.375,
|
||||
"orderly_shutdown": true,
|
||||
"diagnostic_errors": [],
|
||||
"forced_termination": false,
|
||||
"forced_root_termination": false,
|
||||
"forced_descendant_pids": [],
|
||||
"termination_reason": null,
|
||||
"dialog_supervision": {
|
||||
"evidence_path": "G:\\dx33\\acceptance\\d7-mentor-idle\\batch-resources\\765ec10f41134b80b4d2d7a49ef01fe5\\generation-1\\cad-dialogs-408b2726a75547929b58a0f1fe3bcfbe.json",
|
||||
"dialogs_seen": 2,
|
||||
"blocked": false,
|
||||
"blocking_titles": [],
|
||||
"current_dialogs": [],
|
||||
"error": "",
|
||||
"monitor_error": ""
|
||||
},
|
||||
"release_state": "released",
|
||||
"project_close_policy": "saved_only"
|
||||
},
|
||||
"release_results": {
|
||||
"mentor_released": true,
|
||||
"desktop_released": true
|
||||
},
|
||||
"release_rechecks": [],
|
||||
"error": null,
|
||||
"pending": 0
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
{
|
||||
"projects": 100,
|
||||
"first_return": {
|
||||
"completed": 9,
|
||||
"blocked": 2,
|
||||
"pending": 89
|
||||
},
|
||||
"before_release": {
|
||||
"completed": 9,
|
||||
"blocked": 2,
|
||||
"pending": 89
|
||||
},
|
||||
"queue_id": "d935388f7bab4bf98c882280ec6c76a3",
|
||||
"writer_pid": 56064,
|
||||
"writer_gone": true,
|
||||
"calls": [
|
||||
{
|
||||
"project": 1,
|
||||
"job_id": "c959a1eba7fb46f9b22d95f9afdff465_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 2,
|
||||
"job_id": "ab1fb1a7058a4b41b5886c3c01008aa7_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 3,
|
||||
"job_id": "490c1abb2a9441d8b5a8d70cbe5c0aa8_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 4,
|
||||
"job_id": "56b8dfaacb514a94ab506c632b37b647_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 5,
|
||||
"job_id": "d0d223381b9e4a01ababa484fcc07e82_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 6,
|
||||
"job_id": "abe6fa9a9919494ba433983cd125d1ac_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 7,
|
||||
"job_id": "2f103677ed4347938888e03b9b26b87f_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 8,
|
||||
"job_id": "5d4eeaed50bd46e89fd6830b51e8c3fb_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 9,
|
||||
"job_id": "ff4f78bf6e834c758fcb0fe9382a28fe_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 10,
|
||||
"job_id": "31ad660420e74b8499bd54abfbe250f5_0",
|
||||
"result": "batch_saved_unverified"
|
||||
},
|
||||
{
|
||||
"project": 11,
|
||||
"job_id": "321e40d86fe147bb977ba9865c1d24b9_0",
|
||||
"result": "batch_saved_unverified"
|
||||
}
|
||||
],
|
||||
"supervisor_calls": [
|
||||
{
|
||||
"batch_id": "d31e906c280e4849a22a3176ced4bee0",
|
||||
"queue_id": null,
|
||||
"resource_batch_id": null
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,542 @@
|
||||
{
|
||||
"projects": 100,
|
||||
"first_return": {
|
||||
"completed": 97,
|
||||
"blocked": 3
|
||||
},
|
||||
"before_release": {
|
||||
"completed": 9,
|
||||
"blocked": 2,
|
||||
"pending": 89
|
||||
},
|
||||
"final": {
|
||||
"completed": 97,
|
||||
"blocked": 3
|
||||
},
|
||||
"supervisor_calls": [
|
||||
{
|
||||
"batch_id": "15fcc3425d5f4a9ea172b7725023dd91",
|
||||
"queue_id": null,
|
||||
"resource_batch_id": null
|
||||
},
|
||||
{
|
||||
"batch_id": "78718bb8a02147358b441c540c902899",
|
||||
"queue_id": "af07e3269bcd4a08afbf064af9126123",
|
||||
"resource_batch_id": "15fcc3425d5f4a9ea172b7725023dd91"
|
||||
},
|
||||
{
|
||||
"batch_id": "862fad3b3d754c4a944135ff8256b1d8",
|
||||
"queue_id": "af07e3269bcd4a08afbf064af9126123",
|
||||
"resource_batch_id": null
|
||||
},
|
||||
{
|
||||
"batch_id": "69c5a03140bc4c5ca7d9bb52f6ff528f",
|
||||
"queue_id": "af07e3269bcd4a08afbf064af9126123",
|
||||
"resource_batch_id": null
|
||||
}
|
||||
],
|
||||
"queue_id": "af07e3269bcd4a08afbf064af9126123",
|
||||
"shared_source_blocked": 12,
|
||||
"writer_pid": 25028,
|
||||
"release_checks": [
|
||||
10,
|
||||
11
|
||||
],
|
||||
"calls": [
|
||||
{
|
||||
"project": 1,
|
||||
"job_id": "388bad5bafc54ae3b766a574f07feb44_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 2,
|
||||
"job_id": "78c6aa3632484ef795705071c4f6871e_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 3,
|
||||
"job_id": "b1e96b8625df4e8cb50f44c2faed14be_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 4,
|
||||
"job_id": "1c1419a896374821ac7c51a3117b75e1_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 5,
|
||||
"job_id": "df4e71b52bf842f093029d4dad56f797_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 6,
|
||||
"job_id": "1fcb7b6d75f44cdcbaed93accaa1c07d_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 7,
|
||||
"job_id": "6eeb02803cde4b2483ee776c9afeba1c_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 8,
|
||||
"job_id": "84c54eeb256d404582eda32019de17d8_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 9,
|
||||
"job_id": "05cf0fb9ad8b4c7d90d039d466de25a7_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 10,
|
||||
"job_id": "7c2ea733df924c1a9e04750f22134738_0",
|
||||
"result": "batch_saved_unverified"
|
||||
},
|
||||
{
|
||||
"project": 11,
|
||||
"job_id": "807cafae32bc495a894f5b35a6d1cb5e_0",
|
||||
"result": "batch_saved_unverified"
|
||||
},
|
||||
{
|
||||
"project": 13,
|
||||
"job_id": "304752f4d4c64e1bbabcbf55bff365fb_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 14,
|
||||
"job_id": "2040d066abc4482da2323b1b313e6e0e_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 15,
|
||||
"job_id": "908898c13c47472bb6f115f4910cccf4_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 16,
|
||||
"job_id": "3abda0f30178471c9af61afd5738b530_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 17,
|
||||
"job_id": "6c7365afea284aa3854b66af096bd098_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 18,
|
||||
"job_id": "f210b5d510344eb08f8d93ce05d001fe_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 19,
|
||||
"job_id": "eaaa69c064f0433fbab3874e0b331090_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 20,
|
||||
"job_id": "edc20d8c922f4bbaad379a3ce0db6891_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 21,
|
||||
"job_id": "f5cdef2f94b54d7da8c9c9c730557b8e_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 22,
|
||||
"job_id": "1dfc6665bfcf455e9246e212f92c689c_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 23,
|
||||
"job_id": "75385b75cf9140629f9aa1022bb2c53c_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 24,
|
||||
"job_id": "809cef1ba35b44d9be4ffd1dbd1ab000_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 25,
|
||||
"job_id": "367c3ffd715c4ef586f2e8824bbef491_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 26,
|
||||
"job_id": "bf5f3bdd3fb14fcc9740436fa464be37_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 27,
|
||||
"job_id": "a60a8566d058464495773969e6a99017_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 28,
|
||||
"job_id": "0c4c8103d7104788a5da9f017c0f1ace_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 29,
|
||||
"job_id": "eaa9e2e922e44c39a012af2519d951cf_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 30,
|
||||
"job_id": "e84022b8f6f949ddaee69e8067b9a795_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 31,
|
||||
"job_id": "8ab8ba8bad0e4b859e4720d0af2d56d8_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 32,
|
||||
"job_id": "0e7d3863480e4382b6b07ededa94f012_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 33,
|
||||
"job_id": "fbe7d3bf153644859f9b6a785fc98d64_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 34,
|
||||
"job_id": "6e1e4e3e44ad4aeeb51896837e6b84fb_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 35,
|
||||
"job_id": "efe7a9fb23944560bdac2212b2154cbe_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 36,
|
||||
"job_id": "50ef7be31e7740bbbf337e570690de86_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 37,
|
||||
"job_id": "8696162e1e7b4169b562f5454f8ddfb0_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 38,
|
||||
"job_id": "657ca58af33a4b7db33b19007e1ce071_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 39,
|
||||
"job_id": "a18f78199fd74601a007e8eb9ee15433_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 40,
|
||||
"job_id": "badd43d9a5624a689cc693bb7ea31652_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 41,
|
||||
"job_id": "bab81db14eb54782b869252fac15e570_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 42,
|
||||
"job_id": "92617c885ead4d838432c68e2255f7d0_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 43,
|
||||
"job_id": "216b4cda3f4148e7bc9d75ee5be8b6cb_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 44,
|
||||
"job_id": "3d57183d53304ce69933c982311b0f35_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 45,
|
||||
"job_id": "528549b58fd64769bc5016d3a4357aab_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 46,
|
||||
"job_id": "f8d51cf682604a08bd046123ab6a509a_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 47,
|
||||
"job_id": "c73cc80bbc35445b8e4ffbb26a884bb0_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 48,
|
||||
"job_id": "40a362b535034d15b4c89c4bc9af0c91_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 49,
|
||||
"job_id": "4df4aafeb2c841b494b9949c8ca230d2_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 50,
|
||||
"job_id": "7064b1e06df642c9a6c2fca037287ec4_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 51,
|
||||
"job_id": "f6caf03914f74a26b769873941506bd1_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 52,
|
||||
"job_id": "a2dea8f52ac04ed6ac1a2a28d9f8ef63_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 53,
|
||||
"job_id": "42e312a4cf6d453a88ee9b2163b191b5_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 54,
|
||||
"job_id": "45dbef10be42411c9a2a0248946d9037_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 55,
|
||||
"job_id": "2d6bfff0905149659324f152a5a37053_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 56,
|
||||
"job_id": "687a85f8e4684ebb99ae3371f08da745_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 57,
|
||||
"job_id": "f03c1b7e292d458fa1cf34fa32fcc6dc_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 58,
|
||||
"job_id": "2ddfbc06b4864f6cb76f7253fa35fab5_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 59,
|
||||
"job_id": "14e6219fdebe4b54bbd95cd95d82fe27_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 60,
|
||||
"job_id": "328b84460d394545a8b3a1701bb4668e_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 61,
|
||||
"job_id": "932ee1968d8548cb9b20d2205cbda07f_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 62,
|
||||
"job_id": "d61878a4fb6b42f69bc29d5a9039151f_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 63,
|
||||
"job_id": "df606318c32a445f83fe0aaafa47dd8b_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 64,
|
||||
"job_id": "810306d724314216b533239129fa5f00_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 65,
|
||||
"job_id": "95d51023c87b4fa6be5ed8c36b884b02_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 66,
|
||||
"job_id": "490361523d184a738048546ad39c5051_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 67,
|
||||
"job_id": "d51096842332404b97c5bd9b320e2b72_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 68,
|
||||
"job_id": "07beb872e39e4ed99bd63520b0b6f9e9_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 69,
|
||||
"job_id": "7fd5188c1c1d4eb3874c45629db474b2_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 70,
|
||||
"job_id": "b1690759022045288b9e3cec1089284f_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 71,
|
||||
"job_id": "f7e247a2619642f2a1f881891e8eeb57_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 72,
|
||||
"job_id": "aea8b540c89842d6869bc34564aa8a8f_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 73,
|
||||
"job_id": "1deab0ea04ee4ee2be2bf8a5564fcf7c_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 74,
|
||||
"job_id": "8808d235aba149bd8651675f2b10ceed_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 75,
|
||||
"job_id": "30505f56d58848be97ce2af31bf8590d_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 76,
|
||||
"job_id": "1aceadb5a89d4d068f318f8eeed650e4_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 77,
|
||||
"job_id": "b75a90feeb3f4737a3bbc31c55aa418c_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 78,
|
||||
"job_id": "21fe6401ceb34a80865a0d548ef707e5_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 79,
|
||||
"job_id": "4ca98380c3494062bbca254f3efb91e6_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 80,
|
||||
"job_id": "2eee50b616934bf9849d116fe4e313f4_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 81,
|
||||
"job_id": "32cf6eb628bd4039a6d591682c96c661_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 82,
|
||||
"job_id": "966a29d95f7040ceb044d818e0abcde0_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 83,
|
||||
"job_id": "8aa901efbd6149bc9744714992fd6021_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 84,
|
||||
"job_id": "9e6b5ecf9b714354b191e92add01d6c3_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 85,
|
||||
"job_id": "08bd3aac43aa4b7ea9dd980540951c8f_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 86,
|
||||
"job_id": "b70f927d89354785939daa703ae65dc3_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 87,
|
||||
"job_id": "e1f98f7188b6446c8218d83a2041d906_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 88,
|
||||
"job_id": "9c75b996f185424d9507fd00f2262fae_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 89,
|
||||
"job_id": "2671fb1be481453cbd382973d8d3807c_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 90,
|
||||
"job_id": "20044c501cf84140bc54114f903d40fd_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 91,
|
||||
"job_id": "a5eda4530b8940178dabf9f8e85b1a2a_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 92,
|
||||
"job_id": "fafda99d5f8344f18c574d4440c57518_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 93,
|
||||
"job_id": "b3247626d9e441208779273cd3e607bc_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 94,
|
||||
"job_id": "4dc0c755982f4fc1bd63803b83466aab_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 95,
|
||||
"job_id": "b41bcead3e0c45fe855f2fa08dfc668b_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 96,
|
||||
"job_id": "397b58aa73b042719410592f9b6ed4a1_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 97,
|
||||
"job_id": "012bde1609484512b83f23809f333c9d_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 98,
|
||||
"job_id": "00a4507a1c1f45f797e3f9e466c633b1_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 99,
|
||||
"job_id": "300db9dee9b947be85a596b9f538128e_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 100,
|
||||
"job_id": "c748b639f5034e8baaa0b2a6bed638ae_0",
|
||||
"result": "saved_ok"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
{
|
||||
"projects": 8,
|
||||
"first_return": {
|
||||
"completed": 3,
|
||||
"pending": 5
|
||||
},
|
||||
"final": {
|
||||
"completed": 8
|
||||
},
|
||||
"queue_id": "6bbbdf75c72e4a21844c51d1938ee725",
|
||||
"calls": [
|
||||
{
|
||||
"project": 1,
|
||||
"job_id": "d4a210a4bea9478dbbe552f6fe87e125_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 2,
|
||||
"job_id": "b595108e12e24858ae8faa006b63c103_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 3,
|
||||
"job_id": "c74e034af94c4fdabaedee1b1d482771_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 4,
|
||||
"job_id": "1a7c1b81b15844f2bce705755164e2d9_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 5,
|
||||
"job_id": "267ea09123c44f20be66b0141f94177c_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 6,
|
||||
"job_id": "8d9f2932a57846da8d087d80ddaed2fb_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 7,
|
||||
"job_id": "a7e1d97f74d6495aa112831364ec47cc_0",
|
||||
"result": "saved_ok"
|
||||
},
|
||||
{
|
||||
"project": 8,
|
||||
"job_id": "6a77966ac69a47c1b8c984bcc655cd7e_0",
|
||||
"result": "saved_ok"
|
||||
}
|
||||
],
|
||||
"paused_in_pid": 54160,
|
||||
"resumed_in_pid": 60636
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
# 工程校验闭环标准 v1
|
||||
|
||||
本标准用于 N12 及后续功能。写完代码、测试通过、工程检查一致、业务闭环通过、允许发布,是不同结论。每次验收必须声明正在证明哪一个结论。
|
||||
|
||||
## 单次功能闭环的通过条件
|
||||
|
||||
| 编号 | 必须证明 | 不满足时 |
|
||||
| --- | --- | --- |
|
||||
| C01 输入冻结 | 开始前写下预期工程名单、数量、前后摘要、输入版本和检查策略;配对预览与实际导入相符 | 失败;不能从运行后的结果反推预期 |
|
||||
| C02 完整执行 | 用户显式开始;运行成员与冻结范围完全相同,每项都有属于本次运行的终态尝试 | 有排队、运行、停止、中断、漏项或重复项,均不能算完整闭环 |
|
||||
| C03 判断正确 | 每项结论符合事先指定的预期;执行成功与 CONSISTENT/WARNING/DIFFERENT 分开;必查未知不得通过 | 误报、漏报、未知充当一致都失败 |
|
||||
| C04 事实同源 | 页面、逐脚表、JSON和HTML报告绑定同一 item、输入版本、attempt、generation、输入摘要和证据摘要;原文摘要可复核 | 任何串版本、旧结果、缺证据或报告不符都失败 |
|
||||
| C05 只读安全 | 校验前后全部已冻结源文件摘要不变,新增换料操作数为0,执行资源退出有证明;已有换料历史以开始前基线计数核对 | 不变性或退出证明缺失,失败并保留现场 |
|
||||
| C06 重启回读 | 正常退出后重启,结果及证据仍可查看,尝试数不增加、不自动重跑 | 失败 |
|
||||
| C07 重校验 | 同一输入重新执行时 attempt 更新、generation 递增;旧结果保留,新旧报告均可追溯 | 失败 |
|
||||
| C08 异常隔离 | 反脚/断线等业务异常不挡后续工程;停止后未派发项仍待校验;资源/存储未知暂停正确范围;仍可新建独立任务 | 相应异常用例失败;不能以“正常样本跑过”替代 |
|
||||
|
||||
只有本次要求的检查全部通过,才写“该功能闭环通过”。验证程序对失败必须非零退出;结构性检查失败不能被 WARNING、正常进程退出或成功生成文件覆盖。某项故障测试验证了预期失败,不等于故障工程已经检查通过。
|
||||
|
||||
## 固定业务反例
|
||||
|
||||
物理脚1/2互换、断线、短接、位号或物理脚号变化必须为 DIFFERENT;loop→outloop 且连接不变必须为 WARNING;必查字段缺失必须为 INCOMPLETE。图中固定物理脚号位置,异常端点可与逐脚表和原文对应。自建格式夹具用于反例和可复现测试,必须明确标注,不能当成真实CAD导出证据。
|
||||
|
||||
## 两条业务路径分别验收
|
||||
|
||||
1. 独立输入:实际开发包中批量添加 → 开始全部 → 原生导出 → 查看图表 → 导出报告 → 正常关闭 → 重启查看 → 重校验 → 再导出。
|
||||
2. 成功结果交接:真正已落盘的成功换料回执 → 自动登记校验 → 同一套执行、复核与报告。重复接收不重复建项,未保存项不得作为成功项。
|
||||
|
||||
两条路径不能互相代替。受控服务测试可证明交接合同、幂等和非阻塞;没有取得实际成功回执触发的包内证据时,该路径记“实际闭环未测”。本任务不为补验收重新执行客户换料,也不修改其他任务的旧执行器。
|
||||
|
||||
## 留证与发布
|
||||
|
||||
验收记录至少包含:代码提交、EXE SHA256、证据类型、预期清单、输入和报告摘要、任务/运行/尝试身份、每项标准的 passed/failed/not_run、失败原因、截图和实际命令。前一次运行、仅有截图、历史分组测试覆盖均不能替代本次闭环。
|
||||
|
||||
发布还要求相关回归通过、连续默认全量无未解决失败、实际包身份与源码相符、声明的两条实际路径通过。现有时序波动仍是发布保留项,不在本功能中改断言掩盖。引脚级Value和确切库内脚到焊盘映射仍未覆盖;不能写成“封装全部正确”。
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
主工具顶部固定显示左右两个入口:左侧 **任务中心**,右侧 **DSH助手**,单击直接切换,无需展开菜单。助手也可按 `Ctrl+Shift+D` 打开;切回任务中心再进入助手时保留同一个网页、会话和未发送草稿。右侧“任务监管”读取主工具当前选中的任务。
|
||||
|
||||
这里直接运行 [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) 的官方前端与运行时,固定 npm 版本 `0.2.1-rc.5`,通过 Qt WebEngine 嵌入主窗口。官方三栏框架、原生 SVG、鲸鱼悬停动画、输入编辑器、模型选择、侧栏与停靠交互均由上游代码提供。项目增加任务监管插件和“DSH助手”名称,不再使用 Qt 控件重画聊天页面。上游许可见 `licenses/DeepSeek-Harness-MIT.txt`。
|
||||
这里直接运行 [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) 的官方前端与运行时,通过 Qt WebEngine 嵌入主窗口。当前 npm 版本以 `integration/dsh/package.json` 为准。官方三栏框架、原生 SVG、鲸鱼悬停动画、输入编辑器、模型选择、侧栏与停靠交互均由上游代码提供。项目增加任务监管插件和“DSH助手”名称,不再使用 Qt 控件重画聊天页面。上游许可见 `licenses/DeepSeek-Harness-MIT.txt`。
|
||||
|
||||
不显示上游账户登录、注册、充值和首次产品引导,也不注册其账户模型提供方。左下角 **工具设置** 单击打开原生设置页,包含“DSH工具”“通用设置”和“模型”;首页提示和任务监管面板围绕器件替换任务。输入框下方选择已配置的模型。
|
||||
|
||||
@@ -178,6 +178,14 @@ node tools/verify_dsh_runtime.mjs
|
||||
python tools/accept_dsh_desktop.py
|
||||
```
|
||||
|
||||
源码工作区可从 npm 更新 DSH。先退出任务中心,运行更新命令,再重新打开任务中心。
|
||||
|
||||
```powershell
|
||||
powershell -ExecutionPolicy Bypass -File tools/Install-DshRuntime.ps1 -Version latest
|
||||
```
|
||||
|
||||
将 `latest` 换成 `0.2.2-rc.5` 这样的完整版本号即可安装指定版本。脚本先在临时目录启动候选运行时并验证任务插件,通过后更新依赖声明、锁文件和实际依赖。更新成功时会打印 `build/dsh-update-…` 路径,其中 `previous` 保存旧运行时,`verification/report.json` 记录验收结果。便携版随应用打包 DSH,通过重新构建的应用发行包更新。
|
||||
|
||||
CLI 验证启动真实官方内核,检查工具与 preset 名单,实际读取快照、执行禁止工具探针,并测试本机请求认证、跨任务与过期动作边界。桌面验收启动真实主工具,用 Qt 鼠标事件单击左右导航,用 Chromium Input 事件操作官方页面,核对全新数据下无账户或引导弹窗、工具设置、任务刷新、会话、侧栏、SVG 动画、模型选择、草稿保留、取消确认和正常退出。验收只使用独立测试数据,不启动 CAD 或修改用户工程;未配置模型的验收不计为真实模型回复验证。
|
||||
|
||||
已配置本机模型时,可执行真实 API 桌面验收:
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
# 工程校验
|
||||
|
||||
在第四个“工程校验”页面随时新建任务。选择修改前、修改后两份已保存的 `.prj` 工程添加比较项,不能选择同一文件或共用数据库的两个工程。已有替换任务不影响新建;替换已保存的成功项会自动交接,缺少前后副本的项显示无法校验,不能用当前工程补造历史版本。
|
||||
|
||||
大量工程可点击“批量添加”,选择修改前、修改后两个根目录,再点“读取配对”。两个目录不能相同或互相包含。工具沿用工程目录扫描规则:发现含原理图工程的目录后,不再扫描其子目录;数据目录不参与扫描。
|
||||
|
||||
配对只认相对路径,例如前目录的 `Board-A/board.prj` 对应后目录的 `Board-A/board.prj`;不同子目录中同名工程不会混配。预览列出缺失或无法唯一配对的项,它们不能勾选。不符合这个目录结构的工程,仍可用“添加工程对”逐对指定。
|
||||
|
||||
批量导入后,任务内保留这个相对路径作为工程名称,列表、历史和报告中都能区分不同目录里的同名工程。
|
||||
|
||||
批量名称沿用任务库的 256 字符上限;相对路径超过上限时该项显示导入失败,可缩短目录层级或使用“添加工程对”单独添加。不会把任务库拒收误报成导入成功。
|
||||
|
||||
勾选后点“导入所选”,只建立前后只读副本,随后回到任务点击“开始全部”或“校验所选”。单项导入失败后继续其他项,失败原因保留在状态提示中;取消或关闭导入窗口时保留已导入项,未处理项可继续选择导入。磁盘空间或存储故障会中断整批并保留已导入项。此窗口不阻止新建其他校验任务。
|
||||
|
||||
“开始全部”处理当前任务中当时待校验/中断的工程;筛选不会缩小这个范围。“校验所选”和“重校验”明确处理所选工程当前版本。运行期间后到的新项或新版本留待下次开始。校验只读副本,不会重新换料或自动换脚。
|
||||
|
||||
工程表每页最多显示 100 项,点击“下一页”继续查看;自动刷新保留当前页,修改搜索或筛选后回到第一页。分页和筛选都不影响“开始全部”的范围。
|
||||
|
||||
一致表示已覆盖的必查项未发现差异;需关注表示有文字或属性变化需要人工判断;异常表示已证明位号、物理脚号、连接或声明目标等不符合;无法校验表示证据不足。没有固定换料清单时始终显示“未核对换料规则”。执行结束不等于工程一致。
|
||||
|
||||
选择工程,在右侧选择位号查看固定脚号的前后接线图和逐脚事实。红线对应连接变化;纯名称变化以关注提示。图由网表生成,不是原理图截图。原始证据入口会核对摘要;历史版本仅供查看,不改变当前结论。导出报告包含同一份图表、检查范围、输入和尝试摘要,不复制整个工程。
|
||||
|
||||
停止采用安全收尾。未派发项保留待校验,已开始项保留停止记录。重启不会自动重跑;缺少进程退出证明的项保留现场并暂停新的原生导出,不按 PID 猜测或终止其他进程。
|
||||
|
||||
首版未证明引脚级 Value 读取和确切库内部引脚→焊盘映射,页面明确未覆盖。电气类型按原生码展示,不臆造语义。本网表比较不宣称完成 ERC、PCB 或封装库内部正确性验证。普通操作历史清空和运行日志保留不会删除校验快照与证据。
|
||||
Generated
+4138
-3271
File diff suppressed because it is too large.
Load diff
@@ -2,7 +2,15 @@
|
||||
"name": "dxdesigner-dsh-runtime",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {"doctor": "node start.mjs --doctor", "start": "node start.mjs"},
|
||||
"engines": {"node": ">=24.9.0"},
|
||||
"dependencies": {"@deepseek-ai/dsh": "0.2.1-rc.5", "fflate": "0.8.3"}
|
||||
"scripts": {
|
||||
"doctor": "node start.mjs --doctor",
|
||||
"start": "node start.mjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=24.9.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@deepseek-ai/dsh": "0.2.2-rc.5",
|
||||
"fflate": "0.8.3"
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@ export const FILE_TOOLS=['read','read_image','write','edit','glob','grep','worki
|
||||
|
||||
const root = path.dirname(fileURLToPath(import.meta.url));
|
||||
const require = createRequire(import.meta.url);
|
||||
export const VERSION = '0.2.1-rc.5';
|
||||
export const VERSION = require('./package.json').dependencies['@deepseek-ai/dsh'];
|
||||
export const DISABLED = [
|
||||
'desktop-product-telemetry','product-analytics','session-telemetry-otel',
|
||||
];
|
||||
|
||||
@@ -6,6 +6,7 @@ Const VDM_COMPPIN = 4096
|
||||
Const VD_ALL = 0
|
||||
Const QP_COMPONENT_COORDINATE_TOLERANCE = 10
|
||||
Const QP_ATTRIBUTE_COORDINATE_TOLERANCE = 10
|
||||
Const QP_DATABOOK_TIMEOUT_EXIT = 4
|
||||
|
||||
Dim QP_Fso
|
||||
Dim QP_Root
|
||||
@@ -1123,7 +1124,8 @@ Sub QPDiscardFailedBatchProject(ByRef ErrorDescription)
|
||||
If (Not QP_BatchMode And Not QP_SessionMode) Or Not QP_OwnedProject Or QP_App Is Nothing Then Exit Sub
|
||||
HasStagedItems = False
|
||||
If IsObject(QP_SessionItems) Then HasStagedItems = (QP_SessionItems.Count > 0)
|
||||
If QP_NativeMutationPossible Or QP_BatchSaveRequested Or QP_BatchSaveCommitted Or HasStagedItems Then
|
||||
If QP_NativeMutationPossible Or QP_NativeCallActive Or QP_RestoreTransactionOpen Or _
|
||||
QP_BatchSaveRequested Or QP_BatchSaveCommitted Or HasStagedItems Then
|
||||
ErrorDescription = "write or save outcome requires reconciliation; owned project retained without automatic save or discard"
|
||||
Exit Sub
|
||||
End If
|
||||
@@ -1645,7 +1647,7 @@ Sub QPAutomaticReplaceAndRestore(ByRef Command, ByVal SnapshotPath)
|
||||
End Sub
|
||||
|
||||
Sub QPNativeReplace(ByRef Command, ByVal SnapshotPath)
|
||||
Dim Shell, ExitCode, CommandLine, ErrorPath, ErrorDetail
|
||||
Dim Shell, ExitCode, CommandLine, ErrorPath, ErrorDetail, ErrorSource
|
||||
QPProgress "before_native", 0, 1
|
||||
QPInvalidatePinIndex
|
||||
If Len(QP_HelperExecutable) = 0 Or Not QP_Fso.FileExists(QP_HelperExecutable) Then _
|
||||
@@ -1658,6 +1660,7 @@ Sub QPNativeReplace(ByRef Command, ByVal SnapshotPath)
|
||||
End If
|
||||
CommandLine = CommandLine & " --native-helper --snapshot " & Chr(34) & SnapshotPath & Chr(34)
|
||||
Set Shell = CreateObject("WScript.Shell")
|
||||
QP_Stage = "native_replace"
|
||||
QP_NativeCallActive = True
|
||||
QPProgress "native_replace", 0, 1
|
||||
ExitCode = Shell.Run(CommandLine, 0, True)
|
||||
@@ -1667,15 +1670,18 @@ Sub QPNativeReplace(ByRef Command, ByVal SnapshotPath)
|
||||
QPInvalidatePinIndex
|
||||
QPProgress "native_replace", 1, 1
|
||||
If ExitCode <> 0 Then
|
||||
ErrorSource = "QuickPartReplace"
|
||||
If ExitCode = QP_DATABOOK_TIMEOUT_EXIT And Not QP_NativeMutationPossible Then _
|
||||
ErrorSource = "QuickPartReplace.DxDataBookLookup"
|
||||
ErrorPath = SnapshotPath & ".native.error.txt"
|
||||
ErrorDetail = ""
|
||||
If QP_Fso.FileExists(ErrorPath) Then ErrorDetail = Trim(QPReadUtf8(ErrorPath))
|
||||
If Len(ErrorDetail) > 0 Then
|
||||
Err.Raise vbObjectError + 839, "QuickPartReplace", _
|
||||
Err.Raise vbObjectError + 839, ErrorSource, _
|
||||
"automatic native replacement failed: " & ErrorDetail & _
|
||||
"; report: " & SnapshotPath & ".native.json"
|
||||
Else
|
||||
Err.Raise vbObjectError + 839, "QuickPartReplace", _
|
||||
Err.Raise vbObjectError + 839, ErrorSource, _
|
||||
"automatic native replacement failed (exit=" & CStr(ExitCode) & "); see " & SnapshotPath & ".native.json"
|
||||
End If
|
||||
End If
|
||||
@@ -3993,9 +3999,12 @@ Sub QPWriteStatus(ByVal Root, ByVal JobId, ByVal State, ByVal Code, ByVal Messag
|
||||
End Sub
|
||||
|
||||
Sub QPFail(ByVal Root, ByVal State, ByVal Number, ByVal Source, ByVal Description)
|
||||
Dim Code
|
||||
On Error Resume Next
|
||||
If Len(CStr(QP_CurrentJobId)) > 0 Then
|
||||
QPWriteStatus Root, QP_CurrentJobId, State, CStr(Number), _
|
||||
Code = CStr(Number)
|
||||
If Source = "QuickPartReplace.DxDataBookLookup" Then Code = "lookup_unavailable"
|
||||
QPWriteStatus Root, QP_CurrentJobId, State, Code, _
|
||||
CStr(Source) & ": " & CStr(Description)
|
||||
End If
|
||||
QPLog Root, "ERROR", "stage=" & CStr(QP_Stage) & " number=" & Number & " source=" & Source & _
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
DeepSeek Harness native frontend and runtime
|
||||
Pinned release: @deepseek-ai/dsh 0.2.1-rc.5
|
||||
Package: @deepseek-ai/dsh
|
||||
Source: https://github.com/deepseek-ai/deepseek-harness
|
||||
|
||||
MIT License
|
||||
|
||||
@@ -1,14 +1,23 @@
|
||||
"""Execute a natively confirmed frozen scope and persist its actual receipt."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import asdict
|
||||
from datetime import datetime, timezone
|
||||
from hashlib import sha256
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
from time import monotonic
|
||||
|
||||
from . import task_lifecycle as tasks
|
||||
from .run_journal import RunJournal
|
||||
from .run_journal import RunJournal, _check_scope, _json
|
||||
from .scheduling import ScheduleStore
|
||||
from .cad_verification import CadVerificationAdapter
|
||||
from ..trial_task_center import batch_resources
|
||||
from ..trial_task_center.batch_admission import validate_batch_admission
|
||||
from ..trial_task_center.batch_summary import _checkpoint_source, collect_batch_summary, refresh_batch_resources
|
||||
from ..trial_task_center.errors import TaskCenterError
|
||||
from ..trial_task_center.path_access import canonical_path, internal_path
|
||||
from ..trial_task_center.task_queue import execute_task_queue
|
||||
|
||||
|
||||
@@ -37,7 +46,68 @@ def _failure_evidence(service, journal, run_id, baseline):
|
||||
return evidence
|
||||
|
||||
|
||||
def execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, resume=None, schedule=None, automatic=False):
|
||||
def execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, resume=None, schedule=None,
|
||||
automatic=False, admission=None):
|
||||
root = Path(root)
|
||||
if resume or admission is not None:
|
||||
ids, hashes = _check_scope(run_id, task_ids, report['plan_hashes'])
|
||||
directory = internal_path(root / 'batch-runs' / run_id)
|
||||
manifest_path = directory / 'manifest.json'
|
||||
if admission is not None and not resume:
|
||||
if (list(admission['runnable_task_ids']) != ids or admission['plan_hashes'] != hashes
|
||||
or admission['execution_report'] != report):
|
||||
raise TaskCenterError('run_scope', '已确认的批次范围与执行报告不一致。')
|
||||
manifest = _json({**admission, 'schema_version': 1, 'run_id': run_id,
|
||||
'confirmed_utc': datetime.now(timezone.utc).isoformat()})
|
||||
try:
|
||||
directory.mkdir(parents=True, exist_ok=False)
|
||||
except FileExistsError as error:
|
||||
raise TaskCenterError('run_conflict', '批次已有冻结清单,请读取原执行记录。') from error
|
||||
batch_resources.write_record(manifest_path, manifest)
|
||||
elif manifest_path.is_file():
|
||||
manifest = json.loads(manifest_path.read_bytes())
|
||||
if manifest['run_id'] != run_id or manifest['runnable_task_ids'] != ids or manifest['plan_hashes'] != hashes:
|
||||
raise TaskCenterError('run_scope', '冻结批次的身份或执行计划已变化。')
|
||||
else:
|
||||
if resume and RunJournal(root).batch_retry_revalidator(service, run_id) is not None:
|
||||
raise TaskCenterError('batch_manifest', '原批次的冻结清单缺失,不能按旧版队列继续。')
|
||||
manifest = None
|
||||
else:
|
||||
manifest = None
|
||||
if manifest is None:
|
||||
return _execute_with_schedule(service, root, task_ids, report, stop, run_id,
|
||||
resume=resume, schedule=schedule, automatic=automatic)
|
||||
start = monotonic()
|
||||
original_supervisor = getattr(service, '_last_supervisor_batch_id', None)
|
||||
journal = RunJournal(root)
|
||||
previous_run = journal.get(run_id) if resume else None
|
||||
try:
|
||||
receipt = _execute_with_schedule(service, root, task_ids, report, stop, run_id,
|
||||
resume=resume, schedule=schedule, automatic=automatic, admission=admission,
|
||||
manifest_digest=manifest['manifest_digest'])
|
||||
except Exception as error:
|
||||
current = journal.get(run_id)
|
||||
if resume and current == previous_run:
|
||||
raise
|
||||
receipt = (current or {}).get('result') or {}
|
||||
if not receipt:
|
||||
code = getattr(error, 'code', 'execution_interrupted')
|
||||
receipt = {'status': 'interrupted' if current else
|
||||
'cancelled' if code == 'operation_cancelled' else 'rejected',
|
||||
'paused': bool(current), 'code': code}
|
||||
completed = getattr(error, 'completed_result', None)
|
||||
if current and completed is not None and hasattr(completed, 'netlist_verification'):
|
||||
entries = [asdict(entry) for entry in completed.entries]
|
||||
receipt = {**receipt, 'entries': entries, 'paused': completed.paused,
|
||||
'queue_id': completed.queue_id, 'execution_status': _business_status(entries, completed.paused),
|
||||
'netlist_verification': completed.netlist_verification}
|
||||
_finish_batch_summary(service, root, journal, manifest, receipt, start, original_supervisor)
|
||||
raise
|
||||
return _finish_batch_summary(service, root, journal, manifest, receipt, start, original_supervisor)
|
||||
|
||||
|
||||
def _execute_with_schedule(service, root, task_ids, report, stop, run_id, *, resume=None, schedule=None,
|
||||
automatic=False, admission=None, manifest_digest=None):
|
||||
prior = RunJournal(root).get(run_id) if resume else None
|
||||
schedule_id = schedule['schedule_id'] if schedule else (prior or {}).get('schedule_id')
|
||||
if schedule_id:
|
||||
@@ -47,7 +117,8 @@ def execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, resu
|
||||
if resume:
|
||||
_bound_schedule(schedules, prior)
|
||||
receipt = _execute_confirmed_run(service, root, task_ids, report, stop, run_id,
|
||||
resume=resume, schedule=schedule, automatic=automatic)
|
||||
resume=resume, schedule=schedule, automatic=automatic, admission=admission,
|
||||
manifest_digest=manifest_digest)
|
||||
if resume:
|
||||
schedules.finish(schedule_id, 'interrupted' if receipt['status'] in {'paused', 'blocked'} else receipt['status'],
|
||||
repair_run_id=run_id, run_id=run_id, receipt=receipt)
|
||||
@@ -59,10 +130,12 @@ def execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, resu
|
||||
raise TaskCenterError('schedule_run_conflict', '运行已不再绑定当前排期执行租约。')
|
||||
_finish_failed_schedule(schedules, RunJournal(root), original)
|
||||
raise
|
||||
return _execute_confirmed_run(service, root, task_ids, report, stop, run_id, resume=resume)
|
||||
return _execute_confirmed_run(service, root, task_ids, report, stop, run_id, resume=resume,
|
||||
admission=admission, manifest_digest=manifest_digest)
|
||||
|
||||
|
||||
def _execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, resume=None, schedule=None, automatic=False):
|
||||
def _execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, resume=None, schedule=None,
|
||||
automatic=False, admission=None, manifest_digest=None):
|
||||
if tasks.fingerprint(service, task_ids) != report['fingerprint']:
|
||||
raise TaskCenterError('assistant_stale', '任务状态已变化,请重新预检后确认。')
|
||||
journal = RunJournal(root)
|
||||
@@ -70,6 +143,29 @@ def _execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, res
|
||||
initialized = False
|
||||
claimed = False
|
||||
baseline = {}
|
||||
def begin_batch():
|
||||
nonlocal initialized
|
||||
current = validate_batch_admission(service, admission)
|
||||
if current['plan_hashes'] != report['plan_hashes'] or current['fingerprint'] != report['fingerprint']:
|
||||
raise TaskCenterError('assistant_stale', '任务状态已变化,请重新预检后确认。')
|
||||
journal.begin(run_id, task_ids, current['plan_hashes'], schedule_id=schedule['schedule_id'] if schedule else None)
|
||||
initialized = True
|
||||
|
||||
def resume_batch():
|
||||
nonlocal initialized
|
||||
check_batch_sources()
|
||||
current = journal.inspect(service, resume['run_id'])
|
||||
if not current['resume_ready'] or current['plan_hashes'] != report['plan_hashes']:
|
||||
raise TaskCenterError('run_blocked', '原执行范围或证据已变化,请先核验。')
|
||||
journal.resume(run_id)
|
||||
initialized = True
|
||||
journal.repair_retry_checkpoint(service, run_id)
|
||||
|
||||
def check_batch_sources():
|
||||
from ..trial_task_center.batch_admission import validate_batch_resume
|
||||
manifest_path = internal_path(root / 'batch-runs' / run_id / 'manifest.json')
|
||||
validate_batch_resume(service, json.loads(manifest_path.read_bytes()))
|
||||
|
||||
try:
|
||||
if schedule:
|
||||
current = next((r for r in schedules.evaluate(service) if r['schedule_id'] == schedule['schedule_id']), None)
|
||||
@@ -81,16 +177,22 @@ def _execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, res
|
||||
if not inspected['resume_ready'] or inspected['plan_hashes'] != report['plan_hashes']:
|
||||
raise TaskCenterError('run_blocked', '原执行范围或证据已变化,请先核验。')
|
||||
baseline = inspected.get('result') or {}
|
||||
journal.resume(run_id)
|
||||
initialized = True
|
||||
journal.repair_retry_checkpoint(service, run_id)
|
||||
else:
|
||||
if not manifest_digest:
|
||||
journal.resume(run_id)
|
||||
initialized = True
|
||||
journal.repair_retry_checkpoint(service, run_id)
|
||||
elif not manifest_digest:
|
||||
journal.begin(run_id, task_ids, report['plan_hashes'], schedule_id=schedule['schedule_id'] if schedule else None)
|
||||
initialized = True
|
||||
initialized = True
|
||||
resource_batch_id = inspected.get('resource_batch_id') if resume else None
|
||||
result = execute_task_queue(service, tuple(task_ids), stop_event=stop,
|
||||
expected_plan_hashes=report['plan_hashes'],
|
||||
queue_id=run_id if resume and resume['queue_available'] else None,
|
||||
checkpoint_id=None if resume and resume['queue_available'] else run_id)
|
||||
checkpoint_id=None if resume and resume['queue_available'] else run_id,
|
||||
**({'revalidate': resume_batch if resume else begin_batch} if manifest_digest else {}),
|
||||
**({'continuation_revalidate': check_batch_sources} if manifest_digest else {}),
|
||||
**({'manifest_digest': manifest_digest} if manifest_digest else {}),
|
||||
**({'resource_batch_id': resource_batch_id} if resource_batch_id else {}))
|
||||
except Exception as error:
|
||||
failure = {**(_failure_evidence(service, journal, run_id, baseline) if initialized else {}),
|
||||
'status': 'interrupted', 'run_id': run_id, 'queue_id': run_id,
|
||||
@@ -101,23 +203,32 @@ def _execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, res
|
||||
schedules.finish(schedule['schedule_id'], 'interrupted', run_id=run_id, receipt=failure)
|
||||
raise
|
||||
return _finish_execution_run(service, root, task_ids, stop, run_id, result,
|
||||
baseline=baseline, schedule=schedule if claimed else None)
|
||||
baseline=baseline, schedule=schedule if claimed else None, resource_report_pending=bool(manifest_digest))
|
||||
|
||||
|
||||
def _finish_execution_run(service, root, task_ids, stop, run_id, result, *, baseline, schedule=None):
|
||||
def _finish_execution_run(service, root, task_ids, stop, run_id, result, *, baseline, schedule=None,
|
||||
resource_report_pending=False):
|
||||
journal = RunJournal(root)
|
||||
schedules = ScheduleStore(root) if schedule is not None else None
|
||||
entries = [{'task_id': e.task_id, 'state': e.state, 'message': e.message} for e in result.entries]
|
||||
status = ('blocked' if any(e['state'] == 'blocked' for e in entries)
|
||||
else 'paused' if result.paused else 'failed' if any(e['state'] == 'failed' for e in entries) else 'completed')
|
||||
status = _business_status(entries, result.paused)
|
||||
from ..trial_task_center.netlist_verification import verification_summary
|
||||
acceptance = verification_summary(result.netlist_verification)
|
||||
overall = 'failed' if status == 'completed' and acceptance['status'] in {'different', 'unavailable'} else status
|
||||
if overall == 'completed' and resource_report_pending:
|
||||
overall = 'paused'
|
||||
receipt = {'status': overall, 'execution_status': status, 'acceptance': acceptance,
|
||||
'run_id': run_id, 'queue_id': result.queue_id, 'paused': result.paused,
|
||||
'user_pause_requested': bool(stop.is_set()), 'awaiting_user_resume': bool(result.paused and stop.is_set()),
|
||||
'entries': entries, 'tasks': [], 'reporting_errors': [],
|
||||
'message': '请按每项实际计数判断;未命中不表示已替换保存。'}
|
||||
batch_id = getattr(service, '_last_supervisor_batch_id', None)
|
||||
if result.paused and not stop.is_set() and batch_id:
|
||||
from ..trial_task_center.task_queue import resource_pause_admitted
|
||||
run = journal.get(run_id)
|
||||
if (run and resource_pause_admitted(root, batch_id, tuple(task_ids), run['plan_hashes'],
|
||||
result, require_released=False)):
|
||||
receipt['resource_batch_id'] = batch_id
|
||||
if result.netlist_verification:
|
||||
receipt['netlist_verification'] = result.netlist_verification
|
||||
# Persist the executor's known outcome before optional readback/enrichment.
|
||||
@@ -152,9 +263,237 @@ def _finish_execution_run(service, root, task_ids, stop, run_id, result, *, base
|
||||
receipt['reporting_errors'].append({'code': getattr(error, 'code', 'schedule_receipt_unavailable')})
|
||||
_persist_execution_receipt(service, journal, run_id, receipt, baseline)
|
||||
raise
|
||||
# Optional downstream delivery follows the durable replacement receipt.
|
||||
# Delivery failure must never turn a saved replacement into a repeat request.
|
||||
try:
|
||||
verification = getattr(service, 'verification', None)
|
||||
if verification is not None:
|
||||
from ..trial_task_center.verification.contracts import digest
|
||||
delivery = verification.receive_successful_results(
|
||||
receipt, submission_id=f'run:{run_id}:{digest(receipt)}')
|
||||
if delivery['rejected']:
|
||||
receipt['reporting_errors'].append({'code': 'verification_delivery_pending',
|
||||
'rejected': delivery['rejected']})
|
||||
except Exception as error:
|
||||
receipt['reporting_errors'].append({'code': 'verification_delivery_pending',
|
||||
'error': type(error).__name__})
|
||||
return receipt
|
||||
|
||||
|
||||
def _business_status(entries, paused):
|
||||
if any(entry['state'] == 'blocked' for entry in entries):
|
||||
return 'blocked'
|
||||
if paused:
|
||||
return 'paused'
|
||||
return 'failed' if any(entry['state'] == 'failed' for entry in entries) else 'completed'
|
||||
|
||||
|
||||
def _bound_supervisors(root, manifest):
|
||||
from ..trial_task_center.supervisor_protocol import VERSION, decode, valid_journal
|
||||
|
||||
records = []
|
||||
for path in internal_path(root / 'batch-resources').glob('*/request.json'):
|
||||
try:
|
||||
raw = path.read_bytes()
|
||||
request = json.loads(raw)
|
||||
journal = json.loads(path.with_name('supervisor.json').read_bytes())
|
||||
batch_id = path.parent.name
|
||||
if (not valid_journal(journal, batch_id) or sha256(raw).hexdigest() != journal['request_sha256']
|
||||
or request['version'] != VERSION or canonical_path(request['root']) != canonical_path(root)
|
||||
or request['batch_id'] != batch_id or request['attempt_id'] != journal['attempt_id']
|
||||
or request['operation'] != journal['operation'] or journal['operation'] != 'execute_task_queue'
|
||||
or request['task_ids'] != journal['task_ids']
|
||||
or journal['task_ids'] != manifest['runnable_task_ids']):
|
||||
continue
|
||||
arguments = decode(request['arguments'])
|
||||
if ((arguments.get('queue_id') or arguments.get('checkpoint_id')) == manifest['run_id']
|
||||
and list(arguments.get('task_ids', ())) == manifest['runnable_task_ids']
|
||||
and arguments.get('expected_plan_hashes') == manifest['plan_hashes']
|
||||
and arguments.get('manifest_digest') == manifest['manifest_digest']):
|
||||
records.append((journal.get('started_at') or 0, batch_id))
|
||||
except (OSError, ValueError, TypeError, KeyError):
|
||||
continue
|
||||
return [batch_id for _, batch_id in sorted(records)]
|
||||
|
||||
|
||||
def _recover_supervised_business(root, manifest, batch_ids):
|
||||
from ..trial_task_center.supervisor_protocol import MessageGate, VERSION
|
||||
from ..trial_task_center.supervisor_result import validated_outcome
|
||||
|
||||
if not batch_ids:
|
||||
return {}
|
||||
checkpoint, _, _, _ = _checkpoint_source(root, manifest)
|
||||
if checkpoint.get('manifest_digest') != manifest['manifest_digest']:
|
||||
return {}
|
||||
batch_id = batch_ids[-1]
|
||||
directory = internal_path(root / 'batch-resources' / batch_id)
|
||||
try:
|
||||
supervisor = json.loads((directory / 'supervisor.json').read_bytes())
|
||||
attempt_id = supervisor['attempt_id']
|
||||
try:
|
||||
envelope = json.loads((directory / 'result.json').read_bytes())
|
||||
except FileNotFoundError:
|
||||
business = json.loads((directory / 'business-result.json').read_bytes())
|
||||
if business.get('version') != VERSION or business['payload']['business_succeeded'] is not True:
|
||||
return {}
|
||||
envelope = {**business, 'type': 'result', 'sequence': 1}
|
||||
if not MessageGate(batch_id, attempt_id).accept(envelope) or envelope['type'] != 'result':
|
||||
return {}
|
||||
result, _, _ = validated_outcome('execute_task_queue', envelope['payload'])
|
||||
if result is None or result.queue_id != manifest['run_id']:
|
||||
return {}
|
||||
entries = [asdict(entry) for entry in result.entries]
|
||||
if ([entry['task_id'] for entry in entries] != manifest['runnable_task_ids']
|
||||
or any(checkpoint['entries'][entry['task_id']].get('state') != entry['state'] for entry in entries)
|
||||
or (not result.paused and any(entry['state'] in {'pending', 'paused', 'running'} for entry in entries))):
|
||||
return {}
|
||||
netlist = result.netlist_verification or {}
|
||||
if checkpoint.get('netlist_verification', netlist) != netlist:
|
||||
return {}
|
||||
status = _business_status(entries, result.paused)
|
||||
user_paused = supervisor.get('stopping_reason') == 'user_pause'
|
||||
return {'run_id': manifest['run_id'], 'queue_id': result.queue_id, 'entries': entries,
|
||||
'execution_status': status, 'status': status, 'paused': result.paused,
|
||||
'netlist_verification': netlist, 'user_pause_requested': user_paused,
|
||||
'awaiting_user_resume': result.paused and user_paused}
|
||||
except (OSError, ValueError, TypeError, KeyError, AttributeError):
|
||||
return {}
|
||||
|
||||
|
||||
def _finish_batch_summary(service, root, journal, manifest, receipt, start, original_supervisor=None,
|
||||
*, incident_batch_ids=()):
|
||||
run_id = manifest['run_id']
|
||||
elapsed = round(monotonic() - start, 3)
|
||||
log = service._logging.logger
|
||||
receipt = {**receipt, 'elapsed_seconds': elapsed}
|
||||
has_run = False
|
||||
try:
|
||||
has_run = journal.get(run_id) is not None
|
||||
batch_ids = list(dict.fromkeys([*_bound_supervisors(root, manifest), *incident_batch_ids]))
|
||||
current = getattr(service, '_last_supervisor_batch_id', None)
|
||||
if isinstance(current, str) and current != original_supervisor and re.fullmatch('[0-9a-f]{32}', current):
|
||||
has_request = internal_path(root / 'batch-resources' / current / 'request.json').is_file()
|
||||
if not has_request and current not in batch_ids:
|
||||
batch_ids.append(current)
|
||||
summary = collect_batch_summary(service, root, manifest, receipt,
|
||||
batch_ids=batch_ids, elapsed_seconds=elapsed, no_dispatch=not has_run)
|
||||
if not has_run:
|
||||
summary.update(queue_id=None, dispatch_count=0)
|
||||
summary = _publish_batch_summary(root, journal, summary, receipt, has_run=has_run)
|
||||
except Exception as error:
|
||||
receipt.setdefault('reporting_errors', []).append(
|
||||
{'code': 'batch_summary_unavailable', 'error': type(error).__name__})
|
||||
log.warning('batch_summary_unavailable run_id=%s error=%s', run_id, type(error).__name__)
|
||||
if has_run:
|
||||
try:
|
||||
journal.finish(run_id, receipt)
|
||||
except Exception as save_error:
|
||||
log.error('batch_summary_reporting_error_unavailable run_id=%s error=%s',
|
||||
run_id, type(save_error).__name__)
|
||||
return receipt
|
||||
log.info('batch_summary run_id=%s revision=%s status=%s tasks=%s targets=%s',
|
||||
run_id, summary['revision'], summary['status'], summary['task_counts'], summary['operation_total'])
|
||||
return {**receipt, 'status': summary['status'], 'execution_status': summary['execution_status'],
|
||||
'acceptance': summary['acceptance'], 'reporting_errors': summary['reporting_errors'], 'summary': summary}
|
||||
|
||||
|
||||
def _republish_incident_batch_summary(service, root, run_id, receipt, *, batch_id=None):
|
||||
"""Update the original batch revision after an admitted incident retry."""
|
||||
root = Path(root)
|
||||
path = internal_path(root / 'batch-runs' / run_id / 'manifest.json')
|
||||
if not path.is_file():
|
||||
return receipt
|
||||
journal = RunJournal(root)
|
||||
manifest = json.loads(path.read_bytes())
|
||||
run = journal.get(run_id)
|
||||
if (not run or manifest['run_id'] != run_id or manifest['runnable_task_ids'] != run['task_ids']
|
||||
or manifest['plan_hashes'] != run['plan_hashes']):
|
||||
raise TaskCenterError('run_scope', '原批次回执身份变化,无法更新。')
|
||||
previous = journal.batch_summary(run_id) or {}
|
||||
batch_ids = list(previous.get('resource_batch_ids', ()))
|
||||
if isinstance(batch_id, str) and re.fullmatch('[0-9a-f]{32}', batch_id):
|
||||
batch_ids.append(batch_id)
|
||||
return _finish_batch_summary(service, root, journal, manifest, receipt, monotonic(),
|
||||
getattr(service, '_last_supervisor_batch_id', None),
|
||||
incident_batch_ids=batch_ids)
|
||||
|
||||
|
||||
def _publish_batch_summary(root, journal, summary, receipt, *, has_run):
|
||||
run_id = summary['run_id']
|
||||
summary = (journal.save_batch_summary(run_id, summary, receipt) if has_run else dict(summary, revision=1))
|
||||
try:
|
||||
batch_resources.write_record(root / 'batch-runs' / run_id / 'batch-receipt.json', summary)
|
||||
except OSError as error:
|
||||
summary['reporting_errors'].append({'code': 'batch_receipt_export_unavailable', 'error': type(error).__name__})
|
||||
if has_run:
|
||||
journal.save_batch_summary(run_id, summary, receipt, revision=summary['revision'])
|
||||
return summary
|
||||
|
||||
|
||||
def recover_batch_receipts(service, root):
|
||||
"""Rebuild absent or stale JSON from recorded evidence, without dispatch."""
|
||||
from ..trial_task_center.batch_supervisor import mutation_lease
|
||||
|
||||
root = Path(root)
|
||||
paths = internal_path(root / 'batch-runs')
|
||||
if not paths.is_dir():
|
||||
return
|
||||
try:
|
||||
with mutation_lease(root):
|
||||
_recover_batch_receipts(service, root, paths)
|
||||
except TaskCenterError as error:
|
||||
if error.code != 'supervisor_busy':
|
||||
raise
|
||||
|
||||
|
||||
def _recover_batch_receipts(service, root, paths):
|
||||
journal = RunJournal(root)
|
||||
for path in paths.glob('*/manifest.json'):
|
||||
run_id = path.parent.name
|
||||
if not re.fullmatch('[0-9a-f]{32}', run_id):
|
||||
continue
|
||||
try:
|
||||
manifest = json.loads(path.read_bytes())
|
||||
run = journal.get(run_id)
|
||||
output = path.with_name('batch-receipt.json')
|
||||
if (not run or manifest['run_id'] != run_id or manifest['runnable_task_ids'] != run['task_ids']
|
||||
or manifest['plan_hashes'] != run['plan_hashes']):
|
||||
continue
|
||||
receipt = run['result'] or {}
|
||||
durable = journal.batch_summary(run_id)
|
||||
running = run['status'] == 'running'
|
||||
if (not running and durable
|
||||
and receipt.get('summary', {}).get('revision') == durable['revision']):
|
||||
refreshed = refresh_batch_resources(root, manifest, durable)
|
||||
if refreshed is not durable:
|
||||
_publish_batch_summary(root, journal, refreshed, receipt, has_run=True)
|
||||
continue
|
||||
try:
|
||||
if json.loads(output.read_bytes()) == durable:
|
||||
continue
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
batch_resources.write_record(output, durable)
|
||||
continue
|
||||
batch_ids = _bound_supervisors(root, manifest)
|
||||
if running or not receipt:
|
||||
previous_ids = set((durable or {}).get('resource_batch_ids', ())) if running else set()
|
||||
current_ids = [batch_id for batch_id in batch_ids if batch_id not in previous_ids]
|
||||
recovered = _recover_supervised_business(root, manifest, current_ids)
|
||||
if recovered:
|
||||
receipt = recovered
|
||||
elif running:
|
||||
receipt.update(status='interrupted', execution_status='interrupted', code='execution_interrupted')
|
||||
receipt.setdefault('status', 'interrupted')
|
||||
elapsed = receipt.get('elapsed_seconds') or 0
|
||||
summary = collect_batch_summary(service, root, manifest, receipt, elapsed_seconds=elapsed,
|
||||
batch_ids=batch_ids)
|
||||
_publish_batch_summary(root, journal, summary, receipt, has_run=True)
|
||||
except (OSError, ValueError, KeyError, TypeError, RuntimeError) as error:
|
||||
service._logging.logger.warning('batch_receipt_recovery_unavailable run_id=%s error=%s',
|
||||
run_id, type(error).__name__)
|
||||
|
||||
|
||||
def _persist_execution_receipt(service, journal, run_id, receipt, baseline):
|
||||
try:
|
||||
journal.finish(run_id, receipt)
|
||||
@@ -216,6 +555,7 @@ def _execute_incident_retry(service, root, task_id, run_id, *, expected_item, st
|
||||
root = Path(root)
|
||||
journal = RunJournal(root)
|
||||
original = journal.get(run_id)
|
||||
revalidate = journal.batch_retry_revalidator(service, run_id)
|
||||
child = service.for_project_task(task_id) if hasattr(service, 'for_project_task') else service
|
||||
if original and (task_id not in original['task_ids']
|
||||
or _plan_hash(child, task_id) != original['plan_hashes'][task_id]):
|
||||
@@ -232,6 +572,8 @@ def _execute_incident_retry(service, root, task_id, run_id, *, expected_item, st
|
||||
raise TaskCenterError('run_scope', '原队列检查点身份或范围已变化;不执行重试。')
|
||||
retry_run = journal.begin_retry(service, run_id, task_id, operation_keys)
|
||||
baseline = (retry_run.get('result') or {}) if original else {}
|
||||
before_batch = None
|
||||
retry_dispatched = False
|
||||
try:
|
||||
if original:
|
||||
checkpoint['entries'][task_id].update(state='running', message='仅执行已预约的原失败项重试。')
|
||||
@@ -240,7 +582,10 @@ def _execute_incident_retry(service, root, task_id, run_id, *, expected_item, st
|
||||
with NetlistVerification(root, token, stop_event) as checks:
|
||||
# Never capture a partially replaced project as a new "before".
|
||||
checks.before_task(child, task_id, existing_only=True)
|
||||
outcome = service.execute_quick_run_queue(task_id, expected_item=expected_item, stop_event=stop_event)
|
||||
before_batch = getattr(service, '_last_supervisor_batch_id', None)
|
||||
retry_dispatched = True
|
||||
outcome = service.execute_quick_run_queue(task_id, expected_item=expected_item, stop_event=stop_event,
|
||||
**({'revalidate': revalidate} if revalidate is not None else {}))
|
||||
current = service.task_context(task_id)
|
||||
p = current.progress
|
||||
complete = p.queue_complete and not p.failed_items and not current.interrupted and not outcome.paused
|
||||
@@ -296,7 +641,11 @@ def _execute_incident_retry(service, root, task_id, run_id, *, expected_item, st
|
||||
result = TaskQueueResult(original['queue_id'], tuple(TaskQueueEntry(**entries[key])
|
||||
for key in original['task_ids']), outcome.paused, netlist_verification=merged)
|
||||
receipt = _finish_execution_run(service, root, original['task_ids'], stop_event, run_id, result,
|
||||
baseline=baseline)
|
||||
baseline=baseline, resource_report_pending=revalidate is not None)
|
||||
if revalidate is not None:
|
||||
batch_id = getattr(service, '_last_supervisor_batch_id', None)
|
||||
receipt = _republish_incident_batch_summary(service, root, run_id, receipt,
|
||||
batch_id=batch_id if batch_id != before_batch else None)
|
||||
verification.update(run_receipt_updated=True, run_status=receipt['status'])
|
||||
return outcome, current, verification
|
||||
except Exception as error:
|
||||
@@ -315,4 +664,12 @@ def _execute_incident_retry(service, root, task_id, run_id, *, expected_item, st
|
||||
failure['reporting_errors'] = [{'code': 'context_unavailable',
|
||||
'error': type(readback_error).__name__}]
|
||||
journal.finish(run_id, failure)
|
||||
if revalidate is not None:
|
||||
batch_id = getattr(service, '_last_supervisor_batch_id', None)
|
||||
try:
|
||||
_republish_incident_batch_summary(service, root, run_id, failure,
|
||||
batch_id=batch_id if retry_dispatched and batch_id != before_batch else None)
|
||||
except Exception as reporting_error:
|
||||
service._logging.logger.error('incident_batch_receipt_unavailable run_id=%s error=%s',
|
||||
run_id, type(reporting_error).__name__)
|
||||
raise
|
||||
@@ -365,16 +365,22 @@ class IncidentRunner:
|
||||
# Consume before entering a service mutation. A crash or changed error
|
||||
# code must never buy another replay of the same authorized run.
|
||||
try:
|
||||
if reserve_retry is not None:
|
||||
reserved = reserve_retry(task_id, source='dsh')
|
||||
if not reserved:
|
||||
raise FileExistsError('retry_budget_spent')
|
||||
else:
|
||||
budget_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with budget_path.open('x', encoding='utf8') as stream:
|
||||
json.dump({'incident_id': incident_id, 'task_id': task_id, 'run_id': run_id, 'attempts': 1}, stream)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
from .run_journal import RunJournal
|
||||
from ..trial_task_center.batch_supervisor import mutation_lease
|
||||
revalidate = RunJournal(self.data_root).batch_retry_revalidator(self.service, run_id)
|
||||
with mutation_lease(self.data_root) if revalidate is not None else nullcontext():
|
||||
if revalidate is not None:
|
||||
revalidate()
|
||||
if reserve_retry is not None:
|
||||
reserved = reserve_retry(task_id, source='dsh')
|
||||
if not reserved:
|
||||
raise FileExistsError('retry_budget_spent')
|
||||
else:
|
||||
budget_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with budget_path.open('x', encoding='utf8') as stream:
|
||||
json.dump({'incident_id': incident_id, 'task_id': task_id, 'run_id': run_id, 'attempts': 1}, stream)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
except FileExistsError:
|
||||
gates['retry_budget_available'] = False
|
||||
write_json(evidence.directory / 'gates.json', gates)
|
||||
|
||||
@@ -12,9 +12,6 @@ from uuid import uuid4
|
||||
from .snapshot import TaskSnapshot
|
||||
from ..trial_task_center.path_access import retry_sharing_violation
|
||||
|
||||
HARNESS_VERSION = '0.2.1-rc.5'
|
||||
|
||||
|
||||
def integration_root() -> Path:
|
||||
if getattr(sys, 'frozen', False):
|
||||
return Path(sys._MEIPASS) / 'dsh-runtime'
|
||||
|
||||
@@ -60,6 +60,8 @@ class RunJournal:
|
||||
db.execute("""CREATE TABLE IF NOT EXISTS run_journal_receipts (
|
||||
receipt_id INTEGER PRIMARY KEY AUTOINCREMENT, run_id TEXT NOT NULL,
|
||||
finished_utc TEXT NOT NULL, status TEXT NOT NULL, result TEXT NOT NULL)""")
|
||||
db.execute("""CREATE TABLE IF NOT EXISTS run_batch_summaries (
|
||||
run_id TEXT PRIMARY KEY, revision INTEGER NOT NULL, summary TEXT NOT NULL)""")
|
||||
|
||||
@contextmanager
|
||||
def _connect(self):
|
||||
@@ -128,6 +130,33 @@ class RunJournal:
|
||||
db.execute("COMMIT")
|
||||
return current
|
||||
|
||||
def batch_summary(self, run_id):
|
||||
with self._connect() as db:
|
||||
row = db.execute('SELECT summary FROM run_batch_summaries WHERE run_id=?', (run_id,)).fetchone()
|
||||
return json.loads(row[0]) if row else None
|
||||
|
||||
def save_batch_summary(self, run_id, summary, receipt, *, revision=None):
|
||||
"""Publish the same summary revision in the durable run result."""
|
||||
with self._connect() as db:
|
||||
db.execute('BEGIN IMMEDIATE')
|
||||
if db.execute('SELECT 1 FROM run_journal WHERE run_id=?', (run_id,)).fetchone() is None:
|
||||
raise TaskCenterError('run_missing', 'run does not exist')
|
||||
previous = db.execute('SELECT revision FROM run_batch_summaries WHERE run_id=?', (run_id,)).fetchone()
|
||||
previous_revision = previous[0] if previous else 0
|
||||
if revision is not None and revision != previous_revision:
|
||||
raise TaskCenterError('batch_receipt_stale', '批次回执版本已经更新。')
|
||||
revision = revision if revision is not None else previous_revision + 1
|
||||
value = _json(dict(summary, revision=revision))
|
||||
db.execute('''INSERT INTO run_batch_summaries VALUES (?,?,?)
|
||||
ON CONFLICT(run_id) DO UPDATE SET revision=excluded.revision,summary=excluded.summary''',
|
||||
(run_id, revision, json.dumps(value, ensure_ascii=False)))
|
||||
run_result = {**receipt, 'status': value['status'], 'execution_status': value['execution_status'],
|
||||
'acceptance': value['acceptance'], 'reporting_errors': value['reporting_errors'], 'summary': value}
|
||||
db.execute('UPDATE run_journal SET status=?, result=? WHERE run_id=?',
|
||||
(run_result['status'], json.dumps(_json(run_result), ensure_ascii=False), run_id))
|
||||
db.execute('COMMIT')
|
||||
return value
|
||||
|
||||
def resume(self, run_id):
|
||||
"""Mark a natively reconfirmed continuation; keep its last durable receipt."""
|
||||
with self._connect() as db:
|
||||
@@ -144,6 +173,53 @@ class RunJournal:
|
||||
|
||||
def begin_retry(self, service, run_id, task_id, operation_keys):
|
||||
"""Persist one reserved retry baseline before its first CAD dispatch."""
|
||||
revalidate = self.batch_retry_revalidator(service, run_id)
|
||||
if revalidate is not None:
|
||||
from ..trial_task_center.batch_supervisor import mutation_lease
|
||||
with mutation_lease(self.data_root):
|
||||
revalidate()
|
||||
return self._begin_retry(service, run_id, task_id, operation_keys)
|
||||
return self._begin_retry(service, run_id, task_id, operation_keys)
|
||||
|
||||
def batch_retry_revalidator(self, service, run_id):
|
||||
"""Read and bind the original batch manifest under the caller's mutation lease."""
|
||||
from ..trial_task_center.path_access import internal_path
|
||||
if not isinstance(run_id, str) or not _ID.fullmatch(run_id):
|
||||
return None
|
||||
path = internal_path(self.data_root / 'batch-runs' / run_id / 'manifest.json')
|
||||
try:
|
||||
path.parent.stat()
|
||||
except FileNotFoundError:
|
||||
if not self.batch_summary(run_id):
|
||||
checkpoint = internal_path(self.data_root / 'task-queues' / (run_id + '.json'))
|
||||
try:
|
||||
if not json.loads(checkpoint.read_bytes()).get('manifest_digest'):
|
||||
return None
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
except (OSError, ValueError, TypeError, AttributeError) as error:
|
||||
raise TaskCenterError('run_scope', '无法读取原队列检查点,不能自动重试。') from error
|
||||
raise TaskCenterError('batch_manifest', '原批次的冻结清单缺失,请保留证据。')
|
||||
except OSError as error:
|
||||
raise TaskCenterError('batch_manifest', '无法读取原批次的冻结清单。') from error
|
||||
|
||||
def revalidate():
|
||||
from ..trial_task_center.batch_admission import validate_batch_resume
|
||||
try:
|
||||
manifest = json.loads(path.read_bytes())
|
||||
row = self.get(run_id)
|
||||
if (not row or manifest['run_id'] != run_id or manifest['runnable_task_ids'] != row['task_ids']
|
||||
or manifest['plan_hashes'] != row['plan_hashes']):
|
||||
raise ValueError('batch manifest binding mismatch')
|
||||
except (OSError, ValueError, TypeError, KeyError) as error:
|
||||
raise TaskCenterError('batch_manifest', '无法核验原批次的冻结清单。') from error
|
||||
validate_batch_resume(service, manifest)
|
||||
if row['status'] == 'blocked':
|
||||
raise TaskCenterError('quick_run_uncertain', '原批次仍处于待核验暂停,请在工程核验后重新确认继续。')
|
||||
|
||||
return revalidate
|
||||
|
||||
def _begin_retry(self, service, run_id, task_id, operation_keys):
|
||||
selected = set(operation_keys or ())
|
||||
child = service.for_project_task(task_id)
|
||||
store = child._store
|
||||
@@ -332,6 +408,22 @@ class RunJournal:
|
||||
released_primary = {key for key, entry in (queue['entries'].items() if workspace and queue else ())
|
||||
if entry['released'] and entry['state'] in {'completed', 'failed', 'skipped', 'blocked'}}
|
||||
isolated = {key for key in released_primary if queue['entries'][key]['state'] == 'blocked'}
|
||||
resource_batch_id = None
|
||||
if queue and not workspace:
|
||||
isolated.update(key for key in queue.get('isolated_tasks', {})
|
||||
if key in queue['entries'] and queue['entries'][key]['state'] == 'blocked')
|
||||
receipt = row.get('result') or {}
|
||||
pause = queue.get('resource_pause')
|
||||
if (receipt.get('paused') is True and receipt.get('user_pause_requested') is False
|
||||
and isinstance(pause, dict) and pause.get('business_determined') is True
|
||||
and receipt.get('resource_batch_id', pause.get('batch_id')) == pause.get('batch_id')):
|
||||
from ..trial_task_center.task_queue import resource_pause_admitted
|
||||
batch_id = pause.get('batch_id')
|
||||
paused = resource_pause_admitted(self.data_root, batch_id,
|
||||
tuple(row['task_ids']), row['plan_hashes'])
|
||||
if paused and paused.queue_id == run_id:
|
||||
resource_batch_id = batch_id
|
||||
released_primary.update(isolated)
|
||||
safe_continuations = set()
|
||||
for task_id in row["task_ids"]:
|
||||
item = {"task_id": task_id, "status": "unknown", "saved_items": 0, "failed_items": 0, "no_match_items": 0}
|
||||
@@ -356,7 +448,7 @@ class RunJournal:
|
||||
for key in ("saved_items", "failed_items", "no_match_items"):
|
||||
counters[key] += item[key]
|
||||
counters["total"] += item["total_items"]
|
||||
if context.interrupted and task_id not in isolated:
|
||||
if context.interrupted:
|
||||
blockers.append("interrupted")
|
||||
if getattr(progress, "failed_items", 0) and task_id not in released_primary | safe_continuations:
|
||||
blockers.append("failed_items")
|
||||
@@ -380,7 +472,8 @@ class RunJournal:
|
||||
counters["completed"] = sum(queue["entries"][task_id]["state"] in {"completed", "failed", "skipped"} for task_id in row["task_ids"])
|
||||
remaining = [task_id for task_id in row["task_ids"] if not queue or queue["entries"][task_id]["state"] not in {"completed", "failed", "skipped"}]
|
||||
if queue and not workspace and queue.get('phase') in {'primary', 'problems'}:
|
||||
remaining = [key for key in row['task_ids'] if key in remaining or key in released_primary]
|
||||
remaining = [key for key in row['task_ids'] if key not in isolated and
|
||||
(key in remaining or key in released_primary)]
|
||||
if workspace and queue:
|
||||
primary_exhausted = all(entry['state'] in {'completed', 'failed', 'skipped', 'blocked'} for entry in queue['entries'].values())
|
||||
remaining = [key for key in row['task_ids'] if key not in isolated and (
|
||||
@@ -407,6 +500,7 @@ class RunJournal:
|
||||
blockers.append("resources_pending")
|
||||
blockers = list(dict.fromkeys(blockers))
|
||||
value = {**row, "queue_available": queue is not None, "tasks": tasks, "counters": counters,
|
||||
'resource_batch_id': resource_batch_id,
|
||||
'isolated_task_ids': [key for key in row['task_ids'] if key in isolated],
|
||||
'released_primary_task_ids': [key for key in row['task_ids'] if key in released_primary],
|
||||
'safe_continuation_task_ids': [key for key in row['task_ids'] if key in safe_continuations],
|
||||
|
||||
@@ -9,12 +9,13 @@ import platform
|
||||
import sys
|
||||
from typing import Sequence
|
||||
|
||||
from PySide6.QtCore import QTimer, QThreadPool
|
||||
from PySide6.QtCore import QTimer, QThreadPool, Qt
|
||||
from PySide6.QtGui import QIcon
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
from dx_productivity.trial_task_center.logging_setup import LoggingContext, configure_logging, install_exception_hooks
|
||||
from dx_productivity.trial_task_center.service import TaskCenterService
|
||||
from dx_productivity.trial_task_center.single_instance import InstanceUnavailable, gui_instance, listen_for_activation
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
from dx_productivity.trial_task_center.version import VERSION
|
||||
|
||||
@@ -161,10 +162,28 @@ def main(argv: Sequence[str] | None = None) -> int:
|
||||
from dx_productivity.trial_task_center.sceneos_cli import run
|
||||
|
||||
return run(data_root)
|
||||
try:
|
||||
with gui_instance(data_root) as endpoint:
|
||||
if endpoint is None:
|
||||
return 0
|
||||
return _run_gui(argv, arguments, data_root, endpoint)
|
||||
except (OSError, InstanceUnavailable) as error:
|
||||
message = f'无法打开 DxPartReplace。\n{data_root}\n{error}'
|
||||
if sys.stderr is not None:
|
||||
print(message, file=sys.stderr)
|
||||
if os.name == 'nt' and bool(getattr(sys, 'frozen', False)):
|
||||
import ctypes
|
||||
|
||||
ctypes.windll.user32.MessageBoxW(None, message, 'DxPartReplace', 0x30)
|
||||
return 1
|
||||
|
||||
|
||||
def _run_gui(argv, arguments, data_root, endpoint):
|
||||
logging_context = configure_logging(data_root)
|
||||
install_exception_hooks(logging_context)
|
||||
store: TaskStore | None = None
|
||||
window = None
|
||||
activation_server = None
|
||||
try:
|
||||
database_path = data_root / "task-center.db"
|
||||
_log_startup(logging_context, data_root, database_path)
|
||||
@@ -177,6 +196,16 @@ def main(argv: Sequence[str] | None = None) -> int:
|
||||
configure_application_identity(qt_application)
|
||||
window = _load_window()(service)
|
||||
window.show()
|
||||
|
||||
def activate():
|
||||
logging_context.logger.info('instance_conflict data_root=%s', data_root)
|
||||
window.setWindowState(window.windowState() & ~Qt.WindowState.WindowMinimized)
|
||||
window.show()
|
||||
window.raise_()
|
||||
window.activateWindow()
|
||||
window.statusBar().showMessage('此数据目录已在使用,已切换到现有窗口。', 6000)
|
||||
|
||||
activation_server = listen_for_activation(endpoint, activate)
|
||||
if arguments.smoke_test:
|
||||
QTimer.singleShot(0, lambda: (window.close(), qt_application.quit()))
|
||||
exit_code = qt_application.exec()
|
||||
@@ -187,6 +216,8 @@ def main(argv: Sequence[str] | None = None) -> int:
|
||||
logging_context.report_exception("startup", error)
|
||||
return 1
|
||||
finally:
|
||||
if activation_server is not None:
|
||||
activation_server.close()
|
||||
if store is not None:
|
||||
# The window invalidates queued UI results on close. Finish the
|
||||
# remaining read before releasing the shared SQLite connection.
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
"""Explicit batch scope and per-project admission; strict single-task checks stay intact."""
|
||||
from dataclasses import asdict
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .models import TaskStatus
|
||||
from ..dsh import task_lifecycle
|
||||
|
||||
_digest = task_lifecycle._digest
|
||||
|
||||
POLICY_VERSION = 'issue44-strict-v1'
|
||||
|
||||
|
||||
def resolve_batch_task_ids(tasks, group_id, *, selected_ids=None):
|
||||
records = {task.task_id: task for task in tasks}
|
||||
members = sorted((task for task in records.values() if task.group_id == group_id
|
||||
and task.status is not TaskStatus.DELETED),
|
||||
key=lambda task: (task.group_position, task.task_id))
|
||||
if not group_id or not members:
|
||||
raise TaskCenterError('batch_scope', '请先选择一个有效的工程批次。')
|
||||
if selected_ids is None:
|
||||
return tuple(task.task_id for task in members)
|
||||
selected = tuple(selected_ids)
|
||||
if (not selected or len(set(selected)) != len(selected)
|
||||
or any(key not in records or records[key].group_id != group_id
|
||||
or records[key].status is TaskStatus.DELETED for key in selected)):
|
||||
raise TaskCenterError('batch_scope', '请选择同一批次中不同的有效任务,跨批任务请分批执行。')
|
||||
return tuple(task.task_id for task in members if task.task_id in selected)
|
||||
|
||||
|
||||
def build_batch_admission(service, task_ids, *, scope_kind):
|
||||
if scope_kind not in {'batch', 'selected'} or not task_ids:
|
||||
raise TaskCenterError('batch_scope', '请选择本批或所选工程范围。')
|
||||
records = tuple(service.tasks())
|
||||
owner = next((task for task in records if task.task_id == task_ids[0]), None)
|
||||
if owner is None:
|
||||
raise TaskCenterError('batch_scope', '任务范围已变化,请重新选择并确认。')
|
||||
ids = resolve_batch_task_ids(records, owner.group_id,
|
||||
selected_ids=tuple(task_ids) if scope_kind == 'selected' else None)
|
||||
if ids != tuple(task_ids):
|
||||
raise TaskCenterError('batch_scope', '本批成员或顺序已变化,请重新确认。')
|
||||
from .batch_resources import resource_blockers
|
||||
blockers, decisions, fingerprints, paths, runnable = [], [], [], set(), []
|
||||
try:
|
||||
if resource_blockers(service.pending_batch_resources()):
|
||||
blockers.append('后台资源尚未确认物理释放,请先重试释放资源。')
|
||||
except Exception as error:
|
||||
blockers.append(f'无法确认后台资源状态:{type(error).__name__}')
|
||||
# Selecting another member cannot bypass an uncertain write in this batch.
|
||||
for task in records:
|
||||
if task.group_id == owner.group_id and task.status is not TaskStatus.DELETED:
|
||||
if task.status is TaskStatus.BLOCKED or service.has_interrupted_quick_run(task.task_id):
|
||||
blockers.append(f'{task.name} 的写入结果待核验,请核验后重新确认本批。')
|
||||
for order, task_id in enumerate(ids):
|
||||
task = next(task for task in records if task.task_id == task_id)
|
||||
row = dict(task_id=task_id, name=task.name, order=order, project='',
|
||||
classification='skipped', reason_code='', message='', enabled_scope=0,
|
||||
component_count=None, target_count=None, verification_pending=False)
|
||||
decisions.append(row)
|
||||
try:
|
||||
context = service.task_context(task_id)
|
||||
fingerprints.append(asdict(context))
|
||||
row['project'] = str(context.project.path) if context.project else ''
|
||||
if context.interrupted or task.status is TaskStatus.BLOCKED:
|
||||
row.update(classification='held', reason_code='quick_run_uncertain', message='写入结果待核验,本批暂停。')
|
||||
continue
|
||||
if (task.status is TaskStatus.COMPLETED and context.progress.queue_complete
|
||||
and not context.progress.failed_items):
|
||||
row.update(classification='already_completed', reason_code='already_completed',
|
||||
message='本轮已有完整执行结果,不重复派发。')
|
||||
continue
|
||||
if context.project is None or not context.project.path.is_file():
|
||||
row.update(reason_code='project_missing', message='工程文件不存在或不可访问。')
|
||||
continue
|
||||
path_key = str(context.project.path.resolve()).casefold()
|
||||
if path_key in paths:
|
||||
blockers.append('本批重复包含同一个工程,请核对任务绑定。')
|
||||
row.update(reason_code='project_duplicate', message='工程在本次范围重复。')
|
||||
continue
|
||||
paths.add(path_key)
|
||||
report = task_lifecycle.preflight(service, [task_id])
|
||||
item = report['tasks'][0]
|
||||
count = item['enabled_rules']
|
||||
exact = bool(task.target_plan_mode) and not context.pending_bom
|
||||
row.update(enabled_scope=count, component_count=count if exact else None,
|
||||
target_count=count if exact else None,
|
||||
verification_pending=item['verification_pending'])
|
||||
if item['blockers']:
|
||||
row.update(reason_code='configuration_blocked', message=';'.join(item['blockers']))
|
||||
continue
|
||||
from .project_isolation import write_sources
|
||||
sources = sorted(write_sources(context.project.path, strict=True))
|
||||
row.update(classification='executable', reason_code='ready', message='可执行。', write_sources=sources)
|
||||
runnable.append(task_id)
|
||||
except (FileNotFoundError, PermissionError, NotADirectoryError) as error:
|
||||
row.update(reason_code='project_unavailable', message=f'工程不可访问:{error}')
|
||||
except Exception as error:
|
||||
# Unreadable execution evidence is not an ordinary configuration skip.
|
||||
row.update(classification='held', reason_code=getattr(error, 'code', 'evidence_unavailable'),
|
||||
message=f'无法核对工程或执行证据:{error}')
|
||||
blockers.append(f'{task.name}:{row["message"]}')
|
||||
report = task_lifecycle.preflight(service, runnable) if runnable and not blockers else None
|
||||
if report is not None and not report['ready']:
|
||||
blockers.append('可执行子集的状态已变化,请重新预检。')
|
||||
result = dict(schema_version=1, policy_version=POLICY_VERSION, scope_kind=scope_kind,
|
||||
group_id=owner.group_id, candidate_task_ids=list(ids), decisions=decisions,
|
||||
runnable_task_ids=runnable, plan_hashes=report['plan_hashes'] if report else {},
|
||||
candidate_fingerprint=_digest(fingerprints), global_blockers=list(dict.fromkeys(blockers)),
|
||||
ready=bool(runnable and not blockers and report and report['ready']), execution_report=report)
|
||||
result['manifest_digest'] = _digest(result)
|
||||
return result
|
||||
|
||||
|
||||
def validate_batch_admission(service, admission):
|
||||
current = build_batch_admission(service, tuple(admission['candidate_task_ids']),
|
||||
scope_kind=admission['scope_kind'])
|
||||
if not current['ready'] or current['manifest_digest'] != admission['manifest_digest']:
|
||||
raise TaskCenterError('assistant_stale', '确认后的任务范围、计划或资源状态已变化,请重新预检并确认。')
|
||||
return current['execution_report']
|
||||
|
||||
|
||||
def validate_batch_resume(service, manifest):
|
||||
"""Check immutable scope and engineering sources without comparing mutable progress."""
|
||||
from .project_isolation import write_sources
|
||||
from .task_queue import _plan_hash
|
||||
payload = {key: value for key, value in manifest.items()
|
||||
if key not in {'manifest_digest', 'run_id', 'confirmed_utc'}}
|
||||
if manifest.get('policy_version') != POLICY_VERSION or _digest(payload) != manifest.get('manifest_digest'):
|
||||
raise TaskCenterError('batch_manifest', '原批次的冻结清单无法核验,请保留证据。')
|
||||
records = tuple(service.tasks())
|
||||
selected = tuple(manifest['candidate_task_ids']) if manifest['scope_kind'] == 'selected' else None
|
||||
ids = resolve_batch_task_ids(records, manifest['group_id'], selected_ids=selected)
|
||||
if ids != tuple(manifest['candidate_task_ids']):
|
||||
raise TaskCenterError('assistant_stale', '原批次成员或顺序已变化,请重新确认。')
|
||||
for task in records:
|
||||
if task.group_id == manifest['group_id'] and task.status is not TaskStatus.DELETED:
|
||||
if task.status is TaskStatus.BLOCKED or service.has_interrupted_quick_run(task.task_id):
|
||||
raise TaskCenterError('quick_run_uncertain', '原批次仍有工程写入结果待核验,不能继续或重试。')
|
||||
for row in manifest['decisions']:
|
||||
if row['classification'] != 'executable':
|
||||
continue
|
||||
task_id = row['task_id']
|
||||
child = service.for_project_task(task_id)
|
||||
if _plan_hash(child, task_id) != manifest['plan_hashes'][task_id]:
|
||||
raise TaskCenterError('assistant_stale', '原批次计划已变化,请重新确认。')
|
||||
projects = child.projects(task_id)
|
||||
if (len(projects) != 1 or str(projects[0].path) != row['project']
|
||||
or sorted(write_sources(projects[0].path, strict=True)) != row.get('write_sources')):
|
||||
raise TaskCenterError('assistant_stale', '原批次工程写入源已变化,请重新确认。')
|
||||
|
||||
|
||||
def write_preflight_receipt(root, admission, status, *, reason=''):
|
||||
if status not in {'rejected', 'cancelled'}:
|
||||
raise ValueError('Only zero-dispatch preflight outcomes are accepted')
|
||||
from .batch_resources import write_record
|
||||
token = uuid4().hex
|
||||
folder = Path(root) / 'batch-runs' / token
|
||||
write_record(folder / 'manifest.json', admission)
|
||||
receipt = dict(schema_version=1, run_id=token, queue_id=None, status=status,
|
||||
manifest_digest=admission['manifest_digest'], dispatch_count=0,
|
||||
candidate_task_ids=admission['candidate_task_ids'], decisions=admission['decisions'],
|
||||
global_blockers=admission['global_blockers'], message=reason,
|
||||
finished_utc=datetime.now(timezone.utc).isoformat())
|
||||
write_record(folder / 'batch-receipt.json', receipt)
|
||||
return folder / 'batch-receipt.json'
|
||||
@@ -37,11 +37,13 @@ def write_release_event(root, path, record, phase, *, context=None, reason='batc
|
||||
'desktop_disappeared': disappeared, 'cad_exit_code': cad.get('cad_exit_code'),
|
||||
'quit_helper_exit_code': cad.get('quit_helper_exit_code'),
|
||||
'cad_shutdown': cad, 'shutdown_warning': record.get('shutdown_warning'),
|
||||
'retries': record.get('retries', {}), 'cleanup': cleanup, 'error': str(error)}
|
||||
'retries': record.get('retries', {}), 'release_rechecks': record.get('release_rechecks', []),
|
||||
'cleanup': cleanup, 'error': str(error)}
|
||||
title = {'started': '开始释放后台资源', 'succeeded': '后台资源释放成功',
|
||||
'failed': '后台资源释放失败,资源释放待处理',
|
||||
'isolated': '后台写入进程已退出,残留桌面已隔离(未确认释放)'}[phase]
|
||||
purpose = {'batch_end': '批次结束', 'rebuild': '安全重建', 'manual_retry': '重新清理',
|
||||
'automatic_recheck': '自动复核释放',
|
||||
'restart_recheck': '重启后重新检查'}.get(reason, reason)
|
||||
cad_text = f"CAD PID={details['cad_pid']}" if details['cad_pid'] else (
|
||||
'CAD 未启动' if record.get('cad_start_requested') is False else
|
||||
|
||||
@@ -15,6 +15,27 @@ from .path_access import canonical_path, internal_path, retry_sharing_violation
|
||||
# Recovery retains owned native handles after failed cleanup. This registry is
|
||||
# never an implicit execution context and never contains COM application objects.
|
||||
LIVE_RESOURCES = {}
|
||||
RESOURCE_RELEASE_BACKOFF_SECONDS = (0.5, 1, 2)
|
||||
|
||||
|
||||
def _observe_release(observe, record):
|
||||
"""Check once immediately, then at most three times after backoff."""
|
||||
record['release_rechecks'] = []
|
||||
for attempt, delay in enumerate((0, *RESOURCE_RELEASE_BACKOFF_SECONDS)):
|
||||
if delay:
|
||||
time.sleep(delay)
|
||||
try:
|
||||
confirmed = observe()
|
||||
except (OSError, TaskCenterError) as error:
|
||||
confirmed, detail = False, str(error)
|
||||
else:
|
||||
detail = ''
|
||||
if attempt:
|
||||
record['release_rechecks'].append({'attempt': attempt, 'delay_seconds': delay,
|
||||
'confirmed': confirmed, 'error': detail})
|
||||
if confirmed:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
class BatchResourceCleanupError(TaskCenterError):
|
||||
@@ -82,9 +103,8 @@ def pending_resources(root):
|
||||
if not _valid_record(record, path):
|
||||
raise ValueError('invalid resource ownership record')
|
||||
if record.get('state') != 'released' or not _released_evidence(record):
|
||||
pending.append(dict(record, record_path=str(path),
|
||||
blocking=not (record.get('state') == 'isolated' and _isolation_evidence(record))))
|
||||
except (OSError, ValueError, TypeError) as error:
|
||||
pending.append(dict(record, record_path=str(path), blocking=True))
|
||||
except (OSError, ValueError, TypeError, KeyError, AttributeError) as error:
|
||||
pending.append({'state': 'blocked', 'record_path': str(path), 'error': str(error)})
|
||||
import sys
|
||||
sessions = getattr(sys.modules.get(__package__ + '.isolated_cad'), 'RETAINED_CAD_SESSIONS', {})
|
||||
@@ -120,9 +140,8 @@ def pending_resources(root):
|
||||
|
||||
|
||||
def resource_blockers(records):
|
||||
"""Only a validated isolated desktop warning may leave the resource gate open."""
|
||||
return tuple(item for item in records
|
||||
if not (item.get('state') == 'isolated' and item.get('blocking') is False))
|
||||
"""Pending resources block until physical release is proven."""
|
||||
return tuple(records)
|
||||
|
||||
|
||||
def blocking_resources(root):
|
||||
@@ -202,8 +221,13 @@ def _released_evidence(record):
|
||||
and (cleanup.get('desktop_confirmation') or {}).get('released') is True)
|
||||
|
||||
|
||||
def guard_pending_resources(root):
|
||||
if blocking_resources(root):
|
||||
def guard_pending_resources(root, *, owner=None):
|
||||
pending = blocking_resources(root)
|
||||
if owner is not None and LIVE_RESOURCES.get(str(owner.path)) is owner:
|
||||
binding = (str(owner.path), owner.session_id, owner.generation, owner.desktop.name, 'ready')
|
||||
pending = tuple(record for record in pending if tuple(record.get(key) for key in
|
||||
('record_path', 'session_id', 'generation', 'desktop', 'state')) != binding)
|
||||
if pending:
|
||||
raise BatchResourceCleanupError('上一批资源尚未确认释放;请先重试释放资源,再开始新批次。')
|
||||
|
||||
|
||||
@@ -216,25 +240,66 @@ def process_identity(process):
|
||||
return result
|
||||
|
||||
|
||||
def _process_gone(identity):
|
||||
def observe_process_identity(identity):
|
||||
"""Observe an exact historical process using query and wait rights only."""
|
||||
pid = identity.get('pid') if isinstance(identity, dict) else None
|
||||
created = identity.get('creation_time') if isinstance(identity, dict) else None
|
||||
if type(pid) is not int or not 0 < pid <= 0xFFFFFFFF or not isinstance(created, str) or not created.strip():
|
||||
return {'state': 'unknown', 'error': 'Missing or invalid process identity', 'error_code': None}
|
||||
import win32api
|
||||
import win32event
|
||||
import win32process
|
||||
try:
|
||||
handle = win32api.OpenProcess(0x101000, False, identity['pid'])
|
||||
except Exception as error:
|
||||
code = getattr(error, 'winerror', error.args[0] if error.args else None)
|
||||
if code == 87:
|
||||
return True
|
||||
raise
|
||||
handle = win32api.OpenProcess(0x101000, False, pid) # SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION
|
||||
except (OSError, win32api.error) as error:
|
||||
code = getattr(error, 'winerror', error.args[0] if error.args and type(error.args[0]) is int else None)
|
||||
return {'state': 'gone' if code == 87 else 'unknown', 'error': str(error), 'error_code': code}
|
||||
try:
|
||||
if win32event.WaitForSingleObject(handle, 0) == 0:
|
||||
return True
|
||||
created = identity.get('creation_time')
|
||||
# A reused PID is an unrelated process and must never be terminated.
|
||||
return created is not None and str(win32process.GetProcessTimes(handle)['CreationTime']) != created
|
||||
finally:
|
||||
handle.Close()
|
||||
try:
|
||||
actual = win32process.GetProcessTimes(handle).get('CreationTime')
|
||||
if actual is None:
|
||||
return {'state': 'unknown', 'error': 'Unable to read process creation time', 'error_code': None}
|
||||
# A reused PID belongs to a different process.
|
||||
if str(actual) != created:
|
||||
return {'state': 'gone', 'error_code': None}
|
||||
status = win32event.WaitForSingleObject(handle, 0)
|
||||
if status in (0, 258): # WAIT_OBJECT_0 or WAIT_TIMEOUT
|
||||
return {'state': 'gone' if status == 0 else 'alive', 'error_code': None}
|
||||
return {'state': 'unknown', 'error': 'Unexpected process wait result', 'error_code': status}
|
||||
finally:
|
||||
handle.Close()
|
||||
except (OSError, win32api.error) as error:
|
||||
code = getattr(error, 'winerror', error.args[0] if error.args and type(error.args[0]) is int else None)
|
||||
return {'state': 'unknown', 'error': str(error), 'error_code': code}
|
||||
|
||||
|
||||
def _process_gone(identity):
|
||||
return observe_process_identity(identity)['state'] == 'gone'
|
||||
|
||||
|
||||
def _historical_writer_trees_closed(record, path):
|
||||
cleanup = record.get('cleanup') or {}
|
||||
if cleanup.get('owned_cleanup_complete') is True:
|
||||
return True
|
||||
if not record.get('processes'):
|
||||
return record.get('cad_pid') is None and record.get('cad_start_requested') is not True
|
||||
if not record.get('cad_process') or record['processes'] != [record['cad_process']]:
|
||||
return False # Older Job snapshots only bind the CAD root's process creation time.
|
||||
# Older blocked records can miss the latest desktop cleanup while already
|
||||
# retaining a complete per-CAD Job accounting record.
|
||||
marker = path.parent / f"generation-{record['generation']}" / 'private-desktop.json'
|
||||
native = json.loads(internal_path(marker).read_text(encoding='utf-8'))
|
||||
if ((native.get('token'), native.get('guid'), native.get('desktop'), native.get('cad_process'))
|
||||
!= (record.get('cad_token'), record.get('cad_guid'), record.get('desktop'), record.get('cad_process'))
|
||||
or not record.get('cad_token') or not record.get('cad_guid') or not record.get('cad_process')):
|
||||
return False
|
||||
observations = (native.get('desktop_cleanup') or {}).get('processes', ())
|
||||
return sum(observation.get('pid') == record['cad_pid']
|
||||
and observation.get('job_membership_verified') is True
|
||||
and observation.get('job_active_processes') == 0
|
||||
and observation.get('job_handle_closed') is True
|
||||
and observation.get('unconfirmed_descendant_handles') == 0
|
||||
for observation in observations) == 1
|
||||
|
||||
|
||||
def cleanup_pending_resources(root, *, logging_context=None, retry_failed=False):
|
||||
@@ -269,6 +334,8 @@ def cleanup_pending_resources(root, *, logging_context=None, retry_failed=False)
|
||||
continue
|
||||
live = LIVE_RESOURCES.get(str(path))
|
||||
if live is not None:
|
||||
if live.record.get('state') != 'blocked':
|
||||
continue # An active generation has not asked for release.
|
||||
try:
|
||||
live.close(reason='manual_retry' if retry_failed else 'resource_recheck')
|
||||
except Exception:
|
||||
@@ -305,30 +372,46 @@ def cleanup_pending_resources(root, *, logging_context=None, retry_failed=False)
|
||||
if not all(_process_gone(item) for item in identities):
|
||||
log('failed', '记录中的进程仍未确认退出')
|
||||
continue
|
||||
if not _historical_writer_trees_closed(record, path):
|
||||
log('failed', '缺少历史写入进程树退出证明')
|
||||
continue
|
||||
desktop = record.get('desktop')
|
||||
if (record.get('cleanup') or {}).get('desktop_lease'):
|
||||
# A return belongs to this past lease, even while the same name
|
||||
# is now serving another batch. Never open or stop its new owner.
|
||||
proof = isolation_proof(record)
|
||||
from .desktop_slot import managed_desktop_disappeared
|
||||
if not managed_desktop_disappeared(record['cleanup']['desktop_lease']):
|
||||
receipt = record['cleanup']['desktop_lease']
|
||||
absent = _observe_release(lambda: managed_desktop_disappeared(receipt), record)
|
||||
if not absent:
|
||||
record.pop('record_path', None)
|
||||
record.update(state='isolated', blocking=False, isolation_proof=proof)
|
||||
record.update(state='isolated', blocking=True, isolation_proof=proof)
|
||||
write_record(path, record)
|
||||
log('isolated')
|
||||
continue
|
||||
elif desktop:
|
||||
try:
|
||||
_Win32Api().confirm_desktop_released(desktop)
|
||||
except Exception as error:
|
||||
# A residual desktop name is only a warning after owned
|
||||
# handle closure and independently revalidated writer exit.
|
||||
from .desktop_slot import observe_current_desktop_name
|
||||
api = None
|
||||
|
||||
def observe():
|
||||
nonlocal api
|
||||
managed = observe_current_desktop_name(desktop) if os.name == 'nt' else None
|
||||
if managed is not None:
|
||||
return managed
|
||||
if api is None:
|
||||
api = _Win32Api()
|
||||
api.confirm_desktop_released(desktop)
|
||||
return True
|
||||
|
||||
if not _observe_release(observe, record):
|
||||
# Keep the closed writer proof while the desktop still blocks admission.
|
||||
proof = isolation_proof(record)
|
||||
record.pop('record_path', None)
|
||||
record.update(state='isolated', blocking=False, isolation_proof=proof,
|
||||
isolation_warning=str(error))
|
||||
warning = '桌面仍在或同名桌面正在使用,未取得桌面消失证明'
|
||||
record.update(state='isolated', blocking=True, isolation_proof=proof,
|
||||
isolation_warning=warning)
|
||||
write_record(path, record)
|
||||
log('isolated', str(error))
|
||||
log('isolated', warning)
|
||||
continue
|
||||
# After restart only confirm disappearance. Never attach to COM,
|
||||
# close a project, or terminate a PID whose handles we no longer own.
|
||||
|
||||
@@ -12,7 +12,7 @@ from uuid import UUID, uuid4
|
||||
|
||||
from .batch_resources import (BatchResourceCleanupError, LIVE_RESOURCES, cleanup_pending_resources,
|
||||
guard_pending_resources, pending_resources, process_identity, project_checkpoint_released, write_record,
|
||||
isolation_proof)
|
||||
isolation_proof, RESOURCE_RELEASE_BACKOFF_SECONDS)
|
||||
from .errors import TaskCenterError
|
||||
from .path_access import canonical_path, internal_path, legacy_path
|
||||
from .isolated_desktop import PrivateDesktop, ProcessNotStartedError
|
||||
@@ -203,12 +203,14 @@ class BatchCadRuntime:
|
||||
'generation': self.generation, **details})
|
||||
|
||||
def _ensure_desktop(self, abort_event=None):
|
||||
if self.record['state'] == 'blocked':
|
||||
if self.record['state'] in {'blocked', 'isolated'}:
|
||||
raise BatchResourceCleanupError('当前批次资源已阻断,不能启动新的工作进程。')
|
||||
if self.record['state'] == 'isolated':
|
||||
if self.desktop is not None:
|
||||
raise BatchResourceCleanupError('隔离桌面已停止使用,请为后续工程创建新的运行会话。')
|
||||
write_record(self.path.parent / f'isolated-generation-{self.generation}.json', self.record)
|
||||
if self.desktop is not None:
|
||||
slot = getattr(self.desktop, '_slot', None)
|
||||
if (getattr(self.desktop, '_handle', True) is None
|
||||
or slot is not None and (slot.handle is None or slot.receipt is not None)):
|
||||
raise BatchResourceCleanupError('当前批次桌面租约已变化,不能启动新的工作进程。')
|
||||
guard_pending_resources(self.root, owner=self if self.desktop is not None else None)
|
||||
if self.desktop is None:
|
||||
check_cancelled(self.stop_event if abort_event is None else abort_event)
|
||||
generation = self.generation + 1
|
||||
@@ -222,6 +224,7 @@ class BatchCadRuntime:
|
||||
blocking=True, isolation_proof=None,
|
||||
stopping_reason='', wait_reason='', primary_error=None,
|
||||
cad_process=None, cad_token=None, cad_shutdown=None, cad_start_requested=False, cleanup=None,
|
||||
release_rechecks=[],
|
||||
release_state={'mentor': 'not_started', 'desktop': 'pending'})
|
||||
self.generation = generation
|
||||
self.desktop = desktop
|
||||
@@ -357,7 +360,8 @@ class BatchCadRuntime:
|
||||
value = json.loads(path.read_text(encoding='utf-8'))
|
||||
if not isinstance(value, dict):
|
||||
return None
|
||||
return {key: value.get(key) for key in ('job_id', 'stage', 'done', 'total', 'safe_stop')}
|
||||
return {key: value.get(key) for key in ('job_id', 'stage', 'done', 'total', 'safe_stop',
|
||||
'stop_requested', 'stopping_reason', 'idle_timeout_seconds', 'failure_completion_grace_seconds')}
|
||||
except (OSError, ValueError, TypeError):
|
||||
return None
|
||||
|
||||
@@ -570,7 +574,7 @@ class BatchCadRuntime:
|
||||
from .isolated_cad import PrivateCadStartupError, is_identity_conflict
|
||||
from .worker_monitor import run_monitored_process
|
||||
cooperative_abort = cooperative_abort or self.read_only
|
||||
if self.read_only and abort_event is None:
|
||||
if abort_event is None:
|
||||
abort_event = self.stop_event
|
||||
root = canonical_path(command[3])
|
||||
if self.cad is not None and self.record.get('active_project'):
|
||||
@@ -950,10 +954,41 @@ class BatchCadRuntime:
|
||||
if not self._release_lock.acquire(blocking=False):
|
||||
raise BatchResourceCleanupError('资源释放正在进行,请等待当前释放结果。')
|
||||
try:
|
||||
return self._close_once(rebuilding=rebuilding, reason=reason)
|
||||
try:
|
||||
return self._close_once(rebuilding=rebuilding, reason=reason)
|
||||
except BatchResourceCleanupError as initial:
|
||||
shutdown = self.record.get('cad_shutdown') or {}
|
||||
if (reason in {'resource_recheck', 'automatic_recheck'}
|
||||
or not shutdown.get('forced_termination')
|
||||
or self.record['state'] not in {'blocked', 'released'}):
|
||||
raise
|
||||
self.record['shutdown_warning'] = str(initial)
|
||||
for attempt, delay in enumerate(RESOURCE_RELEASE_BACKOFF_SECONDS, start=1):
|
||||
time.sleep(delay)
|
||||
self.record.setdefault('release_rechecks', []).append({'attempt': attempt, 'delay_seconds': delay})
|
||||
try:
|
||||
self._close_once(rebuilding=rebuilding, reason='automatic_recheck')
|
||||
except BatchResourceCleanupError:
|
||||
continue
|
||||
self._save()
|
||||
if self._completed_project_after_shutdown():
|
||||
return
|
||||
break
|
||||
self._save()
|
||||
raise
|
||||
finally:
|
||||
self._release_lock.release()
|
||||
|
||||
def _completed_project_after_shutdown(self):
|
||||
shutdown = self.record.get('cad_shutdown') or {}
|
||||
proof = self.record.get('release_proof') or {}
|
||||
return (self.result is not None and getattr(self, '_cad_close_error', None) is None
|
||||
and self._active_evidence is not None and not self._active_attempts
|
||||
and shutdown.get('project_close_policy') == 'saved_only'
|
||||
and proof.get('method') == 'owned_cleanup'
|
||||
and not internal_path(self._active_evidence / 'uncertain.flag').exists()
|
||||
and project_checkpoint_released(self._active_evidence))
|
||||
|
||||
def _close_once(self, *, rebuilding=False, reason=None):
|
||||
if self.desktop is None and not self.generation:
|
||||
return # A cache-only batch never acquired resources.
|
||||
@@ -967,7 +1002,7 @@ class BatchCadRuntime:
|
||||
for event in cleanup.get('desktop_handle_history', ()))):
|
||||
raise BatchResourceCleanupError(str(self._close_failure),
|
||||
completed_result=self.result, cleanup_error=self._close_failure)
|
||||
if (reason == 'resource_recheck'
|
||||
if (reason in {'resource_recheck', 'automatic_recheck'}
|
||||
and self.record.get('release_results', {}).get('desktop_released') is not True
|
||||
and cleanup.get('desktop_handle_closed') is True
|
||||
and not getattr(self.desktop, '_processes', getattr(self.desktop, 'processes', ()))
|
||||
@@ -1102,7 +1137,7 @@ class BatchCadRuntime:
|
||||
pass
|
||||
else:
|
||||
phases['desktop'] = 'isolated'
|
||||
self._save(state='isolated', blocking=False, isolation_proof=proof,
|
||||
self._save(state='isolated', blocking=True, isolation_proof=proof,
|
||||
isolation_warning='; '.join(errors), release_state=phases, wait_reason='')
|
||||
LIVE_RESOURCES.pop(str(self.path), None)
|
||||
if shutdown_errors:
|
||||
@@ -1124,6 +1159,10 @@ class BatchCadRuntime:
|
||||
'cad_pid': self.record['cad_pid'], 'cad_guid': self.record['cad_guid'],
|
||||
'cleanup': self.record['cleanup'], 'released_at': released_at}
|
||||
releases = [*self.record.get('generation_releases', ()), release]
|
||||
shutdown = self.record.get('cad_shutdown') or {}
|
||||
if shutdown.get('forced_termination') and (release['cleanup'] or {}).get('owned_cleanup_complete') is True:
|
||||
proof = isolation_proof(self.record)
|
||||
self.record['release_proof'] = dict(proof, desktop_released=True, method='owned_cleanup')
|
||||
self._save(state='released', blocking=False, released_at=released_at, processes=[], generation_releases=releases,
|
||||
wait_reason='')
|
||||
LIVE_RESOURCES.pop(str(self.path), None)
|
||||
@@ -1153,7 +1192,7 @@ class BatchCadRuntime:
|
||||
self.close(reason='project_failure')
|
||||
except BatchResourceCleanupError as cleanup:
|
||||
from .batch_resources import blocking_resources
|
||||
if (self.record['state'] not in {'released', 'isolated'} or blocking_resources(self.root)
|
||||
if (self.record['state'] != 'released' or blocking_resources(self.root)
|
||||
or not self.owned_processes_exited() or not self._other_writers_exited()):
|
||||
raise
|
||||
cleanup_warning = str(cleanup)
|
||||
|
||||
@@ -0,0 +1,347 @@
|
||||
"""Project a frozen batch scope from its current queue and operation evidence."""
|
||||
from collections import Counter
|
||||
from hashlib import sha256
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
|
||||
from . import batch_resources
|
||||
from .execution_journal import ExecutionJournal, _targets
|
||||
from .path_access import internal_path
|
||||
|
||||
|
||||
_TASK_STATES = ('completed', 'failed', 'blocked', 'skipped', 'already_completed',
|
||||
'pending', 'paused', 'running')
|
||||
_OPERATION_STATES = ('pending', 'prepared', 'running', 'pending_save', 'verified',
|
||||
'no_match', 'failed', 'uncertain', 'restored', 'unknown')
|
||||
|
||||
|
||||
def summarize_batch(manifest, queue, operation_rows, resource_snapshot, *, elapsed_seconds):
|
||||
"""Count engineering entries, jobs and distinct current-round targets."""
|
||||
decisions = {row['task_id']: row for row in manifest['decisions']}
|
||||
entries = {}
|
||||
for task_id in manifest['candidate_task_ids']:
|
||||
decision = decisions[task_id]
|
||||
classification = decision['classification']
|
||||
if classification == 'executable':
|
||||
entry = queue.get('entries', {}).get(task_id, {})
|
||||
state = entry.get('state', 'pending')
|
||||
if state not in _TASK_STATES or state == 'already_completed':
|
||||
state = 'blocked'
|
||||
message = entry.get('message', '')
|
||||
else:
|
||||
state = 'blocked' if classification == 'held' else classification
|
||||
message = decision.get('message') or decision.get('reason') or ''
|
||||
entries[task_id] = {**decision, 'state': state, 'message': message}
|
||||
task_counts = dict.fromkeys(_TASK_STATES, 0)
|
||||
for entry in entries.values():
|
||||
task_counts[entry['state']] += 1
|
||||
|
||||
operation_scope = {key for key, entry in entries.items() if entry['state'] != 'skipped'}
|
||||
effective = {}
|
||||
for row in operation_rows:
|
||||
if (row['task_id'] not in operation_scope or not row.get('current_round', True)
|
||||
or row.get('superseded') or row['state'] == 'superseded'):
|
||||
continue
|
||||
key = (row['task_id'], row['round_id'], row['operation_key'])
|
||||
previous = effective.get(key)
|
||||
if previous is None or row['generation'] >= previous['generation']:
|
||||
effective[key] = row
|
||||
|
||||
job_counts = Counter()
|
||||
unknown_targets = set(queue.get('operation_evidence_missing', ())) & operation_scope
|
||||
targets = {}
|
||||
unsafe = {row['task_id'] for row in effective.values()
|
||||
if row['state'] in {'pending', 'prepared', 'running', 'pending_save', 'uncertain'}}
|
||||
batch_retry_blocked = (bool(task_counts['blocked'] or queue.get('operation_evidence_missing')
|
||||
or manifest.get('global_blockers'))
|
||||
or any(row['state'] in {'prepared', 'running', 'pending_save', 'uncertain', 'unknown'}
|
||||
for row in effective.values()))
|
||||
for row in effective.values():
|
||||
state = row['state'] if row['state'] in _OPERATION_STATES else 'unknown'
|
||||
job_counts[state] += 1
|
||||
if row.get('target_keys') is None:
|
||||
unknown_targets.add(row['task_id'])
|
||||
continue
|
||||
for target in row['target_keys']:
|
||||
key = (row['task_id'], row['round_id'], target)
|
||||
# A verified commit survives a later failed attempt or reporting error.
|
||||
precedence = (state == 'verified', row['generation'])
|
||||
if key not in targets or precedence >= targets[key][0]:
|
||||
targets[key] = (precedence, state)
|
||||
|
||||
counts = Counter(state for _, state in targets.values())
|
||||
targets_by_task = Counter(key[0] for key in targets)
|
||||
jobs_by_task = Counter(row['task_id'] for row in effective.values())
|
||||
for task_id in operation_scope:
|
||||
planned = decisions[task_id].get('target_count')
|
||||
known = targets_by_task[task_id]
|
||||
if type(planned) is int and planned >= known:
|
||||
counts['pending'] += planned - known
|
||||
elif not jobs_by_task[task_id]:
|
||||
unknown_targets.add(task_id)
|
||||
operation_counts = {state: counts[state] for state in _OPERATION_STATES}
|
||||
operation_counts['saved'] = operation_counts['verified']
|
||||
failures = [{**{key: row[key] for key in ('task_id', 'round_id', 'operation_key', 'generation', 'state')},
|
||||
'code': row['code'], 'message': row.get('message') or ''}
|
||||
for row in effective.values()
|
||||
if row['state'] in {'failed', 'uncertain', 'pending_save', 'prepared'} and row.get('code')]
|
||||
|
||||
retry = [
|
||||
{key: row[key] for key in ('task_id', 'round_id', 'operation_key', 'generation')}
|
||||
for row in effective.values()
|
||||
if not batch_retry_blocked and row['state'] == 'failed' and row.get('can_retry') and row['task_id'] not in unsafe
|
||||
and row.get('target_keys')
|
||||
and all(targets[(row['task_id'], row['round_id'], target)][1] == 'failed'
|
||||
for target in row['target_keys'])
|
||||
]
|
||||
if task_counts['blocked'] or any(job_counts[state] for state in ('prepared', 'pending_save', 'uncertain')):
|
||||
execution_status = 'blocked'
|
||||
elif task_counts['paused'] or queue.get('paused'):
|
||||
execution_status = 'paused'
|
||||
elif task_counts['running']:
|
||||
execution_status = 'running'
|
||||
elif task_counts['pending']:
|
||||
execution_status = 'pending'
|
||||
elif task_counts['failed']:
|
||||
execution_status = 'failed'
|
||||
else:
|
||||
execution_status = 'completed'
|
||||
execution_status = queue.get('execution_status') or execution_status
|
||||
if execution_status == 'completed' and any(job_counts[state] for state in ('prepared', 'pending_save', 'uncertain')):
|
||||
execution_status = 'blocked'
|
||||
resource_state = resource_snapshot.get('state')
|
||||
if resource_state not in {'released', 'pending', 'isolated'}:
|
||||
resource_state = 'unknown'
|
||||
acceptance = queue.get('acceptance') or {'status': 'not_required'}
|
||||
status = execution_status
|
||||
if execution_status == 'completed':
|
||||
if acceptance['status'] not in {'verified', 'not_required'}:
|
||||
status = 'failed'
|
||||
elif resource_state != 'released' or queue.get('snapshot_unstable') or queue.get('operation_evidence_missing'):
|
||||
status = 'paused'
|
||||
return {'status': status, 'execution_status': execution_status,
|
||||
'resource_state': resource_state, 'resource': resource_snapshot,
|
||||
'acceptance_status': acceptance['status'], 'acceptance': acceptance,
|
||||
'candidate_count': len(entries), 'entries': list(entries.values()), 'task_counts': task_counts,
|
||||
'operation_job_count': len(effective), 'operation_job_counts': dict(job_counts),
|
||||
'operation_total': None if unknown_targets else sum(counts.values()),
|
||||
'operation_counts': operation_counts, 'operation_evidence_missing': sorted(unknown_targets),
|
||||
'failure_code_counts': dict(Counter(row['code'] for row in failures)),
|
||||
'operation_failures': failures,
|
||||
'retry_selection': retry, 'elapsed_seconds': elapsed_seconds}
|
||||
|
||||
|
||||
def _digest(value):
|
||||
return sha256(json.dumps(value, ensure_ascii=False, sort_keys=True).encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def _operation_sources(service, task_ids):
|
||||
rows, versions, missing = [], {}, []
|
||||
for task_id in task_ids:
|
||||
try:
|
||||
store = service.for_project_task(task_id)._store
|
||||
with store._lock:
|
||||
round_row = store._connection.execute(
|
||||
'SELECT * FROM execution_rounds WHERE task_id=?', (task_id,)).fetchone()
|
||||
if not round_row:
|
||||
versions[task_id] = {'round_id': None}
|
||||
continue
|
||||
round_id = round_row['round_id']
|
||||
raw_rows = [dict(row) for row in store._connection.execute('''SELECT o.*,
|
||||
p.classification, p.auto_retries, p.state AS problem_state, p.code, p.message
|
||||
FROM execution_operations o LEFT JOIN execution_problems p
|
||||
ON p.task_id=o.task_id AND p.round_id=o.round_id AND p.operation_key=o.operation_key
|
||||
WHERE o.task_id=? AND o.round_id=? ORDER BY o.operation_key''', (task_id, round_id))]
|
||||
commits = [dict(row) for row in store._connection.execute('''SELECT * FROM execution_project_commits
|
||||
WHERE task_id=? AND round_id=? ORDER BY session_token''', (task_id, round_id))]
|
||||
task_rows = []
|
||||
for row in raw_rows:
|
||||
command = json.loads(row['command_json'])
|
||||
if command.get('target_scope') == 'targets':
|
||||
target_keys = _targets(command)
|
||||
elif command.get('execution_unit') == 'inventory_empty':
|
||||
target_keys = ()
|
||||
else:
|
||||
target_keys = None
|
||||
can_retry = (row['state'] == 'failed' and row['classification'] == 'retryable' and row['problem_state'] == 'open'
|
||||
and not row['auto_retries'] and command.get('execution_unit') == 'component'
|
||||
and not any(commit['state'] in {'verified', 'pending_save'} for commit in commits))
|
||||
if can_retry:
|
||||
receipt = json.loads(row['receipt_json'] or '{}')
|
||||
can_retry = ExecutionJournal(store).failure_certified(task_id,
|
||||
dict(command, task_id=task_id, job_id=receipt.get('job_id')))
|
||||
task_rows.append({**row, 'target_keys': target_keys, 'can_retry': can_retry})
|
||||
rows.extend(task_rows)
|
||||
versions[task_id] = {'round_id': round_id, 'digest': _digest([dict(round_row), task_rows, commits])}
|
||||
except (LookupError, TypeError, ValueError, OSError, RuntimeError, sqlite3.Error):
|
||||
versions[task_id] = {'state': 'unknown'}
|
||||
missing.append(task_id)
|
||||
return rows, versions, missing
|
||||
|
||||
|
||||
def _checkpoint_source(root, manifest):
|
||||
queue_id = manifest['run_id']
|
||||
names = [Path(folder) / f'{queue_id}.json' for folder in ('task-queues', 'workspace-queues')]
|
||||
paths = [name for name in names if internal_path(root / name).is_file()]
|
||||
if len(paths) != 1:
|
||||
return {}, None, None, 'checkpoint_unavailable' if paths else None
|
||||
try:
|
||||
raw = internal_path(root / paths[0]).read_bytes()
|
||||
value = json.loads(raw)
|
||||
scope = manifest['runnable_task_ids']
|
||||
if (value['task_ids'] != scope or value['plan_hashes'] != manifest['plan_hashes']
|
||||
or set(value['entries']) != set(scope)):
|
||||
raise ValueError('checkpoint scope changed')
|
||||
return value, sha256(raw).hexdigest(), paths[0].as_posix(), None
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
return {}, None, None, 'checkpoint_unavailable'
|
||||
|
||||
|
||||
def _resource_source(root, batch_ids, *, scope, no_dispatch):
|
||||
from .batch_supervisor import pending_supervisors
|
||||
from .supervisor_protocol import valid_journal
|
||||
|
||||
references, generations, states = [], [], []
|
||||
try:
|
||||
related = batch_resources.pending_resources(root)
|
||||
if not batch_ids:
|
||||
states.extend('unknown' if record.get('error') else
|
||||
'isolated' if record.get('state') == 'isolated' else 'pending' for record in related)
|
||||
for batch_id in batch_ids:
|
||||
directory = Path('batch-resources') / batch_id
|
||||
for name in ('session.json', 'supervisor.json', 'result.json', 'request.json'):
|
||||
path = directory / name
|
||||
if internal_path(root / path).is_file():
|
||||
references.append(path.as_posix())
|
||||
record_path = internal_path(root / directory / 'session.json')
|
||||
supervisor_path = internal_path(root / directory / 'supervisor.json')
|
||||
try:
|
||||
record = json.loads(record_path.read_bytes())
|
||||
supervisor = json.loads(supervisor_path.read_bytes())
|
||||
if (not batch_resources._valid_record(record, record_path)
|
||||
or not valid_journal(supervisor, batch_id)):
|
||||
raise ValueError('resource record scope changed')
|
||||
tasks = supervisor['task_ids']
|
||||
if not ((supervisor['operation'] == 'execute_task_queue' and tasks == scope)
|
||||
or (supervisor['operation'] == 'execute_quick_run_queue'
|
||||
and len(tasks) == 1 and tasks[0] in scope)):
|
||||
raise ValueError('resource record scope changed')
|
||||
matching = [item for item in related if item.get('session_id') == batch_id
|
||||
or f'/{batch_id}/' in item.get('record_path', '').replace('\\', '/')]
|
||||
states.extend('unknown' if item.get('error') else
|
||||
'isolated' if item.get('state') == 'isolated' else 'pending' for item in matching)
|
||||
for item in matching:
|
||||
name = Path(item['record_path']).name
|
||||
if name.startswith('isolated-generation-'):
|
||||
references.append((directory / name).as_posix())
|
||||
generations.extend({'session_id': batch_id, 'generation': release['generation'],
|
||||
'state': 'released', 'reason': release.get('reason')}
|
||||
for release in record.get('generation_releases', ())
|
||||
if release['generation'] != record['generation'])
|
||||
declared = record['state']
|
||||
if not matching:
|
||||
if declared == 'released' and batch_resources._released_evidence(record):
|
||||
states.append('released')
|
||||
else:
|
||||
states.append('unknown')
|
||||
generations.append({'session_id': batch_id, 'generation': record['generation'],
|
||||
'state': declared, 'supervisor_status': supervisor.get('outcome'),
|
||||
'stopping_reason': supervisor.get('stopping_reason') or record.get('stopping_reason'),
|
||||
'stop_requested_at': supervisor.get('stop_requested_at'),
|
||||
'business_idle_timeout_seconds': supervisor.get('business_idle_timeout_seconds'),
|
||||
'worker_idle_timeout_seconds': supervisor.get('worker_idle_timeout_seconds'),
|
||||
'worker_failure_completion_grace_seconds': supervisor.get('worker_failure_completion_grace_seconds'),
|
||||
'record_digest': _digest(record),
|
||||
'supervisor_digest': _digest(supervisor)})
|
||||
except (OSError, ValueError, TypeError, KeyError, AttributeError):
|
||||
states.append('unknown')
|
||||
for item in pending_supervisors(root):
|
||||
if not batch_ids or item.get('batch_id') in batch_ids:
|
||||
states.append('unknown' if item.get('error') else 'pending')
|
||||
except (OSError, ValueError, TypeError, KeyError, RuntimeError):
|
||||
states.append('unknown')
|
||||
state = next((state for state in ('unknown', 'isolated', 'pending') if state in states),
|
||||
'released' if states or no_dispatch else 'unknown')
|
||||
return {'state': state, 'generations': generations, 'evidence': references}
|
||||
|
||||
|
||||
def collect_batch_summary(service, root, manifest, receipt, *, batch_ids, elapsed_seconds, no_dispatch=False):
|
||||
"""Read versioned sources twice and retry once when writes overlap the read."""
|
||||
from .netlist_verification import verification_summary
|
||||
|
||||
decisions = manifest['decisions']
|
||||
task_ids = [row['task_id'] for row in decisions if row['classification'] != 'skipped']
|
||||
|
||||
def sources():
|
||||
rows, rounds, missing = _operation_sources(service, task_ids)
|
||||
checkpoint, checkpoint_digest, path, error = _checkpoint_source(root, manifest)
|
||||
resource = _resource_source(root, batch_ids, scope=manifest['runnable_task_ids'], no_dispatch=no_dispatch)
|
||||
return rows, missing, checkpoint, resource, path, error, {
|
||||
'rounds': rounds, 'checkpoint_digest': checkpoint_digest, 'resource_digest': _digest(resource)}
|
||||
|
||||
first = sources()
|
||||
current = sources()
|
||||
if first[6] != current[6]:
|
||||
first, current = current, sources()
|
||||
unstable = first[6] != current[6]
|
||||
rows, missing, checkpoint, resource, path, error, versions = current
|
||||
if unstable:
|
||||
rows, missing, resource = [], task_ids, {**resource, 'state': 'unknown'}
|
||||
entries = {row['task_id']: row for row in receipt.get('entries', [])}
|
||||
entries.update(checkpoint.get('entries', {}))
|
||||
execution_status = receipt.get('execution_status') or receipt.get('status')
|
||||
netlist = receipt.get('netlist_verification') or checkpoint.get('netlist_verification') or {}
|
||||
required = {row['task_id'] for row in receipt.get('tasks', ()) if row.get('saved_items')}
|
||||
required.update(row['task_id'] for row in rows if row['state'] == 'verified'
|
||||
and row['task_id'] in manifest['runnable_task_ids'])
|
||||
acceptance = verification_summary(netlist, required_task_ids=required)
|
||||
summary = summarize_batch(manifest, {'entries': entries, 'paused': receipt.get('paused'),
|
||||
'acceptance': acceptance, 'execution_status': execution_status, 'snapshot_unstable': unstable,
|
||||
'operation_evidence_missing': missing}, rows, resource, elapsed_seconds=elapsed_seconds)
|
||||
reporting_errors = list(receipt.get('reporting_errors', ()))
|
||||
if error or unstable:
|
||||
reporting_errors.append({'code': 'batch_snapshot_unstable' if unstable else error})
|
||||
stop_reason = receipt.get('code') or receipt.get('stop_reason')
|
||||
if stop_reason == 'batch_resources_pending' and summary['execution_status'] in {'completed', 'failed'}:
|
||||
stop_reason = 'resource_pending' if summary['resource_state'] != 'released' else None
|
||||
if not stop_reason and receipt.get('user_pause_requested'):
|
||||
stop_reason = 'user_pause'
|
||||
if not stop_reason and summary['status'] in {'paused', 'blocked'}:
|
||||
stopping = [row for row in resource['generations'] if row.get('stopping_reason')]
|
||||
if stopping:
|
||||
stop_reason = max(stopping, key=lambda row: row.get('stop_requested_at') or 0)['stopping_reason']
|
||||
if not stop_reason and summary['status'] in {'paused', 'blocked'}:
|
||||
stop_reason = ('save_unverified' if summary['operation_job_counts'].get('pending_save')
|
||||
or summary['operation_job_counts'].get('uncertain')
|
||||
or summary['operation_job_counts'].get('prepared') else
|
||||
'resource_pending' if summary['resource_state'] != 'released' else 'queue_paused')
|
||||
return {**summary, 'schema_version': 1, 'manifest_digest': manifest['manifest_digest'],
|
||||
'run_id': manifest['run_id'], 'queue_id': receipt.get('queue_id') or manifest['run_id'],
|
||||
'stop_reason': stop_reason,
|
||||
'resource_batch_ids': list(batch_ids), 'reporting_errors': reporting_errors,
|
||||
'netlist_verification': netlist, 'source_versions': versions,
|
||||
'evidence': {'queue_checkpoint': path, 'resource_records': resource['evidence'],
|
||||
'manifest': f"batch-runs/{manifest['run_id']}/manifest.json"}}
|
||||
|
||||
|
||||
def refresh_batch_resources(root, manifest, summary):
|
||||
"""Reconcile resource closure while keeping the durable business snapshot."""
|
||||
batch_ids = summary['resource_batch_ids']
|
||||
if summary['resource_state'] == 'released' or not batch_ids:
|
||||
return summary
|
||||
resource = _resource_source(root, batch_ids, scope=manifest['runnable_task_ids'], no_dispatch=False)
|
||||
if resource['state'] != 'released':
|
||||
return summary
|
||||
status = summary['status']
|
||||
stop_reason = summary['stop_reason']
|
||||
source_unavailable = (any(row.get('state') == 'unknown' for row in summary['source_versions']['rounds'].values())
|
||||
or any(row.get('code') == 'batch_snapshot_unstable' for row in summary['reporting_errors']))
|
||||
if (summary['execution_status'] == 'completed' and summary['acceptance_status'] in {'verified', 'not_required'}
|
||||
and stop_reason == 'resource_pending' and not source_unavailable):
|
||||
status = 'completed'
|
||||
if stop_reason == 'resource_pending':
|
||||
stop_reason = None
|
||||
return {**summary, 'status': status, 'stop_reason': stop_reason, 'resource_state': 'released', 'resource': resource,
|
||||
'source_versions': {**summary['source_versions'], 'resource_digest': _digest(resource)},
|
||||
'evidence': {**summary['evidence'], 'resource_records': resource['evidence']}}
|
||||
@@ -31,12 +31,25 @@ class BusinessProgressWatch:
|
||||
self.last_progress = started
|
||||
self.idle_timeout = idle_timeout
|
||||
self.signatures = {}
|
||||
self.stage_progress = {}
|
||||
self.worker_stop_requested = False
|
||||
self.stop_requested = False
|
||||
|
||||
def observe(self, kind, payload, now):
|
||||
if kind == 'heartbeat':
|
||||
return
|
||||
if kind == 'state':
|
||||
payload = {key: payload.get(key) for key in ('phase', 'queue', 'batch', 'business_progress', 'active_project')}
|
||||
progress = payload.get('business_progress') or {}
|
||||
self.worker_stop_requested = bool(progress.get('stop_requested') or payload.get('stopping_reason'))
|
||||
payload = {key: payload.get(key) for key in ('phase', 'queue', 'active_project')}
|
||||
payload['business_progress'] = {key: progress.get(key) for key in ('job_id', 'stage')}
|
||||
stage = json.dumps(payload, ensure_ascii=True, sort_keys=True, default=str)
|
||||
done = progress.get('done')
|
||||
done = done if type(done) is int else -1
|
||||
if stage not in self.stage_progress or done > self.stage_progress[stage]:
|
||||
self.stage_progress[stage] = done
|
||||
self.last_progress = now
|
||||
return
|
||||
if kind not in {'state', 'progress', 'phase'}:
|
||||
return
|
||||
signature = json.dumps([kind, payload], ensure_ascii=True, sort_keys=True, default=str)
|
||||
@@ -47,10 +60,17 @@ class BusinessProgressWatch:
|
||||
def stalled(self, now):
|
||||
return now - self.last_progress >= self.idle_timeout
|
||||
|
||||
def request_cooperative_stop(self, now, publish):
|
||||
if self.stop_requested or self.worker_stop_requested or not self.stalled(now):
|
||||
return False
|
||||
publish('inactivity')
|
||||
self.stop_requested = True
|
||||
return True
|
||||
|
||||
|
||||
def request_manual_dialog_action(root, binding, dialog, button_hwnd):
|
||||
"""Publish one explicit UI choice for the current supervisor generation."""
|
||||
from .batch_resources import write_record, _valid_record, _process_gone
|
||||
from .batch_resources import write_record, _valid_record, observe_process_identity
|
||||
from uuid import UUID
|
||||
batch_id, attempt_id = binding['batch_id'], binding['attempt_id']
|
||||
if UUID(batch_id).hex != batch_id or UUID(attempt_id).hex != attempt_id:
|
||||
@@ -60,7 +80,8 @@ def request_manual_dialog_action(root, binding, dialog, button_hwnd):
|
||||
resource = json.loads(internal_path(directory / 'session.json').read_text(encoding='utf-8'))
|
||||
if (not valid_journal(journal, batch_id) or journal['attempt_id'] != attempt_id
|
||||
or journal['state'] not in {'running', 'blocked'} or not journal.get('process')
|
||||
or _process_gone(journal['process']) or not _valid_record(resource, directory / 'session.json')
|
||||
or observe_process_identity(journal['process'])['state'] != 'alive'
|
||||
or not _valid_record(resource, directory / 'session.json')
|
||||
or binding.get('generation') != resource['generation'] or not binding.get('session_token')
|
||||
or binding['session_token'] != resource.get('cad_token')
|
||||
or dialog.get('pid') != resource.get('cad_pid') or type(button_hwnd) is not int):
|
||||
@@ -275,7 +296,7 @@ def mutation_lease(root):
|
||||
|
||||
|
||||
def pending_supervisors(root):
|
||||
from .batch_resources import _process_gone
|
||||
from .batch_resources import observe_process_identity
|
||||
from .read_recovery import process_tree_exited
|
||||
pending = []
|
||||
for path in (internal_path(root) / 'batch-resources').glob('*/supervisor.json'):
|
||||
@@ -289,15 +310,15 @@ def pending_supervisors(root):
|
||||
pending.append(dict(value, record_path=str(canonical_path(path)), state='blocked'))
|
||||
continue
|
||||
identity = value.get('process') or value.get('parent_process')
|
||||
observation = observe_process_identity(identity)
|
||||
if value.get('state') == 'finished':
|
||||
if value.get('process') is None or _process_gone(value['process']):
|
||||
if value.get('process') is None or observation['state'] == 'gone':
|
||||
continue
|
||||
pending.append(dict(value, record_path=str(canonical_path(path)), state='blocked'))
|
||||
elif (value.get('state') in {'starting', 'running'} and observation['state'] == 'alive'
|
||||
and observe_process_identity(value.get('parent_process'))['state'] == 'alive'):
|
||||
continue
|
||||
if (value.get('state') in {'starting', 'running'} and identity and not _process_gone(identity)
|
||||
and value.get('parent_process') and not _process_gone(value['parent_process'])):
|
||||
continue
|
||||
pending.append(dict(value, record_path=str(canonical_path(path)), state='blocked'))
|
||||
pending.append(dict(value, record_path=str(canonical_path(path)), state='blocked',
|
||||
process_observation=observation))
|
||||
except (OSError, ValueError, TypeError, KeyError) as error:
|
||||
pending.append({'state': 'blocked', 'record_path': str(canonical_path(path)), 'error': str(error)})
|
||||
return tuple(pending)
|
||||
@@ -314,7 +335,9 @@ def reconcile_supervisors(root):
|
||||
if owner is not None and not process_tree_exited(owner[1]):
|
||||
continue
|
||||
identity = record.get('process')
|
||||
if not record.get('batch_id') or (identity and not _process_gone(identity)):
|
||||
if (not record.get('batch_id')
|
||||
or (record.get('process_observation') or {}).get('state') == 'unknown'
|
||||
or (identity and not _process_gone(identity))):
|
||||
continue
|
||||
if record.get('outcome') not in {'interrupted', 'completed_resources_pending'}:
|
||||
_mark_interrupted(root, record, 'Supervisor ended without a reconciled final result')
|
||||
@@ -348,26 +371,29 @@ def _environment():
|
||||
|
||||
def _finish_response(root, journal, response, context):
|
||||
"""A supervisor exit may release its last USER reference. Never repeat work."""
|
||||
from .batch_resources import cleanup_pending_resources, resource_blockers, write_record
|
||||
from .batch_resources import cleanup_pending_resources, _isolation_evidence, write_record
|
||||
from .supervisor_result import validated_outcome, resource_pending_error, application_shutdown_error
|
||||
result, error, primary = validated_outcome(journal['operation'], response)
|
||||
pending = cleanup_pending_resources(root, logging_context=context)
|
||||
related = tuple(item for item in pending if item.get('session_id') == journal['batch_id'] or not item.get('session_id'))
|
||||
blockers = resource_blockers(related)
|
||||
warnings = tuple(item for item in related if item not in blockers)
|
||||
journal['state'] = 'blocked' if blockers else 'finished'
|
||||
journal['outcome'] = ('completed_resources_pending' if blockers and response.get('business_succeeded')
|
||||
isolated = tuple(item for item in related if item.get('state') == 'isolated' and _isolation_evidence(item))
|
||||
writers_exited = len(related) == len(isolated)
|
||||
journal['state'] = 'blocked' if related else 'finished'
|
||||
journal['outcome'] = ('completed_resources_pending' if related and response.get('business_succeeded')
|
||||
else response.get('status', 'interrupted'))
|
||||
journal['resource_recheck'] = {'pending': bool(blockers), 'warnings': list(warnings),
|
||||
'desktop_released': not related, 'owned_writers_exited': not blockers, 'checked_at': time.time()}
|
||||
journal['resource_recheck'] = {'pending': bool(related), 'warnings': list(isolated),
|
||||
'desktop_released': not related, 'owned_writers_exited': writers_exited, 'checked_at': time.time()}
|
||||
write_record(Path(root) / 'batch-resources' / journal['batch_id'] / 'supervisor.json', journal)
|
||||
if blockers:
|
||||
raise resource_pending_error(journal['operation'], result, error, primary)
|
||||
if related:
|
||||
failure = resource_pending_error(journal['operation'], result, error, primary or error)
|
||||
failure.resources_released = False
|
||||
failure.owned_writers_exited = writers_exited
|
||||
failure.resource_warnings = isolated
|
||||
raise failure
|
||||
for failure in (error, primary):
|
||||
if failure is not None:
|
||||
failure.resources_released = not warnings
|
||||
failure.resources_released = True
|
||||
failure.owned_writers_exited = True
|
||||
failure.resource_warnings = warnings
|
||||
resource_path = internal_path(Path(root) / 'batch-resources' / journal['batch_id'] / 'session.json')
|
||||
def preserve_shutdown_failure(detail):
|
||||
try:
|
||||
@@ -378,9 +404,8 @@ def _finish_response(root, journal, response, context):
|
||||
journal['shutdown_record_error'] = str(record_error)
|
||||
def shutdown_failure():
|
||||
failure = application_shutdown_error(result, error, primary)
|
||||
failure.resources_released = not warnings
|
||||
failure.resources_released = True
|
||||
failure.owned_writers_exited = True
|
||||
failure.resource_warnings = warnings
|
||||
return failure
|
||||
try:
|
||||
resource = json.loads(resource_path.read_text(encoding='utf-8'))
|
||||
@@ -416,7 +441,8 @@ def _finish_response(root, journal, response, context):
|
||||
raise TaskCenterError('supervisor_interrupted', '批次监督进程异常退出;未重放任务,请检查已有结果和保护记录。')
|
||||
|
||||
|
||||
def run_supervised(service, operation, arguments, *, stop_event=None, on_progress=None, on_phase=None):
|
||||
def run_supervised(service, operation, arguments, *, stop_event=None, on_progress=None, on_phase=None,
|
||||
revalidate=None):
|
||||
from .batch_resources import write_record, process_identity
|
||||
from .isolated_desktop import _Win32Api
|
||||
from .stop_control import StopControl
|
||||
@@ -438,6 +464,13 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
|
||||
_LIVE_SUPERVISORS.pop(key)
|
||||
if operation != 'cleanup_batch_resources' and pending_supervisors(root):
|
||||
raise TaskCenterError('batch_resources_pending', '上一监督进程尚未完成资源复核,请先重新清理资源。')
|
||||
if operation != 'cleanup_batch_resources':
|
||||
from .batch_resources import guard_pending_resources
|
||||
guard_pending_resources(root)
|
||||
if revalidate is not None:
|
||||
revalidate()
|
||||
if stop_event is not None and stop_event.is_set():
|
||||
raise TaskCenterError('operation_cancelled', '本批操作已取消,未启动监督进程。')
|
||||
batch_id, attempt_id = uuid4().hex, uuid4().hex
|
||||
service._last_supervisor_batch_id = batch_id
|
||||
directory = root / 'batch-resources' / batch_id
|
||||
@@ -475,6 +508,16 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
|
||||
ownership_cleanup_error = None
|
||||
force_accepted = False
|
||||
last_message = None
|
||||
def publish_cancel(reason):
|
||||
nonlocal sent_cancel
|
||||
value = {'version': VERSION, 'batch_id': batch_id, 'attempt_id': attempt_id}
|
||||
if reason == 'inactivity':
|
||||
value['reason'] = reason
|
||||
write_record(directory / 'cancel.json', value)
|
||||
sent_cancel = True
|
||||
journal.update(stop_mode='safe', stopping_reason=reason, stop_requested_at=time.time())
|
||||
write_record(directory / 'supervisor.json', journal)
|
||||
|
||||
def receive():
|
||||
try:
|
||||
while line := process.stdout.readline(1024 * 1024):
|
||||
@@ -518,6 +561,7 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
|
||||
if stalled and not stall_reported:
|
||||
journal['business_stalled'] = True
|
||||
journal['business_stalled_at'] = time.time()
|
||||
journal['business_idle_timeout_seconds'] = business_watch.idle_timeout
|
||||
write_record(directory / 'supervisor.json', journal)
|
||||
service._logging.logger.warning('supervisor_business_stalled batch_id=%s; owned processes retained', batch_id)
|
||||
stall_reported = True
|
||||
@@ -533,16 +577,14 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
|
||||
else:
|
||||
force_accepted = True
|
||||
break
|
||||
if stop_event is not None and stop_event.is_set() and not sent_cancel:
|
||||
if not sent_cancel and process.poll() is None and operation != 'cleanup_batch_resources':
|
||||
try:
|
||||
write_record(directory / 'cancel.json', {'version': VERSION, 'batch_id': batch_id, 'attempt_id': attempt_id})
|
||||
journal.setdefault('stop_mode', 'safe')
|
||||
journal.setdefault('stop_requested_at', time.time())
|
||||
write_record(directory / 'supervisor.json', journal)
|
||||
sent_cancel = True
|
||||
if stop_event is not None and stop_event.is_set():
|
||||
publish_cancel('user_pause')
|
||||
else:
|
||||
business_watch.request_cooperative_stop(time.monotonic(), publish_cancel)
|
||||
except OSError as error:
|
||||
if hasattr(stop_event, 'control_error'):
|
||||
stop_event.control_error = '停止请求尚未成功记录,正在重试:' + str(error)
|
||||
force_control.control_error = '停止请求尚未成功记录,正在重试:' + str(error)
|
||||
try:
|
||||
value = messages.get(timeout=.1)
|
||||
except queue.Empty:
|
||||
@@ -567,6 +609,13 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
|
||||
state = decode(value['payload'])
|
||||
service._supervisor_state = state
|
||||
business_watch.observe('state', state, time.monotonic())
|
||||
worker_progress = state.get('business_progress') or {}
|
||||
if worker_progress.get('idle_timeout_seconds') is not None:
|
||||
journal['worker_idle_timeout_seconds'] = worker_progress['idle_timeout_seconds']
|
||||
journal['worker_failure_completion_grace_seconds'] = worker_progress.get(
|
||||
'failure_completion_grace_seconds')
|
||||
if worker_progress.get('stop_requested') and worker_progress.get('stopping_reason') == 'inactivity':
|
||||
journal.setdefault('stopping_reason', 'inactivity')
|
||||
service._task_queue_feedback = getattr(service, '_workspace_queue_context', None) or state['queue']
|
||||
service._batch_feedback = state['batch']
|
||||
service._supervisor_waiting = bool(state.get('waiting_for_resolution')) or stalled
|
||||
|
||||
@@ -39,7 +39,7 @@ def _output_stream():
|
||||
|
||||
|
||||
def _admit_request(directory, request, request_bytes):
|
||||
from .batch_resources import _process_gone, process_identity
|
||||
from .batch_resources import observe_process_identity, process_identity
|
||||
import win32api
|
||||
deadline = time.monotonic() + 5
|
||||
while True:
|
||||
@@ -49,7 +49,7 @@ def _admit_request(directory, request, request_bytes):
|
||||
or journal.get('state') not in {'starting', 'running'}
|
||||
or journal.get('request_sha256') != hashlib.sha256(request_bytes).hexdigest()
|
||||
or not journal.get('parent_process', {}).get('creation_time')
|
||||
or _process_gone(journal['parent_process'])):
|
||||
or observe_process_identity(journal['parent_process'])['state'] != 'alive'):
|
||||
raise ValueError('Stale or unowned supervisor request')
|
||||
if journal.get('process'):
|
||||
break
|
||||
@@ -183,7 +183,11 @@ def run(request_path):
|
||||
cancel = internal_path(directory / 'cancel.json')
|
||||
if cancel.is_file():
|
||||
value = json.loads(cancel.read_text(encoding='utf-8'))
|
||||
if value == {'version': VERSION, 'batch_id': batch_id, 'attempt_id': attempt_id}:
|
||||
binding = {'version': VERSION, 'batch_id': batch_id, 'attempt_id': attempt_id}
|
||||
if value == binding:
|
||||
stop.set()
|
||||
elif value == dict(binding, reason='inactivity') and not stop.is_set():
|
||||
stop.stopping_reason = 'inactivity'
|
||||
stop.set()
|
||||
consume_manual_dialog_actions(directory, runtime, batch_id, attempt_id)
|
||||
emit('heartbeat')
|
||||
@@ -219,7 +223,7 @@ def run(request_path):
|
||||
def phase(value, message):
|
||||
emit('phase', encode((value, str(message))))
|
||||
if operation == 'cleanup_batch_resources':
|
||||
result = service.cleanup_batch_resources()
|
||||
result = service.cleanup_batch_resources(automatic=arguments.get('automatic') is True)
|
||||
response.update(status='ok', business_succeeded=True, result=encode(result))
|
||||
else:
|
||||
with runtime:
|
||||
@@ -273,7 +277,7 @@ def run(request_path):
|
||||
response['status'] = 'error'
|
||||
response.setdefault('error', encode_error(cleanup_error))
|
||||
if runtime.record.get('state') == 'isolated':
|
||||
response['resource_warning'] = {'state': 'isolated', 'blocking': False,
|
||||
response['resource_warning'] = {'state': 'isolated', 'blocking': True,
|
||||
'desktop': runtime.record['desktop'], 'desktop_released': False,
|
||||
'owned_writers_exited': True}
|
||||
evidence.try_append('worker_closing', status=response.get('status'), business_succeeded=response.get('business_succeeded'))
|
||||
|
||||
@@ -48,6 +48,7 @@ class BomImportReport:
|
||||
source_map_path: Path | None = None
|
||||
passed_preview: BomBatchPreview | None = None
|
||||
deferred: bool = False
|
||||
warnings: tuple[str, ...] = ()
|
||||
|
||||
@property
|
||||
def total_rows(self):
|
||||
|
||||
@@ -77,7 +77,9 @@ def resolution_binding(store, task_id):
|
||||
|
||||
def import_drafts(service, task_id, sources, *, stop_event=None, on_progress=None, on_phase=None, allow_partial=False):
|
||||
"""Persist routed spreadsheet requests without opening CAD or resolving parts."""
|
||||
rows = load_sources(sources, stop_event=stop_event, on_progress=on_progress, allow_partial=allow_partial)
|
||||
warnings = []
|
||||
rows = load_sources(sources, stop_event=stop_event, on_progress=on_progress,
|
||||
allow_partial=allow_partial, warnings=warnings)
|
||||
scope = _scope(service._store, task_id)
|
||||
paths = tuple(project.path for _, project in scope)
|
||||
names = {project.path: task.name for task, project in scope}
|
||||
@@ -93,7 +95,8 @@ def import_drafts(service, task_id, sources, *, stop_event=None, on_progress=Non
|
||||
write_routed_bom(normalized, rows, routes, project_names=names)
|
||||
append_task_event(service._logging, level='INFO', task_id=task_id,
|
||||
operation='import_bom_drafts', message='BOM 表格来源记录已保存,工程位号待核验',
|
||||
details={'source_map_path': str(mapping), 'source_count': len({row.source for row in rows})})
|
||||
details={'source_map_path': str(mapping), 'source_count': len({row.source for row in rows}),
|
||||
'warnings': warnings})
|
||||
try:
|
||||
report = inspect_batch(service, task_id, normalized, stop_event=stop_event, on_progress=on_progress,
|
||||
on_phase=on_phase, spreadsheet_only=True, allow_partial=allow_partial)
|
||||
@@ -110,7 +113,7 @@ def import_drafts(service, task_id, sources, *, stop_event=None, on_progress=Non
|
||||
if report.deferred and result.project_path not in failed_paths:
|
||||
reason = '表格已保存,执行前核验工程位号'
|
||||
annotated.append(replace(result, source_file=str(source.source), source_row=source.excel_row, reason=reason))
|
||||
report = replace(report, rows=tuple(annotated), source_map_path=mapping)
|
||||
report = replace(report, rows=tuple(annotated), source_map_path=mapping, warnings=tuple(warnings))
|
||||
if report.deferred:
|
||||
accepted_sources = tuple(source for result, source in zip(report.rows, rows, strict=True)
|
||||
if result.project_path not in failed_paths)
|
||||
|
||||
@@ -135,6 +135,14 @@ def managed_desktop_disappeared(receipt):
|
||||
backend.unlock(mutex)
|
||||
|
||||
|
||||
def observe_current_desktop_name(name):
|
||||
"""Observe a historical name in this logon without opening a desktop handle."""
|
||||
slot = DesktopSlot()
|
||||
if slot.name != name:
|
||||
return None
|
||||
return managed_desktop_disappeared({'scope': slot.scope, 'name': slot.name})
|
||||
|
||||
|
||||
class DesktopSlot:
|
||||
def __init__(self, *, root=None, context=None, backend=None):
|
||||
self.context = _context() if context is None else context
|
||||
|
||||
@@ -56,6 +56,9 @@ def _scrub_json(value):
|
||||
|
||||
|
||||
def _allowed(parts):
|
||||
if parts[0] == 'batch-runs':
|
||||
return (len(parts) == 3 and bool(re.fullmatch(r'[0-9a-f]{32}', parts[1]))
|
||||
and parts[2] in {'manifest.json', 'batch-receipt.json'})
|
||||
if parts[0] == 'execution-proof' or (len(parts) > 3 and parts[0] == 'tasks' and parts[2] == 'execution-proof'):
|
||||
return (parts[-1] == 'completion.json'
|
||||
or bool(re.fullmatch(r'project-(?:commit|pause)-[a-f0-9]{32}\.tsv', parts[-1]))
|
||||
@@ -74,7 +77,8 @@ def _allowed(parts):
|
||||
if len(parts) == 2 and parts[0] == 'logs':
|
||||
return bool(re.fullmatch(r'[^/]+\.log(?:\.\d+)?', parts[-1]))
|
||||
if len(parts) == 3 and parts[0] == 'batch-resources':
|
||||
return parts[-1] in _BATCH_NAMES or bool(re.fullmatch(r'manual-dialog-[a-f0-9]{32}\.json', parts[-1]))
|
||||
return (parts[-1] in _BATCH_NAMES
|
||||
or bool(re.fullmatch(r'(?:manual-dialog-[a-f0-9]{32}|isolated-generation-\d+)\.json', parts[-1])))
|
||||
if len(parts) >= 5 and parts[0] == 'batch-resources' and parts[2] == 'attempts':
|
||||
return parts[-1].endswith('.json')
|
||||
if len(parts) >= 2 and parts[0] == 'attempts':
|
||||
@@ -119,7 +123,7 @@ def export_diagnostic_bundle(data_root, destination: Path) -> Path:
|
||||
info = entry.lstat()
|
||||
if stat.S_ISLNK(info.st_mode) or getattr(info, 'st_file_attributes', 0) & 0x400:
|
||||
manifest['omissions'].append({'path': _scrub_text(relative), 'reason': 'link_or_reparse_point'})
|
||||
elif base == physical and name not in {'logs', 'batch-resources', 'attempts', 'tasks', 'queue', 'queues', 'task-queues', 'workspace-queues', 'quick-run', 'quick-run-history', 'execution-proof'}:
|
||||
elif base == physical and name not in {'logs', 'batch-runs', 'batch-resources', 'attempts', 'tasks', 'queue', 'queues', 'task-queues', 'workspace-queues', 'quick-run', 'quick-run-history', 'execution-proof'}:
|
||||
manifest['omissions'].append({'path': _scrub_text(relative), 'reason': 'outside_allowlist'})
|
||||
else:
|
||||
safe_folders.append(name)
|
||||
|
||||
@@ -27,3 +27,7 @@ class TaskCenterError(ValueError):
|
||||
def _new_error_id() -> str:
|
||||
date = datetime.now(timezone.utc).strftime("%Y%m%d")
|
||||
return f"DXT-{date}-{secrets.token_hex(4).upper()}"
|
||||
|
||||
|
||||
class ProjectPathError(TaskCenterError):
|
||||
"""An expected filesystem failure while reading or selecting projects."""
|
||||
@@ -8,7 +8,8 @@ from .errors import TaskCenterError
|
||||
RULE_VERSION = 'evidence-prewrite-v2'
|
||||
# Error codes describe causes, never establish absence of a write.
|
||||
TRANSIENT_CODES = frozenset({'cad_attachment_failed', 'worker_timeout_before_write',
|
||||
'worker_error', 'worker_timeout', 'timeout', 'quick_run_failed', 'execution_failed', 'native_failed'})
|
||||
'worker_error', 'worker_timeout', 'timeout', 'lookup_unavailable',
|
||||
'quick_run_failed', 'execution_failed', 'native_failed'})
|
||||
DETERMINISTIC_CODES = frozenset({'target_identity', 'probe_baseline_missing', 'task_not_retryable',
|
||||
'assistant_stale', 'target_cell', 'invalid_target', 'target_not_found'})
|
||||
RESOURCE_UNCERTAIN_CODES = frozenset({'inventory_cleanup', 'quick_run_uncertain',
|
||||
|
||||
@@ -258,7 +258,9 @@ def _stop_and_wait(process):
|
||||
running = process.poll() is None
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
if running:
|
||||
termination_requested = (isinstance(process, _Win32Process)
|
||||
and process.cleanup_record.get('forced_root_termination'))
|
||||
if running and not termination_requested:
|
||||
try:
|
||||
if isinstance(process, _Win32Process):
|
||||
process.terminate(reason='root_process_active')
|
||||
|
||||
@@ -17,7 +17,7 @@ import time
|
||||
import traceback
|
||||
from typing import Any, Mapping
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .errors import ProjectPathError, TaskCenterError
|
||||
from .path_access import internal_path
|
||||
from .retention import rotate_text_log
|
||||
|
||||
@@ -62,15 +62,18 @@ class LoggingContext:
|
||||
reported = error
|
||||
else:
|
||||
reported = TaskCenterError("unhandled_exception", "发生未处理异常")
|
||||
detail = "".join(
|
||||
traceback.format_exception(type(error), error, traceback_object or error.__traceback__)
|
||||
)
|
||||
message = reported.message
|
||||
if not isinstance(error, ProjectPathError):
|
||||
detail = "".join(
|
||||
traceback.format_exception(type(error), error, traceback_object or error.__traceback__)
|
||||
)
|
||||
message += "\n" + detail.rstrip()
|
||||
self.logger.error(
|
||||
"error_id=%s operation=%s message=%s\n%s",
|
||||
"error_id=%s operation=%s code=%s message=%s",
|
||||
reported.error_id,
|
||||
operation,
|
||||
reported.message,
|
||||
detail.rstrip(),
|
||||
reported.code,
|
||||
message,
|
||||
)
|
||||
_flush_handlers(self.logger)
|
||||
return reported
|
||||
|
||||
@@ -19,6 +19,11 @@ import traceback
|
||||
|
||||
|
||||
_SNAPSHOT_REFERENCE_KEYS = ContextVar('snapshot_reference_keys', default={})
|
||||
_DATABOOK_TIMEOUT_EXIT = 4 # QuickPartReplace.vbs status protocol.
|
||||
|
||||
|
||||
class DxDataBookLookupTimeout(TimeoutError):
|
||||
"""The browser could not confirm an exact target during preflight."""
|
||||
|
||||
|
||||
@contextmanager
|
||||
@@ -292,7 +297,8 @@ def wait_for(callback, description, timeout=15):
|
||||
raise TimeoutError(description)
|
||||
|
||||
|
||||
def wait_for_library_rows(callback, target, timeout=30, stable_for=0.45, poll_interval=0.15):
|
||||
def wait_for_library_rows(callback, target, timeout=30, stable_for=0.45, poll_interval=0.15,
|
||||
scope=lambda: None):
|
||||
deadline = time.monotonic() + timeout
|
||||
previous = None
|
||||
stable_since = None
|
||||
@@ -309,7 +315,7 @@ def wait_for_library_rows(callback, target, timeout=30, stable_for=0.45, poll_in
|
||||
previous = stable_since = None
|
||||
time.sleep(poll_interval)
|
||||
continue
|
||||
signature = tuple(tuple(str(value) for value in columns) for _, columns in latest)
|
||||
signature = (scope(), tuple(tuple(str(value) for value in columns) for _, columns in latest))
|
||||
now = time.monotonic()
|
||||
if signature != previous:
|
||||
previous = signature
|
||||
@@ -321,6 +327,106 @@ def wait_for_library_rows(callback, target, timeout=30, stable_for=0.45, poll_in
|
||||
raise TimeoutError(f"Native DxDataBook did not finish loading target part: {target}")
|
||||
|
||||
|
||||
def load_databook_target(snapshot, report, target, *, controls, browse, filter_part,
|
||||
list_rows, dialogs, close_dialog):
|
||||
"""Load the target before the native submit boundary and retry a prepared batch once."""
|
||||
from .batch_attempt import can_retry_attempt
|
||||
|
||||
diagnostic = report.setdefault('databook', {})
|
||||
loads = diagnostic['loads'] = []
|
||||
baseline = {row['hwnd'] for row in dialogs()}
|
||||
initial = snapshot_attempt(snapshot)
|
||||
warm = controls() is not None
|
||||
for index in range(2):
|
||||
timeout = 20 if warm else 45
|
||||
started = time.monotonic()
|
||||
load = {'mode': 'warm' if warm else 'cold', 'timeout_seconds': timeout,
|
||||
'attempt_state_before_load': initial[1]['state'] if initial else None}
|
||||
loads.append(load)
|
||||
save_report(snapshot, report)
|
||||
pair = None
|
||||
|
||||
def read():
|
||||
nonlocal pair
|
||||
current = controls()
|
||||
if current is None:
|
||||
pair = None
|
||||
return []
|
||||
try:
|
||||
if current != pair:
|
||||
filter_part(current[1])
|
||||
pair = current
|
||||
load.update(list_handle=pair[0], filter_handle=pair[1])
|
||||
return list_rows(pair[0])
|
||||
except Exception as error:
|
||||
if (getattr(error, 'winerror', None) != 1400 # ERROR_INVALID_WINDOW_HANDLE
|
||||
and getattr(error, 'hresult', None) != -2147220991): # UIA_E_ELEMENTNOTAVAILABLE
|
||||
raise
|
||||
pair = None
|
||||
return []
|
||||
|
||||
try:
|
||||
if index == 0 or controls() is None:
|
||||
browse()
|
||||
rows = wait_for_library_rows(read, target, timeout=timeout, scope=lambda: pair)
|
||||
except TimeoutError as error:
|
||||
load['error'] = str(error)
|
||||
load['elapsed_seconds'] = round(time.monotonic() - started, 3)
|
||||
load['dialogs'] = [row for row in dialogs() if row['hwnd'] not in baseline]
|
||||
bound = snapshot_attempt(snapshot)
|
||||
prepared = initial is not None and initial[1]['state'] == 'prepared' and can_retry_attempt(*initial)
|
||||
load['attempt_state'] = bound[1]['state'] if bound else None
|
||||
blockers = [row for row in load['dialogs'] if not row.get('browser')]
|
||||
candidates = [row for row in blockers if row['dismissible']]
|
||||
retry = index == 0 and prepared and bool(os.environ.get('DXPART_DESKTOP'))
|
||||
# A different modal must get its normal operator handling.
|
||||
retry = retry and (not blockers or len(blockers) == len(candidates) == 1)
|
||||
load['retry'] = retry
|
||||
save_report(snapshot, report)
|
||||
if not retry:
|
||||
raise DxDataBookLookupTimeout(str(error)) from error
|
||||
if candidates:
|
||||
close_dialog(candidates[0])
|
||||
load['closed_dialog'] = candidates[0]['hwnd']
|
||||
warm = True
|
||||
else:
|
||||
load['elapsed_seconds'] = round(time.monotonic() - started, 3)
|
||||
return pair[0], rows
|
||||
|
||||
|
||||
def databook_dialogs(gui, process, pid, replacement, main_handle):
|
||||
from .cad_dialogs import _text
|
||||
|
||||
replacement_thread, _ = process.GetWindowThreadProcessId(replacement)
|
||||
rows = []
|
||||
|
||||
def dialog(handle, _):
|
||||
if (handle in {replacement, main_handle} or not gui.IsWindowVisible(handle)
|
||||
or process.GetWindowThreadProcessId(handle)[1] != pid
|
||||
or gui.GetClassName(handle) != '#32770'):
|
||||
return
|
||||
owner = gui.GetWindow(handle, 4) # GW_OWNER
|
||||
row = {'hwnd': handle, 'owner': owner, 'pid': pid, 'title': '', 'children': [],
|
||||
'browser': False, 'dismissible': False}
|
||||
rows.append(row)
|
||||
children = []
|
||||
try:
|
||||
row['title'] = _text(handle)
|
||||
gui.EnumChildWindows(handle, lambda child, _: children.append(child), None)
|
||||
row['children'] = [{'hwnd': child, 'parent': gui.GetParent(child), 'class': gui.GetClassName(child),
|
||||
'id': gui.GetDlgCtrlID(child)} for child in children[:64]]
|
||||
row['browser'] = {('SysListView32', 4000), ('Edit', 4006)} <= {
|
||||
(child['class'], child['id']) for child in row['children']}
|
||||
row['dismissible'] = (not row['title'].strip() and not children and owner == replacement
|
||||
and process.GetWindowThreadProcessId(handle)[0] == replacement_thread
|
||||
and not gui.IsWindowEnabled(replacement))
|
||||
except (OSError, gui.error) as error:
|
||||
row['read_error'] = str(error)
|
||||
|
||||
gui.EnumWindows(dialog, None)
|
||||
return rows
|
||||
|
||||
|
||||
def target_symbol_matches(displayed, library_symbol, slot_count):
|
||||
actual = str(displayed).casefold()
|
||||
expected = str(library_symbol).casefold()
|
||||
@@ -848,8 +954,8 @@ def run_native(snapshot, report):
|
||||
raise ValueError("Multiple replacement dialogs")
|
||||
return matches[0] if matches else None
|
||||
|
||||
def message(handle, code, wparam=0, lparam=0):
|
||||
return win32gui.SendMessageTimeout(handle, code, wparam, lparam, win32con.SMTO_ABORTIFHUNG, 15000)
|
||||
def message(handle, code, wparam=0, lparam=0, *, timeout=15000):
|
||||
return win32gui.SendMessageTimeout(handle, code, wparam, lparam, win32con.SMTO_ABORTIFHUNG, timeout)
|
||||
|
||||
def control_text(control):
|
||||
buffer = ctypes.create_unicode_buffer(2048)
|
||||
@@ -865,9 +971,9 @@ def run_native(snapshot, report):
|
||||
control = dlg_item(dialog, identifier)
|
||||
if not control:
|
||||
raise ValueError(f"Required native option {identifier} is unavailable")
|
||||
if win32gui.SendMessage(control, 0x00F0, 0, 0) != 1:
|
||||
if message(control, 0x00F0)[1] != 1:
|
||||
click(control)
|
||||
if win32gui.SendMessage(control, 0x00F0, 0, 0) != 1:
|
||||
if message(control, 0x00F0)[1] != 1:
|
||||
raise ValueError(f"Native option {identifier} was not enabled")
|
||||
report.setdefault("native_options", {})[str(identifier)] = {
|
||||
"text": control_text(control),
|
||||
@@ -896,31 +1002,68 @@ def run_native(snapshot, report):
|
||||
"main_visible_before_browse": bool(win32gui.IsWindowVisible(main_handle)),
|
||||
"browse_button": int(dlg_item(dialog, 1366)),
|
||||
}
|
||||
click(dlg_item(dialog, 1366))
|
||||
|
||||
def part_list():
|
||||
report["databook"]["main_visible_during_wait"] = bool(
|
||||
win32gui.IsWindowVisible(main_handle)
|
||||
)
|
||||
def query_message(handle, code, wparam=0, lparam=0):
|
||||
try:
|
||||
message(handle, code, wparam, lparam, timeout=5000)
|
||||
except win32gui.error as error:
|
||||
if error.winerror == 1460:
|
||||
raise TimeoutError('Native DxDataBook browse or filter did not respond') from error
|
||||
raise
|
||||
|
||||
def browse():
|
||||
button = dlg_item(dialog, 1366)
|
||||
if button and win32gui.IsWindowEnabled(dialog) and win32gui.IsWindowEnabled(button):
|
||||
query_message(button, 0x00F5) # BM_CLICK
|
||||
|
||||
def controls():
|
||||
lists, filters = {}, {}
|
||||
for handle in owned_windows(include_hidden=True):
|
||||
if win32gui.GetClassName(handle) == "SysListView32" and win32gui.GetDlgCtrlID(handle) == 4000:
|
||||
return handle
|
||||
return None
|
||||
list_handle = wait_for(part_list, "Native DxDataBook part list did not open", timeout=30)
|
||||
try:
|
||||
kind = (win32gui.GetClassName(handle), win32gui.GetDlgCtrlID(handle))
|
||||
if kind == ('SysListView32', 4000):
|
||||
lists[handle] = win32gui.GetAncestor(handle, 2)
|
||||
elif kind == ('Edit', 4006):
|
||||
filters[handle] = win32gui.GetAncestor(handle, 2)
|
||||
except win32gui.error:
|
||||
if win32gui.IsWindow(handle):
|
||||
raise
|
||||
pairs = [(part_list, part_filter) for part_list, list_root in lists.items()
|
||||
for part_filter, filter_root in filters.items() if list_root == filter_root]
|
||||
visible = [pair for pair in pairs if all(win32gui.IsWindowVisible(handle) for handle in pair)]
|
||||
pairs = visible or pairs
|
||||
return pairs[0] if len(pairs) == 1 else None
|
||||
|
||||
def filter_part(handle):
|
||||
query_message(handle, win32con.WM_SETTEXT, 0, metadata[3])
|
||||
|
||||
def current_library_rows(list_handle):
|
||||
try:
|
||||
return [(row, [text.window_text() for text in row.children(control_type="Text")])
|
||||
for row in desktop.window(handle=list_handle).descendants(control_type="ListItem")]
|
||||
except Exception:
|
||||
if win32gui.IsWindow(list_handle):
|
||||
raise
|
||||
return []
|
||||
|
||||
def dialogs():
|
||||
return databook_dialogs(win32gui, win32process, process_id, dialog, main_handle)
|
||||
|
||||
def close_dialog(expected):
|
||||
if expected not in dialogs():
|
||||
raise OSError('DxDataBook dialog changed before close')
|
||||
win32gui.PostMessage(expected['hwnd'], win32con.WM_CLOSE, 0, 0)
|
||||
wait_for(lambda: not win32gui.IsWindowVisible(expected['hwnd']),
|
||||
'Native DxDataBook dialog did not close', timeout=3)
|
||||
|
||||
list_handle, rows = load_databook_target(snapshot, report, metadata[3], controls=controls,
|
||||
browse=browse, filter_part=filter_part, list_rows=current_library_rows,
|
||||
dialogs=dialogs, close_dialog=close_dialog)
|
||||
report["databook"].update(
|
||||
list_handle=int(list_handle),
|
||||
list_visible=bool(win32gui.IsWindowVisible(list_handle)),
|
||||
main_visible_after_load=bool(win32gui.IsWindowVisible(main_handle)),
|
||||
)
|
||||
filter_handles = [handle for handle in owned_windows(include_hidden=True)
|
||||
if win32gui.GetDlgCtrlID(handle) == 4006 and win32gui.GetClassName(handle) == "Edit"]
|
||||
if len(filter_handles) != 1:
|
||||
raise ValueError("Cannot uniquely identify native Part Number filter")
|
||||
message(filter_handles[0], win32con.WM_SETTEXT, 0, metadata[3])
|
||||
def current_library_rows():
|
||||
return [(row, [text.window_text() for text in row.children(control_type="Text")])
|
||||
for row in desktop.window(handle=list_handle).descendants(control_type="ListItem")]
|
||||
rows = wait_for_library_rows(current_library_rows, metadata[3])
|
||||
row, columns = exact_target(rows, metadata[3])
|
||||
report["library_row"] = columns
|
||||
symbol_parts = columns[2].split(":", 1)
|
||||
@@ -930,6 +1073,9 @@ def run_native(snapshot, report):
|
||||
report["slot_count"] = slot_count
|
||||
if slot_count < 1:
|
||||
raise ValueError("Library target has no valid slots")
|
||||
current_pair = controls()
|
||||
if current_pair is None or current_pair[0] != list_handle:
|
||||
raise ValueError("DxDataBook controls changed after target selection")
|
||||
rectangle = row.rectangle()
|
||||
list_rectangle = win32gui.GetWindowRect(list_handle)
|
||||
if rectangle.height() <= 0 or rectangle.top < list_rectangle[1] or rectangle.bottom > list_rectangle[3]:
|
||||
@@ -1079,6 +1225,7 @@ def run(snapshot):
|
||||
report.update(snapshot=str(snapshot), ok=False)
|
||||
report.pop("error", None)
|
||||
report.pop("traceback", None)
|
||||
report.pop("code", None)
|
||||
def timeout():
|
||||
report.update(ok=False, error="Native helper timed out; inspect schematic before retrying")
|
||||
save_report(snapshot, report)
|
||||
@@ -1102,6 +1249,9 @@ def run(snapshot):
|
||||
except Exception as error:
|
||||
report["error"] = f"{type(error).__name__}: {error}"
|
||||
report["traceback"] = traceback.format_exc()
|
||||
if isinstance(error, DxDataBookLookupTimeout) and report.get("stage") == "preflight":
|
||||
report["code"] = "lookup_unavailable"
|
||||
return _DATABOOK_TIMEOUT_EXIT
|
||||
return 1
|
||||
finally:
|
||||
watchdog.cancel()
|
||||
|
||||
@@ -6,20 +6,28 @@ import re
|
||||
from .path_access import canonical_path, internal_path
|
||||
|
||||
|
||||
def write_sources(project):
|
||||
def write_sources(project, *, strict=False):
|
||||
project = canonical_path(project)
|
||||
sources = {str(project).casefold()}
|
||||
try:
|
||||
from .native_inventory_protocol import read_native_text
|
||||
text = read_native_text(internal_path(project))
|
||||
match = re.search(r'^\s*KEY\s+iCDBDir\s+"([^"\r\n]+)"', text, re.MULTILINE | re.IGNORECASE)
|
||||
if strict:
|
||||
definitions = re.findall(r'^[ \t]*KEY[ \t]+iCDBDir\b([^\r\n]*)', text,
|
||||
re.MULTILINE | re.IGNORECASE)
|
||||
match = re.fullmatch(r'[ \t]+"([^"\r\n]+)"[ \t]*', definitions[0]) if len(definitions) == 1 else None
|
||||
if not match:
|
||||
raise ValueError('The iCDBDir write source must be declared once')
|
||||
else:
|
||||
match = re.search(r'^\s*KEY\s+iCDBDir\s+"([^"\r\n]+)"', text, re.MULTILINE | re.IGNORECASE)
|
||||
if match:
|
||||
directory = Path(match[1])
|
||||
if not directory.is_absolute():
|
||||
directory = project.parent / directory
|
||||
sources.add(str(canonical_path(directory / 'icdb.dat')).casefold())
|
||||
except (OSError, UnicodeError, ValueError):
|
||||
pass
|
||||
if strict:
|
||||
raise
|
||||
return sources
|
||||
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from contextlib import contextmanager
|
||||
from threading import Event
|
||||
|
||||
import os
|
||||
@@ -10,20 +11,44 @@ from pathlib import Path
|
||||
import stat
|
||||
from uuid import uuid4
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .errors import ProjectPathError, TaskCenterError
|
||||
from .path_access import canonical_path, internal_path, strip_extended_prefix
|
||||
from .models import TaskRecord, TaskStatus
|
||||
from .scanner import _is_schematic_project, _reject_reparse
|
||||
from .store import TaskStore
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _path_errors(path: Path):
|
||||
try:
|
||||
yield
|
||||
except FileNotFoundError as error:
|
||||
raise ProjectPathError(
|
||||
"path_missing", f"找不到路径「{path}」。请确认目录或工程是否已移动或删除,然后重新选择并读取。"
|
||||
) from error
|
||||
except PermissionError as error:
|
||||
raise ProjectPathError(
|
||||
"path_denied", f"无法读取路径「{path}」。请检查当前用户的读取权限,然后重试。"
|
||||
) from error
|
||||
except NotADirectoryError as error:
|
||||
raise _not_directory(path) from error
|
||||
|
||||
|
||||
def _not_directory(path: Path) -> ProjectPathError:
|
||||
return ProjectPathError(
|
||||
"path_not_directory", f"路径「{path}」中有一项不是目录。请选择工程目录后重试。"
|
||||
)
|
||||
|
||||
|
||||
def _validated_root(root: Path, excluded_roots: tuple[Path, ...]) -> tuple[Path, tuple[Path, ...]]:
|
||||
root = Path(os.path.abspath(strip_extended_prefix(root)))
|
||||
for ancestor in (*reversed(root.parents), root):
|
||||
_reject_reparse(internal_path(ancestor).lstat(), ancestor)
|
||||
root = canonical_path(root, strict=True)
|
||||
if not internal_path(root).is_dir():
|
||||
raise TaskCenterError("discovery_root", "project root is not a directory")
|
||||
with _path_errors(root):
|
||||
for ancestor in (*reversed(root.parents), root):
|
||||
details = internal_path(ancestor).lstat()
|
||||
_reject_reparse(details, ancestor)
|
||||
if not stat.S_ISDIR(details.st_mode):
|
||||
raise _not_directory(root)
|
||||
root = canonical_path(root, strict=True)
|
||||
excluded = tuple(canonical_path(path) 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")
|
||||
@@ -50,12 +75,13 @@ def scan_project_directory(root: Path, *, excluded_roots: tuple[Path, ...] = (),
|
||||
while pending:
|
||||
check_cancelled()
|
||||
directory = pending.pop()
|
||||
_reject_reparse(internal_path(directory).lstat(), directory)
|
||||
children = []
|
||||
with os.scandir(internal_path(directory)) as entries:
|
||||
for entry in entries:
|
||||
check_cancelled()
|
||||
children.append(entry)
|
||||
with _path_errors(directory):
|
||||
_reject_reparse(internal_path(directory).lstat(), directory)
|
||||
with os.scandir(internal_path(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()):
|
||||
@@ -63,12 +89,13 @@ def scan_project_directory(root: Path, *, excluded_roots: tuple[Path, ...] = (),
|
||||
path = Path(strip_extended_prefix(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(canonical_path(path, strict=True))
|
||||
with _path_errors(path):
|
||||
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(canonical_path(path, strict=True))
|
||||
found.extend(projects)
|
||||
visited += 1
|
||||
if on_progress is not None:
|
||||
@@ -84,35 +111,41 @@ def _validate_selected(root: Path, selected_paths: tuple[Path, ...], excluded: t
|
||||
ancestor_projects: dict[Path, bool] = {}
|
||||
for candidate in selected_paths:
|
||||
path = Path(os.path.abspath(strip_extended_prefix(candidate)))
|
||||
if not path.is_relative_to(root) or any(path.is_relative_to(blocked) for blocked in excluded):
|
||||
if path == root or not path.is_relative_to(root) or any(path.is_relative_to(blocked) for blocked in excluded):
|
||||
raise TaskCenterError("project_selection", "selected project is outside discovery results")
|
||||
relative = path.relative_to(root)
|
||||
cursor = root
|
||||
for part in relative.parts:
|
||||
cursor /= part
|
||||
_reject_reparse(internal_path(cursor).lstat(), cursor)
|
||||
if not internal_path(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")
|
||||
with _path_errors(path):
|
||||
for part in relative.parts:
|
||||
cursor /= part
|
||||
details = internal_path(cursor).lstat()
|
||||
_reject_reparse(details, cursor)
|
||||
if cursor != path and not stat.S_ISDIR(details.st_mode):
|
||||
raise _not_directory(path)
|
||||
if not stat.S_ISREG(details.st_mode) or path.suffix.casefold() != ".prj" or not _is_schematic_project(path):
|
||||
raise TaskCenterError("project_selection", "selected file is not a schematic project")
|
||||
# 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(internal_path(directory)) as entries:
|
||||
with _path_errors(directory), os.scandir(internal_path(directory)) as entries:
|
||||
for entry in entries:
|
||||
sibling = Path(strip_extended_prefix(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
|
||||
with _path_errors(sibling):
|
||||
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(canonical_path(path, strict=True))
|
||||
with _path_errors(path):
|
||||
selected.add(canonical_path(path, strict=True))
|
||||
return tuple(sorted(selected, key=lambda path: str(path).casefold()))
|
||||
|
||||
|
||||
|
||||
@@ -102,6 +102,14 @@ def _default_path_opener(path: Path) -> None:
|
||||
class TaskCenterService:
|
||||
"""The only API used by UI workers and widgets."""
|
||||
|
||||
@property
|
||||
def verification(self):
|
||||
with self._store._lock:
|
||||
if not hasattr(self, '_verification_service'):
|
||||
from .verification.service import VerificationService
|
||||
self._verification_service = VerificationService(self._store, self._logging.root)
|
||||
return self._verification_service
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
store: TaskStore,
|
||||
@@ -237,7 +245,8 @@ class TaskCenterService:
|
||||
on_phase(BomImportPhase.READING, message)
|
||||
if on_progress is not None:
|
||||
on_progress(message)
|
||||
rows = load_sources(sources, stop_event=stop_event, on_progress=on_progress,
|
||||
warnings = []
|
||||
rows = load_sources(sources, stop_event=stop_event, on_progress=on_progress, warnings=warnings,
|
||||
**({'allow_partial': True} if allow_partial else {}))
|
||||
scope = _scope(self._store, task_id)
|
||||
paths = tuple(project.path for _, project in scope)
|
||||
@@ -270,7 +279,7 @@ class TaskCenterService:
|
||||
reason = '位号在 BOM 中重复(' + ';'.join(locations) + ')'
|
||||
annotated.append(replace(row, source_file=str(source.source), source_row=source.excel_row,
|
||||
reason=reason + f';来源:{source.source} 第 {source.excel_row} 行'))
|
||||
annotated_report = replace(report, rows=tuple(annotated), source_map_path=mapping)
|
||||
annotated_report = replace(report, rows=tuple(annotated), source_map_path=mapping, warnings=tuple(warnings))
|
||||
return bind_source_report(annotated_report,
|
||||
tuple(dict.fromkeys((str(row.source), row.source_sha256) for row in rows)), mapping)
|
||||
|
||||
@@ -282,7 +291,8 @@ class TaskCenterService:
|
||||
write_routed_bom(normalized, rows, routes, project_names=names)
|
||||
append_task_event(self._logging, level='INFO', task_id=task_id,
|
||||
operation='preview_bom_sources', message='BOM 导入来源记录已保存',
|
||||
details={'source_map_path': str(mapping), 'source_count': len({row.source for row in rows})})
|
||||
details={'source_map_path': str(mapping), 'source_count': len({row.source for row in rows}),
|
||||
'warnings': warnings})
|
||||
report = inspect_batch(self, task_id, normalized, stop_event=stop_event,
|
||||
on_progress=on_progress, on_phase=inspection_phase, runtime=runtime,
|
||||
**({'allow_partial': True} if allow_partial else {}))
|
||||
@@ -871,30 +881,34 @@ class TaskCenterService:
|
||||
continue_after_backup_failure: bool = False,
|
||||
reuse_project_session: bool = True,
|
||||
runtime=None,
|
||||
revalidate=None,
|
||||
):
|
||||
if runtime is None and self._supervised:
|
||||
return self._supervise('execute_quick_run_queue', {'task_id': task_id, 'expected_item': expected_item,
|
||||
'continue_after_backup_failure': continue_after_backup_failure,
|
||||
'reuse_project_session': reuse_project_session}, stop_event=stop_event)
|
||||
'reuse_project_session': reuse_project_session}, stop_event=stop_event,
|
||||
**({'revalidate': revalidate} if revalidate is not None else {}))
|
||||
if runtime is None:
|
||||
from .batch_runtime import BatchCadRuntime
|
||||
with BatchCadRuntime(self._logging.root, 'quick_run_queue', stop_event) as owned_runtime:
|
||||
owned_runtime.bind_logs(self._logging, (task_id,))
|
||||
result = self.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, runtime=owned_runtime)
|
||||
reuse_project_session=reuse_project_session, runtime=owned_runtime, revalidate=revalidate)
|
||||
owned_runtime.result = result
|
||||
return result
|
||||
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, runtime=runtime)
|
||||
reuse_project_session=reuse_project_session, runtime=runtime, revalidate=revalidate)
|
||||
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 revalidate is not None:
|
||||
revalidate()
|
||||
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}:
|
||||
@@ -1070,10 +1084,10 @@ class TaskCenterService:
|
||||
return self._operation('force_pending_owned_resources', None,
|
||||
lambda: force_pending_owned_resources(self._logging.root, confirmed=confirmed))
|
||||
|
||||
def cleanup_batch_resources(self):
|
||||
def cleanup_batch_resources(self, *, automatic=False):
|
||||
"""Retry owned-resource release without opening or changing any project."""
|
||||
if self._supervised:
|
||||
result = self._supervise('cleanup_batch_resources', {})
|
||||
self._supervise('cleanup_batch_resources', {'automatic': True} if automatic else {})
|
||||
from .batch_supervisor import reconcile_supervisors
|
||||
reconcile_supervisors(self._logging.root)
|
||||
return self.pending_batch_resources()
|
||||
@@ -1082,7 +1096,7 @@ class TaskCenterService:
|
||||
assert_task_queue_idle(self._logging.root)
|
||||
with _quick_run_lease(self._logging.root):
|
||||
return self._operation('cleanup_batch_resources', None,
|
||||
lambda: cleanup_pending_resources(self._logging.root, logging_context=self._logging, retry_failed=True))
|
||||
lambda: cleanup_pending_resources(self._logging.root, logging_context=self._logging, retry_failed=not automatic))
|
||||
|
||||
def inspect_bom_batch(self, task_id: str, path: Path, *, stop_event=None, on_progress=None, on_phase=None, runtime=None):
|
||||
if runtime is None and self._supervised:
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Hold a data-root lock while the GUI owns its database and layout."""
|
||||
|
||||
from contextlib import contextmanager
|
||||
import errno
|
||||
import os
|
||||
import time
|
||||
|
||||
from PySide6.QtNetwork import QLocalServer, QLocalSocket
|
||||
|
||||
from .path_access import internal_path
|
||||
from .task_queue import _os_lock
|
||||
|
||||
|
||||
class InstanceUnavailable(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
@contextmanager
|
||||
def gui_instance(data_root):
|
||||
root = internal_path(data_root)
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
# OS locks release on process death. Keep the file so every contender locks the same inode.
|
||||
with (root / '.gui-instance.lock').open('a+b') as handle:
|
||||
identity = os.fstat(handle.fileno())
|
||||
endpoint = f'DxPartReplace-{identity.st_dev:x}-{identity.st_ino:x}'
|
||||
deadline = time.monotonic() + 30
|
||||
while True:
|
||||
try:
|
||||
_os_lock(handle, True)
|
||||
break
|
||||
except OSError as error:
|
||||
if error.errno not in (errno.EACCES, errno.EAGAIN, errno.EDEADLK):
|
||||
raise
|
||||
if _activate(endpoint):
|
||||
yield None
|
||||
return
|
||||
if time.monotonic() >= deadline:
|
||||
raise InstanceUnavailable('此数据目录已在使用,现有窗口暂未响应。')
|
||||
time.sleep(.05)
|
||||
yield endpoint
|
||||
|
||||
|
||||
def _activate(endpoint):
|
||||
socket = QLocalSocket()
|
||||
socket.connectToServer(endpoint)
|
||||
if not socket.waitForConnected(100):
|
||||
return False
|
||||
if os.name == 'nt':
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
|
||||
pid = wintypes.DWORD()
|
||||
get_pipe_pid = ctypes.windll.kernel32.GetNamedPipeServerProcessId
|
||||
get_pipe_pid.argtypes = (wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD))
|
||||
if get_pipe_pid(int(socket.socketDescriptor()), ctypes.byref(pid)):
|
||||
ctypes.windll.user32.AllowSetForegroundWindow(pid.value)
|
||||
socket.write(b'activate\n')
|
||||
socket.flush()
|
||||
return (socket.bytesAvailable() > 0 or socket.waitForReadyRead(1000)) and socket.readAll() == b'1'
|
||||
|
||||
|
||||
def listen_for_activation(endpoint, activate):
|
||||
server = QLocalServer()
|
||||
server.setSocketOptions(QLocalServer.SocketOption.UserAccessOption)
|
||||
if os.name != 'nt':
|
||||
QLocalServer.removeServer(endpoint) # The lock owner can remove a crashed owner's socket.
|
||||
if not server.listen(endpoint):
|
||||
raise RuntimeError(server.errorString())
|
||||
|
||||
def accept():
|
||||
while server.hasPendingConnections():
|
||||
socket = server.nextPendingConnection()
|
||||
|
||||
def respond(socket=socket):
|
||||
if socket.canReadLine() and socket.readLine() == b'activate\n':
|
||||
activate()
|
||||
socket.write(b'1')
|
||||
socket.flush()
|
||||
socket.disconnectFromServer()
|
||||
|
||||
socket.disconnected.connect(socket.deleteLater)
|
||||
socket.readyRead.connect(respond)
|
||||
respond()
|
||||
|
||||
server.newConnection.connect(accept)
|
||||
return server
|
||||
@@ -65,6 +65,8 @@ class StoreSchema:
|
||||
from .execution_journal import create_execution_schema
|
||||
create_history_schema(self._store._connection)
|
||||
create_execution_schema(self._store._connection)
|
||||
from .verification.store import create_schema as create_verification_schema
|
||||
create_verification_schema(self._store._connection)
|
||||
|
||||
def _create_schema_v1(self) -> None:
|
||||
statements = (
|
||||
|
||||
@@ -141,6 +141,18 @@ def _save(path: Path, state: dict) -> None:
|
||||
'task_queue_state', '不能保存任务队列检查点。')
|
||||
|
||||
|
||||
def _uncertainty_root(root, child, task_id):
|
||||
preparer = getattr(child, '_quick_run_preparer', None)
|
||||
return (preparer.data_root if preparer is not None else Path(root) / 'tasks' / task_id) / 'quick-run'
|
||||
|
||||
|
||||
def _task_uncertain(root, child, task_id):
|
||||
from .path_access import internal_path
|
||||
interrupted = getattr(child, 'has_interrupted_quick_run', None)
|
||||
return (bool(interrupted and interrupted(task_id))
|
||||
or internal_path(_uncertainty_root(root, child, task_id) / 'uncertain.flag').exists())
|
||||
|
||||
|
||||
def reconcile_interrupted_queue(root, journal):
|
||||
"""After confirmed supervisor exit, retire only its persisted running entries."""
|
||||
import hashlib
|
||||
@@ -183,10 +195,88 @@ def reconcile_interrupted_queue(root, journal):
|
||||
_save(path, state)
|
||||
|
||||
|
||||
def resource_pause_admitted(root, batch_id, task_ids, plan_hashes, result=None, *, require_released=True):
|
||||
"""Bind a completed supervisor's resource pause to the frozen queue."""
|
||||
from .batch_resources import _process_gone, blocking_resources
|
||||
from .batch_supervisor import pending_supervisors
|
||||
from .path_access import canonical_path, internal_path
|
||||
from .supervisor_protocol import MessageGate, decode, valid_journal
|
||||
|
||||
def token(value):
|
||||
return isinstance(value, str) and len(value) == 32 and all(c in '0123456789abcdef' for c in value)
|
||||
|
||||
if not token(batch_id) or not plan_hashes:
|
||||
return False
|
||||
root = canonical_path(root)
|
||||
directory = internal_path(root / 'batch-resources' / batch_id)
|
||||
try:
|
||||
journal = json.loads((directory / 'supervisor.json').read_bytes())
|
||||
if (not valid_journal(journal, batch_id) or journal['state'] not in {'blocked', 'finished'}
|
||||
or journal['operation'] != 'execute_task_queue' or journal['task_ids'] != list(task_ids)
|
||||
or not journal['process'] or journal.get('business_uncertain') or 'stop_requested_at' in journal
|
||||
or journal.get('stopping_reason')
|
||||
or journal.get('stop_mode') in {'safe', 'forced'} or (directory / 'cancel.json').exists()):
|
||||
return False
|
||||
raw_request = (directory / 'request.json').read_bytes()
|
||||
request = json.loads(raw_request)
|
||||
arguments = decode(request['arguments'])
|
||||
if (hashlib.sha256(raw_request).hexdigest() != journal['request_sha256']
|
||||
or request['batch_id'] != batch_id or request['attempt_id'] != journal['attempt_id']
|
||||
or request['operation'] != journal['operation'] or canonical_path(request['root']) != root
|
||||
or list(arguments['task_ids']) != list(task_ids) or arguments['expected_plan_hashes'] != plan_hashes):
|
||||
return False
|
||||
message = json.loads((directory / 'result.json').read_bytes())
|
||||
if not MessageGate(batch_id, journal['attempt_id']).accept(message) or message['type'] != 'result':
|
||||
return False
|
||||
payload = message['payload']
|
||||
recorded = decode(payload['result'])
|
||||
if (payload['business_succeeded'] is not True or not isinstance(recorded, TaskQueueResult)
|
||||
or result is not None and recorded != result or not recorded.paused
|
||||
or not token(recorded.queue_id) or recorded.current_task_id not in task_ids
|
||||
or (arguments['queue_id'] or arguments['checkpoint_id']) != recorded.queue_id):
|
||||
return False
|
||||
result = recorded
|
||||
checkpoint = internal_path(root / 'task-queues' / (result.queue_id + '.json'))
|
||||
state = json.loads(checkpoint.read_bytes())
|
||||
current = result.current_task_id
|
||||
if (state['version'] != 1 or state['task_ids'] != list(task_ids) or state['plan_hashes'] != plan_hashes
|
||||
or state['phase'] != 'primary' or set(state['entries']) != set(task_ids)
|
||||
or list(entry.task_id for entry in result.entries) != list(task_ids)
|
||||
or any(state['entries'][entry.task_id]['state'] != entry.state for entry in result.entries)
|
||||
or state['entries'][current]['state'] not in {'completed', 'failed'}
|
||||
or any(entry.state in {'paused', 'running'} for entry in result.entries)
|
||||
or not any(state['entries'][item]['state'] == 'pending' for item in task_ids[task_ids.index(current) + 1:])):
|
||||
return False
|
||||
if batch_id in state.get('consumed_resource_pauses', {}):
|
||||
return False
|
||||
pause = state.get('resource_pause') or {}
|
||||
intended = ((pause.get('task_id'), pause.get('batch_id')) == (current, batch_id)
|
||||
and pause.get('business_determined') is True
|
||||
and pause.get('manifest_digest') == state.get('manifest_digest') == arguments.get('manifest_digest')
|
||||
and isinstance(pause.get('sources'), dict)
|
||||
and set(pause['sources']) == set(task_ids))
|
||||
if intended:
|
||||
for item in task_ids:
|
||||
actual = journal.get('uncertainty_roots', {}).get(item)
|
||||
allowed = {root, canonical_path(root / 'tasks' / item)}
|
||||
evidence = {canonical_path(actual)} if actual and canonical_path(actual) in allowed else allowed
|
||||
if any(internal_path(location / 'quick-run' / 'uncertain.flag').exists() for location in evidence):
|
||||
return False
|
||||
if intended and (not require_released or (journal['state'] == 'finished'
|
||||
and _process_gone(journal['process']) and not blocking_resources(root) and not pending_supervisors(root))):
|
||||
return result
|
||||
return False
|
||||
except (OSError, ValueError, TypeError, KeyError, AttributeError):
|
||||
return False
|
||||
|
||||
|
||||
def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||
queue_id: str | None = None, runtime=None, expected_plan_hashes=None, checkpoint_id=None,
|
||||
defer_problem_pass=False) -> TaskQueueResult:
|
||||
defer_problem_pass=False, resource_batch_id=None, revalidate=None,
|
||||
manifest_digest=None, continuation_revalidate=None) -> TaskQueueResult:
|
||||
"""Execute the frozen order; uncertain state stops before the next project."""
|
||||
if revalidate is None and resource_batch_id is not None:
|
||||
revalidate = continuation_revalidate
|
||||
if runtime is None and getattr(service, '_supervised', False):
|
||||
# Existing per-project checkpoints keep their original resume owner.
|
||||
if (isinstance(queue_id, str) and len(queue_id) == 32
|
||||
@@ -195,16 +285,43 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||
from .workspace_execution import execute_workspace_projects
|
||||
return execute_workspace_projects(service, task_ids, queue_id=queue_id, stop_event=stop_event,
|
||||
expected_plan_hashes=expected_plan_hashes, checkpoint_id=checkpoint_id,
|
||||
defer_problem_pass=defer_problem_pass)
|
||||
return service._supervise('execute_task_queue', {'task_ids': tuple(task_ids),
|
||||
defer_problem_pass=defer_problem_pass, revalidate=revalidate)
|
||||
arguments = {'task_ids': tuple(task_ids),
|
||||
'queue_id': queue_id, 'expected_plan_hashes': expected_plan_hashes,
|
||||
'checkpoint_id': checkpoint_id, 'defer_problem_pass': defer_problem_pass}, stop_event=stop_event)
|
||||
'checkpoint_id': checkpoint_id, 'defer_problem_pass': defer_problem_pass}
|
||||
if resource_batch_id:
|
||||
arguments['resource_batch_id'] = resource_batch_id
|
||||
if manifest_digest is not None:
|
||||
arguments['manifest_digest'] = manifest_digest
|
||||
controls = {'revalidate': revalidate} if revalidate is not None else {}
|
||||
recovered = set()
|
||||
while True:
|
||||
try:
|
||||
result = service._supervise('execute_task_queue', arguments, stop_event=stop_event, **controls)
|
||||
except TaskCenterError as error:
|
||||
result = getattr(error, 'completed_result', None)
|
||||
batch_id = getattr(service, '_last_supervisor_batch_id', None)
|
||||
if (error.code not in {'batch_resources_pending', 'application_shutdown_failed'}
|
||||
or stop_event.is_set() or not isinstance(result, TaskQueueResult)
|
||||
or not resource_pause_admitted(service._logging.root, batch_id, tuple(task_ids),
|
||||
expected_plan_hashes, result, require_released=False)):
|
||||
raise
|
||||
if (not result.paused or stop_event.is_set() or result.current_task_id in recovered
|
||||
or not resource_pause_admitted(service._logging.root,
|
||||
batch_id := getattr(service, '_last_supervisor_batch_id', None), tuple(task_ids),
|
||||
expected_plan_hashes, result)):
|
||||
return result
|
||||
recovered.add(result.current_task_id)
|
||||
controls = {'revalidate': continuation_revalidate} if continuation_revalidate is not None else {}
|
||||
arguments = dict(arguments, queue_id=result.queue_id, checkpoint_id=None, resource_batch_id=batch_id)
|
||||
if runtime is None:
|
||||
from .batch_runtime import BatchCadRuntime
|
||||
with BatchCadRuntime(service._logging.root, 'task_queue', stop_event) as owned_runtime:
|
||||
result = execute_task_queue(service, task_ids, stop_event=stop_event,
|
||||
queue_id=queue_id, runtime=owned_runtime, expected_plan_hashes=expected_plan_hashes,
|
||||
checkpoint_id=checkpoint_id, defer_problem_pass=defer_problem_pass)
|
||||
checkpoint_id=checkpoint_id, defer_problem_pass=defer_problem_pass,
|
||||
resource_batch_id=resource_batch_id, revalidate=revalidate,
|
||||
manifest_digest=manifest_digest)
|
||||
owned_runtime.result = result
|
||||
return result
|
||||
ids = tuple(task_ids)
|
||||
@@ -212,8 +329,12 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||
raise TaskCenterError('task_queue_selection', '请选择不同的单工程任务。')
|
||||
root = service._logging.root
|
||||
with _queue_lease(root):
|
||||
if revalidate is not None:
|
||||
from .batch_supervisor import mutation_lease
|
||||
with mutation_lease(root):
|
||||
revalidate()
|
||||
children = {task_id: service.for_project_task(task_id) for task_id in ids}
|
||||
project_paths = []
|
||||
project_paths, projects_by_task = [], {}
|
||||
sources = {}
|
||||
for task_id, child in children.items():
|
||||
task = child.get_task(task_id)
|
||||
@@ -221,9 +342,14 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||
if not getattr(task, 'primary_project_id', None) or len(projects) != 1:
|
||||
raise TaskCenterError('project_binding', '顺序执行仅支持绑定单个工程的任务。')
|
||||
project_paths.append(str(projects[0].path.resolve(strict=False)).casefold())
|
||||
projects_by_task[task_id] = projects[0].path
|
||||
sources[task_id] = write_sources(projects[0].path)
|
||||
if len(set(project_paths)) != len(ids):
|
||||
raise TaskCenterError('task_queue_selection', '不能在同一队列重复处理同一个工程。')
|
||||
try:
|
||||
frozen_sources = {item: sorted(write_sources(projects_by_task[item], strict=True)) for item in ids}
|
||||
except (OSError, UnicodeError, ValueError):
|
||||
frozen_sources = None
|
||||
runtime.bind_logs(service._logging, ids)
|
||||
hashes = {task_id: _plan_hash(child, task_id) for task_id, child in children.items()}
|
||||
if expected_plan_hashes is not None and hashes != expected_plan_hashes:
|
||||
@@ -242,6 +368,7 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||
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 state.get('manifest_digest') != manifest_digest
|
||||
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)
|
||||
@@ -252,6 +379,8 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||
else:
|
||||
state = {'version': 1, 'task_ids': list(ids), 'plan_hashes': hashes, 'phase': 'primary',
|
||||
'entries': {task_id: {'state': 'pending', 'message': ''} for task_id in ids}}
|
||||
if manifest_digest is not None:
|
||||
state['manifest_digest'] = manifest_digest
|
||||
_save(path, state)
|
||||
paused = False
|
||||
current = None
|
||||
@@ -260,6 +389,23 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||
isolated_tasks = state.setdefault('isolated_tasks', {})
|
||||
isolated_sources = state.setdefault('isolated_sources', {})
|
||||
dependency_tasks = state.setdefault('dependency_tasks', {})
|
||||
held = next((item for item in ids if _task_uncertain(root, children[item], item)), None)
|
||||
if held is not None:
|
||||
state['entries'][held] = {'state': 'blocked', 'message': '已有原生写入结果待核验,整批暂停。'}
|
||||
_save(path, state)
|
||||
return TaskQueueResult(token, tuple(TaskQueueEntry(item, **state['entries'][item]) for item in ids),
|
||||
True, held, state.get('netlist_verification'))
|
||||
if resource_batch_id:
|
||||
evidence = resource_pause_admitted(root, resource_batch_id, ids, hashes)
|
||||
if not evidence or evidence.queue_id != queue_id:
|
||||
raise TaskCenterError('task_queue_state', '原队列的资源释放或阻断回执无法核验。')
|
||||
item = evidence.current_task_id
|
||||
if not frozen_sources or frozen_sources != state['resource_pause']['sources']:
|
||||
raise TaskCenterError('task_queue_state', '工程写入源已变化或无法核验,须重新确认。')
|
||||
sources = {task: set(values) for task, values in frozen_sources.items()}
|
||||
state.setdefault('consumed_resource_pauses', {})[resource_batch_id] = item
|
||||
state.pop('resource_pause', None)
|
||||
_save(path, state)
|
||||
from .netlist_verification import NetlistVerification
|
||||
checks = NetlistVerification(root, token, stop_event)
|
||||
try:
|
||||
@@ -289,7 +435,8 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||
continue
|
||||
if state['entries'][task_id]['state'] in _TERMINAL:
|
||||
if state['entries'][task_id]['state'] == 'completed':
|
||||
checks.before_task(children[task_id], task_id, existing_only=True)
|
||||
if not resource_batch_id or task_id not in state.get('netlist_verification', {}):
|
||||
checks.before_task(children[task_id], task_id, existing_only=True)
|
||||
continue
|
||||
if stop_event.is_set():
|
||||
paused = True
|
||||
@@ -303,6 +450,8 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||
service._task_queue_feedback = (token, task_id, ids.index(task_id) + 1, len(ids))
|
||||
resolving_bom = False
|
||||
execution_dispatched = False
|
||||
resource_only = False
|
||||
uncertain_error = None
|
||||
try:
|
||||
if hasattr(runtime, 'begin_task'):
|
||||
runtime.begin_task(task_id)
|
||||
@@ -376,32 +525,36 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||
entry = {'state': 'failed' if safe else 'paused' if error.code == 'operation_cancelled' else 'blocked',
|
||||
'message': f'{error.code}: {error.message}' if resolving_bom else error.message}
|
||||
paused = not safe
|
||||
if not safe and error.code != 'operation_cancelled' and not stop_event.is_set():
|
||||
if (error.code in {'batch_resources_pending', 'application_shutdown_failed'}
|
||||
and execution_dispatched and hasattr(child, '_store')
|
||||
and not _task_uncertain(root, child, task_id)):
|
||||
try:
|
||||
isolated = isolate_project(runtime, child, task_id, error)
|
||||
except Exception as cleanup_error:
|
||||
entry['message'] += '; 资源收尾未确认:' + str(cleanup_error)
|
||||
isolated = False
|
||||
if isolated:
|
||||
isolated_tasks[task_id] = entry['message']
|
||||
isolated_sources.update((source,task_id) for source in sources[task_id])
|
||||
paused = False
|
||||
progress = child.quick_run_progress(task_id)
|
||||
if progress.queue_complete:
|
||||
resource_only = True
|
||||
entry['state'] = 'failed' if progress.failed_items else 'completed'
|
||||
except (OSError, ValueError, TaskCenterError):
|
||||
pass
|
||||
if paused and not resource_only and (error.code != 'operation_cancelled'
|
||||
or _task_uncertain(root, child, task_id)):
|
||||
uncertain_error = error
|
||||
except Exception as error:
|
||||
entry = {'state': 'blocked', 'message': str(error)}
|
||||
paused = True
|
||||
uncertain_error = error
|
||||
state['entries'][task_id] = entry
|
||||
if uncertain_error is not None:
|
||||
from .stop_control import protect_interruption
|
||||
protect_interruption(_uncertainty_root(root, child, task_id), 'project_failure: ' + str(uncertain_error))
|
||||
_save(path, state)
|
||||
if uncertain_error is not None:
|
||||
if not stop_event.is_set():
|
||||
try:
|
||||
isolated = isolate_project(runtime, child, task_id, error)
|
||||
isolate_project(runtime, child, task_id, uncertain_error)
|
||||
except Exception as cleanup_error:
|
||||
entry['message'] += '; 资源收尾未确认:' + str(cleanup_error)
|
||||
isolated = False
|
||||
if isolated:
|
||||
isolated_tasks[task_id] = entry['message']
|
||||
isolated_sources.update((source,task_id) for source in sources[task_id])
|
||||
paused = False
|
||||
state['entries'][task_id] = entry
|
||||
_save(path, state)
|
||||
record_task_outcome(child, task_id, entry['state'], entry['message'])
|
||||
_save(path, state)
|
||||
if (entry['state'] in {'completed', 'failed'} and task_id in checks.tasks
|
||||
and not child.has_interrupted_quick_run(task_id)):
|
||||
progress = child.quick_run_progress(task_id)
|
||||
@@ -409,6 +562,10 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||
execution_summary={key: getattr(progress, key, None)
|
||||
for key in ('saved_items', 'failed_items', 'no_match_items')})
|
||||
if paused:
|
||||
if resource_only and not stop_event.is_set() and frozen_sources and hasattr(runtime, 'session_id'):
|
||||
state['resource_pause'] = {'task_id': task_id, 'batch_id': runtime.session_id,
|
||||
'sources': frozen_sources, 'business_determined': True, 'manifest_digest': manifest_digest}
|
||||
_save(path, state)
|
||||
break
|
||||
if (not paused and stop_event.is_set() and state.get('phase') != 'finished'
|
||||
and any(entry['state'] == 'failed' for entry in state['entries'].values())):
|
||||
|
||||
@@ -30,6 +30,7 @@ def icon(name: str, primary: bool = False) -> QIcon:
|
||||
BUTTON_ICONS = {
|
||||
'task_center_navigation': 'grid', 'dsh_navigation': 'chat',
|
||||
'history_navigation': 'clock',
|
||||
'verification_navigation': 'check', 'verificationNew': 'plus',
|
||||
'newTaskButton': 'plus', 'editTaskButton': 'sliders', 'deleteTaskButton': 'trash',
|
||||
'selectAllTasks': 'check', 'clearTaskSelection': 'close',
|
||||
'restoreTaskButton': 'refresh', 'taskRecycleBin': 'trash',
|
||||
|
||||
@@ -4,7 +4,7 @@ from threading import Event
|
||||
from ..stop_control import StopControl
|
||||
from shiboken6 import isValid
|
||||
import time
|
||||
from PySide6.QtCore import QElapsedTimer, QSettings, QSignalBlocker, QThreadPool, QTimer, Qt
|
||||
from PySide6.QtCore import QByteArray, QElapsedTimer, QRect, QSettings, QSignalBlocker, QThreadPool, QTimer, Qt
|
||||
from PySide6.QtGui import QAction, QActionGroup
|
||||
from PySide6.QtWidgets import (QApplication, QCheckBox, QDialog, QFileDialog, QHBoxLayout, QMessageBox,
|
||||
QPushButton, QLabel, QSizePolicy, QSplitter, QStackedWidget, QTabWidget, QToolButton, QVBoxLayout, QWidget)
|
||||
@@ -60,6 +60,8 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self.dsh_action = QAction('DSH助手', self)
|
||||
self.dsh_action.setShortcut('Ctrl+Shift+D')
|
||||
self.dsh_action.triggered.connect(self._open_dsh)
|
||||
self.verification_action = QAction('工程校验', self)
|
||||
self.verification_action.triggered.connect(lambda: self.content_stack.setCurrentWidget(self.verification_panel))
|
||||
self._navigation_actions = QActionGroup(self)
|
||||
self._navigation_actions.setExclusive(True)
|
||||
navigation = QWidget(objectName='toolNavigation')
|
||||
@@ -70,7 +72,8 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
navigation_layout.addWidget(brand)
|
||||
navigation_layout.addSpacing(24)
|
||||
for name, action in (('task_center_navigation', self.task_center_action),
|
||||
('history_navigation', self.history_action), ('dsh_navigation', self.dsh_action)):
|
||||
('history_navigation', self.history_action), ('dsh_navigation', self.dsh_action),
|
||||
('verification_navigation', self.verification_action)):
|
||||
action.setCheckable(True)
|
||||
self._navigation_actions.addAction(action)
|
||||
self.addAction(action)
|
||||
@@ -119,6 +122,9 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self._batch_stop = None
|
||||
self._active_quick_run_task_id = None
|
||||
self._project_queues = {}
|
||||
self._batch_confirmation_admission = None
|
||||
self._receipt_recovery_started = False
|
||||
self._resource_queue_resume = None
|
||||
self._execution_after_save = None
|
||||
self._generation = 0
|
||||
self._message = ''
|
||||
@@ -146,6 +152,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self.task_list.up_button.clicked.connect(lambda: self._move_project_task(-1))
|
||||
self.task_list.down_button.clicked.connect(lambda: self._move_project_task(1))
|
||||
self.task_list.queue_button.clicked.connect(self._execute_project_tasks)
|
||||
self.task_list.selected_queue_button.clicked.connect(lambda: self._execute_project_tasks(selected=True))
|
||||
self.project_summary = ProjectSummary()
|
||||
self.project_summary.refresh_button.clicked.connect(self._refresh_bound_project)
|
||||
self.mapping_table = MappingTable(self._rule_enabled_changed)
|
||||
@@ -181,6 +188,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self.archive_on_close_check.setToolTip('默认关闭。仅归档安全任务,保留计划、日志和文件;待核验或资源未释放的任务保留在当前列表。')
|
||||
self._build_layout()
|
||||
self._layout_settings = QSettings(str(service.layout_settings_path), QSettings.Format.IniFormat)
|
||||
self._restore_window_geometry()
|
||||
self.auto_intervention_check.setChecked(self._layout_settings.value(
|
||||
'dsh/auto_intervention', True, type=bool))
|
||||
self.auto_intervention_check.toggled.connect(self._set_auto_intervention)
|
||||
@@ -211,6 +219,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self._dsh_stall_timer.start()
|
||||
self._resource_status.changed.connect(self._update_gates)
|
||||
self._resource_status.changed.connect(self._observe_dsh_resource_blockers)
|
||||
self._resource_status.changed.connect(self._resume_resource_queue)
|
||||
self._resource_status.refresh()
|
||||
self._refresh_task_list()
|
||||
self._update_gates()
|
||||
@@ -292,14 +301,20 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self.history_panel = OperationHistoryPage(self.service, self)
|
||||
self.history_panel.busy_changed.connect(self._history_activity_changed)
|
||||
self.content_stack.addWidget(self.history_panel)
|
||||
from .verification_workspace import VerificationWorkspace
|
||||
self.verification_panel = VerificationWorkspace(self.service, self)
|
||||
self.content_stack.addWidget(self.verification_panel)
|
||||
self.content_stack.currentChanged.connect(self._workspace_changed)
|
||||
self.setCentralWidget(self.content_stack)
|
||||
self._reset_layout()
|
||||
|
||||
def _workspace_changed(self, index):
|
||||
history = self.content_stack.widget(index) is self.history_panel
|
||||
(self.task_center_action if index == 0 else self.history_action if history else self.dsh_action).setChecked(True)
|
||||
verification = self.content_stack.widget(index) is self.verification_panel
|
||||
action = self.task_center_action if index == 0 else self.history_action if history else self.verification_action if verification else self.dsh_action
|
||||
action.setChecked(True)
|
||||
self.history_panel.set_active(history)
|
||||
self.verification_panel.set_active(verification)
|
||||
|
||||
def _history_activity_changed(self):
|
||||
self._update_gates()
|
||||
@@ -310,6 +325,34 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
return {'workspace': self.workspace_splitter, 'detail': self.detail_splitter,
|
||||
'rules': self.mapping_table.horizontalHeader(), 'targets': self.plan_panel.table.horizontalHeader()}
|
||||
|
||||
def _restore_window_geometry(self):
|
||||
saved = self._layout_settings.value('main_window/geometry')
|
||||
if saved is None:
|
||||
return
|
||||
default = self.geometry()
|
||||
restored = isinstance(saved, QByteArray) and self.restoreGeometry(saved)
|
||||
normal = self.normalGeometry() if restored else default
|
||||
screen = QApplication.screenAt(normal.center()) if restored else None
|
||||
screen = screen or QApplication.primaryScreen()
|
||||
if screen is None:
|
||||
return
|
||||
available = screen.availableGeometry()
|
||||
if restored and available.contains(normal) and normal.size().expandedTo(self.minimumSize()) == normal.size():
|
||||
return
|
||||
|
||||
# Qt may reject a saved geometry after a DPI change. Keep the normal
|
||||
# window reachable on the current display, even when its minimum exceeds it.
|
||||
available = available.adjusted(8, 36, -8, -8)
|
||||
state = self.windowState()
|
||||
self.setWindowState(Qt.WindowState.WindowNoState)
|
||||
size = normal.size().boundedTo(available.size()).expandedTo(self.minimumSize())
|
||||
fallback = QRect(available.topLeft(), size)
|
||||
fallback.moveCenter(available.center())
|
||||
fallback.moveLeft(max(fallback.left(), available.left()))
|
||||
fallback.moveTop(max(fallback.top(), available.top()))
|
||||
self.setGeometry(fallback)
|
||||
self.setWindowState(state)
|
||||
|
||||
def _reset_layout(self):
|
||||
self.workspace_splitter.setSizes((240, 1040))
|
||||
self.detail_splitter.setSizes((650, 110))
|
||||
@@ -400,14 +443,23 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self._dsh_view.stopped.connect(lambda: QTimer.singleShot(0, self, self.close))
|
||||
self._dsh_view.shutdown()
|
||||
return
|
||||
if self.verification_panel.busy:
|
||||
self._close_pending = True
|
||||
self.verification_panel.begin_shutdown()
|
||||
event.ignore()
|
||||
QTimer.singleShot(100, self.close)
|
||||
return
|
||||
self._cancel_dsh_diagnosis()
|
||||
self._layout_settings.setValue('main_window/geometry', self.saveGeometry())
|
||||
for name, widget in self._layout_widgets().items():
|
||||
self._layout_settings.setValue(f'single_project/{name}', widget.saveState())
|
||||
self._layout_settings.setValue('tasks/sort', self.task_list.sort.currentData())
|
||||
self._layout_settings.sync()
|
||||
self._closed = True
|
||||
self._dsh_status.close()
|
||||
self._dsh_stall_timer.stop()
|
||||
self.history_panel.shutdown()
|
||||
self.verification_panel.shutdown()
|
||||
if self._dsh_operations:
|
||||
self._dsh_operations.close()
|
||||
self._context_query.close()
|
||||
@@ -582,8 +634,10 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
group_dirty = self.plan_panel.has_unsaved_plan(group_ids)
|
||||
group_active = any(t.status in {TaskStatus.RUNNING, TaskStatus.PAUSED} for t in self._tasks if t.task_id in group_ids)
|
||||
batch_pending = pending_batch_tasks(self._tasks, context.task.group_id if grouped else None)
|
||||
self.task_list.queue_button.setEnabled(bool(batch_pending) and not busy and not group_dirty
|
||||
and not context.interrupted and not resources_pending)
|
||||
self.task_list.queue_button.setEnabled(bool(batch_pending) and not busy and not group_dirty and not resources_pending)
|
||||
selected_ids = self.task_list.selected_task_ids()
|
||||
self.task_list.selected_queue_button.setEnabled(grouped and bool(selected_ids) and not busy
|
||||
and not self.plan_panel.has_unsaved_plan(selected_ids) and not resources_pending)
|
||||
for button in (self.task_list.up_button, self.task_list.down_button):
|
||||
button.setEnabled(grouped and not busy and not group_active
|
||||
and self.task_list.sort.currentData() == 'execution'
|
||||
@@ -853,36 +907,87 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self._bind_dsh_context()
|
||||
self._run_async(execute, done, self.run_panel.quick_run_button, expected_task_id=task_id)
|
||||
|
||||
def _execute_project_tasks(self):
|
||||
if not self.task_list.queue_button.isEnabled():
|
||||
def _execute_project_tasks(self, *, resource_resume=False, selected=False):
|
||||
button = self.task_list.selected_queue_button if selected else self.task_list.queue_button
|
||||
if not button.isEnabled() or self._context is None:
|
||||
return
|
||||
owner_task_id = self._context.task.task_id
|
||||
group = self._context.task.group_id
|
||||
tasks = pending_batch_tasks(self._tasks, group)
|
||||
if not tasks:
|
||||
return
|
||||
token, ids = self._project_queues.get(group, (None, tuple(t.task_id for t in tasks)))
|
||||
if self.plan_panel.has_unsaved_plan(ids):
|
||||
self._save_plans_before_execution(ids, batch=True)
|
||||
return
|
||||
from ...dsh import task_lifecycle as lifecycle
|
||||
from ..batch_admission import build_batch_admission, resolve_batch_task_ids
|
||||
try:
|
||||
candidates = resolve_batch_task_ids(self._tasks, group,
|
||||
selected_ids=self.task_list.selected_task_ids() if selected else None)
|
||||
except TaskCenterError as error:
|
||||
self._show_error(error, owner_task_id=owner_task_id)
|
||||
return
|
||||
token, ids = self._project_queues.get(group, (None, candidates))
|
||||
if token and selected and tuple(ids) != candidates:
|
||||
self._set_operator_message('本批有原队列待接续,请按原确认范围继续,或先核验并结束原批次。', 'warning')
|
||||
return
|
||||
prepared = []
|
||||
def inspect():
|
||||
if token:
|
||||
from ...dsh.run_journal import resume_preflight
|
||||
report = resume_preflight(self.service, self._dsh_operations.runs.inspect(self.service, token))
|
||||
inspected = self._dsh_operations.runs.inspect(self.service, token)
|
||||
if resource_resume and not inspected.get('resource_batch_id'):
|
||||
return None
|
||||
report = resume_preflight(self.service, inspected)
|
||||
import json
|
||||
manifest = self.service.layout_settings_path.parent / 'batch-runs' / token / 'manifest.json'
|
||||
admission = json.loads(manifest.read_text(encoding='utf-8')) if manifest.is_file() else None
|
||||
else:
|
||||
report = lifecycle.preflight(self.service, list(ids), allow_completed=True)
|
||||
except Exception as error:
|
||||
self._show_error(error, owner_task_id=ids[0])
|
||||
return
|
||||
if not self._execution_report_ready(report):
|
||||
return
|
||||
admission = build_batch_admission(self.service, candidates,
|
||||
scope_kind='selected' if selected else 'batch')
|
||||
report = admission['execution_report']
|
||||
return admission, report
|
||||
def collected(value):
|
||||
if value is not None:
|
||||
prepared.append(value)
|
||||
def confirm():
|
||||
if not prepared or self._closed or self._close_pending or self._task_id != owner_task_id:
|
||||
return
|
||||
admission, report = prepared[0]
|
||||
if admission is not None and not admission['ready'] and not token:
|
||||
from ..batch_admission import write_preflight_receipt
|
||||
path = write_preflight_receipt(self.service.layout_settings_path.parent, admission, 'rejected')
|
||||
reasons = admission['global_blockers'] or [row['message'] for row in admission['decisions']]
|
||||
self._set_operator_message('本批未启动:' + ';'.join(reasons) + f'\n逐任务清单:{path}', 'warning')
|
||||
return
|
||||
if not report or not self._execution_report_ready(report):
|
||||
return
|
||||
self._batch_confirmation_admission = admission
|
||||
self._dsh_confirmation_impact = report.get('impact', {})
|
||||
enabled = report.get('impact', {}).get('enabled_scope', 0)
|
||||
active = tuple(ids) if token else tuple(admission['runnable_task_ids'])
|
||||
if not resource_resume and not self._quick_run_confirmer('batch', len(active), enabled):
|
||||
if admission is not None:
|
||||
from ..batch_admission import write_preflight_receipt
|
||||
write_preflight_receipt(self.service.layout_settings_path.parent, admission, 'cancelled')
|
||||
return
|
||||
try:
|
||||
current_selection = (resolve_batch_task_ids(self._tasks, group,
|
||||
selected_ids=self.task_list.selected_task_ids()) if selected else candidates)
|
||||
except TaskCenterError:
|
||||
current_selection = ()
|
||||
if current_selection != candidates:
|
||||
from ..batch_admission import write_preflight_receipt
|
||||
reason = '所选任务范围已变化,请重新预检并确认。'
|
||||
self._set_operator_message('未启动执行:' + reason, 'warning')
|
||||
if admission is not None:
|
||||
write_preflight_receipt(self.service.layout_settings_path.parent, admission, 'rejected', reason=reason)
|
||||
return
|
||||
if self.plan_panel.has_unsaved_plan(candidates):
|
||||
self._set_operator_message('候选任务有未保存编辑,请保存后重新确认。', 'warning')
|
||||
return
|
||||
if not self._confirmed_execution_allowed(owner_task_id, active, button):
|
||||
return
|
||||
self._start_project_batch(owner_task_id, group, token, active, report,
|
||||
admission if not token else None, button)
|
||||
self._run_async(inspect, collected, button, expected_task_id=owner_task_id,
|
||||
operation_area='batch_preflight', on_finished=confirm)
|
||||
|
||||
def _start_project_batch(self, owner_task_id, group, token, ids, report, admission, button):
|
||||
self._dsh_confirmation_impact = report.get('impact', {})
|
||||
enabled = report.get('impact', {}).get('enabled_scope', 0)
|
||||
if not self._quick_run_confirmer('batch', len(ids), enabled):
|
||||
return
|
||||
if not self._confirmed_execution_allowed(owner_task_id, ids, self.task_list.queue_button):
|
||||
return
|
||||
self._dsh_authorized_tasks.update(ids)
|
||||
self._begin_run(ids[0])
|
||||
self._dsh_live_run['task_ids'] = list(ids)
|
||||
@@ -890,7 +995,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self._dsh_run_id = run_id
|
||||
self._dsh_live_run['run_id'] = run_id
|
||||
stop = self._batch_stop
|
||||
def done(result):
|
||||
def done(result, receipt=None):
|
||||
if result.paused:
|
||||
self._project_queues[group] = (result.queue_id, ids)
|
||||
else:
|
||||
@@ -905,8 +1010,22 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self._queue_dsh_incident(entry.task_id,
|
||||
'task_queue_blocked' if entry.state == 'blocked' else 'execution_failed', entry.message)
|
||||
self._show_task_log(force=True)
|
||||
self._set_operator_message(f'本批任务已暂停。失败/阻断 {failures} 项。' if result.paused else f'本批任务已结束。失败 {failures} 项。',
|
||||
'warning' if result.paused or failures else 'success')
|
||||
summary = (receipt or {}).get('summary')
|
||||
if summary:
|
||||
counts = summary['task_counts']
|
||||
operations = summary['operation_counts']
|
||||
title = '本批任务已暂停' if result.paused else '本批任务已收尾'
|
||||
resource_label = {'released': '已释放', 'pending': '待清理',
|
||||
'isolated': '已隔离,尚未释放', 'unknown': '尚未确认'}.get(summary['resource_state'], '尚未确认')
|
||||
self._set_operator_message(
|
||||
f'{title}:完成 {counts.get("completed", 0)},失败 {counts.get("failed", 0)},'
|
||||
f'待核验 {counts.get("blocked", 0)},跳过 {counts.get("skipped", 0)};'
|
||||
f'已保存 {operations.get("saved", 0)},保存待核验 {operations.get("pending_save", 0)}。'
|
||||
f'资源:{resource_label}。',
|
||||
'success' if summary.get('status') == 'completed' else 'warning')
|
||||
else:
|
||||
self._set_operator_message(f'本批任务已暂停。失败/阻断 {failures} 项。' if result.paused else f'本批任务已结束。失败 {failures} 项。',
|
||||
'warning' if result.paused or failures else 'success')
|
||||
def execute():
|
||||
from ...dsh.execution_runs import execute_confirmed_run
|
||||
from ..task_queue import TaskQueueEntry, TaskQueueResult
|
||||
@@ -914,20 +1033,41 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
if token:
|
||||
resume = self._dsh_operations.runs.inspect(self.service, token)
|
||||
receipt = execute_confirmed_run(self.service, self.service.layout_settings_path.parent,
|
||||
list(ids), report, stop, run_id, resume=resume)
|
||||
list(ids), report, stop, run_id, resume=resume, admission=admission)
|
||||
result = TaskQueueResult(receipt['queue_id'], tuple(TaskQueueEntry(**entry) for entry in receipt['entries']),
|
||||
receipt['paused'])
|
||||
return result, receipt
|
||||
def completed(value):
|
||||
if isinstance(value, tuple):
|
||||
result, receipt = value
|
||||
done(result)
|
||||
done(result, receipt)
|
||||
self._show_receipt_verification(receipt)
|
||||
self._dsh_last_execution = receipt
|
||||
self._bind_dsh_context()
|
||||
if (result.paused and receipt.get('resource_batch_id') and not stop.is_set()
|
||||
and not self._close_pending and not self._closed):
|
||||
self._resource_queue_resume = (group, result.queue_id, ids)
|
||||
else:
|
||||
done(value)
|
||||
self._run_async(execute, completed, self.task_list.queue_button)
|
||||
self._run_async(execute, completed, button, on_finished=self._check_resource_queue)
|
||||
|
||||
def _check_resource_queue(self):
|
||||
if self._resource_queue_resume and self._resource_status.blocked and not self._workers:
|
||||
self._cleanup_batch_resources(automatic=True)
|
||||
else:
|
||||
self._resume_resource_queue()
|
||||
|
||||
def _resume_resource_queue(self):
|
||||
pending = self._resource_queue_resume
|
||||
if (not pending or self._closed or self._close_pending or self._workers or self._loading
|
||||
or self._resource_status.busy or not self._resource_status.known or self._resource_status.blocked):
|
||||
return
|
||||
group, token, ids = pending
|
||||
if (self._context is None or self._context.task.group_id != group
|
||||
or self._project_queues.get(group) != (token, ids) or self.plan_panel.has_unsaved_plan(ids)):
|
||||
return
|
||||
self._resource_queue_resume = None
|
||||
self._execute_project_tasks(resource_resume=True)
|
||||
|
||||
def _begin_run(self, task_id):
|
||||
from uuid import uuid4
|
||||
@@ -1016,11 +1156,13 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self._close_pending = False
|
||||
self._set_operator_message(self.run_panel.operator_band.text() + '\n' + details, 'warning')
|
||||
|
||||
def _cleanup_batch_resources(self):
|
||||
if not self.run_panel.cleanup_resources_button.isEnabled():
|
||||
def _cleanup_batch_resources(self, *, automatic=False):
|
||||
if not automatic and not self.run_panel.cleanup_resources_button.isEnabled():
|
||||
return
|
||||
state = getattr(self.service, '_supervisor_dialog_state', None) or {}
|
||||
if (state.get('supervision') or {}).get('blocked'):
|
||||
if automatic:
|
||||
return
|
||||
from .cad_dialog_operations import show_cad_dialogs
|
||||
show_cad_dialogs(self)
|
||||
self._update_gates()
|
||||
@@ -1038,6 +1180,10 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
nonlocal cleanup_finished
|
||||
cleanup_finished = True
|
||||
start_force_if_ready()
|
||||
if not force_started and not self._workers:
|
||||
from ...dsh.execution_runs import recover_batch_receipts
|
||||
self._run_async(lambda: recover_batch_receipts(self.service, self.service.layout_settings_path.parent),
|
||||
lambda _: None, operation_area='batch_receipts', on_finished=self._resume_resource_queue)
|
||||
def forced(remaining):
|
||||
from ..batch_resources import resource_blockers
|
||||
self._resource_status.refresh()
|
||||
@@ -1061,7 +1207,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
else:
|
||||
self._dsh_blockers.clear('resource-release')
|
||||
self._update_gates()
|
||||
if pending and not any(row.get('force_available', True) for row in pending):
|
||||
if automatic or pending and not any(row.get('force_available', True) for row in pending):
|
||||
return
|
||||
if pending and QMessageBox.question(self, '强制结束自有残留进程',
|
||||
'安全释放尚未完成。是否强制结束本程序仍持有且能证明归属的残留进程?\n\n'
|
||||
@@ -1071,7 +1217,8 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
force_confirmed = True
|
||||
# A modal question can deliver finished before returning Yes.
|
||||
start_force_if_ready()
|
||||
self._run_async(self.service.cleanup_batch_resources, done,
|
||||
cleanup = (lambda: self.service.cleanup_batch_resources(automatic=True)) if automatic else self.service.cleanup_batch_resources
|
||||
self._run_async(cleanup, done,
|
||||
self.run_panel.cleanup_resources_button, operation_area='resources', on_finished=after_cleanup)
|
||||
|
||||
def _startup_resource_recheck(self):
|
||||
@@ -1080,9 +1227,15 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
if self._workers or self._loading or not self._resource_status.known or self._resource_status.busy:
|
||||
QTimer.singleShot(250, self._startup_resource_recheck)
|
||||
return
|
||||
if self._resource_status.blocked:
|
||||
if not self._receipt_recovery_started:
|
||||
self._receipt_recovery_started = True
|
||||
from ...dsh.execution_runs import recover_batch_receipts
|
||||
self._run_async(lambda: recover_batch_receipts(self.service, self.service.layout_settings_path.parent),
|
||||
lambda _: None, operation_area='batch_receipts', on_finished=self._startup_resource_recheck)
|
||||
return
|
||||
if self._resource_status.records:
|
||||
self._update_gates()
|
||||
self._cleanup_batch_resources() # Resource-only; never resumes a queue.
|
||||
self._cleanup_batch_resources(automatic=True)
|
||||
|
||||
def _export_diagnostics(self):
|
||||
from pathlib import Path
|
||||
@@ -1211,13 +1364,21 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
|
||||
def _confirm_quick_run(self, scope, selected_projects, enabled_rules):
|
||||
context = self._context
|
||||
names = context.project.path if scope == 'current' else '\n'.join(
|
||||
f'{t.group_position+1}. {t.name}' for t in pending_batch_tasks(self._tasks, context.task.group_id))
|
||||
admission = self._batch_confirmation_admission if scope != 'current' else None
|
||||
names = (context.project.path if scope == 'current' else '\n'.join(
|
||||
f'{index + 1}. {row["name"]}' for index, row in enumerate(admission['decisions'])
|
||||
if row['classification'] == 'executable') if admission is not None else '\n'.join(
|
||||
f'{t.group_position+1}. {t.name}' for t in pending_batch_tasks(self._tasks, context.task.group_id)))
|
||||
text = (f'执行范围:{names}\n\n' + ('' if scope == 'current' else f'按顺序处理 {selected_projects} 个工程任务。\n')
|
||||
+ f'勾选目标/规则:{enabled_rules}\n'
|
||||
+ '逐项执行原生 Replace Part + Library Wins,保留每行 Value/NC 策略;创建备份并自动保存、关闭、重开核验。'
|
||||
+ '\n默认在受监督的私有桌面执行,结束后释放自有 CAD 会话;主桌面可继续查看其他文件。请确保待处理工程未在其他 CAD 会话中打开。'
|
||||
+ '\n确认后连续执行,暂停等待当前步骤收尾;状态不确定时停止。')
|
||||
if admission is not None:
|
||||
labels = {'executable': '执行', 'skipped': '跳过', 'held': '待核验', 'already_completed': '已完成,不重放'}
|
||||
text = (f'候选 {len(admission["candidate_task_ids"])} 个工程,可执行 {selected_projects} 个工程。\n'
|
||||
+ '\n'.join(f'{index + 1}. [{labels[row["classification"]]}] {row["name"]}:{row["message"]}'
|
||||
for index, row in enumerate(admission['decisions'])) + '\n\n' + text)
|
||||
impact = getattr(self, '_dsh_confirmation_impact', {})
|
||||
if impact:
|
||||
text += '\n\n执行影响:' + ('器件数量未知,执行时按实际命中核验。' if impact['component_count'] is None else f"已选中 {impact['component_count']} 个器件。")
|
||||
|
||||
@@ -3,6 +3,8 @@ from datetime import datetime
|
||||
import json
|
||||
import re
|
||||
|
||||
from ..errors import ProjectPathError
|
||||
|
||||
ERROR_TEXT = {
|
||||
"dsh_startup": "DSH助手启动失败,请检查发布包中的运行时和 Node.js。",
|
||||
'user_forced_stop': '操作已强制中断,结果待核验。',
|
||||
@@ -57,6 +59,8 @@ ERROR_TEXT = {
|
||||
|
||||
|
||||
def format_operation_error(error):
|
||||
if isinstance(error, ProjectPathError):
|
||||
return f'{error.message}\n错误代码:{error.code} · 错误编号:{error.error_id}'
|
||||
title = ERROR_TEXT.get(error.code, '操作未完成')
|
||||
report = getattr(error, 'bom_report', None)
|
||||
if report is not None:
|
||||
|
||||
@@ -18,6 +18,7 @@ STATES={'verified':'已核验完成','no_match':'未命中','failed':'失败','f
|
||||
'uncertain':'待核验','saved_unverified':'保存待核验','skipped':'已跳过','recorded':'已记录',
|
||||
'running':'执行中','paused':'已暂停','pending':'待执行','restored':'已恢复'}
|
||||
OPERATIONS={'quick_run_executed':'替换执行','quick_run_prepared':'准备执行',
|
||||
'verification_completed':'工程校验',
|
||||
'quick_run_recovered':'核验恢复','quick_run_queue_paused':'暂停执行',
|
||||
'quick_run_retry_prepared':'准备失败项重试','create_project_tasks':'创建工程任务',
|
||||
'create_task':'新建任务','update_task':'编辑任务','delete_task':'归档任务',
|
||||
|
||||
@@ -19,6 +19,8 @@ from .workers import ServiceWorker
|
||||
from .operation_state import OperationPhase
|
||||
from .command_menu import CommandMenu
|
||||
from .icons import icon
|
||||
from .messages import format_operation_error
|
||||
from ..errors import ProjectPathError
|
||||
from ..bom_import_state import BomImportMachine, BomImportPhase, BomImportState
|
||||
from ..bom_pending import retained_bom_rows
|
||||
|
||||
@@ -44,6 +46,9 @@ class DirectoryTaskDialog(QDialog):
|
||||
self.scan = QPushButton('读取工程', objectName='readTaskProjects')
|
||||
self.projects = QListWidget(objectName='taskProjectCandidates')
|
||||
self.summary = QLabel('先读取工程,再勾选需要创建任务的项目。')
|
||||
self.summary.setWordWrap(True)
|
||||
self.summary.setTextFormat(Qt.TextFormat.PlainText)
|
||||
self.summary.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
|
||||
self.buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
|
||||
self.buttons.button(QDialogButtonBox.StandardButton.Ok).setText('创建任务')
|
||||
self.buttons.button(QDialogButtonBox.StandardButton.Ok).setEnabled(False)
|
||||
@@ -137,7 +142,10 @@ class DirectoryTaskDialog(QDialog):
|
||||
if self._closed:
|
||||
return
|
||||
self._scanned_root = None
|
||||
self.summary.setText(getattr(error, 'message', str(error)))
|
||||
if isinstance(error, ProjectPathError):
|
||||
self.summary.setText(format_operation_error(error))
|
||||
else:
|
||||
self.summary.setText(getattr(error, 'message', str(error)))
|
||||
|
||||
def _finished(self):
|
||||
self._worker = None
|
||||
@@ -779,21 +787,22 @@ class ProjectPlanPanel(QWidget):
|
||||
report = state.report
|
||||
if report is None:
|
||||
return '', '', ''
|
||||
warning_summary = f' · 警告 {len(report.warnings)} 项' if report.warnings else ''
|
||||
if report.deferred:
|
||||
failed_paths = {row.project_path for row in report.rows if row.status == 'failed'}
|
||||
accepted = tuple(row for row in report.rows if row.project_path not in failed_paths)
|
||||
summary = (f'BOM 表格已保存,工程位号待核验:{len(accepted)} 行、'
|
||||
f'{len({row.project_path for row in accepted})} 个工程;失败 {report.failed_rows} 行。')
|
||||
details = [summary, '确认执行后仅核验当前工程;本次导入未读取工程位号。']
|
||||
f'{len({row.project_path for row in accepted})} 个工程;失败 {report.failed_rows} 行{warning_summary}。')
|
||||
details = [summary, *report.warnings, '确认执行后仅核验当前工程;本次导入未读取工程位号。']
|
||||
details.extend(f'{row.project_name} · {Path(row.source_file).name} 第 {row.source_row} 行:{row.reason}'
|
||||
for row in report.rows)
|
||||
return summary, '\n'.join(details), 'BOM 已保存 · 待核验 · 详情'
|
||||
return summary, '\n'.join(details), f'BOM 已保存 · 待核验{warning_summary} · 详情'
|
||||
outcome = '校验通过' if state.phase is BomImportPhase.PREVIEW_READY else '校验未通过'
|
||||
summary = (f'BOM {outcome}:共 {report.total_rows} 行,通过 {report.passed_rows} 行、'
|
||||
f'失败 {report.failed_rows} 行、未检查 {report.unchecked_rows} 行;'
|
||||
f'共 {report.total_projects} 个工程,通过 {report.passed_projects} 个、'
|
||||
f'失败 {report.failed_projects} 个、未检查 {report.unchecked_projects} 个。')
|
||||
details = [summary, *report.errors]
|
||||
f'失败 {report.failed_projects} 个、未检查 {report.unchecked_projects} 个{warning_summary}。')
|
||||
details = [summary, *report.errors, *report.warnings]
|
||||
if report.source_map_path is not None:
|
||||
details.append(f'导入来源记录:{report.source_map_path}')
|
||||
details.extend(f'{Path(row.source_file).name + " · " if row.source_file else ""}'
|
||||
|
||||
@@ -79,6 +79,10 @@ class TaskList(QWidget):
|
||||
self.recycle_button = QPushButton('回收站', objectName='taskRecycleBin')
|
||||
self.recycle_button.setCheckable(True)
|
||||
self.count = QLabel(objectName='taskCount')
|
||||
self.empty_hint = QLabel(objectName='taskEmptyHint')
|
||||
self.empty_hint.setTextFormat(Qt.TextFormat.PlainText)
|
||||
self.empty_hint.setWordWrap(True)
|
||||
self.empty_hint.hide()
|
||||
self.filter = QComboBox(objectName="taskFilter")
|
||||
for label, key, picture in (('全部任务', 'all', 'grid'), ('未完成', 'unfinished', 'clock'),
|
||||
('待开始', 'pending', 'clock'), ('执行中', 'running', 'clock'),
|
||||
@@ -101,6 +105,8 @@ class TaskList(QWidget):
|
||||
self.restore_button = QPushButton("恢复", objectName="restoreTaskButton")
|
||||
self.queue_button = QPushButton("顺序执行本批任务", objectName="executeProjectTasks")
|
||||
self.queue_button.setToolTip('按保存的执行顺序执行本批全部任务,不受搜索和显示排序影响。')
|
||||
self.selected_queue_button = QPushButton('顺序执行所选任务', objectName='executeSelectedProjectTasks')
|
||||
self.selected_queue_button.setToolTip('仅处理列表中明确选中的同批任务,仍按保存的执行顺序;执行前列出逐任务裁决。')
|
||||
self.up_button = QPushButton("上移任务", objectName="moveTaskUp")
|
||||
self.down_button = QPushButton("下移任务", objectName="moveTaskDown")
|
||||
self.new_button.setProperty('appearance','quiet')
|
||||
@@ -146,8 +152,10 @@ class TaskList(QWidget):
|
||||
layout.addWidget(self.filter)
|
||||
layout.addLayout(batch)
|
||||
layout.addLayout(selection)
|
||||
layout.addWidget(self.empty_hint)
|
||||
layout.addWidget(self.list, 1)
|
||||
layout.addWidget(self.queue_button)
|
||||
layout.addWidget(self.selected_queue_button)
|
||||
layout.addLayout(footer)
|
||||
def selected():
|
||||
task_id = self.current_task_id()
|
||||
@@ -166,6 +174,9 @@ class TaskList(QWidget):
|
||||
item = self.list.currentItem()
|
||||
return str(item.data(Qt.ItemDataRole.UserRole)) if item is not None else None
|
||||
|
||||
def selected_task_ids(self) -> tuple[str, ...]:
|
||||
return tuple(str(item.data(Qt.ItemDataRole.UserRole)) for item in self.list.selectedItems())
|
||||
|
||||
def populate(self, tasks: Iterable[object], *, selected_task_id: str | None = None) -> None:
|
||||
preserve_selection = selected_task_id in (None, self.current_task_id())
|
||||
selected_ids = {item.data(Qt.ItemDataRole.UserRole) for item in self.list.selectedItems()}
|
||||
@@ -212,6 +223,7 @@ class TaskList(QWidget):
|
||||
current = current.split(' · 已选 ', 1)[0]
|
||||
if current:
|
||||
self.count.setText(current + suffix)
|
||||
self.view_changed.emit()
|
||||
|
||||
def _render(self):
|
||||
selected = self._selected_task_id
|
||||
@@ -254,6 +266,17 @@ class TaskList(QWidget):
|
||||
if getattr(task, "task_id") == selected:
|
||||
self.list.setCurrentItem(item)
|
||||
hidden = selected and self.current_task_id() is None
|
||||
self.count.setText(f'{len(tasks)} / {len(self._tasks)} 个任务' + (' · 当前任务已隐藏' if hidden else ''))
|
||||
if not tasks:
|
||||
category_text = self.filter.currentText() if category != 'all' and not self.recycle_button.isChecked() else ''
|
||||
if not self._tasks:
|
||||
hint = '回收站为空。' if self.recycle_button.isChecked() else '暂无任务,点击“新建任务”导入工程。'
|
||||
elif query:
|
||||
scope = f'“{category_text}”中' if category_text else ''
|
||||
hint = f'{scope}未找到与“{self.search.text().strip()}”匹配的任务。'
|
||||
else:
|
||||
hint = f'暂无“{category_text}”任务。'
|
||||
self.empty_hint.setText(hint)
|
||||
self.empty_hint.setVisible(not tasks)
|
||||
self.count.setText(f'匹配 {len(tasks)} / 共 {len(self._tasks)} 个任务' + (' · 当前任务已隐藏' if hidden else ''))
|
||||
self._update_selection_state()
|
||||
self.view_changed.emit()
|
||||
@@ -0,0 +1,187 @@
|
||||
"""Nonmodal preview and sequential import of saved project pairs."""
|
||||
from threading import Event
|
||||
from uuid import uuid4
|
||||
|
||||
from PySide6.QtCore import QObject, Signal, Qt
|
||||
from PySide6.QtWidgets import (QDialog, QFileDialog, QHeaderView, QHBoxLayout, QLabel,
|
||||
QLineEdit, QPushButton, QTableWidget, QTableWidgetItem, QVBoxLayout)
|
||||
|
||||
|
||||
LABELS = {'ready': '可导入', 'missing_before': '缺少修改前工程', 'missing_after': '缺少修改后工程',
|
||||
'ambiguous': '无法唯一配对', 'imported': '已导入', 'failed': '导入失败,可重试'}
|
||||
|
||||
|
||||
class _Progress(QObject):
|
||||
changed = Signal(object, int, int)
|
||||
|
||||
|
||||
class VerificationBatchDialog(QDialog):
|
||||
changed = Signal()
|
||||
|
||||
def __init__(self, service, controller, task_id, task_name, parent=None):
|
||||
super().__init__(parent)
|
||||
self.service, self.controller, self.task_id = service, controller, task_id
|
||||
self._phase = None
|
||||
self._closed = False
|
||||
self._stop = Event()
|
||||
self._rows = []
|
||||
self._selection = []
|
||||
self.setWindowTitle('批量添加工程对')
|
||||
self.resize(860, 540)
|
||||
layout = QVBoxLayout(self)
|
||||
title = QLabel(f'添加到:{task_name}')
|
||||
title.setWordWrap(True)
|
||||
layout.addWidget(title)
|
||||
explanation = QLabel('按两个目录中的相对路径精确配对;先预览再导入。只建立只读副本,不自动开始校验。')
|
||||
explanation.setWordWrap(True)
|
||||
layout.addWidget(explanation)
|
||||
self.before = QLineEdit(objectName='verificationBeforeRoot')
|
||||
self.after = QLineEdit(objectName='verificationAfterRoot')
|
||||
self._browsers = []
|
||||
for label, field in (('修改前目录', self.before), ('修改后目录', self.after)):
|
||||
row = QHBoxLayout()
|
||||
row.addWidget(QLabel(label)); row.addWidget(field, 1)
|
||||
browse = QPushButton('选择目录')
|
||||
browse.clicked.connect(lambda _, f=field: self._browse(f))
|
||||
self._browsers.append(browse); row.addWidget(browse)
|
||||
layout.addLayout(row)
|
||||
field.textChanged.connect(self._invalidate)
|
||||
actions = QHBoxLayout()
|
||||
self.scan = QPushButton('读取配对', objectName='verificationScanPairs')
|
||||
self.select_all = QPushButton('全选可导入项')
|
||||
self.select_none = QPushButton('清空选择')
|
||||
for button in (self.scan, self.select_all, self.select_none): actions.addWidget(button)
|
||||
actions.addStretch(); layout.addLayout(actions)
|
||||
self.table = QTableWidget(0, 4, objectName='verificationPairPreview')
|
||||
self.table.setHorizontalHeaderLabels(['工程相对路径', '修改前工程', '修改后工程', '状态'])
|
||||
self.table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
|
||||
self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
|
||||
layout.addWidget(self.table, 1)
|
||||
self.summary = QLabel('选择前后目录后读取配对。'); self.summary.setWordWrap(True)
|
||||
layout.addWidget(self.summary)
|
||||
bottom = QHBoxLayout()
|
||||
self.import_button = QPushButton('导入所选', objectName='verificationImportPairs')
|
||||
self.cancel_button = QPushButton('取消当前操作')
|
||||
close_button = QPushButton('关闭')
|
||||
bottom.addWidget(self.import_button); bottom.addWidget(self.cancel_button); bottom.addStretch(); bottom.addWidget(close_button)
|
||||
layout.addLayout(bottom)
|
||||
self.scan.clicked.connect(self._scan)
|
||||
self.select_all.clicked.connect(lambda: self._select(Qt.CheckState.Checked))
|
||||
self.select_none.clicked.connect(lambda: self._select(Qt.CheckState.Unchecked))
|
||||
self.table.itemChanged.connect(self._selection_changed)
|
||||
self.import_button.clicked.connect(self._import)
|
||||
self.cancel_button.clicked.connect(self.cancel_operation)
|
||||
close_button.clicked.connect(self.reject)
|
||||
self._gates()
|
||||
|
||||
@property
|
||||
def busy(self): return self._phase is not None
|
||||
|
||||
def _browse(self, field):
|
||||
selected = QFileDialog.getExistingDirectory(self, '选择工程根目录', field.text())
|
||||
if selected: field.setText(selected)
|
||||
|
||||
def _invalidate(self):
|
||||
if not self.busy:
|
||||
self._rows = []; self.table.setRowCount(0)
|
||||
self.summary.setText('目录已改变,请重新读取配对。'); self._gates()
|
||||
|
||||
def _selected(self):
|
||||
return [n for n, row in enumerate(self._rows) if row['status'] in ('ready', 'failed')
|
||||
and self.table.item(n, 0).checkState() == Qt.CheckState.Checked]
|
||||
|
||||
def _gates(self):
|
||||
for widget in (self.before, self.after, *self._browsers, self.select_all, self.select_none, self.table):
|
||||
widget.setEnabled(not self.busy)
|
||||
self.scan.setEnabled(not self.busy and bool(self.before.text().strip()) and bool(self.after.text().strip()))
|
||||
self.import_button.setEnabled(not self.busy and bool(self._selected()))
|
||||
self.cancel_button.setEnabled(self.busy and not self._stop.is_set())
|
||||
|
||||
def _select(self, state):
|
||||
for n, row in enumerate(self._rows):
|
||||
if row['status'] in ('ready', 'failed'): self.table.item(n, 0).setCheckState(state)
|
||||
|
||||
def _selection_changed(self):
|
||||
if not self.busy:
|
||||
self.summary.setText(f'共 {len(self._rows)} 项,已选 {len(self._selected())} 对;缺失或不唯一的项目不会导入。')
|
||||
self._gates()
|
||||
|
||||
def _scan(self):
|
||||
before, after = self.before.text().strip(), self.after.text().strip()
|
||||
self._phase = 'scan'; self._stop = Event(); self._rows = []; self.table.setRowCount(0)
|
||||
self.summary.setText('正在读取前后目录…'); self._gates()
|
||||
stop = self._stop
|
||||
self.controller.command(lambda: self.service.preview_pairs(before, after, stop_event=stop), self._scanned, self._failed)
|
||||
|
||||
def _scanned(self, rows):
|
||||
self._phase = None
|
||||
if self._closed: return
|
||||
self._rows = rows
|
||||
self.table.blockSignals(True)
|
||||
try:
|
||||
self.table.setRowCount(len(rows))
|
||||
for n, row in enumerate(rows):
|
||||
for col, value in enumerate((row['relative_path'], row['before'] or '—', row['after'] or '—', LABELS[row['status']])):
|
||||
item = QTableWidgetItem(value); item.setToolTip(value)
|
||||
if col == 0:
|
||||
item.setCheckState(Qt.CheckState.Checked if row['status']=='ready' else Qt.CheckState.Unchecked)
|
||||
if row['status']!='ready': item.setFlags(item.flags() & ~Qt.ItemFlag.ItemIsUserCheckable)
|
||||
self.table.setItem(n, col, item)
|
||||
finally: self.table.blockSignals(False)
|
||||
self._selection_changed()
|
||||
|
||||
def _import(self):
|
||||
self._selection = self._selected()
|
||||
pairs = tuple((self._rows[n]['before'], self._rows[n]['after']) for n in self._selection)
|
||||
names = tuple(self._rows[n]['relative_path'] for n in self._selection)
|
||||
self._phase = 'import'; self._stop = Event()
|
||||
self.summary.setText(f'正在导入 0/{len(pairs)} 对…'); self._gates()
|
||||
progress = _Progress(self); progress.changed.connect(self._progress)
|
||||
stop, request = self._stop, uuid4().hex
|
||||
self.controller.command(lambda: self.service.import_pairs(self.task_id, pairs, request_id=request,
|
||||
stop_event=stop, on_progress=progress.changed.emit, display_names=names), self._imported, self._failed)
|
||||
|
||||
def _progress(self, row, processed, total):
|
||||
if self._closed: return
|
||||
n = self._selection[row['index']]
|
||||
self._rows[n]['status'] = row['status']
|
||||
status = self.table.item(n, 3)
|
||||
status.setText(LABELS[row['status']]); status.setToolTip(row.get('reason', LABELS[row['status']]))
|
||||
if row['status'] == 'imported':
|
||||
self.table.item(n, 0).setCheckState(Qt.CheckState.Unchecked)
|
||||
self.table.item(n, 0).setFlags(self.table.item(n, 0).flags() & ~Qt.ItemFlag.ItemIsUserCheckable)
|
||||
self.summary.setText(f'已处理 {processed}/{total} 对;单项失败后继续,已导入项予以保留。')
|
||||
|
||||
def _imported(self, result):
|
||||
self._phase = None
|
||||
self.changed.emit()
|
||||
if self._closed: return
|
||||
imported = sum(r['status']=='imported' for r in result['rows'])
|
||||
failed = sum(r['status']=='failed' for r in result['rows'])
|
||||
state = '已取消,未处理项可继续导入' if result['cancelled'] else '本批导入完成'
|
||||
self.summary.setText(f'{state}:已导入 {imported} 对,失败 {failed} 对;尚未开始校验。')
|
||||
self._gates()
|
||||
|
||||
def _failed(self, error):
|
||||
phase, self._phase = self._phase, None
|
||||
self.changed.emit()
|
||||
if self._closed: return
|
||||
if getattr(error, 'code', None) in ('discovery_cancelled', 'operation_cancelled'):
|
||||
self.summary.setText('已取消读取,请重新读取配对。')
|
||||
else:
|
||||
prefix = '导入中断,已导入项保留:' if phase=='import' else '读取失败:'
|
||||
self.summary.setText(prefix+str(error))
|
||||
self._gates()
|
||||
|
||||
def cancel_operation(self):
|
||||
self._stop.set()
|
||||
if self.busy and not self._closed:
|
||||
self.summary.setText('正在取消,已导入项保留…'); self._gates()
|
||||
|
||||
def reject(self):
|
||||
self._closed = True; self.cancel_operation()
|
||||
super().reject()
|
||||
|
||||
def closeEvent(self, event):
|
||||
self._closed = True; self.cancel_operation()
|
||||
super().closeEvent(event)
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Asynchronous verification reads; each selection owns its own query generation."""
|
||||
from PySide6.QtCore import QObject,QThreadPool,Signal,Slot
|
||||
from .queries import LatestQuery
|
||||
from .workers import ServiceWorker
|
||||
|
||||
|
||||
class VerificationController(QObject):
|
||||
changed=Signal()
|
||||
failed=Signal(object)
|
||||
def __init__(self,service,parent=None):
|
||||
super().__init__(parent);self.service=service;self.task_id=None;self.item_id=None
|
||||
self.tasks_query=LatestQuery(self);self.task_query=LatestQuery(self);self.item_query=LatestQuery(self)
|
||||
self.workers={};self.closed=False
|
||||
for query in (self.tasks_query,self.task_query,self.item_query):query.settled.connect(self.changed)
|
||||
|
||||
@property
|
||||
def busy(self):
|
||||
return bool(self.workers) or any(q.busy for q in (self.tasks_query,self.task_query,self.item_query)) or getattr(self.service,'busy',False)
|
||||
|
||||
def command(self,action,received,failed=None):
|
||||
if self.closed:return
|
||||
worker=ServiceWorker(action);self.workers[worker.signals]=(worker,received,failed)
|
||||
worker.signals.succeeded.connect(self._received);worker.signals.failed.connect(self._failed)
|
||||
worker.signals.finished.connect(self._finished);QThreadPool.globalInstance().start(worker);self.changed.emit()
|
||||
|
||||
@Slot(object)
|
||||
def _received(self,result):
|
||||
entry=self.workers.get(self.sender())
|
||||
if entry and not self.closed:entry[1](result)
|
||||
|
||||
@Slot(object)
|
||||
def _failed(self,error):
|
||||
entry=self.workers.get(self.sender())
|
||||
if entry and not self.closed:
|
||||
(entry[2] or self.failed.emit)(error)
|
||||
|
||||
@Slot()
|
||||
def _finished(self):self.workers.pop(self.sender(),None);self.changed.emit()
|
||||
|
||||
def close(self):
|
||||
self.closed=True
|
||||
for q in (self.tasks_query,self.task_query,self.item_query):q.close()
|
||||
@@ -0,0 +1,149 @@
|
||||
"""Deterministic before/after netlist drawing and matching facts."""
|
||||
import json
|
||||
from PySide6.QtCore import QRectF,Qt,Signal
|
||||
from PySide6.QtCore import QSignalBlocker
|
||||
from PySide6.QtGui import QColor,QPainter,QPen
|
||||
from PySide6.QtWidgets import (QWidget,QLabel,QVBoxLayout,QHBoxLayout,QComboBox,QTableWidget,
|
||||
QTableWidgetItem,QHeaderView,QTabWidget,QScrollArea,QPlainTextEdit,QPushButton)
|
||||
from ..verification.evidence import PIN_FACT_COLORS,pin_fact,verify_evidence
|
||||
|
||||
ATTEMPTS={'queued':'排队中','running':'执行中','publishing':'保存结果中','stopping':'安全收尾中',
|
||||
'succeeded':'执行完成','failed':'执行失败','cancelled':'已停止','interrupted':'已中断'}
|
||||
|
||||
|
||||
def _choices(combo,rows,selected):
|
||||
current=[(combo.itemText(n),combo.itemData(n)) for n in range(combo.count())]
|
||||
with QSignalBlocker(combo):
|
||||
if current!=rows:
|
||||
combo.clear()
|
||||
for label,value in rows:combo.addItem(label,value)
|
||||
combo.setCurrentIndex(combo.findData(selected))
|
||||
|
||||
|
||||
def pin_text(pin):
|
||||
if pin is None:return '不存在/未覆盖'
|
||||
if not pin['nets']:return '明确未连接'
|
||||
return '\n'.join(n['name']+' · '+', '.join(f'{e[1]}.{e[2]}' for e in n['endpoints'] if e!=[None]) for n in pin['nets'])
|
||||
|
||||
|
||||
class ConnectionDiagram(QWidget):
|
||||
def __init__(self,parent=None):
|
||||
super().__init__(parent);self.pins=[];self.facts=[];self.setMinimumSize(320,220)
|
||||
|
||||
def set_pins(self,pins,facts):
|
||||
self.pins=pins;self.facts=facts;self.setMinimumHeight(max(220,100+len(pins)*100));self.update()
|
||||
|
||||
def paintEvent(self,event):
|
||||
painter=QPainter(self);painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
painter.fillRect(self.rect(),QColor('#ffffff'));w=self.width()/2
|
||||
for column,phase,title in ((0,'before','修改前'),(1,'after','修改后')):
|
||||
x=column*w+12
|
||||
painter.setPen(QColor('#34445b'));painter.drawText(QRectF(x,8,w-24,26),Qt.AlignmentFlag.AlignLeft,title)
|
||||
painter.setPen(QPen(QColor('#dfe6ef'),1));painter.drawRoundedRect(QRectF(x,40,w-24,self.height()-55),9,9)
|
||||
for n,row in enumerate(self.pins):
|
||||
y=64+n*100;pin=row[phase]
|
||||
label,state=self.facts[n]
|
||||
color=QColor(PIN_FACT_COLORS[state])
|
||||
name=pin['logical_name'] if pin else ('不存在' if label.startswith('器件') else '未覆盖')
|
||||
change=f' · {label}' if state!='equal' else ''
|
||||
painter.setPen(color);painter.drawText(QRectF(x+12,y,w-46,24),Qt.AlignmentFlag.AlignLeft,
|
||||
f"脚 {row['endpoint'][2]} {name}{change}")
|
||||
painter.drawLine(int(x+18),int(y+37),int(x+40),int(y+37))
|
||||
painter.setPen(QColor('#516078'))
|
||||
font=painter.font();font.setPointSizeF(8.5);painter.setFont(font)
|
||||
painter.drawText(QRectF(x+44,y+24,w-78,64),Qt.TextFlag.TextWordWrap,pin_text(pin))
|
||||
painter.end()
|
||||
|
||||
|
||||
class VerificationInspector(QWidget):
|
||||
open_raw=Signal(str)
|
||||
select_version=Signal(int)
|
||||
select_attempt=Signal(str)
|
||||
def __init__(self,parent=None):
|
||||
super().__init__(parent);self.evidence=None
|
||||
layout=QVBoxLayout(self);layout.setContentsMargins(12,8,12,8)
|
||||
self.heading=QLabel('选择工程查看证据',objectName='projectTitle');layout.addWidget(self.heading)
|
||||
self.coverage=QLabel('未覆盖:封装库内部映射');self.coverage.setWordWrap(True);layout.addWidget(self.coverage)
|
||||
row=QHBoxLayout();self.components=QComboBox();self.components.setMinimumWidth(100)
|
||||
self.versions=QComboBox();self.versions.setToolTip('查看历史输入版本,不改变当前输入')
|
||||
row.addWidget(self.components,1);row.addWidget(self.versions);layout.addLayout(row)
|
||||
self.attempts=QComboBox();layout.addWidget(self.attempts)
|
||||
self.issues=QComboBox();layout.addWidget(self.issues)
|
||||
self.tabs=QTabWidget();layout.addWidget(self.tabs,1)
|
||||
self.diagram=ConnectionDiagram();scroll=QScrollArea();scroll.setWidgetResizable(True);scroll.setWidget(self.diagram)
|
||||
self.tabs.addTab(scroll,'前后接线图')
|
||||
self.pin_table=QTableWidget(0,6);self.pin_table.setHorizontalHeaderLabels(['脚号','前名称','后名称','前连接','后连接','变化'])
|
||||
self.pin_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
|
||||
self.pin_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.ResizeToContents)
|
||||
self.tabs.addTab(self.pin_table,'逐脚事实')
|
||||
self.facts=QPlainTextEdit();self.facts.setReadOnly(True);self.tabs.addTab(self.facts,'检查与范围')
|
||||
self.raw=QComboBox();self.raw_button=QPushButton('打开原始证据')
|
||||
rawrow=QHBoxLayout();rawrow.addWidget(self.raw,1);rawrow.addWidget(self.raw_button);layout.addLayout(rawrow)
|
||||
self.raw_button.clicked.connect(lambda:self.open_raw.emit(self.raw.currentData()) if self.raw.currentData() else None)
|
||||
self.components.currentIndexChanged.connect(self._component)
|
||||
self.issues.currentIndexChanged.connect(self._issue)
|
||||
self.versions.activated.connect(lambda _:self.select_version.emit(self.versions.currentData()))
|
||||
self.attempts.activated.connect(lambda _:self.select_attempt.emit(self.attempts.currentData()) if self.attempts.currentData() else None)
|
||||
|
||||
def set_record(self,record):
|
||||
versions=record.get('versions',sorted({record['current_version'],*(h['input_version'] for h in record['history'])},reverse=True))
|
||||
_choices(self.versions,[(f'输入 v{v}',v) for v in versions],record['input_version'])
|
||||
attempts=[(f"第 {e['generation']} 次校验 · {ATTEMPTS.get(e['state'],'未完成')}",e['attempt_id'])
|
||||
for e in record['history'] if e['input_version']==record['input_version']]
|
||||
_choices(self.attempts,attempts,record.get('attempt_id'))
|
||||
result=((record.get('attempt') or {}).get('result') or {})
|
||||
if record.get('evidence_error'):
|
||||
self.set_evidence(None);self.heading.setText(record['display_name']+' · 证据不可用')
|
||||
self.facts.setPlainText(record['evidence_error']);return
|
||||
evidence=result.get('evidence')
|
||||
if (evidence or {}).get('digest')!=(self.evidence or {}).get('digest'):self.set_evidence(evidence)
|
||||
self.heading.setText(record['display_name']+' · '+{'CONSISTENT':'一致','WARNING':'需关注','DIFFERENT':'异常','INCOMPLETE':'无法完整校验'}.get(result.get('verdict'),'待校验'))
|
||||
details=json.dumps({'范围':result.get('scope',record['scope']),'检查':result.get('checks',[]),
|
||||
'问题':result.get('issues',[]),'执行原因':result.get('reason') or record.get('reason') or record.get('unavailable_reason'),
|
||||
'输入摘要':record['payload']['payload_digest'],'尝试':record.get('attempt_id')},ensure_ascii=False,indent=2)
|
||||
if self.facts.toPlainText()!=details:self.facts.setPlainText(details)
|
||||
|
||||
def clear(self):
|
||||
self.heading.setText('选择工程查看证据');self.facts.clear();self.versions.clear();self.attempts.clear();self.set_evidence(None)
|
||||
|
||||
def set_evidence(self,evidence):
|
||||
if evidence:verify_evidence(evidence)
|
||||
previous=self.components.currentData()
|
||||
self.evidence=evidence;self.components.blockSignals(True);self.components.clear();self.issues.blockSignals(True);self.issues.clear();self.raw.clear()
|
||||
if evidence:
|
||||
for key in sorted({tuple(p['endpoint'][:2]) for p in evidence['pins']}):self.components.addItem(f'{key[1]} · {key[0]}',key)
|
||||
self.issues.addItem('全部问题',None)
|
||||
def priority(issue):
|
||||
related=sum(i.get('refdes')==issue.get('refdes') and i.get('instance_path')==issue.get('instance_path') for i in evidence['issues'])
|
||||
return (0 if issue['state']=='error' else 1,-related,issue.get('refdes',''))
|
||||
for issue in sorted(evidence['issues'],key=priority):self.issues.addItem(f"{issue.get('refdes','工程')} · {issue['reason']}",issue)
|
||||
for raw in evidence['binding'].get('raw',[]):self.raw.addItem(raw['artifact_id'],raw['artifact_id'])
|
||||
self.coverage.setText('由网表生成 · 图页未定位\n未覆盖:封装库内部映射、引脚级 Value')
|
||||
self.components.blockSignals(False);self.issues.blockSignals(False);self._component()
|
||||
old=next((n for n in range(self.components.count()) if self.components.itemData(n)==previous),-1)
|
||||
if old>=0:self.components.setCurrentIndex(old)
|
||||
elif self.issues.count()>1:self.issues.setCurrentIndex(1);self._issue()
|
||||
|
||||
def _issue(self):
|
||||
issue=self.issues.currentData()
|
||||
if issue:
|
||||
key=(issue.get('instance_path'),issue.get('refdes'))
|
||||
index=next((n for n in range(self.components.count()) if tuple(self.components.itemData(n))==key),-1)
|
||||
if index>=0:self.components.setCurrentIndex(index)
|
||||
|
||||
def _component(self):
|
||||
key=self.components.currentData()
|
||||
evidence=self.evidence or {}
|
||||
pins=[p for p in evidence.get('pins',[]) if tuple(p['endpoint'][:2])==key]
|
||||
issues={issue['issue_id']:issue for issue in evidence.get('issues',())}
|
||||
facts=[pin_fact(pin,issues) for pin in pins]
|
||||
self.diagram.set_pins(pins,facts);self.pin_table.setRowCount(len(pins))
|
||||
for n,row in enumerate(pins):
|
||||
l,r=row['before'],row['after']
|
||||
for col,value in enumerate((row['endpoint'][2],l['logical_name'] if l else '未知',r['logical_name'] if r else '未知',pin_text(l),pin_text(r))):
|
||||
self.pin_table.setItem(n,col,QTableWidgetItem(value))
|
||||
label,state=facts[n]
|
||||
cell=QTableWidgetItem(label)
|
||||
cell.setForeground(QColor(PIN_FACT_COLORS[state]))
|
||||
self.pin_table.setItem(n,5,cell)
|
||||
self.pin_table.resizeRowsToContents()
|
||||
@@ -0,0 +1,280 @@
|
||||
"""The fourth workspace: independently creatable tasks and continuous handoff."""
|
||||
from threading import Event
|
||||
from uuid import uuid4
|
||||
from PySide6.QtCore import Qt,QTimer,Signal,QSignalBlocker,QItemSelectionModel
|
||||
from PySide6.QtGui import QColor
|
||||
from PySide6.QtWidgets import (QWidget,QVBoxLayout,QHBoxLayout,QLabel,QPushButton,QListWidget,QListWidgetItem,
|
||||
QTableWidget,QTableWidgetItem,QSplitter,QLineEdit,QComboBox,QInputDialog,QFileDialog,QHeaderView)
|
||||
from .verification_controller import VerificationController
|
||||
from .verification_inspector import VerificationInspector
|
||||
|
||||
LABELS={'consistent':'一致','warning':'需关注','different':'异常','unavailable':'无法校验',
|
||||
'waiting':'待校验','running':'校验中','stopped':'已停止','interrupted':'已中断'}
|
||||
|
||||
|
||||
class VerificationWorkspace(QWidget):
|
||||
busy_changed=Signal()
|
||||
def __init__(self,service,parent=None):
|
||||
super().__init__(parent);self.service=service.verification;self.controller=VerificationController(self.service,self)
|
||||
self._active=False;self._closed=False;self._run_id=None;self._rows=[];self._cursor=None;self._intake_stop=Event()
|
||||
layout=QVBoxLayout(self);layout.setContentsMargins(16,12,16,12)
|
||||
head=QHBoxLayout();self.title=QLabel('工程校验',objectName='verificationTitle');head.addWidget(self.title);head.addStretch()
|
||||
self.title.setStyleSheet('font-size:20px;font-weight:600;color:#34445b')
|
||||
self._scroll_to_selection=False;self._view_version=None;self._view_attempt=None;self._selected_attempt=None
|
||||
self._page_cursor=None
|
||||
self._task_list_cursor=None
|
||||
self._next_tasks_cursor=None
|
||||
self._previous_tasks_cursors=[]
|
||||
self.new_button=QPushButton('新建校验',objectName='verificationNew');self.import_button=QPushButton('添加工程对')
|
||||
self.batch_button=QPushButton('批量添加',objectName='verificationBatchImport');self._batch_dialog=None
|
||||
head.addWidget(self.import_button);head.addWidget(self.batch_button);head.addWidget(self.new_button);layout.addLayout(head)
|
||||
description=QLabel('替换完成后接续核对,也可随时添加两份工程独立校验。');description.setWordWrap(True);layout.addWidget(description)
|
||||
self.splitter=QSplitter();layout.addWidget(self.splitter,1)
|
||||
left=QWidget();ll=QVBoxLayout(left);ll.setContentsMargins(0,0,8,0);ll.addWidget(QLabel('校验任务'))
|
||||
self.tasks=QListWidget();ll.addWidget(self.tasks,1)
|
||||
task_paging=QHBoxLayout()
|
||||
self.previous_tasks_button=QPushButton('上一页')
|
||||
self.next_tasks_button=QPushButton('下一页')
|
||||
self.previous_tasks_button.setAccessibleName('校验任务上一页')
|
||||
self.next_tasks_button.setAccessibleName('校验任务下一页')
|
||||
task_paging.addWidget(self.previous_tasks_button)
|
||||
task_paging.addWidget(self.next_tasks_button)
|
||||
ll.addLayout(task_paging)
|
||||
self.state_filter=QComboBox();self.state_filter.addItem('全部工程','')
|
||||
for key,value in LABELS.items():self.state_filter.addItem(value,key)
|
||||
ll.addWidget(self.state_filter);self.splitter.addWidget(left)
|
||||
middle=QWidget();ml=QVBoxLayout(middle);ml.setContentsMargins(4,0,4,0)
|
||||
self.search=QLineEdit();self.search.setPlaceholderText('搜索工程、位号、料号');self.search.setClearButtonEnabled(True);ml.addWidget(self.search)
|
||||
controls=QHBoxLayout();self.start_button=QPushButton('开始全部');self.selected_button=QPushButton('校验所选');self.stop_button=QPushButton('停止')
|
||||
for button in (self.start_button,self.selected_button,self.stop_button):controls.addWidget(button)
|
||||
ml.addLayout(controls)
|
||||
self.table=QTableWidget(0,4);self.table.setHorizontalHeaderLabels(['工程','版本','结果','范围'])
|
||||
self.table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows);self.table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
|
||||
self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch);ml.addWidget(self.table,1)
|
||||
bottom=QHBoxLayout();self.more_button=QPushButton('下一页');self.rerun_button=QPushButton('重校验');self.export_button=QPushButton('导出报告')
|
||||
for button in (self.more_button,self.rerun_button,self.export_button):bottom.addWidget(button)
|
||||
ml.addLayout(bottom);self.splitter.addWidget(middle)
|
||||
self.inspector=VerificationInspector();self.splitter.addWidget(self.inspector);self.splitter.setSizes([180,430,570])
|
||||
self.footer=QLabel('新建一个校验任务开始。');self.footer.setWordWrap(True);layout.addWidget(self.footer)
|
||||
self.notice=QLabel('');self.notice.setWordWrap(True);layout.addWidget(self.notice)
|
||||
self.new_button.clicked.connect(self._new);self.import_button.clicked.connect(self._import)
|
||||
self.batch_button.clicked.connect(self._batch_import)
|
||||
self.tasks.currentItemChanged.connect(self._task_selected);self.table.itemSelectionChanged.connect(self._item_selected)
|
||||
self.previous_tasks_button.clicked.connect(lambda:self._turn_tasks_page(False))
|
||||
self.next_tasks_button.clicked.connect(lambda:self._turn_tasks_page(True))
|
||||
self.state_filter.currentIndexChanged.connect(self._filters_changed);self.search.textChanged.connect(self._search_changed)
|
||||
self.more_button.clicked.connect(lambda:self.refresh_task(append=True));self.start_button.clicked.connect(lambda:self._start(False))
|
||||
self.selected_button.clicked.connect(lambda:self._start(True));self.stop_button.clicked.connect(self._stop)
|
||||
self.rerun_button.clicked.connect(self._rerun);self.export_button.clicked.connect(self._export)
|
||||
self.inspector.open_raw.connect(self._open_raw);self.inspector.select_version.connect(self._version)
|
||||
self.inspector.select_attempt.connect(self._attempt)
|
||||
self.controller.failed.connect(self._error);self.controller.changed.connect(self._gates)
|
||||
self._timer=QTimer(self);self._timer.setInterval(1500);self._timer.timeout.connect(self._poll)
|
||||
self._debounce=QTimer(self);self._debounce.setSingleShot(True);self._debounce.setInterval(250);self._debounce.timeout.connect(self._filters_changed)
|
||||
self._gates()
|
||||
|
||||
@property
|
||||
def busy(self):return self.controller.busy
|
||||
|
||||
def _error(self,error):self.notice.setText(str(error))
|
||||
|
||||
def _gates(self):
|
||||
has=bool(self.controller.task_id);item=any(r['item_id']==self.controller.item_id for r in self._rows)
|
||||
self.import_button.setEnabled(has);self.start_button.setEnabled(has);self.selected_button.setEnabled(has and bool(self.table.selectionModel().selectedRows()))
|
||||
self.batch_button.setEnabled(has)
|
||||
self.rerun_button.setEnabled(item);self.export_button.setEnabled(has)
|
||||
self.stop_button.setEnabled(bool(self._run_id))
|
||||
can_page=not self.controller.tasks_query.current_busy
|
||||
self.previous_tasks_button.setEnabled(can_page and bool(self._previous_tasks_cursors))
|
||||
self.next_tasks_button.setEnabled(can_page and self._next_tasks_cursor is not None)
|
||||
self.busy_changed.emit()
|
||||
|
||||
def set_active(self,active):
|
||||
self._active=active
|
||||
if active:
|
||||
self._timer.start();self.controller.command(self.service.initialize,lambda _:self.refresh())
|
||||
else:self._timer.stop()
|
||||
|
||||
def refresh(self):
|
||||
if self._closed:return
|
||||
self._refresh_tasks()
|
||||
if self.controller.task_id:self.refresh_task()
|
||||
self._gates()
|
||||
|
||||
def _refresh_tasks(self):
|
||||
cursor=self._task_list_cursor
|
||||
self.controller.tasks_query.request(
|
||||
lambda control:self.service.list_tasks(cursor=cursor,read_control=control),
|
||||
self._tasks_received,self._tasks_failed,cancellable=True)
|
||||
|
||||
def _turn_tasks_page(self,forward):
|
||||
if forward and self._next_tasks_cursor is not None:
|
||||
self._previous_tasks_cursors.append(self._task_list_cursor)
|
||||
self._task_list_cursor=self._next_tasks_cursor
|
||||
elif not forward and self._previous_tasks_cursors:
|
||||
self._task_list_cursor=self._previous_tasks_cursors.pop()
|
||||
else:
|
||||
return
|
||||
self._refresh_tasks()
|
||||
self._gates()
|
||||
|
||||
def _tasks_failed(self,error):
|
||||
if self._task_list_cursor is not None and getattr(error,'code',None)=='verification_cursor':
|
||||
self._task_list_cursor=None
|
||||
self._previous_tasks_cursors.clear()
|
||||
self._refresh_tasks()
|
||||
else:
|
||||
self._error(error)
|
||||
|
||||
def _poll(self):
|
||||
# Let a slow current read finish; periodic ticks must not keep cancelling it.
|
||||
queries=(self.controller.tasks_query,self.controller.task_query,self.controller.item_query)
|
||||
if not self._debounce.isActive() and not any(q.current_busy for q in queries):self.refresh()
|
||||
|
||||
def _tasks_received(self,result):
|
||||
self._next_tasks_cursor=result['cursor']
|
||||
with QSignalBlocker(self.tasks):
|
||||
self.tasks.clear()
|
||||
for row in result['tasks']:
|
||||
item=QListWidgetItem(row['name']+f" {row['summary']['processed']}/{row['summary']['total']}")
|
||||
item.setData(Qt.ItemDataRole.UserRole,row['task_id']);self.tasks.addItem(item)
|
||||
item.setToolTip(row['name'])
|
||||
if row['task_id']==self.controller.task_id:self.tasks.setCurrentItem(item)
|
||||
if not self.controller.task_id and self.tasks.count():self.open_task(self.tasks.item(0).data(Qt.ItemDataRole.UserRole))
|
||||
|
||||
def open_task(self,task_id,item_id=None):
|
||||
self.controller.task_id=task_id;self.controller.item_id=item_id;self._cursor=None;self._run_id=None;self.notice.clear()
|
||||
self._scroll_to_selection=True;self._view_version=None;self._view_attempt=None;self._selected_attempt=None
|
||||
self._rows=[];self._page_cursor=None
|
||||
with QSignalBlocker(self.table):self.table.setRowCount(0)
|
||||
self.controller.item_query.invalidate();self.inspector.clear();self.refresh();self._gates()
|
||||
|
||||
def _task_selected(self,item,previous):
|
||||
if item:self.open_task(item.data(Qt.ItemDataRole.UserRole))
|
||||
|
||||
def _search_changed(self):
|
||||
self._page_cursor=None;self._cursor=None;self._debounce.start()
|
||||
|
||||
def _filters_changed(self,*_):
|
||||
self._page_cursor=None;self._cursor=None;self.refresh_task()
|
||||
|
||||
def refresh_task(self,*_,append=False):
|
||||
task=self.controller.task_id
|
||||
if not task or self._closed:return
|
||||
cursor=self._cursor if append else self._page_cursor
|
||||
state,query=self.state_filter.currentData(),self.search.text()
|
||||
self.controller.task_query.request(lambda control:self.service.read_task(task,state=state,
|
||||
query=query,cursor=cursor,read_control=control),lambda result:self._task_received(result,cursor),
|
||||
lambda error:self._task_failed(error,cursor),cancellable=True)
|
||||
|
||||
def _task_failed(self,error,cursor):
|
||||
if getattr(error,'code',None)=='verification_cursor' and cursor is not None:
|
||||
self._page_cursor=None;self._cursor=None;self.refresh_task()
|
||||
else:self._error(error)
|
||||
|
||||
def _task_received(self,result,cursor):
|
||||
self._run_id=(result.get('run') or {}).get('run_id')
|
||||
selected_ids={self._rows[i.row()]['item_id'] for i in self.table.selectionModel().selectedRows() if i.row()<len(self._rows)}
|
||||
previous=self._rows;self._rows=result['items'];self._page_cursor=cursor;self._cursor=result['cursor']
|
||||
selected=self.controller.item_id
|
||||
if selected and not selected_ids:selected_ids.add(selected)
|
||||
if previous!=self._rows:
|
||||
with QSignalBlocker(self.table):
|
||||
self.table.setRowCount(len(self._rows));self.table.clearSelection();self.table.setCurrentCell(-1,-1)
|
||||
for n,row in enumerate(self._rows):
|
||||
for col,value in enumerate((row['display_name'],str(row['input_version']),LABELS[row['status']],row['scope'])):
|
||||
cell=QTableWidgetItem(value);cell.setData(Qt.ItemDataRole.UserRole,row['item_id']);self.table.setItem(n,col,cell)
|
||||
cell.setToolTip(value)
|
||||
if col==2:cell.setForeground(QColor({'different':'#b83d4a','warning':'#9c6b1e','consistent':'#39817d'}.get(row['status'],'#61758e')))
|
||||
if row['item_id'] in selected_ids:
|
||||
self.table.selectionModel().select(self.table.model().index(n,0),QItemSelectionModel.SelectionFlag.Select|QItemSelectionModel.SelectionFlag.Rows)
|
||||
if row['item_id']==selected:self.table.setCurrentCell(n,0,QItemSelectionModel.SelectionFlag.NoUpdate)
|
||||
if self._scroll_to_selection and self.table.currentRow()>=0:
|
||||
self.table.scrollToItem(self.table.item(self.table.currentRow(),0));self._scroll_to_selection=False
|
||||
self.more_button.setEnabled(bool(self._cursor))
|
||||
s=result['summary'];self.footer.setText(f"已处理 {s['processed']}/{s['total']} · 一致 {s['consistent']} · 关注 {s['warning']} · 异常 {s['different']} · 无法校验 {s['unavailable']} · 待校验 {s['waiting']}")
|
||||
if selected:self._load_item(selected,self._view_version,self._view_attempt)
|
||||
self._gates()
|
||||
|
||||
def _item_selected(self):
|
||||
row=self.table.currentRow()
|
||||
if 0<=row<len(self._rows):
|
||||
self._view_version=None;self._view_attempt=None;self.controller.item_id=self._rows[row]['item_id'];self._load_item(self.controller.item_id);self._gates()
|
||||
|
||||
def _load_item(self,item,version=None,attempt=None):
|
||||
self.controller.item_query.request(lambda control:self.service.read_item(item,version=version,attempt_id=attempt,read_control=control),self._record_received,self._error,cancellable=True)
|
||||
|
||||
def _record_received(self,record):
|
||||
self._selected_attempt=record['attempt_id'];self.inspector.set_record(record)
|
||||
|
||||
def _attempt(self,attempt):
|
||||
self._view_attempt=attempt
|
||||
if self.controller.item_id:self._load_item(self.controller.item_id,attempt=attempt)
|
||||
|
||||
def _version(self,version):
|
||||
self._view_version=version
|
||||
self._view_attempt=None
|
||||
if self.controller.item_id:self._load_item(self.controller.item_id,version)
|
||||
|
||||
def _new(self):
|
||||
name,ok=QInputDialog.getText(self,'新建校验','任务名称',text='校验任务')
|
||||
if ok and name.strip():
|
||||
self.controller.command(lambda:self.service.create_task(name.strip(),request_id=uuid4().hex),self._open_new_task)
|
||||
|
||||
def _open_new_task(self,row):
|
||||
self._task_list_cursor=None
|
||||
self._previous_tasks_cursors.clear()
|
||||
self.open_task(row['task_id'])
|
||||
|
||||
def _import(self):
|
||||
task=self.controller.task_id
|
||||
before,_=QFileDialog.getOpenFileName(self,'选择修改前工程','','DxDesigner (*.prj)')
|
||||
if not before:return
|
||||
after,_=QFileDialog.getOpenFileName(self,'选择修改后工程','','DxDesigner (*.prj)')
|
||||
if after:
|
||||
self.controller.command(lambda:self.service.import_pair(task,before,after,request_id=uuid4().hex,stop_event=self._intake_stop),lambda _:self.refresh())
|
||||
|
||||
def _start(self,selected):
|
||||
task=self.controller.task_id
|
||||
selection=tuple((self._rows[i.row()]['item_id'],self._rows[i.row()]['input_version']) for i in self.table.selectionModel().selectedRows()) if selected else None
|
||||
if task:self.controller.command(lambda:self.service.start(task,selection=selection,request_id=uuid4().hex),self._started)
|
||||
|
||||
def _batch_import(self):
|
||||
if self._batch_dialog is not None and (self._batch_dialog.isVisible() or self._batch_dialog.busy):
|
||||
if self._batch_dialog.isVisible():self._batch_dialog.raise_();self._batch_dialog.activateWindow()
|
||||
else:self.notice.setText('上一批正在取消,已导入项会保留,请稍候。')
|
||||
return
|
||||
from .verification_batch_import import VerificationBatchDialog
|
||||
current=self.tasks.currentItem()
|
||||
name=current.text() if current else '校验任务'
|
||||
self._batch_dialog=VerificationBatchDialog(self.service,self.controller,self.controller.task_id,name,self)
|
||||
self._batch_dialog.changed.connect(self.refresh);self._batch_dialog.show()
|
||||
|
||||
def _started(self,result):self._run_id=result['run_id'];self.refresh()
|
||||
|
||||
def _stop(self):
|
||||
run_id=self._run_id
|
||||
if run_id:self.controller.command(lambda:self.service.stop(run_id,request_id=uuid4().hex),lambda _:self.refresh())
|
||||
|
||||
def _rerun(self):
|
||||
item=self.controller.item_id
|
||||
row=next((r for r in self._rows if r['item_id']==item),None)
|
||||
if row:self.controller.command(lambda:self.service.rerun(item,row['input_version'],request_id=uuid4().hex),self._started)
|
||||
|
||||
def _export(self):
|
||||
task=self.controller.task_id;folder=QFileDialog.getExistingDirectory(self,'选择报告保存位置')
|
||||
if folder:self.controller.command(lambda:self.service.export_task(task,folder,request_id=uuid4().hex),lambda result:self.notice.setText('报告已保存:'+str(result)))
|
||||
|
||||
def _open_raw(self,artifact):
|
||||
attempt=self._selected_attempt
|
||||
if attempt:self.controller.command(lambda:self.service.open_evidence(attempt,artifact),lambda _:None)
|
||||
|
||||
def begin_shutdown(self):
|
||||
self._timer.stop();self._intake_stop.set()
|
||||
if self._batch_dialog is not None:self._batch_dialog.cancel_operation()
|
||||
for query in (self.controller.tasks_query,self.controller.task_query,self.controller.item_query):query.invalidate()
|
||||
if hasattr(self.service,'begin_shutdown'):self.service.begin_shutdown()
|
||||
|
||||
def shutdown(self):
|
||||
if self._closed:return
|
||||
self._closed=True;self.begin_shutdown();self.controller.close()
|
||||
@@ -0,0 +1 @@
|
||||
"""Independent, read-only project verification and traceable evidence."""
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Exact directory pairing and resumable, sequential snapshot intake."""
|
||||
import errno
|
||||
from pathlib import Path
|
||||
|
||||
from ..errors import TaskCenterError
|
||||
from ..project_tasks import scan_project_directory
|
||||
from .contracts import digest, fail
|
||||
|
||||
|
||||
def preview_pairs(before_root, after_root, *, excluded_roots=(), stop_event=None):
|
||||
given_roots = (before_root, after_root)
|
||||
before_root, after_root = Path(before_root).resolve(), Path(after_root).resolve()
|
||||
if before_root.is_relative_to(after_root) or after_root.is_relative_to(before_root):
|
||||
fail('前后目录不能相同或互相包含。', 'verification_pair_roots')
|
||||
sides = []
|
||||
for given_root, root in zip(given_roots, (before_root, after_root)):
|
||||
groups = {}
|
||||
for path in scan_project_directory(given_root, excluded_roots=excluded_roots, stop_event=stop_event):
|
||||
relative = path.relative_to(root).as_posix()
|
||||
groups.setdefault(relative.casefold(), []).append((relative, str(path)))
|
||||
sides.append(groups)
|
||||
rows = []
|
||||
left, right = sides
|
||||
for key in sorted(left.keys() | right.keys()):
|
||||
a, b = left.get(key, []), right.get(key, [])
|
||||
status = ('ambiguous' if len(a)>1 or len(b)>1 else
|
||||
'missing_before' if not a else 'missing_after' if not b else 'ready')
|
||||
rows.append({'relative_path': (a or b)[0][0],
|
||||
'before': a[0][1] if len(a)==1 else None,
|
||||
'after': b[0][1] if len(b)==1 else None, 'status': status})
|
||||
return rows
|
||||
|
||||
|
||||
def import_pairs(service, task_id, pairs, *, request_id, stop_event, on_progress=None, display_names=None):
|
||||
pairs = tuple((str(a), str(b)) for a, b in pairs)
|
||||
names = tuple(display_names) if display_names is not None else (None,) * len(pairs)
|
||||
if len(names) != len(pairs) or any(n is not None and (not isinstance(n, str) or not n.strip()) for n in names):
|
||||
fail('工程名称必须与工程对一一对应。')
|
||||
body = [task_id, pairs, names]
|
||||
result = {'rows': [], 'processed': 0, 'total': len(pairs), 'cancelled': False}
|
||||
# Successful item receipts survive cancellation; replay never captures them twice.
|
||||
with service._intake_lock:
|
||||
service.repo.task(task_id)
|
||||
with service.repo.store.transaction():
|
||||
old = service.repo._request('import-batch', request_id, body)
|
||||
if old is not None:
|
||||
return old
|
||||
if service.repo._request('import-batch-input', request_id, body) is None:
|
||||
service.repo._remember('import-batch-input', request_id, body, {'bound': True})
|
||||
for index, (before, after) in enumerate(pairs):
|
||||
if stop_event.is_set():
|
||||
result['cancelled'] = True
|
||||
break
|
||||
row = {'index': index, 'before': before, 'after': after}
|
||||
try:
|
||||
receipt = service.import_pair(task_id, before, after,
|
||||
request_id='batch-row:'+digest([request_id, index, before, after]), stop_event=stop_event,
|
||||
display_name=names[index])
|
||||
if receipt['accepted'] or receipt['duplicates']:
|
||||
row.update(status='imported', receipt=receipt)
|
||||
else:
|
||||
reason = ';'.join(r['reason'] for r in receipt['rejected']) or '工程未被任务接收。'
|
||||
if names[index] is not None and len(names[index])>256:
|
||||
reason = '相对路径超过256字符,请缩短目录层级或使用“添加工程对”。'
|
||||
row.update(status='failed', reason=reason, receipt=receipt)
|
||||
except TaskCenterError as error:
|
||||
if error.code == 'operation_cancelled':
|
||||
result['cancelled'] = True
|
||||
break
|
||||
row.update(status='failed', reason=str(error))
|
||||
except OSError as error:
|
||||
# Storage failures affect the whole batch; source-file failures affect one pair.
|
||||
destination = Path(error.filename).resolve() if error.filename else None
|
||||
if error.errno in (errno.ENOSPC, errno.EDQUOT, errno.EIO) or (
|
||||
destination is not None and destination.is_relative_to(service.data_root)):
|
||||
raise
|
||||
row.update(status='failed', reason=str(error))
|
||||
except ValueError as error:
|
||||
row.update(status='failed', reason=str(error))
|
||||
result['rows'].append(row)
|
||||
result['processed'] += 1
|
||||
if on_progress:
|
||||
on_progress(row, result['processed'], result['total'])
|
||||
if not result['cancelled']:
|
||||
with service.repo.store.transaction():
|
||||
service.repo._remember('import-batch', request_id, body, result)
|
||||
return result
|
||||
@@ -0,0 +1,114 @@
|
||||
"""Versioned input contracts and conclusions independent of execution status."""
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
|
||||
from ..errors import TaskCenterError
|
||||
|
||||
CHECKS = frozenset(('inputs','coverage','components','physical_pins','connections','net_names',
|
||||
'declared_attributes','attribute_changes','pin_text','pin_semantics','footprint_mapping','export_identity'))
|
||||
STATES = frozenset(('equal','expected_change','warning','error','unknown','not_requested'))
|
||||
ACTIVE = ('queued','running','publishing','stopping')
|
||||
TERMINAL = ('succeeded','failed','cancelled','interrupted')
|
||||
|
||||
|
||||
def fail(message, code='verification_input'):
|
||||
raise TaskCenterError(code, message)
|
||||
|
||||
|
||||
def digest(value):
|
||||
return hashlib.sha256(json.dumps(value, sort_keys=True, ensure_ascii=False,
|
||||
separators=(',', ':'), allow_nan=False).encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def identifier(value):
|
||||
if not isinstance(value, str) or not value.strip() or len(value) > 256 or any(ord(c) < 32 for c in value):
|
||||
fail('标识不能为空或包含控制字符。')
|
||||
return value
|
||||
|
||||
|
||||
def artifact_ref(value):
|
||||
if value is None:
|
||||
return None
|
||||
if (not isinstance(value, dict) or set(value) != {'manifest_id','sha256'}
|
||||
or re.fullmatch('[0-9a-f]{32}', str(value['manifest_id'])) is None
|
||||
or re.fullmatch('[0-9a-f]{64}', str(value['sha256'])) is None):
|
||||
fail('校验证据引用无效。')
|
||||
return dict(value)
|
||||
|
||||
|
||||
def default_plan():
|
||||
return {'policy_version': 'verification-v1',
|
||||
'required_checks': ['inputs','coverage','components','physical_pins','connections','net_names'],
|
||||
'optional_checks': ['attribute_changes','pin_text','pin_semantics','export_identity'],
|
||||
'excluded_checks': ['footprint_mapping']}
|
||||
|
||||
|
||||
def validate_plan(plan):
|
||||
if not isinstance(plan, dict) or set(plan) != {'policy_version','required_checks','optional_checks','excluded_checks'}:
|
||||
fail('检查计划字段不完整。')
|
||||
if plan['policy_version'] != 'verification-v1':
|
||||
fail('不支持的校验策略版本。')
|
||||
groups = [plan[key] for key in ('required_checks','optional_checks','excluded_checks')]
|
||||
if any(not isinstance(group, (list,tuple)) for group in groups):
|
||||
fail('检查范围必须为列表。')
|
||||
flat = [key for group in groups for key in group]
|
||||
if not groups[0] or any(not isinstance(key,str) or key not in CHECKS for key in flat) or len(set(flat)) != len(flat):
|
||||
fail('检查范围为空、重复或包含未知项目。')
|
||||
return copy.deepcopy(plan)
|
||||
|
||||
|
||||
def validate_input(value):
|
||||
allowed = {'item_key','project_key','input_version','before_ref','after_ref','expectation_ref',
|
||||
'check_plan','display_name','unavailable_reason','handoff_saved_items'}
|
||||
required = {'item_key','project_key','input_version','before_ref','after_ref','expectation_ref','check_plan'}
|
||||
if not isinstance(value,dict) or set(value) - allowed or not required <= set(value):
|
||||
fail('校验输入字段不完整或包含不支持字段。')
|
||||
result = copy.deepcopy(value)
|
||||
for key in ('item_key','project_key'):
|
||||
identifier(result[key])
|
||||
if type(result['input_version']) is not int or not 1 <= result['input_version'] <= 2**31-1:
|
||||
fail('输入版本必须为正整数。')
|
||||
if 'handoff_saved_items' in result:
|
||||
count=result['handoff_saved_items']
|
||||
if type(count) is not int or count<1:fail('交接回执的已保存数量无效。')
|
||||
for key in ('before_ref','after_ref','expectation_ref'):
|
||||
result[key] = artifact_ref(result[key])
|
||||
result['check_plan'] = validate_plan(result['check_plan'])
|
||||
result['display_name'] = identifier(result.get('display_name') or result['project_key'])
|
||||
reason = result.get('unavailable_reason','')
|
||||
if not isinstance(reason,str) or len(reason)>4000:
|
||||
fail('不可用原因无效。')
|
||||
if not result['before_ref'] or not result['after_ref']:
|
||||
reason = reason or '缺少替换前或替换后的可信副本。'
|
||||
result.update(input_state='unavailable' if reason else 'ready', unavailable_reason=reason)
|
||||
result['payload_digest'] = digest(result)
|
||||
return result
|
||||
|
||||
|
||||
def rollup_results(checks, *, required_checks, optional_checks=()):
|
||||
if not required_checks or any(key not in CHECKS for key in (*required_checks,*optional_checks)):
|
||||
fail('必查项目不能为空。', 'verification_check_plan')
|
||||
states = {}
|
||||
partial = set()
|
||||
for row in checks:
|
||||
key, state = row.get('check_id'), row.get('state')
|
||||
if key not in CHECKS or state not in STATES or key in states:
|
||||
fail('检查结果包含重复或未知项目。', 'verification_result')
|
||||
states[key] = state
|
||||
if row.get('coverage')=='partial': partial.add(key)
|
||||
requested = tuple(dict.fromkeys((*required_checks,*optional_checks)))
|
||||
unknown = [key for key in requested if key in partial or states.get(key, 'unknown') in {'unknown','not_requested'}]
|
||||
if any(state=='error' for state in states.values()):
|
||||
verdict = 'DIFFERENT'
|
||||
elif any(key in unknown for key in required_checks):
|
||||
verdict = 'INCOMPLETE'
|
||||
elif any(state=='warning' for state in states.values()):
|
||||
verdict = 'WARNING'
|
||||
else:
|
||||
verdict = 'CONSISTENT'
|
||||
return {'verdict': verdict, 'coverage': 'partial' if unknown else 'complete',
|
||||
'unknown_checks': unknown, 'checked': [key for key in requested if key not in unknown],
|
||||
'warnings': sum(state=='warning' for state in states.values()),
|
||||
'errors': sum(state=='error' for state in states.values())}
|
||||
@@ -0,0 +1,171 @@
|
||||
"""Frozen run membership and cooperative cancellation for the verification domain."""
|
||||
import json
|
||||
from threading import Event,Thread,RLock
|
||||
from uuid import uuid4
|
||||
from .contracts import ACTIVE,digest,fail
|
||||
from .store import encode,now
|
||||
from .ownership import owner_path,write_owner,read_owner,RunStop
|
||||
|
||||
|
||||
class VerificationControl:
|
||||
def __init__(self,service):
|
||||
self.service=service;self.repo=service.repo;self.lock=RLock();self.events={};self.thread=None;self.closing=False
|
||||
self.last_error=None
|
||||
self.owner_id=uuid4().hex;self._owned_runs=set()
|
||||
|
||||
@property
|
||||
def busy(self):
|
||||
with self.lock:return bool(self.thread and self.thread.is_alive())
|
||||
|
||||
def start(self,task_id,*,selection,request_id):
|
||||
if self.closing:fail('校验执行器已暂停:'+self.last_error if self.last_error else '校验执行器正在安全关闭。')
|
||||
body=[task_id,selection]
|
||||
with self.repo.store.transaction():
|
||||
old=self.repo._request('start',request_id,body)
|
||||
if old is not None:return old
|
||||
self.repo.task(task_id)
|
||||
active=self.repo.connection.execute("SELECT * FROM verification_runs WHERE task_id=? AND state IN ('queued','running','stopping') ORDER BY created LIMIT 1",(task_id,)).fetchone()
|
||||
if active:
|
||||
result={'run_id':active['run_id'],'members':json.loads(active['members_json'])}
|
||||
members={(row['item_id'],row['input_version']) for row in result['members']}
|
||||
if selection is not None and not all(tuple(value) in members for value in selection):
|
||||
fail('当前校验正在运行,未包含所选工程或版本。请等本次运行结束后再启动。','verification_run_active')
|
||||
else:
|
||||
rows=self.service.queries._rows(task_id)
|
||||
wanted=set(tuple(v) for v in selection) if selection is not None else None
|
||||
members=[];run_id=uuid4().hex
|
||||
for row in rows:
|
||||
identity=(row['item_id'],row['input_version'])
|
||||
if wanted is not None and identity not in wanted:continue
|
||||
if not row['can_start']:continue
|
||||
# Start all only processes waiting/interrupted items; explicit selection permits recheck.
|
||||
if wanted is None and row['status'] not in {'waiting','interrupted'}:continue
|
||||
attempt=self.repo.create_attempt(*identity,request_id='run-attempt:'+run_id+':'+row['item_id'],run_id=run_id)
|
||||
members.append({'item_id':identity[0],'input_version':identity[1],'attempt_id':attempt['attempt_id']})
|
||||
if wanted and wanted-{(m['item_id'],m['input_version']) for m in members}:fail('所选版本已变化或正在执行,请刷新。')
|
||||
self.repo.connection.execute('INSERT INTO verification_runs(run_id,task_id,members_json,state,created) VALUES (?,?,?,?,?)',
|
||||
(run_id,task_id,encode(members),'queued' if members else 'completed',now()))
|
||||
write_owner(self.service,'runs',run_id,self.owner_id)
|
||||
result={'run_id':run_id,'members':members}
|
||||
self.repo._remember('start',request_id,body,result)
|
||||
owner=read_owner(self.service,'runs',result['run_id'])
|
||||
if owner.get('owner_id')==self.owner_id and result['members']:
|
||||
with self.lock:self._owned_runs.add(result['run_id'])
|
||||
self.wake()
|
||||
return result
|
||||
|
||||
def wake(self):
|
||||
with self.lock:
|
||||
if self._owned_runs and not self.closing and not self.busy:
|
||||
self.thread=Thread(target=self._dispatch,name='verification-runner',daemon=True);self.thread.start()
|
||||
|
||||
def stop(self,run_id,*,request_id):
|
||||
with self.repo.store.transaction():
|
||||
old=self.repo._request('stop',request_id,run_id)
|
||||
if old is not None:return old
|
||||
run=self.repo._one('verification_runs','run_id',run_id)
|
||||
self.repo.connection.execute("UPDATE verification_runs SET stop_requested=1,state=CASE WHEN state='queued' THEN 'stopped' WHEN state='running' THEN 'stopping' ELSE state END WHERE run_id=?",(run_id,))
|
||||
for member in json.loads(run['members_json']):
|
||||
self.repo.connection.execute("UPDATE verification_attempts SET state='cancelled',reason='run_stopped_before_dispatch',resource_state='released',updated=? WHERE attempt_id=? AND state='queued'",(now(),member['attempt_id']))
|
||||
self.repo._touch(run['task_id']);result={'run_id':run_id,'stop_requested':True}
|
||||
self.repo._remember('stop',request_id,run_id,result)
|
||||
with self.lock:self.events.setdefault(run_id,Event()).set()
|
||||
return result
|
||||
|
||||
def _next_run(self):
|
||||
with self.lock:owned=tuple(self._owned_runs)
|
||||
if not owned:return None
|
||||
placeholders=','.join('?' for _ in owned)
|
||||
return self.repo.connection.execute(f"SELECT * FROM verification_runs WHERE state='queued' AND run_id IN ({placeholders}) ORDER BY created LIMIT 1",owned).fetchone()
|
||||
|
||||
def _dispatch(self):
|
||||
from .runner import run_attempt
|
||||
try:
|
||||
while not self.closing:
|
||||
with self.repo.store.transaction():
|
||||
run=self._next_run()
|
||||
if run is None:return
|
||||
run=dict(run)
|
||||
if not run['stop_requested']:
|
||||
self.repo.connection.execute("UPDATE verification_runs SET state='running' WHERE run_id=?",(run['run_id'],))
|
||||
with self.lock:event=self.events.setdefault(run['run_id'],Event())
|
||||
stop=RunStop(self.service,run['run_id'],event)
|
||||
if run['stop_requested']:event.set()
|
||||
blocked=False
|
||||
for member in json.loads(run['members_json']):
|
||||
result={}
|
||||
if stop.is_set() or self.closing:break
|
||||
while not stop.is_set() and not self.closing:
|
||||
result=run_attempt(self.service,member['attempt_id'],stop_event=event)
|
||||
if not result.get('waiting'):break
|
||||
event.wait(.2)
|
||||
if result.get('blocked'):blocked=True;break
|
||||
with self.repo.store.transaction():
|
||||
state='blocked' if blocked else 'stopped' if stop.is_set() or self.closing else 'completed'
|
||||
self.repo.connection.execute('UPDATE verification_runs SET state=? WHERE run_id=?',(state,run['run_id']))
|
||||
self.repo._touch(run['task_id'])
|
||||
with self.lock:self._owned_runs.discard(run['run_id'])
|
||||
except Exception as error:
|
||||
self.closing=True;self.last_error=str(error)
|
||||
from ..batch_resources import write_record
|
||||
try:write_record(self.service.data_root/'verification/engine-paused.json',{
|
||||
'reason':str(error),'error':type(error).__name__,'replayed':False})
|
||||
except OSError:pass
|
||||
finally:
|
||||
with self.lock:
|
||||
self.thread=None
|
||||
# Close the enqueue/empty-dispatch race without polling from the UI.
|
||||
if not self.closing:
|
||||
with self.repo.store._lock:
|
||||
pending=self._next_run()
|
||||
if pending:self.wake()
|
||||
|
||||
def recover(self):
|
||||
if self.busy:return {'interrupted':0,'blocked':0,'published':0}
|
||||
result={'interrupted':0,'blocked':0,'published':0,'live_owners':0}
|
||||
with self.repo.store.transaction():
|
||||
active_runs=self.repo.connection.execute("SELECT run_id FROM verification_runs WHERE state IN ('queued','running','stopping')").fetchall()
|
||||
protected=set()
|
||||
for run in active_runs:
|
||||
owner=read_owner(self.service,'runs',run[0])
|
||||
if owner['state']=='live' and owner.get('owner_id')!=self.owner_id:protected.add(run[0])
|
||||
rows=self.repo.connection.execute("SELECT * FROM verification_attempts WHERE state IN ('queued','running','publishing','stopping')").fetchall()
|
||||
for raw in rows:
|
||||
row=dict(raw);identity=row['attempt_id'];directory=self.service.data_root/'verification'/'attempts'/identity
|
||||
if row['run_id'] in protected:continue
|
||||
owner=read_owner(self.service,'attempts',identity,row['owner_id'])
|
||||
if owner['state']=='live' and owner.get('owner_id')!=self.owner_id:
|
||||
if row['run_id']:protected.add(row['run_id'])
|
||||
continue
|
||||
if row['state']=='queued':state,resource='interrupted','released'
|
||||
else:
|
||||
try:
|
||||
ready=json.loads((directory/'result-ready.json').read_text(encoding='utf-8'))
|
||||
value=self.service.artifacts.read(ready['result_ref'],'result')
|
||||
if value['attempt_id']!=identity or value['generation']!=row['generation']:raise ValueError('身份不符')
|
||||
from .report import validate_result
|
||||
validate_result(value,self.service.data_root)
|
||||
if row['state'] in {'running','publishing'} and self.repo.finish(identity,generation=row['generation'],result=dict(value,result_ref=ready['result_ref'])):
|
||||
result['published']+=1;continue
|
||||
except (OSError,ValueError,KeyError,ImportError):pass
|
||||
try:
|
||||
proof=json.loads((directory/'resource-released.json').read_text(encoding='utf-8'))
|
||||
if proof['owner_id']!=row['owner_id'] or proof['resource_state']!='released':raise ValueError('退出未知')
|
||||
state,resource='interrupted','released'
|
||||
except (OSError,ValueError,KeyError):state,resource='stopping','unknown'
|
||||
self.repo.connection.execute('UPDATE verification_attempts SET state=?,resource_state=?,reason=?,updated=? WHERE attempt_id=?',
|
||||
(state,resource,'上次执行中断;未自动重跑' if resource=='released' else '上次原生进程退出缺少证明,保留现场',now(),identity))
|
||||
self.repo._touch(self.repo.item(row['item_id'])['task_id'])
|
||||
result['blocked' if resource=='unknown' else 'interrupted']+=1
|
||||
for run in active_runs:
|
||||
if run[0] not in protected:self.repo.connection.execute("UPDATE verification_runs SET state='interrupted' WHERE run_id=?",(run[0],))
|
||||
result['live_owners']=len(protected)
|
||||
return result
|
||||
|
||||
def begin_shutdown(self):
|
||||
if self.closing:return
|
||||
self.closing=True
|
||||
with self.lock:runs=tuple(self._owned_runs)
|
||||
for identity in runs:self.stop(identity,request_id='shutdown:'+identity)
|
||||
with self.lock:
|
||||
for event in self.events.values():event.set()
|
||||
@@ -0,0 +1,67 @@
|
||||
"""One immutable fact model for diagrams, tables and reports."""
|
||||
import copy
|
||||
import re
|
||||
from .contracts import digest,fail
|
||||
from .rules import physical_view
|
||||
|
||||
|
||||
def pin_sort(value):
|
||||
return tuple((0,int(part)) if part.isdigit() else (1,part) for part in re.split(r'(\d+)',str(value)))
|
||||
|
||||
|
||||
def build_evidence(before_graph,after_graph,issues,*,binding):
|
||||
views=[];limitations=[]
|
||||
for graph in (before_graph,after_graph):
|
||||
try:views.append(physical_view(graph))
|
||||
except (ValueError,TypeError,KeyError) as error:views.append({});limitations.append(str(error))
|
||||
left,right=views;pins=[]
|
||||
for endpoint in sorted(left.keys()|right.keys(),key=lambda e:(e[:2],pin_sort(e[2]))):
|
||||
l,r=left.get(endpoint),right.get(endpoint)
|
||||
associated=[i['issue_id'] for i in issues if i.get('instance_path')==endpoint[0]
|
||||
and i.get('refdes')==endpoint[1] and (i.get('pin_number') in (None,endpoint[2]))]
|
||||
connection_changed=any(i['issue_id'] in associated and i['check_id'] in {'connections','physical_pins'} and i['state']=='error' for i in issues)
|
||||
pins.append({'endpoint':list(endpoint),'before':l,'after':r,'issue_ids':associated,
|
||||
'connection_changed':connection_changed,
|
||||
'text_changed':bool(l and r and l['logical_name']!=r['logical_name'])})
|
||||
result={'schema_version':1,'binding':copy.deepcopy(binding),'issues':copy.deepcopy(list(issues)),
|
||||
'pins':pins,'page':None,'label':'由网表生成','limitations':limitations+['未覆盖:封装库内部映射']}
|
||||
result['digest']=digest(result)
|
||||
return result
|
||||
|
||||
|
||||
def verify_evidence(evidence):
|
||||
if evidence.get('digest')!=digest({k:v for k,v in evidence.items() if k!='digest'}):
|
||||
fail('证据包摘要不符。','verification_evidence')
|
||||
|
||||
|
||||
def pin_fact(pin, issues_by_id):
|
||||
"""Interpret stored issues without changing the historical evidence digest."""
|
||||
checks={issue['check_id'] for identity in pin['issue_ids']
|
||||
if (issue:=issues_by_id.get(identity)) and issue['state']=='error'}
|
||||
labels=[]
|
||||
if 'components' in checks:
|
||||
labels.append('器件新增' if pin['before'] is None else '器件删除')
|
||||
if 'physical_pins' in checks:
|
||||
labels.append('物理脚变化')
|
||||
if 'connections' in checks:
|
||||
labels.append('连接变化')
|
||||
if 'net_names' in checks:
|
||||
labels.append('网名变化')
|
||||
if pin['text_changed']:
|
||||
labels.append('引脚名称变化')
|
||||
if labels:
|
||||
return '、'.join(labels),'error' if checks else 'warning'
|
||||
if pin['before'] is None or pin['after'] is None:
|
||||
return '无法确认','unknown'
|
||||
return '未发现变化','equal'
|
||||
|
||||
|
||||
PIN_FACT_COLORS={'error':'#b83d4a','warning':'#9c6b1e','unknown':'#61758e','equal':'#39817d'}
|
||||
|
||||
|
||||
def connection_view(evidence,issue_id):
|
||||
verify_evidence(evidence)
|
||||
issue=next((i for i in evidence['issues'] if i['issue_id']==issue_id),None)
|
||||
if issue is None:fail('问题记录不存在。')
|
||||
return {'issue':issue,'pins':[p for p in evidence['pins'] if p['endpoint'][:2]==[issue.get('instance_path'),issue.get('refdes')]],
|
||||
'page':evidence['page'],'binding':evidence['binding'],'label':evidence['label']}
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Managed immutable inputs; native tools never receive arbitrary live paths."""
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
from uuid import uuid4
|
||||
|
||||
from .. import native_netlist
|
||||
from ..batch_resources import write_record
|
||||
from ..operation_control import check_cancelled
|
||||
from ..native_inventory import _project_options
|
||||
from ..path_access import internal_path
|
||||
from .contracts import artifact_ref, fail
|
||||
|
||||
|
||||
class ArtifactStore:
|
||||
def __init__(self, data_root):
|
||||
self.data_root = Path(data_root).resolve()
|
||||
self.root = self.data_root/'verification'/'artifacts'
|
||||
|
||||
def directory(self, identity):
|
||||
artifact_ref({'manifest_id':identity,'sha256':'0'*64})
|
||||
path = self.root/identity
|
||||
if path.resolve().parent != self.root.resolve(): fail('证据目录越界。')
|
||||
return path
|
||||
|
||||
def put(self, kind, payload, *, identity=None):
|
||||
identity = identity or uuid4().hex
|
||||
directory = self.directory(identity); directory.mkdir(parents=True,exist_ok=True)
|
||||
manifest = directory/'manifest.json'
|
||||
if manifest.exists(): fail('不可覆盖已有校验证据。')
|
||||
write_record(manifest, {'schema_version':1,'kind':kind,'payload':payload})
|
||||
return {'manifest_id':identity,'sha256':native_netlist._hash(manifest)}
|
||||
|
||||
def read(self, ref, kind):
|
||||
artifact_ref(ref)
|
||||
if not ref: fail('缺少校验证据。')
|
||||
directory = self.directory(ref['manifest_id'])
|
||||
path = directory/'manifest.json'
|
||||
try:
|
||||
if native_netlist._hash(path) != ref['sha256']: fail('证据清单摘要不符。')
|
||||
manifest = json.loads(path.read_text(encoding='utf-8'))
|
||||
if manifest.get('schema_version') != 1 or manifest.get('kind') != kind: fail('证据类型不符。')
|
||||
payload = manifest['payload']
|
||||
if kind == 'snapshot':
|
||||
capture_root = Path(payload['root']).resolve()
|
||||
if capture_root != (directory/'capture').resolve(): fail('输入副本归属不符。')
|
||||
for relative in payload['capture_hashes']:
|
||||
if not (capture_root/relative).resolve().is_relative_to(capture_root): fail('输入文件越界。')
|
||||
for key,relative in (('project_path','input.prj'),('database_path','database/icdb.dat')):
|
||||
if Path(payload[key]).resolve() != (capture_root/relative).resolve(): fail('输入文件身份不符。')
|
||||
native_netlist._check_capture(payload)
|
||||
return payload
|
||||
except (OSError,ValueError,KeyError,TypeError) as error:
|
||||
fail(f'校验证据不可用:{error}', 'verification_evidence')
|
||||
|
||||
def discard(self, identity):
|
||||
"""Remove a directory allocated by this operation before publication."""
|
||||
directory=internal_path(self.directory(identity))
|
||||
try:
|
||||
shutil.rmtree(directory)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
except OSError:
|
||||
logging.getLogger(__name__).warning('Cannot remove unpublished verification artifact %s',identity,exc_info=True)
|
||||
|
||||
def capture(self, project, *, stop_event, identity=None):
|
||||
check_cancelled(stop_event)
|
||||
identity = identity or uuid4().hex
|
||||
capture = native_netlist.capture_project(Path(project),self.directory(identity)/'capture')
|
||||
check_cancelled(stop_event)
|
||||
return self.put('snapshot',capture,identity=identity)
|
||||
|
||||
def adopt(self, capture, *, identity=None):
|
||||
root = Path(capture['root']).resolve()
|
||||
if not root.is_relative_to(self.data_root): fail('交接副本不属于当前任务库。')
|
||||
native_netlist._check_capture(capture)
|
||||
identity = identity or uuid4().hex
|
||||
destination = self.directory(identity)/'capture'
|
||||
destination.mkdir(parents=True)
|
||||
for relative, sha in capture['capture_hashes'].items():
|
||||
source = (root/relative).resolve(); target=(destination/relative).resolve()
|
||||
if not source.is_relative_to(root) or not target.is_relative_to(destination.resolve()): fail('交接文件路径越界。')
|
||||
target.parent.mkdir(parents=True,exist_ok=True); shutil.copyfile(source,target)
|
||||
if native_netlist._hash(target) != sha: fail('交接副本在复制时变化。')
|
||||
value = dict(capture,root=str(destination),project_path=str(destination/'input.prj'),
|
||||
database_path=str(destination/'database/icdb.dat'),manifest_path=str(destination/'capture.json'))
|
||||
native_netlist._check_capture(capture)
|
||||
write_record(destination/'capture.json',value)
|
||||
return self.put('snapshot',value,identity=identity)
|
||||
|
||||
|
||||
def validate_pair(before, after):
|
||||
before,after = Path(before).resolve(strict=True),Path(after).resolve(strict=True)
|
||||
if before==after or before.samefile(after): fail('请选择不同的前后工程。','verification_same_source')
|
||||
before_db,after_db = _project_options(before)[3],_project_options(after)[3]
|
||||
if Path(before_db).samefile(after_db): fail('两个工程引用同一个数据库。','verification_same_source')
|
||||
return before,after
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Process creation identities for recovery; never terminate a recorded PID."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
from ..batch_resources import process_identity,_process_gone,write_record
|
||||
from .contracts import fail
|
||||
|
||||
|
||||
def owner_path(service,kind,identity):
|
||||
if kind not in {'runs','attempts'} or re.fullmatch('[0-9a-f]{32}',identity or '') is None:fail('执行归属标识无效。')
|
||||
root=(service.data_root/'verification').resolve()
|
||||
path=root/kind/identity/'owner.json'
|
||||
if not path.resolve().is_relative_to(root):fail('执行归属目录越界。')
|
||||
return path
|
||||
|
||||
|
||||
def write_owner(service,kind,identity,owner_id):
|
||||
process={'pid':os.getpid(),'creation_time':None}
|
||||
if os.name=='nt':
|
||||
import win32api
|
||||
process=process_identity(SimpleNamespace(pid=os.getpid(),handle=win32api.GetCurrentProcess()))
|
||||
write_record(owner_path(service,kind,identity),{'version':1,'identity':identity,'owner_id':owner_id,
|
||||
'process':process,'scope':'OwnedCliScope','kill_on_owner_exit':True})
|
||||
|
||||
|
||||
def read_owner(service,kind,identity,expected_owner=None):
|
||||
try:
|
||||
value=json.loads(owner_path(service,kind,identity).read_text(encoding='utf-8'))
|
||||
if (value.get('version')!=1 or value.get('identity')!=identity or value.get('scope')!='OwnedCliScope'
|
||||
or value.get('kill_on_owner_exit') is not True or not isinstance(value.get('owner_id'),str)
|
||||
or (expected_owner and value['owner_id']!=expected_owner)):raise ValueError('归属证明不符')
|
||||
identity_record=value['process']
|
||||
if type(identity_record.get('pid')) is not int or identity_record['pid']<=0:raise ValueError('进程证明无效')
|
||||
if os.name!='nt' or not identity_record.get('creation_time'):state='unknown'
|
||||
else:state='gone' if _process_gone(identity_record) else 'live'
|
||||
return dict(value,state=state)
|
||||
except Exception:return {'state':'unknown'} # An inaccessible process is never proof of release.
|
||||
|
||||
|
||||
class RunStop:
|
||||
"""An Event-compatible token that observes another window's durable stop."""
|
||||
def __init__(self,service,run_id,event):self.service=service;self.run_id=run_id;self.event=event
|
||||
def is_set(self):
|
||||
if self.event.is_set():return True
|
||||
with self.service.repo.store._lock:
|
||||
row=self.service.repo.connection.execute('SELECT stop_requested FROM verification_runs WHERE run_id=?',(self.run_id,)).fetchone()
|
||||
return row is None or bool(row[0])
|
||||
def wait(self,timeout=None):
|
||||
deadline=None if timeout is None else time.monotonic()+timeout
|
||||
while not self.is_set():
|
||||
if deadline is not None and time.monotonic()>=deadline:return False
|
||||
self.event.wait(.05 if deadline is None else min(.05,max(0,deadline-time.monotonic())))
|
||||
return True
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Conservative native text adapter. Missing fields remain unknown."""
|
||||
from pathlib import Path
|
||||
import re
|
||||
from ..native_netlist import _hash, _instance_identity
|
||||
from ..native_inventory import read_native_text
|
||||
from .rules import component_key
|
||||
|
||||
|
||||
def inspect_footprint_mapping(binding):
|
||||
return {'state':'unknown','mapping':None,'reason':'未实现确切库版本的内部引脚到焊盘映射读取'}
|
||||
|
||||
|
||||
def inspect_pin_metadata(export,*,evidence_root):
|
||||
result={'pins':[],'uncovered':['引脚级 Value','库内引脚到焊盘映射']}
|
||||
try:
|
||||
path=Path(export.get('outputs',{})['effective']).resolve()
|
||||
if not path.is_relative_to(Path(evidence_root).resolve()):raise ValueError('原始证据越界')
|
||||
sha=_hash(path);lines=read_native_text(path).splitlines();records=[];record=None
|
||||
for n,line in enumerate(lines,1):
|
||||
if line.startswith(' Symbol '):
|
||||
match=re.fullmatch(r' Symbol (.+?)\tref des ([^\t]*)\tpage ([^\t]*)',line)
|
||||
record={'uid':match[1],'refdes':match[2],'page':match[3],'paths':[],'pins':[]} if match else None
|
||||
if record:records.append(record)
|
||||
elif record is not None:
|
||||
if line.startswith('\tPath '):record['paths'].append(line[6:])
|
||||
elif line.startswith('\tPin '):
|
||||
fields=line[5:].split('\t');values=dict(v.split(' ',1) for v in fields[1:] if ' ' in v)
|
||||
record['pins'].append((fields[0],values,n))
|
||||
graph=export.get('graph',{}).get('components',{})
|
||||
candidates=[]
|
||||
for record in records:
|
||||
for scope in record['paths']:
|
||||
uid=_instance_identity(record['uid'],scope);component=graph.get(uid)
|
||||
if component is None or component.get('refdes')!=record['refdes']:continue
|
||||
for name,values,n in record['pins']:
|
||||
pin=component.get('pins',{}).get(name)
|
||||
if not pin or not values.get('num') or pin.get('number')!=values['num']:continue
|
||||
key=component_key(uid,component)
|
||||
if key is None:continue
|
||||
candidates.append({'endpoint':[*key,values['num']],
|
||||
'logical_name':{'value':name,'confidence':'proven'},
|
||||
'pin_value':{'value':None,'confidence':'unknown'},
|
||||
'electrical_type':{'value':values.get('type'),'confidence':'proven' if 'type' in values else 'unknown'},
|
||||
'raw':{'path':str(path),'sha256':sha,'line':n,'page':record['page'] or None}})
|
||||
from collections import Counter
|
||||
counts=Counter(tuple(p['endpoint']) for p in candidates)
|
||||
result['pins']=[p for p in candidates if counts[tuple(p['endpoint'])]==1]
|
||||
if _hash(path)!=sha:raise ValueError('原始证据在读取时变化')
|
||||
except (OSError,ValueError,KeyError,TypeError) as error:
|
||||
result.update(pins=[],reason=str(error))
|
||||
return result
|
||||
|
||||
|
||||
def compare_metadata(before,after):
|
||||
left={tuple(p['endpoint']):p for p in before['pins']};right={tuple(p['endpoint']):p for p in after['pins']}
|
||||
return {'comparisons':{str(key):dict({phase:{name:row[name]['value'] for name in ('pin_value','electrical_type')}
|
||||
for phase,row in (('before',left[key]),('after',right[key]))}
|
||||
,endpoint=list(key))
|
||||
for key in left.keys()&right.keys()}}
|
||||
@@ -0,0 +1,138 @@
|
||||
"""Snapshot projections: only the current input and latest attempt drive badges."""
|
||||
import json
|
||||
from .contracts import ACTIVE, digest, fail
|
||||
|
||||
|
||||
def checkpoint(control):
|
||||
if control is not None: control.checkpoint()
|
||||
|
||||
|
||||
def project(row):
|
||||
row=dict(row)
|
||||
state=row.get('attempt_state')
|
||||
verdict=row.get('verdict')
|
||||
if row['input_state']!='ready': status='unavailable'
|
||||
elif state in ACTIVE: status='running'
|
||||
elif state=='cancelled' and row.get('reason')=='run_stopped_before_dispatch': status='waiting'
|
||||
elif state=='cancelled': status='stopped'
|
||||
elif state=='interrupted': status='interrupted'
|
||||
elif state=='failed': status='unavailable'
|
||||
elif state=='succeeded': status={'CONSISTENT':'consistent','WARNING':'warning','DIFFERENT':'different'}.get(verdict,'unavailable')
|
||||
else: status='waiting'
|
||||
row.update(status=status,can_start=row['input_state']=='ready' and state not in ACTIVE,
|
||||
scope='包含固定换料规则' if row.get('expectation_ref') else '未核对换料规则')
|
||||
return row
|
||||
|
||||
|
||||
def summarize_items(rows):
|
||||
summary=dict.fromkeys(('total','processed','consistent','warning','different','unavailable','waiting','running','stopped','interrupted'),0)
|
||||
for row in rows:
|
||||
summary['total']+=1; summary[row['status']]+=1
|
||||
if row['status'] in {'consistent','warning','different','unavailable'}: summary['processed']+=1
|
||||
return summary
|
||||
|
||||
|
||||
def paginate(rows,cursor,limit,binding,maximum):
|
||||
if type(limit) is not int or not 1<=limit<=maximum: fail('分页大小超出范围。')
|
||||
offset=0
|
||||
if cursor is not None:
|
||||
if not isinstance(cursor,dict) or cursor.get('binding')!=binding or type(cursor.get('offset')) is not int or cursor['offset']<0:
|
||||
fail('列表已更新,请刷新后重试。','verification_cursor')
|
||||
offset=cursor['offset']
|
||||
return rows[offset:offset+limit],({'offset':offset+limit,'binding':binding} if len(rows)>offset+limit else None)
|
||||
|
||||
|
||||
class VerificationQueries:
|
||||
def __init__(self,repo):self.repo=repo;self.validator=None
|
||||
|
||||
def _validate(self,row,attempt):
|
||||
if self.validator and attempt and attempt['state']=='succeeded':
|
||||
try:self.validator(attempt)
|
||||
except (ValueError,OSError,KeyError,TypeError) as error:
|
||||
row.update(status='unavailable',verdict='INCOMPLETE',evidence_error=str(error))
|
||||
return row
|
||||
|
||||
def _rows(self,task_id,control=None):
|
||||
checkpoint(control)
|
||||
rows=self.repo.connection.execute('''SELECT i.*, r.input_version,
|
||||
json_extract(r.payload_json,'$.input_state') input_state,
|
||||
json_extract(r.payload_json,'$.unavailable_reason') unavailable_reason,
|
||||
json_extract(r.payload_json,'$.expectation_ref') expectation_ref,
|
||||
a.attempt_id,a.state attempt_state,a.generation,a.reason,
|
||||
json_extract(a.result_json,'$.verdict') verdict
|
||||
FROM verification_items i JOIN verification_input_revisions r
|
||||
ON r.item_id=i.item_id AND r.input_version=i.current_version
|
||||
LEFT JOIN verification_attempts a ON a.attempt_id=(SELECT attempt_id FROM verification_attempts
|
||||
WHERE item_id=i.item_id AND input_version=i.current_version ORDER BY generation DESC LIMIT 1)
|
||||
WHERE i.task_id=? ORDER BY i.rowid''',(task_id,)).fetchall()
|
||||
result=[]
|
||||
for row in rows:
|
||||
checkpoint(control);row=project(row)
|
||||
result.append(row)
|
||||
return result
|
||||
|
||||
def validate_rows(self,rows,control=None):
|
||||
for row in rows:
|
||||
checkpoint(control)
|
||||
if self.validator and row['attempt_state']=='succeeded':self._validate(row,self.repo.attempt(row['attempt_id']))
|
||||
return rows
|
||||
|
||||
def list_tasks(self,*,query='',cursor=None,limit=50,read_control=None):
|
||||
with self.repo.store.transaction():
|
||||
tasks=[]
|
||||
for row in self.repo.connection.execute('SELECT * FROM verification_tasks ORDER BY created DESC,task_id').fetchall():
|
||||
checkpoint(read_control)
|
||||
row=dict(row)
|
||||
if query.casefold() in row['name'].casefold():
|
||||
tasks.append(row)
|
||||
binding=digest([query,[r['task_id'] for r in tasks]])
|
||||
page,next_cursor=paginate(tasks,cursor,limit,binding,50)
|
||||
for row in page:
|
||||
row['_rows']=self._rows(row['task_id'],read_control)
|
||||
for row in page:row['summary']=summarize_items(self.validate_rows(row.pop('_rows'),read_control))
|
||||
return {'tasks':page,'cursor':next_cursor}
|
||||
|
||||
def read_task(self,task_id,*,state='',query='',cursor=None,limit=100,read_control=None):
|
||||
with self.repo.store.transaction():
|
||||
task=self.repo.task(task_id);rows=self._rows(task_id,read_control)
|
||||
run=self.repo.connection.execute("SELECT run_id,state,stop_requested FROM verification_runs WHERE task_id=? AND state IN ('queued','running','stopping') ORDER BY created LIMIT 1",(task_id,)).fetchone()
|
||||
self.validate_rows(rows,read_control)
|
||||
filtered=[]
|
||||
for row in rows:
|
||||
checkpoint(read_control)
|
||||
if state and row['status']!=state:continue
|
||||
text=row['display_name']+' '+row['project_key']
|
||||
if query and row.get('attempt_id'):text+=' '+(self.repo.attempt(row['attempt_id'])['result_json'] or '')
|
||||
if query.casefold() in text.casefold():filtered.append(row)
|
||||
binding=digest([task_id,task['view_revision'],state,query])
|
||||
page,next_cursor=paginate(filtered,cursor,limit,binding,100)
|
||||
return dict(task,items=page,cursor=next_cursor,summary=summarize_items(rows),run=dict(run) if run else None)
|
||||
|
||||
def read_item(self,item_id,*,version=None,attempt_id=None,read_control=None):
|
||||
row=self.snapshot_item(item_id,version=version,attempt_id=attempt_id,read_control=read_control)
|
||||
return self._validate(row,row['attempt'])
|
||||
|
||||
def snapshot_item(self,item_id,*,version=None,attempt_id=None,read_control=None):
|
||||
with self.repo.store.transaction():
|
||||
checkpoint(read_control)
|
||||
item=self.repo.item(item_id)
|
||||
attempt=self.repo.attempt(attempt_id) if attempt_id else None
|
||||
if attempt:
|
||||
if attempt['item_id']!=item_id or (version is not None and attempt['input_version']!=version):fail('历史尝试不属于该工程版本。')
|
||||
version=attempt['input_version']
|
||||
version=version or item['current_version']
|
||||
revision=self.repo.revision(item_id,version);attempt=attempt or self.repo.latest_attempt(item_id,version)
|
||||
row=dict(item,**{k:v for k,v in revision['payload'].items() if k not in item})
|
||||
row.update(input_version=version,attempt_id=attempt['attempt_id'] if attempt else None,
|
||||
attempt_state=attempt['state'] if attempt else None,reason=attempt['reason'] if attempt else '',
|
||||
verdict=(attempt['result'] or {}).get('verdict') if attempt else None)
|
||||
history=[dict(r) for r in self.repo.connection.execute('SELECT input_version,generation,attempt_id,state FROM verification_attempts WHERE item_id=? ORDER BY input_version DESC,generation DESC',(item_id,))]
|
||||
versions=[r[0] for r in self.repo.connection.execute('SELECT input_version FROM verification_input_revisions WHERE item_id=? ORDER BY input_version DESC',(item_id,))]
|
||||
return dict(project(row),payload=revision['payload'],attempt=attempt,history=history,versions=versions)
|
||||
|
||||
def read_issues(self,attempt_id,*,kind='',cursor=None,limit=100,read_control=None):
|
||||
checkpoint(read_control)
|
||||
attempt=self.repo.attempt(attempt_id)
|
||||
rows=[r for r in (attempt['result'] or {}).get('issues',()) if not kind or r.get('check_id')==kind]
|
||||
page,next_cursor=paginate(rows,cursor,limit,digest([attempt_id,attempt['updated'],kind]),100)
|
||||
return {'issues':page,'cursor':next_cursor}
|
||||
@@ -0,0 +1,136 @@
|
||||
"""HTML and JSON views of the exact immutable evidence shown in the workspace."""
|
||||
from html import escape
|
||||
import json
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
from ..native_netlist import _hash
|
||||
from ..batch_resources import write_record
|
||||
from ..path_access import internal_path
|
||||
from .contracts import fail,digest
|
||||
from .evidence import PIN_FACT_COLORS,pin_fact,verify_evidence
|
||||
|
||||
|
||||
def validate_result(result,root=None):
|
||||
evidence=result.get('evidence')
|
||||
if evidence:
|
||||
verify_evidence(evidence)
|
||||
for raw in evidence['binding'].get('raw',()):
|
||||
path=Path(raw['path']).resolve()
|
||||
if root is not None and not path.is_relative_to(Path(root).resolve()):fail('证据文件不属于本任务库。')
|
||||
try:
|
||||
if _hash(path)!=raw['sha256']:fail('原始证据已损坏。','verification_evidence')
|
||||
except OSError:fail('原始证据已丢失。','verification_evidence')
|
||||
|
||||
|
||||
def text(value):
|
||||
if isinstance(value,(dict,list,tuple)):value=json.dumps(value,ensure_ascii=False,sort_keys=True)
|
||||
return escape(str(value if value is not None else '未知'))
|
||||
|
||||
|
||||
STYLE='body{font:14px "Segoe UI","Microsoft YaHei",sans-serif;color:#34445b;background:#f5f7fa;margin:24px}main{background:white;padding:24px;border-radius:12px}table{border-collapse:collapse;width:100%;margin:16px 0}td,th{border:1px solid #dae2eb;padding:9px;text-align:left;vertical-align:top}pre{white-space:pre-wrap;overflow-wrap:anywhere}.error{color:#b83d4a}.warning{color:#9c6b1e}svg{max-width:100%;height:auto}'
|
||||
|
||||
|
||||
def diagram(pins,issues):
|
||||
height=max(100,70+len(pins)*90);out=[f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 900 {height}" role="img" aria-label="由网表生成的前后连接对照">']
|
||||
for col,phase,title in ((0,'before','修改前'),(1,'after','修改后')):
|
||||
x=col*450+16;out.append(f'<text x="{x}" y="24" fill="#34445b">{title}</text>')
|
||||
for n,pin in enumerate(pins):
|
||||
y=60+n*90;row=pin[phase];fact,state=pin_fact(pin,issues);color=PIN_FACT_COLORS[state]
|
||||
out.append(f'<g><title>{text(fact)}</title>')
|
||||
name=row['logical_name'] if row else ('不存在' if fact.startswith('器件') else '未知')
|
||||
out.append(f'<text x="{x}" y="{y}" fill="{color}">脚 {text(pin["endpoint"][2])} · {text(name)}</text>')
|
||||
out.append(f'<line x1="{x+4}" y1="{y+22}" x2="{x+30}" y2="{y+22}" stroke="{color}"/>')
|
||||
nets=row['nets'] if row else []
|
||||
label=';'.join(net['name']+' · '+', '.join(e[1]+'.'+e[2] for e in net['endpoints']) for net in nets) or ('明确未连接' if row else name)
|
||||
out.append(f'<text x="{x+36}" y="{y+26}" fill="#516078" font-size="11">{text(label)}</text></g>')
|
||||
return ''.join(out)+'</svg>'
|
||||
|
||||
|
||||
def item_html(result):
|
||||
validate_result(result)
|
||||
evidence=result.get('evidence') or {};pins=evidence.get('pins',[])
|
||||
issues={issue['issue_id']:issue for issue in evidence.get('issues',())}
|
||||
verdict=result.get('verdict','未完成')
|
||||
label={'CONSISTENT':'一致','WARNING':'需关注','DIFFERENT':'异常','INCOMPLETE':'无法完整校验'}.get(verdict,'未完成')
|
||||
out=[f'<h1>{text(result.get("display_name","工程校验"))}</h1>',f'<h2>{label} · {text(verdict)}</h2>',
|
||||
f'<p>{text(result.get("scope","未核对换料规则"))} · 由网表生成 · 未覆盖:封装库内部映射、引脚级 Value</p>']
|
||||
keys=sorted({tuple(p['endpoint'][:2]) for p in pins})
|
||||
for key in keys:
|
||||
subset=[p for p in pins if tuple(p['endpoint'][:2])==key]
|
||||
out.append(f'<h3>{text(key[1])} · {text(key[0])}</h3>');out.append(diagram(subset,issues))
|
||||
out.append('<table><tr><th>物理脚</th><th>修改前</th><th>修改后</th><th>事实</th></tr>')
|
||||
for pin in subset:
|
||||
def description(row):
|
||||
if row is None:return '不存在/未覆盖'
|
||||
nets=';'.join(n['name']+' → '+', '.join(e[1]+'.'+e[2] for e in n['endpoints'] if e!=pin['endpoint']) for n in row['nets'])
|
||||
return '名称:'+row['logical_name']+'\n'+(nets or '明确未连接')
|
||||
label,_=pin_fact(pin,issues)
|
||||
out.append(f'<tr><td>{text(pin["endpoint"][2])}</td><td><pre>{text(description(pin["before"]))}</pre></td><td><pre>{text(description(pin["after"]))}</pre></td><td>{text(label)}</td></tr>')
|
||||
out.append('</table>')
|
||||
out.append('<h2>判断依据</h2><ul>')
|
||||
for issue in result.get('issues',[]):
|
||||
out.append(f'<li class="{text(issue["state"])}">{text(issue.get("refdes","工程"))} {text(issue.get("pin_number",""))} · {text(issue["reason"])}</li>')
|
||||
out.append('</ul>')
|
||||
if result.get('reason'):out.append('<p>执行说明:'+text(result['reason'])+'</p>')
|
||||
out.append('<details><summary>检查范围、版本与完整事实</summary><pre>'+text({key:result.get(key) for key in ('attempt_state','resource_state','checks','issues','uncovered','attempt_id','input_version','input_digest','policy')})+'</pre></details>')
|
||||
out.append('<details><summary>原始证据定位与摘要</summary><pre>'+text(evidence.get('binding',{}))+'</pre></details>')
|
||||
return ''.join(out)
|
||||
|
||||
|
||||
def render_item_report(result_ref,destination):
|
||||
destination=Path(destination)
|
||||
target=internal_path(destination)
|
||||
if target.exists():fail('报告文件已存在,请换一个名称。')
|
||||
fields={'item-id':result_ref.get('item_id'),'attempt-id':result_ref.get('attempt_id'),
|
||||
'input-version':result_ref.get('input_version'),'generation':result_ref.get('generation'),
|
||||
'input-digest':result_ref.get('input_digest'),'evidence-digest':(result_ref.get('evidence') or {}).get('digest')}
|
||||
binding=' '.join(f'data-{key}="{text(value)}"' for key,value in fields.items())
|
||||
html='<!doctype html><html lang="zh-CN"><meta charset="utf-8"><title>工程校验报告</title><style>'+STYLE+'</style><main '+binding+'>'+item_html(result_ref)+'</main></html>'
|
||||
target.parent.mkdir(parents=True,exist_ok=True)
|
||||
temporary=target.with_name('.'+uuid4().hex+'.tmp')
|
||||
try:
|
||||
temporary.write_text(html,encoding='utf-8')
|
||||
# On Windows rename does not overwrite an existing destination.
|
||||
if target.exists():fail('报告文件已存在。')
|
||||
temporary.rename(target)
|
||||
finally:temporary.unlink(missing_ok=True)
|
||||
return destination
|
||||
|
||||
|
||||
def export_task(service,task_id,destination,*,request_id):
|
||||
body=[task_id,str(Path(destination).resolve())]
|
||||
with service._intake_lock:
|
||||
with service.repo.store._lock:
|
||||
old=service.repo._request('export',request_id,body)
|
||||
if old is not None:
|
||||
path=Path(old['path'])
|
||||
if not internal_path(path).is_dir():fail('先前导出的报告已丢失,请重新导出。')
|
||||
return path
|
||||
with service.repo.store.transaction():
|
||||
task=service.repo.task(task_id);rows=service.queries._rows(task_id)
|
||||
records=[service.queries.snapshot_item(row['item_id']) for row in rows]
|
||||
snapshot=dict(task,items=records)
|
||||
for row in records:
|
||||
service.queries._validate(row,row['attempt'])
|
||||
if row.get('evidence_error'):fail('证据不可用,不能导出为有效报告:'+row['evidence_error'])
|
||||
root=Path(destination).resolve();internal_path(root).mkdir(parents=True,exist_ok=True)
|
||||
output=root/f'verification-{task_id[:12]}-v{task["view_revision"]}-{digest(request_id)[:8]}'
|
||||
target=internal_path(output)
|
||||
if target.exists():fail('报告目录已存在。')
|
||||
staging=internal_path(root/('.verification-'+uuid4().hex));staging.mkdir()
|
||||
write_record(staging/'task.json',snapshot)
|
||||
content=[f'<h1>{text(task["name"])}</h1><p>视图版本 {task["view_revision"]} · 生成时冻结,待校验/运行中项尚未完成。</p><ul>']
|
||||
for row in records:
|
||||
filename=row['item_id']+f'-v{row["input_version"]}.html'
|
||||
result=((row.get('attempt') or {}).get('result') or {})
|
||||
if result:
|
||||
render_item_report(dict(result,display_name=row['display_name']),staging/filename)
|
||||
content.append(f'<li><a href="{filename}">{text(row["display_name"])}</a> · {text(row["status"])}</li>')
|
||||
else:content.append(f'<li>{text(row["display_name"])} · {text(row["status"])} · 未完成/无法校验</li>')
|
||||
content.append('</ul>')
|
||||
(staging/'index.html').write_text('<!doctype html><html lang="zh-CN"><meta charset="utf-8"><style>'+STYLE+'</style><main>'+''.join(content)+'</main></html>',encoding='utf-8')
|
||||
# Roundtrip before publication; the destination never contains a partial report.
|
||||
json.loads((staging/'task.json').read_text(encoding='utf-8'))
|
||||
staging.rename(target)
|
||||
with service.repo.store.transaction():service.repo._remember('export',request_id,body,{'path':str(output)})
|
||||
return output
|
||||
@@ -0,0 +1,174 @@
|
||||
"""Electrical comparison at fixed instance/refdes/physical-pin identities."""
|
||||
from collections import Counter, defaultdict
|
||||
from .contracts import CHECKS, digest, rollup_results, validate_plan
|
||||
from ..native_netlist import _is_pcb, _proven_symbol
|
||||
|
||||
|
||||
def component_key(uid,row):
|
||||
scope=row.get('instance_path',uid.rpartition('/')[0]) or 'root'
|
||||
ref=row.get('refdes') or row.get('attributes',{}).get('Ref Designator')
|
||||
return (scope,ref) if ref else None
|
||||
|
||||
|
||||
def component_index(graph):
|
||||
index={};ambiguous=[]
|
||||
for uid,row in graph.get('components',{}).items():
|
||||
if not _is_pcb(row):continue
|
||||
key=component_key(uid,row)
|
||||
if key is None or key in index:ambiguous.append(key)
|
||||
else:index[key]=(uid,row)
|
||||
return index,ambiguous
|
||||
|
||||
|
||||
def match_components(before_graph,after_graph):
|
||||
left,la=component_index(before_graph);right,ra=component_index(after_graph)
|
||||
return {'before':left,'after':right,'ambiguous':la+ra,
|
||||
'matches':{key:(left[key][0],right[key][0]) for key in left.keys()&right.keys()}}
|
||||
|
||||
|
||||
def physical_view(graph):
|
||||
"""Keep unknowns explicit; networks include self to distinguish singles from open pins."""
|
||||
indexed,ambiguous=component_index(graph)
|
||||
if ambiguous:raise ValueError('位号或实例范围对应不唯一')
|
||||
endpoints={};pins={}
|
||||
for uid,row in graph.get('components',{}).items():
|
||||
pcb=_is_pcb(row);key=component_key(uid,row)
|
||||
for name,pin in row.get('pins',{}).items():
|
||||
number=pin.get('number') if pcb else name
|
||||
if pcb and (key is None or not number):raise ValueError('缺少物理脚号')
|
||||
endpoint=(*key,str(number)) if key else ('native',uid,name)
|
||||
if endpoint in pins:raise ValueError('物理脚号重复,无法唯一绑定')
|
||||
endpoints[(uid,name)]=endpoint
|
||||
pins[endpoint]={'logical_name':name,'number':str(number),'nets':[],
|
||||
'uid':uid,'raw_key':['components',uid,'pins',name],
|
||||
'declared_nets':pin.get('nets')}
|
||||
seen=defaultdict(list)
|
||||
for net in graph.get('nets',()):
|
||||
members=[]
|
||||
for uid,name in net['endpoints']:
|
||||
if (uid,name) not in endpoints:raise ValueError('网表端点未覆盖')
|
||||
members.append(endpoints[(uid,name)])
|
||||
if len(set(members))!=len(members):raise ValueError('网络含重复物理端点')
|
||||
for endpoint in members:
|
||||
record={'name':net['name'],'endpoints':[list(e) for e in sorted(members)]}
|
||||
pins[endpoint]['nets'].append(record);seen[endpoint].append(net['name'])
|
||||
for endpoint,pin in pins.items():
|
||||
if pin['declared_nets'] is None or Counter(pin['declared_nets'])!=Counter(seen[endpoint]):
|
||||
raise ValueError('引脚与网络互反覆盖不完整')
|
||||
pin['nets'].sort(key=lambda n:(n['name'],n['endpoints']))
|
||||
return pins
|
||||
|
||||
|
||||
def evaluate(before,after,*,expectations,check_plan,pin_metadata=None):
|
||||
plan=validate_plan(check_plan)
|
||||
requested=set(plan['required_checks'])|set(plan['optional_checks'])
|
||||
states={key:'unknown' if key in requested else 'not_requested' for key in CHECKS}
|
||||
issues=[]
|
||||
rank={'not_requested':0,'equal':1,'expected_change':2,'unknown':3,'warning':4,'error':5}
|
||||
def issue(check,state,reason,*,key=None,pin=None,left=None,right=None,field=None):
|
||||
# Hard facts stay visible even if a user did not request optional enrichment.
|
||||
if rank[state]>rank.get(states[check],0) or states[check]=='unknown':states[check]=state
|
||||
row={'check_id':check,'state':state,'reason':reason,'before':left,'after':right}
|
||||
if key:row.update(instance_path=key[0],refdes=key[1])
|
||||
if pin is not None:row['pin_number']=pin
|
||||
if field:row['field']=field
|
||||
row['issue_id']=digest(row)[:24];issues.append(row)
|
||||
states['inputs']='equal'
|
||||
complete=all(
|
||||
e.get('status')=='success' and e.get('complete') is True
|
||||
and e.get('graph',{}).get('components') and e['graph'].get('nets')
|
||||
for e in (before,after)
|
||||
)
|
||||
left=before.get('graph',{});right=after.get('graph',{})
|
||||
states['coverage']='equal' if complete else 'unknown'
|
||||
if not complete:
|
||||
issue('coverage','unknown','缺少完整原生导出',left=before.get('reason'),right=after.get('reason'))
|
||||
matched=match_components(left,right)
|
||||
if complete and not matched['ambiguous']:
|
||||
states['components']='equal'
|
||||
for key in sorted(matched['before'].keys()^matched['after'].keys()):
|
||||
issue('components','error','器件位号或实例范围增减',key=key,
|
||||
left=key in matched['before'],right=key in matched['after'])
|
||||
else:issue('components','unknown','器件身份或覆盖无法唯一证明')
|
||||
if complete:
|
||||
for key,(lid,rid) in matched['matches'].items():
|
||||
lnums=[p.get('number') for p in left['components'][lid].get('pins',{}).values()]
|
||||
rnums=[p.get('number') for p in right['components'][rid].get('pins',{}).values()]
|
||||
if lnums and rnums and all(lnums+rnums) and Counter(lnums)!=Counter(rnums):
|
||||
issue('physical_pins','error','物理脚号或占用次数变化',key=key,left=lnums,right=rnums)
|
||||
views=[]
|
||||
try:
|
||||
if not complete:raise ValueError('导出不完整')
|
||||
views=[physical_view(left),physical_view(right)]
|
||||
except (ValueError,KeyError,TypeError) as error:
|
||||
issue('coverage','unknown',str(error))
|
||||
if views:
|
||||
if states['physical_pins']!='error':states['physical_pins']='equal'
|
||||
states['connections']=states['net_names']='equal'
|
||||
states['pin_text']='equal' if 'pin_text' in requested else 'not_requested'
|
||||
states['pin_semantics']='equal' if 'pin_semantics' in requested else 'not_requested'
|
||||
lp,rp=views
|
||||
for key in sorted(matched['matches']):
|
||||
lset={e[2] for e in lp if e[:2]==key};rset={e[2] for e in rp if e[:2]==key}
|
||||
if lset!=rset:issue('physical_pins','error','物理脚号集合变化',key=key,left=sorted(lset),right=sorted(rset))
|
||||
for endpoint in sorted(lp.keys()&rp.keys()):
|
||||
l,r=lp[endpoint],rp[endpoint];key=endpoint[:2];pin=endpoint[2]
|
||||
lt=sorted(n['endpoints'] for n in l['nets']);rt=sorted(n['endpoints'] for n in r['nets'])
|
||||
if lt!=rt:issue('connections','error','固定物理脚号的连接变化',key=key,pin=pin,left=l,right=r)
|
||||
elif [n['name'] for n in l['nets']]!=[n['name'] for n in r['nets']]:
|
||||
issue('net_names','error','网络名称变化,需确认',key=key,pin=pin,left=l,right=r)
|
||||
if l['logical_name']!=r['logical_name'] and 'pin_text' in requested:
|
||||
issue('pin_text','warning','引脚名称变化,需人工确认功能',key=key,pin=pin,left=l,right=r)
|
||||
if {l['logical_name'].upper(),r['logical_name'].upper()} & {'GND','VCC','VDD','VSS'}:
|
||||
issue('pin_semantics','warning','疑似电源或地功能变化,高关注',key=key,pin=pin,left=l,right=r)
|
||||
declared=expectations is not None
|
||||
states['declared_attributes']='equal' if declared else 'not_requested'
|
||||
states['attribute_changes']='equal' if 'attribute_changes' in requested else 'not_requested'
|
||||
changes=(expectations or {}).get('changes',{})
|
||||
symbols=(expectations or {}).get('symbols',{})
|
||||
used=set()
|
||||
for key,(lid,rid) in matched['matches'].items():
|
||||
l,r=left['components'][lid],right['components'][rid]
|
||||
expected=dict(l.get('attributes',{}));delta=changes.get(lid,changes.get(key[1],{}));used.add(lid);used.add(key[1])
|
||||
for name,value in delta.items():
|
||||
if value is None:expected.pop(name,None)
|
||||
else:expected[name]=value
|
||||
actual=r.get('attributes',{})
|
||||
if declared:
|
||||
if actual!=expected:issue('declared_attributes','error','器件属性与固定预期不符',key=key,left=expected,right=actual,field='attributes')
|
||||
elif delta:states['declared_attributes']='expected_change' if states['declared_attributes']!='error' else 'error'
|
||||
elif actual!=expected:issue('attribute_changes','warning','器件属性变化;未核对换料规则',key=key,left=expected,right=actual,field='attributes')
|
||||
proof=symbols.get(lid)
|
||||
proven=proof is not None and _proven_symbol(l,r,proof)
|
||||
if proof is not None and not proven:issue('declared_attributes','error','目标符号证明无法绑定',key=key,left=l.get('symbol'),right=r.get('symbol'))
|
||||
for field in ('symbol','other_attributes','ambiguous_attributes'):
|
||||
if field=='symbol' and proven:continue
|
||||
if l.get(field)!=r.get(field):issue('declared_attributes' if declared else 'attribute_changes',
|
||||
'error' if declared else 'warning','符号或其他属性变化',key=key,left=l.get(field),right=r.get(field),field=field)
|
||||
for missing in set(changes)-used:issue('declared_attributes','error','预期清单目标未找到',left=missing)
|
||||
# Proven metadata is enrichment; never substitute component Value for pin Value.
|
||||
if pin_metadata:
|
||||
for key in ('pin_value','electrical_type'):
|
||||
for endpoint,fields in pin_metadata.get('comparisons',{}).items():
|
||||
l,r=fields.get('before',{}).get(key),fields.get('after',{}).get(key)
|
||||
if l is not None and r is not None and l!=r:
|
||||
bound=fields.get('endpoint')
|
||||
issue('pin_text' if key=='pin_value' else 'pin_semantics','warning','引脚字段变化,需人工确认',
|
||||
key=tuple(bound[:2]) if bound else None,pin=bound[2] if bound else None,left=l,right=r,field=key)
|
||||
if 'export_identity' in requested:
|
||||
diffs=[g.get('identity_tables',{}).get('keyin',{}).get('part_number_differences',[]) for g in (left,right)]
|
||||
states['export_identity']='warning' if any(diffs) else 'equal'
|
||||
if any(diffs):issue('export_identity','warning','原生身份表与有效料号存在差异',left=diffs[0],right=diffs[1])
|
||||
checks=[{'check_id':key,'state':states[key],'issues':[i['issue_id'] for i in issues if i['check_id']==key]} for key in sorted(CHECKS)]
|
||||
# This dimension covers names AND pin-level Value. Native text has not proven Value.
|
||||
for check in checks:
|
||||
if check['check_id']=='pin_text' and 'pin_text' in requested:
|
||||
check.update(coverage='partial',unknown_fields=['pin_value'])
|
||||
if check['check_id']=='pin_semantics' and 'pin_semantics' in requested:
|
||||
expected={e for e in views[0] if e[:2] in matched['matches']} if views else set()
|
||||
proven={tuple(fields['endpoint']) for fields in (pin_metadata or {}).get('comparisons',{}).values()
|
||||
if fields.get('endpoint') and all(fields.get(phase,{}).get('electrical_type') is not None for phase in ('before','after'))}
|
||||
if not expected or not expected<=proven:check.update(coverage='partial',unknown_fields=['electrical_type'])
|
||||
return dict(rollup_results(checks,required_checks=plan['required_checks'],optional_checks=plan['optional_checks']),
|
||||
checks=checks,issues=issues,scope='已核对换料规则' if declared else '未核对换料规则',
|
||||
uncovered=['封装库内部引脚到焊盘映射','引脚级 Value(原生输出未证明)'])
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Independent native read-only execution. No replacement or CAD mutation entrypoints."""
|
||||
from pathlib import Path
|
||||
from threading import Lock
|
||||
from uuid import uuid4
|
||||
|
||||
from .. import native_netlist, netlist_verification
|
||||
from ..batch_resources import pending_resources
|
||||
from ..operation_control import check_cancelled
|
||||
from .contracts import rollup_results
|
||||
|
||||
_native_lock=Lock()
|
||||
|
||||
|
||||
def can_start_native_export(service):
|
||||
from ..native_cli import _UNCERTAIN_SCOPES
|
||||
with service.repo.store._lock:
|
||||
held=service.repo.connection.execute("SELECT 1 FROM verification_attempts WHERE state='stopping' OR resource_state='unknown' LIMIT 1").fetchone()
|
||||
if held or _UNCERTAIN_SCOPES or pending_resources(service.data_root):return {'allowed':False,'reason':'资源退出尚未确认'}
|
||||
return {'allowed':not _native_lock.locked(),'reason':'原生导出忙' if _native_lock.locked() else ''}
|
||||
|
||||
|
||||
def export_inputs(service,before_ref,after_ref,*,output,stop_event):
|
||||
before=service.artifacts.read(before_ref,'snapshot')
|
||||
after=service.artifacts.read(after_ref,'snapshot')
|
||||
left=netlist_verification._export_saved_capture(before,Path(output)/'before',stop_event=stop_event)
|
||||
if left.get('cleanup_uncertain'):return left,{}
|
||||
check_cancelled(stop_event)
|
||||
right=netlist_verification._export_saved_capture(after,Path(output)/'after',stop_event=stop_event)
|
||||
return left,right
|
||||
|
||||
|
||||
def run_attempt(service,attempt_id,*,stop_event):
|
||||
if not can_start_native_export(service)['allowed'] or not _native_lock.acquire(blocking=False):
|
||||
return {'published':False,'waiting':True}
|
||||
attempt=None
|
||||
try:
|
||||
check_cancelled(stop_event)
|
||||
from .ownership import write_owner,RunStop
|
||||
with service.repo.store.transaction():
|
||||
attempt=service.repo.claim(attempt_id,owner_id=service.control.owner_id)
|
||||
if attempt:write_owner(service,'attempts',attempt_id,attempt['owner_id'])
|
||||
if attempt is None:return {'published':False}
|
||||
if attempt['run_id']:stop_event=RunStop(service,attempt['run_id'],stop_event)
|
||||
check_cancelled(stop_event)
|
||||
payload=service.repo.revision(attempt['item_id'],attempt['input_version'])['payload']
|
||||
output=service.data_root/'verification'/'attempts'/attempt_id
|
||||
left,right=export_inputs(service,payload['before_ref'],payload['after_ref'],output=output,stop_event=stop_event)
|
||||
if left.get('cleanup_uncertain') or right.get('cleanup_uncertain'):
|
||||
with service.repo.store.transaction():
|
||||
service.repo.connection.execute("UPDATE verification_attempts SET state='stopping',resource_state='unknown',reason=? WHERE attempt_id=?",('原生资源退出未知',attempt_id))
|
||||
return {'published':False,'blocked':True}
|
||||
from ..batch_resources import write_record
|
||||
write_record(output/'resource-released.json',{'owner_id':attempt['owner_id'],'resource_state':'released'})
|
||||
check_cancelled(stop_event)
|
||||
expected=service.artifacts.read(payload['expectation_ref'],'expectations') if payload['expectation_ref'] else None
|
||||
from .rules import evaluate
|
||||
from .pin_metadata import inspect_pin_metadata,compare_metadata
|
||||
metadata={phase:inspect_pin_metadata(export,evidence_root=output) for phase,export in (('before',left),('after',right))}
|
||||
result=dict(evaluate(left,right,expectations=expected,check_plan=payload['check_plan'],
|
||||
pin_metadata=compare_metadata(metadata['before'],metadata['after'])),
|
||||
before=left,after=right,attempt_state='succeeded' if all(e.get('status')=='success' for e in (left,right)) else 'failed',resource_state='released')
|
||||
result['pin_metadata']=metadata
|
||||
result.update(item_id=attempt['item_id'],input_version=attempt['input_version'],attempt_id=attempt_id,
|
||||
generation=attempt['generation'],input_digest=payload['payload_digest'],policy=payload['check_plan'])
|
||||
from .evidence import build_evidence
|
||||
raw=[]
|
||||
for phase,export in (('before',left),('after',right)):
|
||||
for kind,path in export.get('outputs',{}).items():
|
||||
file=Path(path).resolve()
|
||||
if not file.is_relative_to(output.resolve()):raise ValueError('导出证据越界')
|
||||
raw.append({'artifact_id':phase+':'+kind,'path':str(file),'sha256':native_netlist._hash(file)})
|
||||
result['evidence']=build_evidence(left.get('graph',{}),right.get('graph',{}),result['issues'],
|
||||
binding={'attempt_id':attempt_id,'input_version':attempt['input_version'],
|
||||
'input_digest':payload['payload_digest'],'raw':raw})
|
||||
ref=service.artifacts.put('result',result)
|
||||
result['result_ref']=ref
|
||||
write_record(output/'result-ready.json',{'result_ref':ref})
|
||||
check_cancelled(stop_event)
|
||||
published=service.repo.finish(attempt_id,generation=attempt['generation'],result=result)
|
||||
if not published and stop_event.is_set():
|
||||
service.repo.finish(attempt_id,generation=attempt['generation'],result={
|
||||
'attempt_state':'cancelled','resource_state':'released','verdict':'INCOMPLETE','reason':'用户停止先于结果提交',
|
||||
'attempt_id':attempt_id,'input_version':attempt['input_version'],'checks':[],'issues':[]})
|
||||
return dict(result,published=published)
|
||||
except Exception as error:
|
||||
if attempt:
|
||||
from ..native_cli import _UNCERTAIN_SCOPES
|
||||
if _UNCERTAIN_SCOPES:
|
||||
with service.repo.store.transaction():
|
||||
service.repo.connection.execute("UPDATE verification_attempts SET state='stopping',resource_state='unknown',reason=? WHERE attempt_id=?",(str(error),attempt_id))
|
||||
return {'published':False,'blocked':True}
|
||||
cancelled=getattr(error,'code','')=='operation_cancelled'
|
||||
result={'attempt_state':'cancelled' if cancelled else 'failed','resource_state':'released',
|
||||
'verdict':'INCOMPLETE','reason':str(error),'checks':[],'issues':[]}
|
||||
service.repo.finish(attempt_id,generation=attempt['generation'],result=result)
|
||||
return {'published':False,'reason':str(error)}
|
||||
finally:
|
||||
_native_lock.release()
|
||||
@@ -0,0 +1,335 @@
|
||||
"""One interface for standalone verification and successful-result handoff."""
|
||||
from contextlib import ExitStack
|
||||
from hashlib import sha256
|
||||
import json
|
||||
from pathlib import Path
|
||||
from threading import RLock
|
||||
from uuid import uuid4
|
||||
|
||||
from ..native_netlist import _check_capture
|
||||
from ..path_access import canonical_path, internal_path
|
||||
from ..errors import TaskCenterError
|
||||
from ..operation_control import check_cancelled
|
||||
from .contracts import default_plan, digest, fail, identifier, validate_input
|
||||
from .intake import ArtifactStore, validate_pair
|
||||
from .store import VerificationRepository
|
||||
|
||||
|
||||
class VerificationService:
|
||||
def __init__(self, task_store, data_root):
|
||||
self.repo = VerificationRepository(task_store)
|
||||
self.data_root = Path(data_root).resolve()
|
||||
self.artifacts = ArtifactStore(self.data_root)
|
||||
self._intake_lock = RLock()
|
||||
from .queries import VerificationQueries
|
||||
self.queries = VerificationQueries(self.repo)
|
||||
self.queries.validator = self.validate_attempt
|
||||
from .control import VerificationControl
|
||||
self.control = VerificationControl(self)
|
||||
self._recovered=False
|
||||
|
||||
def initialize(self):
|
||||
with self._intake_lock:
|
||||
if not self._recovered:
|
||||
self.recover()
|
||||
self._recovered=True
|
||||
return self.reconcile_deliveries()
|
||||
|
||||
@property
|
||||
def busy(self): return self.control.busy
|
||||
|
||||
def start(self, task_id, *, selection=None, request_id):
|
||||
return self.control.start(task_id,selection=selection,request_id=request_id)
|
||||
|
||||
def stop(self, run_id, *, request_id): return self.control.stop(run_id,request_id=request_id)
|
||||
def rerun(self, item_id, version, *, request_id):
|
||||
return self.start(self.repo.item(item_id)['task_id'],selection=((item_id,version),),request_id=request_id)
|
||||
def recover(self): return self.control.recover()
|
||||
def begin_shutdown(self): return self.control.begin_shutdown()
|
||||
|
||||
def list_tasks(self, **kwargs): return self.queries.list_tasks(**kwargs)
|
||||
def read_task(self, task_id, **kwargs): return self.queries.read_task(task_id, **kwargs)
|
||||
def read_item(self, item_id, **kwargs): return self.queries.read_item(item_id, **kwargs)
|
||||
def read_issues(self, attempt_id, **kwargs): return self.queries.read_issues(attempt_id, **kwargs)
|
||||
|
||||
def export_task(self, task_id, destination, *, request_id):
|
||||
from .report import export_task
|
||||
return export_task(self,task_id,destination,request_id=request_id)
|
||||
|
||||
def validate_attempt(self, attempt):
|
||||
result=attempt.get('result') or {}
|
||||
if not result.get('result_ref'): return
|
||||
stored=self.artifacts.read(result['result_ref'],'result')
|
||||
if stored!={k:v for k,v in result.items() if k!='result_ref'}:fail('结果记录与不可变证据不符。')
|
||||
from .report import validate_result
|
||||
validate_result(stored,self.data_root)
|
||||
payload=self.repo.revision(attempt['item_id'],attempt['input_version'])['payload']
|
||||
for key in ('before_ref','after_ref'):self.artifacts.read(payload[key],'snapshot')
|
||||
if payload['expectation_ref']:self.artifacts.read(payload['expectation_ref'],'expectations')
|
||||
|
||||
def open_evidence(self, attempt_id, artifact_id):
|
||||
attempt=self.repo.attempt(attempt_id);self.validate_attempt(attempt)
|
||||
raw=next((r for r in (attempt['result'] or {}).get('evidence',{}).get('binding',{}).get('raw',[]) if r['artifact_id']==artifact_id),None)
|
||||
if raw is None:fail('原始证据标识不存在。')
|
||||
path=Path(raw['path']).resolve()
|
||||
if not path.is_relative_to(self.data_root/'verification'):fail('原始证据越界。')
|
||||
import os
|
||||
os.startfile(path)
|
||||
return path
|
||||
|
||||
def create_task(self, name, *, request_id):
|
||||
return self.repo.create_task(name,request_id=request_id)
|
||||
|
||||
def preview_pairs(self, before_root, after_root, *, stop_event):
|
||||
from .batch_import import preview_pairs
|
||||
return preview_pairs(before_root,after_root,excluded_roots=(self.data_root,),stop_event=stop_event)
|
||||
|
||||
def import_pairs(self, task_id, pairs, *, request_id, stop_event, on_progress=None, display_names=None):
|
||||
from .batch_import import import_pairs
|
||||
return import_pairs(self,task_id,pairs,request_id=request_id,stop_event=stop_event,on_progress=on_progress,display_names=display_names)
|
||||
|
||||
def publish_inputs(self, task_id, inputs, *, submission_id):
|
||||
body = {'task_id':task_id,'inputs':inputs}
|
||||
with self.repo.store._lock:
|
||||
old = self.repo._request('ingest',submission_id,body)
|
||||
if old is not None: return old
|
||||
normalized=self._validated_inputs(inputs)
|
||||
with self.repo.store.transaction():
|
||||
old=self.repo._request('ingest',submission_id,body)
|
||||
if old is not None:return old
|
||||
result=self.repo.publish(task_id,tuple(normalized),submission_id='ingest:'+submission_id)
|
||||
return self.repo._remember('ingest',submission_id,body,result)
|
||||
|
||||
def _validated_inputs(self, inputs):
|
||||
# Snapshot hashing can be slow; never run it inside a store transaction.
|
||||
normalized=[]
|
||||
for value in inputs:
|
||||
if not isinstance(value,dict):
|
||||
normalized.append(value)
|
||||
continue
|
||||
row=dict(value)
|
||||
try:
|
||||
for field,kind in (('before_ref','snapshot'),('after_ref','snapshot'),('expectation_ref','expectations')):
|
||||
if row.get(field): self.artifacts.read(row[field],kind)
|
||||
except (ValueError,OSError) as error:
|
||||
row['unavailable_reason']=str(error)
|
||||
normalized.append(row)
|
||||
return normalized
|
||||
|
||||
def import_pair(self, task_id, before, after, *, request_id, stop_event, display_name=None):
|
||||
body=[task_id,str(before),str(after)]
|
||||
if display_name is not None:body.append(display_name)
|
||||
with self._intake_lock:
|
||||
with self.repo.store._lock:
|
||||
old=self.repo._request('import',request_id,body)
|
||||
if old is not None:return old
|
||||
check_cancelled(stop_event)
|
||||
self.repo.task(task_id)
|
||||
try: before,after=validate_pair(before,after)
|
||||
except OSError as error: fail(f'工程文件不可用:{error}')
|
||||
project_key=digest([str(before),str(after)])
|
||||
name=after.stem if display_name is None else display_name
|
||||
try:
|
||||
identifier(name or project_key)
|
||||
except TaskCenterError as error:
|
||||
result={'accepted':[],'duplicates':[],'stale_ignored':[],
|
||||
'rejected':[{'index':0,'code':error.code,'reason':error.message}]}
|
||||
with self.repo.store.transaction():
|
||||
old=self.repo._request('import',request_id,body)
|
||||
return old if old is not None else self.repo._remember('import',request_id,body,result)
|
||||
with ExitStack() as unpublished:
|
||||
refs={}
|
||||
for phase,project in (('before',before),('after',after)):
|
||||
identity=uuid4().hex
|
||||
unpublished.callback(self.artifacts.discard,identity)
|
||||
refs[phase]=self.artifacts.capture(project,stop_event=stop_event,identity=identity)
|
||||
row={'item_key':uuid4().hex,'project_key':project_key,'display_name':name,
|
||||
'input_version':1,'before_ref':refs['before'],'after_ref':refs['after'],
|
||||
'expectation_ref':None,'check_plan':default_plan()}
|
||||
normalized=self._validated_inputs((row,))
|
||||
with self.repo.store.transaction():
|
||||
old=self.repo._request('import',request_id,body)
|
||||
if old is not None:return old
|
||||
check_cancelled(stop_event)
|
||||
result=self.repo.publish(task_id,tuple(normalized),submission_id='import:'+request_id)
|
||||
self.repo._remember('import',request_id,body,result)
|
||||
if result['accepted']:
|
||||
unpublished.pop_all()
|
||||
return result
|
||||
|
||||
def receive_successful_results(self, result_ref, *, submission_id):
|
||||
with self._intake_lock:
|
||||
with self.repo.store._lock:
|
||||
completed=self.repo._request('handoff-complete',submission_id,result_ref)
|
||||
if completed is not None:return completed
|
||||
old=self.repo._request('handoff',submission_id,result_ref)
|
||||
if old is not None and not old['rejected']:return old
|
||||
reports=result_ref.get('netlist_verification') or {}
|
||||
candidates=[]
|
||||
for key,report in reports.items():
|
||||
execution=report.get('execution') or {}
|
||||
if execution.get('state')=='completed' and (execution.get('saved_items') or 0)>0:
|
||||
candidates.append((key,report))
|
||||
# A successful save without optional netlist evidence is still visible.
|
||||
for task in result_ref.get('tasks',()):
|
||||
if task.get('state')=='completed' and (task.get('saved_items') or 0)>0 and task['task_id'] not in reports:
|
||||
candidates.append((task['task_id'],{'execution':{'state':'completed','saved_items':task['saved_items']},
|
||||
'task_name':task.get('name',task['task_id'])}))
|
||||
empty={key:[] for key in ('accepted','duplicates','stale_ignored','rejected')}
|
||||
if not candidates:return empty
|
||||
with self.repo.store.transaction():
|
||||
if self.repo._request('handoff-receipt',submission_id,result_ref) is None:
|
||||
self.repo._remember('handoff-receipt',submission_id,result_ref,True)
|
||||
run_key=identifier(str(result_ref.get('queue_id') or result_ref.get('run_id') or submission_id))
|
||||
task=self.create_task('校验任务',request_id='handoff-task:'+run_key)['task_id']
|
||||
result=dict(empty,task_id=task)
|
||||
for index,(key,report) in enumerate(candidates):
|
||||
try:
|
||||
delivery_key=digest([run_key,key,report])
|
||||
status,reference=self._deliver_project(task,str(key),report,delivery_key)
|
||||
except (ValueError,OSError,KeyError,TypeError) as error:
|
||||
result['rejected'].append({'index':index,'code':getattr(error,'code','verification_evidence'),
|
||||
'reason':str(error)})
|
||||
else:
|
||||
result[status].append(reference)
|
||||
if result['rejected']:
|
||||
return result
|
||||
with self.repo.store.transaction():
|
||||
completed=self.repo._request('handoff-complete',submission_id,result_ref)
|
||||
return completed if completed is not None else self.repo._remember(
|
||||
'handoff-complete',submission_id,result_ref,result)
|
||||
|
||||
def _deliver_project(self, task, key, report, delivery_key):
|
||||
for _ in range(3):
|
||||
with self.repo.store._lock:
|
||||
known=self.repo._request('handoff-input',delivery_key,report)
|
||||
if known is not None:
|
||||
return 'duplicates',known
|
||||
current=self.repo.current_input(task,key)
|
||||
legacy=self.repo._request('handoff-row',delivery_key,report)
|
||||
if current and legacy:
|
||||
first=self.repo.revision(current['item_id'],1)
|
||||
if first['payload_digest']==validate_input(legacy)['payload_digest']:
|
||||
return 'duplicates',{'item_id':first['item_id'],'input_version':1}
|
||||
with ExitStack() as unpublished:
|
||||
row=self._prepare_handoff_input(key,report,current,unpublished)
|
||||
with self.repo.store.transaction():
|
||||
known=self.repo._request('handoff-input',delivery_key,report)
|
||||
if known is not None:
|
||||
return 'duplicates',known
|
||||
if self.repo.current_input(task,key)!=current:
|
||||
continue
|
||||
if row is None:
|
||||
reference={field:current[field] for field in ('item_id','input_version')}
|
||||
return 'stale_ignored',reference
|
||||
if current and row['input_version']==current['input_version']:
|
||||
status='duplicates'
|
||||
reference={field:current[field] for field in ('item_id','input_version')}
|
||||
else:
|
||||
if current and row['project_key']!=current['payload']['project_key']:
|
||||
self.repo.connection.execute(
|
||||
'UPDATE verification_items SET project_key=? WHERE item_id=? AND before_id IS NULL',
|
||||
(row['project_key'],current['item_id']))
|
||||
published=self.repo.publish(task,(row,),submission_id='handoff-input:'+delivery_key)
|
||||
if published['rejected']:
|
||||
rejection=published['rejected'][0]
|
||||
fail(rejection['reason'],rejection['code'])
|
||||
status='accepted'
|
||||
reference=published['accepted'][0]
|
||||
self.repo._remember('handoff-input',delivery_key,report,reference)
|
||||
if status=='accepted':
|
||||
unpublished.pop_all()
|
||||
return status,reference
|
||||
fail('交接项正在更新,请稍后重试。','verification_conflict')
|
||||
|
||||
def _prepare_handoff_input(self, key, report, current, unpublished):
|
||||
previous=current['payload'] if current else {}
|
||||
project=str(report.get('project_path') or previous.get('project_key') or key)
|
||||
saved_items=report['execution']['saved_items']
|
||||
project_changed=bool(current and previous['project_key']!=project)
|
||||
expected=None
|
||||
previous_expected=None
|
||||
if previous.get('expectation_ref'):
|
||||
previous_expected=self.artifacts.read(previous['expectation_ref'],'expectations')
|
||||
previous_count=previous.get('handoff_saved_items') or (
|
||||
(previous_expected or {}).get('execution',{}).get('saved_items') or 0)
|
||||
if saved_items<previous_count:
|
||||
return None
|
||||
|
||||
captures={}
|
||||
reason=''
|
||||
for phase in ('before','after'):
|
||||
try:
|
||||
captures[phase]=self._handoff_capture(report.get(phase) or {})
|
||||
except (ValueError,OSError,KeyError,TypeError) as error:
|
||||
reason=reason or str(error)
|
||||
if current and previous['input_state']=='ready' and reason and saved_items<=previous_count:
|
||||
return None
|
||||
if project_changed and (previous.get('before_ref') or not captures.get('before')):
|
||||
fail('交接工程身份变化,请新增比较项。','verification_conflict')
|
||||
|
||||
refs={}
|
||||
for phase in ('before','after'):
|
||||
field=phase+'_ref'
|
||||
ref=previous.get(field)
|
||||
capture=captures.get(phase)
|
||||
if capture and ref:
|
||||
original=self.artifacts.read(ref,'snapshot')
|
||||
if (capture['project'],capture['capture_hashes'])!=(original['project'],original['capture_hashes']):
|
||||
if phase=='before':
|
||||
fail('交接原始基线变化,请新增比较项。','verification_conflict')
|
||||
ref=None
|
||||
if capture and not ref:
|
||||
identity=uuid4().hex
|
||||
unpublished.callback(self.artifacts.discard,identity)
|
||||
ref=self.artifacts.adopt(capture,identity=identity)
|
||||
refs[field]=ref if capture or phase=='before' else None
|
||||
if not reason and 'expected_changes' in report:
|
||||
value={'changes':report['expected_changes'],'symbols':report.get('expected_symbols',{}),
|
||||
'execution':report['execution']}
|
||||
expected=previous.get('expectation_ref') if value==previous_expected else None
|
||||
if expected is None:
|
||||
identity=uuid4().hex
|
||||
unpublished.callback(self.artifacts.discard,identity)
|
||||
expected=self.artifacts.put('expectations',value,identity=identity)
|
||||
plan=default_plan()
|
||||
if expected:plan['required_checks'].append('declared_attributes')
|
||||
name=previous.get('display_name') or report.get('task_name') or Path(project).stem
|
||||
row=dict(refs,item_key=key,project_key=project,display_name=name,
|
||||
expectation_ref=expected,check_plan=plan,unavailable_reason=reason,
|
||||
handoff_saved_items=saved_items)
|
||||
version=previous.get('input_version',0)
|
||||
if saved_items>previous_count or any(previous.get(field)!=value for field,value in row.items()
|
||||
if field!='handoff_saved_items'):
|
||||
version+=1
|
||||
row['input_version']=version
|
||||
return row
|
||||
|
||||
def _handoff_capture(self, evidence):
|
||||
path=canonical_path(evidence.get('export_path',''))
|
||||
if not path.is_relative_to(self.data_root) or not internal_path(path).is_file():
|
||||
fail('缺少可信前后副本。')
|
||||
content=internal_path(path).read_bytes()
|
||||
if sha256(content).hexdigest()!=evidence.get('export_sha256'):
|
||||
fail('交接导出摘要不符。')
|
||||
capture=json.loads(content)['capture']
|
||||
if not canonical_path(capture['root']).is_relative_to(self.data_root):
|
||||
fail('交接副本不属于当前任务库。')
|
||||
_check_capture(capture)
|
||||
return capture
|
||||
|
||||
def reconcile_deliveries(self, *, limit=100):
|
||||
result={'accepted':0,'errors':[]}
|
||||
# Completed queue checkpoints are durable and exist independently of a UI callback.
|
||||
directory=self.data_root/'task-queues'
|
||||
for path in sorted(directory.glob('*.json'),key=lambda p:p.stat().st_mtime,reverse=True)[:limit]:
|
||||
try:
|
||||
value=json.loads(path.read_text(encoding='utf-8'))
|
||||
value.setdefault('run_id',path.stem)
|
||||
record=self.receive_successful_results(value,submission_id='checkpoint:'+digest(value))
|
||||
result['accepted']+=len(record['accepted'])
|
||||
for rejection in record['rejected']:
|
||||
result['errors'].append({'record':path.name,'reason':rejection['reason']})
|
||||
except (ValueError,OSError,KeyError,TypeError) as error:
|
||||
result['errors'].append({'record':path.name,'reason':str(error)})
|
||||
return result
|
||||
@@ -0,0 +1,206 @@
|
||||
"""Transactional verification records; replacement receipts are never modified."""
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
from uuid import uuid4
|
||||
|
||||
from .contracts import ACTIVE, TERMINAL, digest, fail, identifier, validate_input
|
||||
from ..errors import TaskCenterError
|
||||
|
||||
|
||||
def now():
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def encode(value):
|
||||
return json.dumps(value, ensure_ascii=False, sort_keys=True, allow_nan=False)
|
||||
|
||||
|
||||
def create_schema(c):
|
||||
statements = (
|
||||
'''CREATE TABLE IF NOT EXISTS verification_tasks (
|
||||
task_id TEXT PRIMARY KEY, name TEXT NOT NULL, created TEXT NOT NULL,
|
||||
view_revision INTEGER NOT NULL DEFAULT 0)''',
|
||||
'''CREATE TABLE IF NOT EXISTS verification_items (
|
||||
item_id TEXT PRIMARY KEY, task_id TEXT NOT NULL REFERENCES verification_tasks(task_id),
|
||||
item_key TEXT NOT NULL, project_key TEXT NOT NULL, before_id TEXT,
|
||||
display_name TEXT NOT NULL, current_version INTEGER NOT NULL,
|
||||
UNIQUE(task_id,item_key))''',
|
||||
'''CREATE TABLE IF NOT EXISTS verification_input_revisions (
|
||||
item_id TEXT NOT NULL REFERENCES verification_items(item_id), input_version INTEGER NOT NULL,
|
||||
payload_json TEXT NOT NULL, payload_digest TEXT NOT NULL, created TEXT NOT NULL,
|
||||
PRIMARY KEY(item_id,input_version))''',
|
||||
'''CREATE TABLE IF NOT EXISTS verification_attempts (
|
||||
attempt_id TEXT PRIMARY KEY, item_id TEXT NOT NULL, input_version INTEGER NOT NULL,
|
||||
generation INTEGER NOT NULL, state TEXT NOT NULL, owner_id TEXT, run_id TEXT,
|
||||
result_json TEXT, reason TEXT NOT NULL DEFAULT '', resource_state TEXT NOT NULL DEFAULT 'not_started',
|
||||
created TEXT NOT NULL, updated TEXT NOT NULL,
|
||||
FOREIGN KEY(item_id,input_version) REFERENCES verification_input_revisions(item_id,input_version))''',
|
||||
'''CREATE UNIQUE INDEX IF NOT EXISTS verification_active_attempt ON verification_attempts(item_id,input_version)
|
||||
WHERE state IN ('queued','running','publishing','stopping')''',
|
||||
'''CREATE UNIQUE INDEX IF NOT EXISTS verification_attempt_generation
|
||||
ON verification_attempts(item_id,input_version,generation DESC)''',
|
||||
'''CREATE TABLE IF NOT EXISTS verification_runs (
|
||||
run_id TEXT PRIMARY KEY, task_id TEXT NOT NULL REFERENCES verification_tasks(task_id),
|
||||
members_json TEXT NOT NULL, stop_requested INTEGER NOT NULL DEFAULT 0,
|
||||
state TEXT NOT NULL DEFAULT 'queued', created TEXT NOT NULL)''',
|
||||
'''CREATE TABLE IF NOT EXISTS verification_requests (
|
||||
kind TEXT NOT NULL, request_id TEXT NOT NULL, request_hash TEXT NOT NULL, result_json TEXT NOT NULL,
|
||||
PRIMARY KEY(kind,request_id))''',
|
||||
)
|
||||
for statement in statements: c.execute(statement)
|
||||
|
||||
|
||||
class VerificationRepository:
|
||||
def __init__(self, task_store):
|
||||
self.store = task_store
|
||||
with task_store.transaction(): create_schema(task_store._connection)
|
||||
|
||||
@property
|
||||
def connection(self): return self.store._connection
|
||||
|
||||
def _request(self, kind, request_id, body):
|
||||
identifier(request_id)
|
||||
row = self.connection.execute('SELECT * FROM verification_requests WHERE kind=? AND request_id=?',
|
||||
(kind,request_id)).fetchone()
|
||||
if row:
|
||||
if row['request_hash'] != digest(body): fail('相同请求标识对应不同内容。','verification_conflict')
|
||||
return json.loads(row['result_json'])
|
||||
|
||||
def _remember(self, kind, request_id, body, result):
|
||||
self.connection.execute('INSERT INTO verification_requests VALUES (?,?,?,?)',
|
||||
(kind,request_id,digest(body),encode(result)))
|
||||
return result
|
||||
|
||||
def _touch(self, task_id):
|
||||
self.connection.execute('UPDATE verification_tasks SET view_revision=view_revision+1 WHERE task_id=?',(task_id,))
|
||||
|
||||
def _one(self, table, key, value):
|
||||
with self.store._lock:
|
||||
row = self.connection.execute(f'SELECT * FROM {table} WHERE {key}=?',(value,)).fetchone()
|
||||
if row is None: fail('找不到校验记录。','verification_not_found')
|
||||
return dict(row)
|
||||
|
||||
def task(self, task_id): return self._one('verification_tasks','task_id',task_id)
|
||||
def item(self, item_id): return self._one('verification_items','item_id',item_id)
|
||||
|
||||
def current_input(self,task_id,item_key):
|
||||
with self.store._lock:
|
||||
item=self.connection.execute(
|
||||
'SELECT item_id,current_version FROM verification_items WHERE task_id=? AND item_key=?',
|
||||
(task_id,item_key)).fetchone()
|
||||
return self.revision(*item) if item else None
|
||||
|
||||
def revision(self, item_id, version):
|
||||
with self.store._lock:
|
||||
row = self.connection.execute('SELECT * FROM verification_input_revisions WHERE item_id=? AND input_version=?',
|
||||
(item_id,version)).fetchone()
|
||||
if row is None: fail('输入版本不存在。','verification_not_found')
|
||||
return dict(row) | {'payload':json.loads(row['payload_json'])}
|
||||
|
||||
def attempt(self, attempt_id):
|
||||
row = self._one('verification_attempts','attempt_id',attempt_id)
|
||||
row['result'] = json.loads(row['result_json']) if row['result_json'] else None
|
||||
return row
|
||||
|
||||
def latest_attempt(self, item_id, version):
|
||||
with self.store._lock:
|
||||
row = self.connection.execute('SELECT attempt_id FROM verification_attempts WHERE item_id=? AND input_version=? ORDER BY generation DESC LIMIT 1',
|
||||
(item_id,version)).fetchone()
|
||||
return self.attempt(row[0]) if row else None
|
||||
|
||||
def create_task(self, name, *, request_id):
|
||||
name = identifier(name).strip()
|
||||
with self.store.transaction():
|
||||
old = self._request('create',request_id,name)
|
||||
if old is not None: return old
|
||||
task_id = uuid4().hex
|
||||
self.connection.execute('INSERT INTO verification_tasks(task_id,name,created) VALUES (?,?,?)',(task_id,name,now()))
|
||||
return self._remember('create',request_id,name,self.task(task_id))
|
||||
|
||||
def publish(self, task_id, inputs, *, submission_id):
|
||||
body = {'task_id':task_id,'inputs':inputs}
|
||||
with self.store.transaction():
|
||||
self.task(task_id)
|
||||
old = self._request('publish',submission_id,body)
|
||||
if old is not None: return old
|
||||
result = {key:[] for key in ('accepted','duplicates','stale_ignored','rejected')}
|
||||
for index,value in enumerate(inputs):
|
||||
try:
|
||||
row = validate_input(value)
|
||||
item = self.connection.execute('SELECT * FROM verification_items WHERE task_id=? AND item_key=?',
|
||||
(task_id,row['item_key'])).fetchone()
|
||||
before_id = row['before_ref']['manifest_id'] if row['before_ref'] else None
|
||||
if item:
|
||||
if item['project_key'] != row['project_key'] or (item['before_id'] and item['before_id'] != before_id):
|
||||
fail('工程身份或原始基线变化,请新增比较项。','verification_conflict')
|
||||
item_id = item['item_id']
|
||||
existing = self.connection.execute('SELECT payload_digest FROM verification_input_revisions WHERE item_id=? AND input_version=?',
|
||||
(item_id,row['input_version'])).fetchone()
|
||||
ref = {'item_id':item_id,'input_version':row['input_version']}
|
||||
if existing:
|
||||
if existing[0] != row['payload_digest']: fail('同一版本内容冲突。','verification_conflict')
|
||||
result['duplicates'].append(ref); continue
|
||||
if row['input_version'] < item['current_version']:
|
||||
result['stale_ignored'].append(ref); continue
|
||||
else:
|
||||
item_id = uuid4().hex
|
||||
self.connection.execute('INSERT INTO verification_items VALUES (?,?,?,?,?,?,?)',
|
||||
(item_id,task_id,row['item_key'],row['project_key'],before_id,row['display_name'],row['input_version']))
|
||||
self.connection.execute('INSERT INTO verification_input_revisions VALUES (?,?,?,?,?)',
|
||||
(item_id,row['input_version'],encode(row),row['payload_digest'],now()))
|
||||
self.connection.execute('UPDATE verification_items SET current_version=?,before_id=COALESCE(before_id,?),display_name=? WHERE item_id=?',
|
||||
(row['input_version'],before_id,row['display_name'],item_id))
|
||||
result['accepted'].append({'item_id':item_id,'input_version':row['input_version']})
|
||||
self._touch(task_id)
|
||||
except TaskCenterError as error:
|
||||
result['rejected'].append({'index':index,'code':error.code,'reason':error.message})
|
||||
return self._remember('publish',submission_id,body,result)
|
||||
|
||||
def create_attempt(self, item_id, version, *, request_id, run_id=None):
|
||||
body = [item_id,version]
|
||||
with self.store.transaction():
|
||||
old = self._request('attempt',request_id,body)
|
||||
if old is not None: return old
|
||||
item = self.item(item_id)
|
||||
revision = self.revision(item_id,version)
|
||||
if revision['payload']['input_state'] != 'ready': fail('前后输入不可用。')
|
||||
current = self.latest_attempt(item_id,version)
|
||||
if current and current['state'] in ACTIVE:
|
||||
return self._remember('attempt',request_id,body,current)
|
||||
generation = (current['generation'] + 1) if current else 1
|
||||
attempt_id, stamp = uuid4().hex, now()
|
||||
self.connection.execute('''INSERT INTO verification_attempts
|
||||
(attempt_id,item_id,input_version,generation,state,run_id,created,updated)
|
||||
VALUES (?,?,?,?,'queued',?,?,?)''',(attempt_id,item_id,version,generation,run_id,stamp,stamp))
|
||||
self._touch(item['task_id'])
|
||||
return self._remember('attempt',request_id,body,self.attempt(attempt_id))
|
||||
|
||||
def claim(self, attempt_id, *, owner_id):
|
||||
with self.store.transaction():
|
||||
changed = self.connection.execute("UPDATE verification_attempts SET state='running',owner_id=?,updated=? WHERE attempt_id=? AND state='queued'",
|
||||
(identifier(owner_id),now(),attempt_id)).rowcount
|
||||
return self.attempt(attempt_id) if changed else None
|
||||
|
||||
def finish(self, attempt_id, *, generation, result):
|
||||
with self.store.transaction():
|
||||
attempt = self.attempt(attempt_id)
|
||||
if attempt['generation'] != generation or attempt['state'] not in {'running','publishing'}: return False
|
||||
if result.get('resource_state') != 'released': fail('资源退出尚未确认。','verification_resources')
|
||||
state = result.get('attempt_state','succeeded')
|
||||
if state not in TERMINAL: fail('无效校验终态。')
|
||||
if attempt['run_id'] and state not in {'cancelled','interrupted'}:
|
||||
run=self.connection.execute('SELECT stop_requested FROM verification_runs WHERE run_id=?',(attempt['run_id'],)).fetchone()
|
||||
if run and run[0]:return False
|
||||
self.connection.execute('UPDATE verification_attempts SET state=?,result_json=?,resource_state=?,updated=? WHERE attempt_id=?',
|
||||
(state,encode(result),'released',now(),attempt_id))
|
||||
self._touch(self.item(attempt['item_id'])['task_id'])
|
||||
from ..history_store import HistoryRepository
|
||||
item=self.item(attempt['item_id']);task=self.task(item['task_id'])
|
||||
HistoryRepository(self.store).append(task_id=task['task_id'],task_name=task['name'],
|
||||
project_path=item['project_key'],operation='verification_completed',
|
||||
state='verified' if result.get('verdict')=='CONSISTENT' else 'failed' if result.get('verdict')=='DIFFERENT' else 'uncertain',
|
||||
summary='工程校验:'+str(result.get('verdict','INCOMPLETE')),
|
||||
details={'attempt_id':attempt_id,'input_version':attempt['input_version'],'generation':generation,
|
||||
'verdict':result.get('verdict'),'scope':result.get('scope')},
|
||||
source_key='verification:'+attempt_id)
|
||||
return True
|
||||
@@ -130,6 +130,7 @@ class ProgressWatch:
|
||||
self.native_sequence = 0
|
||||
self.native_progress_frames = 0
|
||||
self.stop_requested = False
|
||||
self.stopping_reason = ''
|
||||
self.stage = 'starting'
|
||||
self.done = 0
|
||||
self.total = 0
|
||||
@@ -155,8 +156,7 @@ class ProgressWatch:
|
||||
return False
|
||||
except (ValueError, UnicodeError):
|
||||
return False
|
||||
if ((current_job, fields[4], done, total, bool(safe)) !=
|
||||
(self.current_job_id, self.stage, self.done, self.total, self.safe_stop)):
|
||||
if ((current_job, fields[4]) != (self.current_job_id, self.stage) or done > self.done):
|
||||
self.last_business_progress = now
|
||||
self.waiting_for_safe_completion = False
|
||||
if current_job != self.current_job_id:
|
||||
@@ -199,7 +199,7 @@ class ProgressWatch:
|
||||
self.native_sequence = sequence
|
||||
self.native_progress_frames += 1
|
||||
self.last_progress = now
|
||||
if (done, total) != (self.done, self.total):
|
||||
if done > self.done:
|
||||
self.last_business_progress = now
|
||||
self.waiting_for_safe_completion = False
|
||||
self.done, self.total = done, total
|
||||
@@ -210,6 +210,7 @@ class ProgressWatch:
|
||||
idle_timeout = self.idle_timeout
|
||||
if not self.stop_requested and idle >= idle_timeout:
|
||||
self.stop_requested = True
|
||||
self.stopping_reason = 'inactivity'
|
||||
return 'request_stop'
|
||||
if self.stop_requested and idle >= idle_timeout * 2:
|
||||
if (self.waiting_for_safe_completion
|
||||
@@ -232,6 +233,9 @@ class ProgressWatch:
|
||||
'native_progress_frames': self.native_progress_frames,
|
||||
'business_idle_seconds': max(0.0, now - self.last_business_progress),
|
||||
'heartbeat_idle_seconds': max(0.0, now - self.last_progress),
|
||||
'idle_timeout_seconds': self.idle_timeout,
|
||||
'failure_completion_grace_seconds': FAILURE_COMPLETION_GRACE_SECONDS,
|
||||
'stopping_reason': self.stopping_reason,
|
||||
'elapsed_seconds': max(0.0, now - self.started), 'stage_seconds': stages}
|
||||
|
||||
|
||||
@@ -468,6 +472,7 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
read_cancel_started = time.monotonic()
|
||||
if not watch.stop_requested:
|
||||
watch.stop_requested = True
|
||||
watch.stopping_reason = 'owner_loss'
|
||||
request_stop()
|
||||
if time.monotonic() - read_cancel_started >= READ_ONLY_CANCEL_GRACE_SECONDS:
|
||||
raise WorkerMonitorCancelled('read owner exited before the read completed', stage=watch.stage)
|
||||
@@ -501,7 +506,11 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
# have reached watch yet, so ordinary pause cannot kill here.
|
||||
watch.stop_requested = True
|
||||
watch.last_progress = time.monotonic()
|
||||
watch.last_business_progress = watch.last_progress
|
||||
request_origin = (getattr(abort_event, 'stopping_reason', '')
|
||||
or getattr(getattr(abort_event, 'parent', None), 'stopping_reason', ''))
|
||||
watch.stopping_reason = request_origin or 'user_pause'
|
||||
if request_origin != 'inactivity':
|
||||
watch.last_business_progress = watch.last_progress
|
||||
request_stop()
|
||||
_publish_progress(progress_path, watch.snapshot())
|
||||
if (read_idle_stop_started is not None and time.monotonic() - read_idle_stop_started >=
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
"""Safe multi-file BOM loading and project routing for workspace imports."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from difflib import get_close_matches
|
||||
import hashlib
|
||||
from pathlib import Path, PureWindowsPath
|
||||
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from .bom_import_report import BomImportReport, BomInspectionError
|
||||
from .bom_plan import BOM_HEADERS, _normal_headers, _part_number_text, write_bom_template
|
||||
from .errors import TaskCenterError
|
||||
|
||||
@@ -55,7 +57,37 @@ def _selected_xlsx(sources):
|
||||
return tuple(sorted(paths, key=lambda path: str(path).casefold()))
|
||||
|
||||
|
||||
def load_sources(sources, *, stop_event=None, on_progress=None, allow_partial=False):
|
||||
_REQUIRED_HEADERS = (
|
||||
('old_part_number', '旧料号'), ('new_part_number', '新料号'), ('refdes', '位号'),
|
||||
)
|
||||
|
||||
|
||||
def _source_headers(path, cells):
|
||||
headers = _normal_headers(tuple(cell.value for cell in cells))
|
||||
names = tuple(name for name in headers if name)
|
||||
unknown = tuple(str(cell.value).strip() for cell, name in zip(cells, headers, strict=True)
|
||||
if not name and cell.value is not None and str(cell.value).strip())
|
||||
if any(cell.data_type == 'f' for cell in cells):
|
||||
reason = 'BOM 表头不接受公式'
|
||||
elif len(names) != len(set(names)):
|
||||
reason = 'BOM 列名重复'
|
||||
else:
|
||||
missing = [(name, label) for name, label in _REQUIRED_HEADERS if name not in names]
|
||||
if not missing:
|
||||
return {name: index for index, name in enumerate(headers) if name}, unknown
|
||||
labels = '、'.join(label for _, label in missing)
|
||||
hints = []
|
||||
for name, label in missing:
|
||||
matches = (get_close_matches(label, unknown, n=1, cutoff=.7)
|
||||
or get_close_matches(name, unknown, n=1, cutoff=.8))
|
||||
if matches:
|
||||
hints.append(f'请将「{matches[0]}」改为「{label}」')
|
||||
reason = '。'.join([f'BOM 缺少必需列「{labels}」', *hints])
|
||||
message = f'{path.name} 第 1 行:{reason}'
|
||||
raise BomInspectionError(TaskCenterError('bom_import', message), BomImportReport((), (), errors=(message,)))
|
||||
|
||||
|
||||
def load_sources(sources, *, stop_event=None, on_progress=None, allow_partial=False, warnings=None):
|
||||
"""Read every selected workbook before any CAD operation starts."""
|
||||
from .operation_control import check_cancelled
|
||||
|
||||
@@ -74,17 +106,7 @@ def load_sources(sources, *, stop_event=None, on_progress=None, allow_partial=Fa
|
||||
if len(workbook.worksheets) != 1:
|
||||
raise ValueError('BOM 只能包含一个工作表')
|
||||
rows = iter(workbook.active.iter_rows())
|
||||
header_cells = next(rows, ())
|
||||
headers = _normal_headers(tuple(cell.value for cell in header_cells))
|
||||
names = tuple(name for name in headers if name)
|
||||
if len(names) != len(set(names)):
|
||||
raise ValueError('BOM 列名重复')
|
||||
required = {'old_part_number', 'new_part_number', 'refdes'}
|
||||
if not required <= set(names):
|
||||
raise ValueError('BOM 必须包含旧料号、新料号和位号列')
|
||||
if any(cell.data_type == 'f' for cell in header_cells):
|
||||
raise ValueError('BOM 表头不接受公式')
|
||||
positions = {name: index for index, name in enumerate(headers) if name}
|
||||
positions, unknown = _source_headers(path, next(rows, ()))
|
||||
for excel_row, cells in enumerate(rows, 2):
|
||||
check_cancelled(stop_event)
|
||||
formula = any(cell.data_type == 'f' for cell in cells)
|
||||
@@ -116,6 +138,8 @@ def load_sources(sources, *, stop_event=None, on_progress=None, allow_partial=Fa
|
||||
result.append(SourceRow(path, excel_row, values, value_mode, source_sha256))
|
||||
if hashlib.sha256(path.read_bytes()).hexdigest() != source_sha256:
|
||||
raise ValueError('BOM 来源在读取期间已改变,请重新导入')
|
||||
if warnings is not None:
|
||||
warnings.extend(f'{path.name}:已忽略未知列「{name}」' for name in unknown)
|
||||
except TaskCenterError:
|
||||
raise
|
||||
except Exception as error:
|
||||
|
||||
@@ -50,32 +50,22 @@ def _token(value):
|
||||
return isinstance(value, str) and len(value) == 32 and all(char in '0123456789abcdef' for char in value)
|
||||
|
||||
|
||||
def _released_after_recheck(root, task_id, row):
|
||||
from .batch_resources import _process_gone, pending_resources
|
||||
from .batch_supervisor import pending_supervisors
|
||||
from .supervisor_protocol import valid_journal
|
||||
batch_id = row.get('supervisor_batch_id')
|
||||
if not _token(batch_id):
|
||||
return False
|
||||
try:
|
||||
journal = json.loads(internal_path(root / 'batch-resources' / batch_id / 'supervisor.json').read_text(encoding='utf-8'))
|
||||
return (valid_journal(journal, batch_id) and journal['task_ids'] == [task_id]
|
||||
and journal['state'] == 'finished' and journal.get('process')
|
||||
and _process_gone(journal['process']) and not any(row.get('blocking', True) for row in pending_resources(root))
|
||||
and not any(row.get('blocking', True) for row in pending_supervisors(root)))
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
return False
|
||||
|
||||
|
||||
def execute_workspace_projects(service, task_ids, *, stop_event, queue_id=None,
|
||||
expected_plan_hashes=None, checkpoint_id=None, defer_problem_pass=False):
|
||||
from .task_queue import _plan_hash, TaskQueueEntry, TaskQueueResult
|
||||
expected_plan_hashes=None, checkpoint_id=None, defer_problem_pass=False,
|
||||
revalidate=None):
|
||||
from .task_queue import _plan_hash, _task_uncertain, _uncertainty_root, TaskQueueEntry, TaskQueueResult
|
||||
ids = tuple(task_ids)
|
||||
if not ids or len(set(ids)) != len(ids) or any(not isinstance(item, str) or not item or Path(item).name != item
|
||||
or item in {'.', '..'} for item in ids):
|
||||
raise TaskCenterError('task_queue_selection', '请选择不同的单工程任务。')
|
||||
root = canonical_path(service._logging.root)
|
||||
with _lease(root):
|
||||
if revalidate is not None:
|
||||
from .batch_supervisor import mutation_lease
|
||||
with mutation_lease(root):
|
||||
revalidate()
|
||||
from .batch_resources import guard_pending_resources
|
||||
guard_pending_resources(root)
|
||||
children = {item: service.for_project_task(item) for item in ids}
|
||||
projects = [children[item].projects(item) for item in ids]
|
||||
if any(len(rows) != 1 for rows in projects) or len({str(canonical_path(rows[0].path)).casefold()
|
||||
@@ -119,6 +109,12 @@ def execute_workspace_projects(service, task_ids, *, stop_event, queue_id=None,
|
||||
return TaskQueueResult(token, tuple(TaskQueueEntry(item, state['entries'][item]['state'],
|
||||
state['entries'][item]['message']) for item in ids), paused, current, verification or None)
|
||||
|
||||
held = next((item for item in ids if _task_uncertain(root, children[item], item)), None)
|
||||
if held is not None:
|
||||
state['entries'][held].update(state='blocked', message='已有原生写入结果待核验,整批暂停。')
|
||||
write_record(path, state)
|
||||
return result(True, held)
|
||||
|
||||
def run_project(item, *, problems=False):
|
||||
row = state['entries'][item]
|
||||
previous = row['state']
|
||||
@@ -140,31 +136,32 @@ def execute_workspace_projects(service, task_ids, *, stop_event, queue_id=None,
|
||||
row.update(state=outcome.entries[0].state, message=outcome.entries[0].message, released=True)
|
||||
if row['state'] == 'blocked':
|
||||
record_task_outcome(children[item], item, 'blocked', row['message'])
|
||||
isolated_sources.update((source, item) for source in sources[item])
|
||||
verification = (outcome.netlist_verification or {}).get(item)
|
||||
if verification:
|
||||
row['netlist_verification'] = verification
|
||||
write_record(path, state)
|
||||
return outcome.paused and row['state'] != 'blocked'
|
||||
return outcome.paused or row['state'] == 'blocked'
|
||||
except TaskCenterError as error:
|
||||
from .batch_resources import resource_blockers
|
||||
released = ((getattr(error, 'resources_released', False) is True
|
||||
or getattr(error, 'owned_writers_exited', False) is True)
|
||||
and not resource_blockers(service.pending_batch_resources() if hasattr(service, 'pending_batch_resources') else ()))
|
||||
from .batch_resources import blocking_resources
|
||||
released = getattr(error, 'resources_released', False) is True and not blocking_resources(root)
|
||||
saved = getattr(error, 'completed_result', None)
|
||||
if (isinstance(saved, TaskQueueResult) and saved.queue_id == child_id
|
||||
and len(saved.entries) == 1 and saved.entries[0].task_id == item and not saved.paused
|
||||
and saved.entries[0].state in {'completed', 'failed', 'skipped'}
|
||||
and not _task_uncertain(root, children[item], item)):
|
||||
entry = saved.entries[0]
|
||||
row.update(state=entry.state, message=entry.message, released=released)
|
||||
verification = (saved.netlist_verification or {}).get(item)
|
||||
if verification:
|
||||
row['netlist_verification'] = verification
|
||||
write_record(path, state)
|
||||
return not released
|
||||
row.update(state='blocked', message=error.message, released=released)
|
||||
row['supervisor_batch_id'] = getattr(service, '_last_supervisor_batch_id', None)
|
||||
evidence = getattr(getattr(children[item], '_quick_run_preparer', None), 'data_root', root / 'tasks' / item)
|
||||
protect_interruption(Path(evidence) / 'quick-run', 'project_supervisor_failed: ' + error.message)
|
||||
protect_interruption(_uncertainty_root(root, children[item], item), 'project_supervisor_failed: ' + error.message)
|
||||
record_task_outcome(children[item], item, 'blocked', error.message)
|
||||
isolated_sources.update((source, item) for source in sources[item])
|
||||
if released:
|
||||
from .batch_supervisor import reconcile_supervisors
|
||||
try:
|
||||
row['released'] = not bool(reconcile_supervisors(root))
|
||||
except Exception:
|
||||
row['released'] = False
|
||||
write_record(path, state)
|
||||
return not row['released']
|
||||
return True
|
||||
except BaseException:
|
||||
row['state'] = previous if previous in _TERMINAL else 'blocked'
|
||||
write_record(path, state)
|
||||
@@ -197,9 +194,7 @@ def execute_workspace_projects(service, task_ids, *, stop_event, queue_id=None,
|
||||
write_record(path, state)
|
||||
continue
|
||||
if row['state'] in _TERMINAL:
|
||||
if row['state'] == 'blocked' and not row['released']:
|
||||
if not _released_after_recheck(root, item, row):
|
||||
return result(True, item)
|
||||
if not row['released']:
|
||||
row['released'] = True
|
||||
write_record(path, state)
|
||||
continue
|
||||
|
||||
@@ -123,6 +123,139 @@ def incident(case):
|
||||
run_id=case['run_id'], execution_authorized=True)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def confirmed_incident_batch(rule_run, monkeypatch):
|
||||
from dataclasses import replace
|
||||
from dx_productivity.trial_task_center import batch_admission, batch_resources
|
||||
from dx_productivity.trial_task_center.project_isolation import write_sources
|
||||
|
||||
case = rule_run(initial_saved=False, retry_saved=False)
|
||||
service, task_id, run_id, root = (case[key] for key in ('service', 'task_id', 'run_id', 'root'))
|
||||
task, = service.tasks()
|
||||
sibling_id = 'f' * 32
|
||||
sibling = replace(task, task_id=sibling_id, group_position=task.group_position + 1)
|
||||
monkeypatch.setattr(service, 'tasks', lambda: (task, sibling))
|
||||
original_interrupted = service.has_interrupted_quick_run
|
||||
held = {'value': True}
|
||||
monkeypatch.setattr(service, 'has_interrupted_quick_run',
|
||||
lambda item: held['value'] if item == sibling_id else original_interrupted(item))
|
||||
run = RunJournal(root).get(run_id)
|
||||
project = service.task_context(task_id).project.path
|
||||
manifest = {'schema_version': 1, 'policy_version': batch_admission.POLICY_VERSION, 'scope_kind': 'selected',
|
||||
'group_id': task.group_id, 'candidate_task_ids': [task_id], 'runnable_task_ids': [task_id],
|
||||
'plan_hashes': run['plan_hashes'], 'decisions': [{'task_id': task_id,
|
||||
'classification': 'executable', 'project': str(project), 'write_sources': sorted(write_sources(project, strict=True))}]}
|
||||
batch_resources.write_record(root / 'batch-runs' / run_id / 'manifest.json',
|
||||
dict(manifest, run_id=run_id, manifest_digest=batch_admission._digest(manifest)))
|
||||
return case, held
|
||||
|
||||
|
||||
def test_uncertain_batch_sibling_blocks_incident_before_retry_reservation(confirmed_incident_batch):
|
||||
case, _ = confirmed_incident_batch
|
||||
result = incident(case)
|
||||
assert result['attempts'] == 0
|
||||
assert result['retry_error']['code'] == 'quick_run_uncertain'
|
||||
assert case['calls'] == ['OLD-OK', 'OLD-BAD']
|
||||
assert case['service'].execution_problems(case['task_id'])[0]['auto_retries'] == 0
|
||||
|
||||
|
||||
def test_cleared_sibling_does_not_reopen_a_batch_paused_for_verification(confirmed_incident_batch):
|
||||
case, held = confirmed_incident_batch
|
||||
held['value'] = False
|
||||
journal = RunJournal(case['root'])
|
||||
run = journal.get(case['run_id'])
|
||||
journal.finish(case['run_id'], dict(run['result'], status='blocked', paused=True))
|
||||
result = incident(case)
|
||||
assert result['attempts'] == 0
|
||||
assert result['retry_error']['code'] == 'quick_run_uncertain'
|
||||
assert case['calls'] == ['OLD-OK', 'OLD-BAD']
|
||||
|
||||
|
||||
def test_missing_confirmed_manifest_cannot_fall_back_to_legacy_retry(confirmed_incident_batch):
|
||||
case, held = confirmed_incident_batch
|
||||
held['value'] = False
|
||||
root, run_id = case['root'], case['run_id']
|
||||
folder = root / 'batch-runs' / run_id
|
||||
manifest = json.loads((folder / 'manifest.json').read_bytes())
|
||||
checkpoint = root / 'task-queues' / (run_id + '.json')
|
||||
state = json.loads(checkpoint.read_bytes())
|
||||
checkpoint.write_text(json.dumps(dict(state, manifest_digest=manifest['manifest_digest'])), encoding='utf-8')
|
||||
folder.rename(folder.with_name('copied-evidence'))
|
||||
result = incident(case)
|
||||
assert result['attempts'] == 0
|
||||
assert result['retry_error']['code'] == 'batch_manifest'
|
||||
assert case['calls'] == ['OLD-OK', 'OLD-BAD']
|
||||
|
||||
|
||||
def test_incident_dispatch_failure_exports_original_batch_revision(confirmed_incident_batch, monkeypatch):
|
||||
from dx_productivity.dsh.execution_runs import _republish_incident_batch_summary
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
|
||||
case, held = confirmed_incident_batch
|
||||
held['value'] = False
|
||||
service, task_id, run_id, root = (case[key] for key in ('service', 'task_id', 'run_id', 'root'))
|
||||
journal = RunJournal(root)
|
||||
checkpoint = root / 'task-queues' / (run_id + '.json')
|
||||
folder = root / 'batch-runs' / run_id
|
||||
path = folder / 'batch-receipt.json'
|
||||
manifest = json.loads((folder / 'manifest.json').read_bytes())
|
||||
state = json.loads(checkpoint.read_bytes())
|
||||
checkpoint.write_text(json.dumps(dict(state, manifest_digest=manifest['manifest_digest'])), encoding='utf-8')
|
||||
_republish_incident_batch_summary(service, root, run_id, journal.get(run_id)['result'])
|
||||
previous = json.loads(path.read_bytes())
|
||||
batch_id = '8' * 32
|
||||
dispatched = []
|
||||
|
||||
def failed_dispatch(item, **controls):
|
||||
controls['revalidate']()
|
||||
dispatched.append(item)
|
||||
service._last_supervisor_batch_id = batch_id
|
||||
raise TaskCenterError('supervisor_interrupted', 'worker ended without a durable result')
|
||||
|
||||
monkeypatch.setattr(service, 'execute_quick_run_queue', failed_dispatch)
|
||||
result = incident(case)
|
||||
assert result['retry_error']['code'] == 'supervisor_interrupted'
|
||||
assert dispatched == [task_id]
|
||||
summary = json.loads(path.read_bytes())
|
||||
assert summary['revision'] == previous['revision'] + 1
|
||||
assert summary['stop_reason'] == 'supervisor_interrupted'
|
||||
assert batch_id in summary['resource_batch_ids']
|
||||
|
||||
|
||||
def test_uncertain_batch_sibling_blocks_direct_retry_intent(confirmed_incident_batch):
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
|
||||
case, _ = confirmed_incident_batch
|
||||
service, task_id, run_id, root = (case[key] for key in ('service', 'task_id', 'run_id', 'root'))
|
||||
selected = service.reserve_problem_retry(task_id, source='dsh')
|
||||
service.prepare_failed_quick_run(task_id, operation_keys=selected)
|
||||
journal = RunJournal(root)
|
||||
before = journal.get(run_id)
|
||||
with pytest.raises(TaskCenterError) as caught:
|
||||
journal.begin_retry(service, run_id, task_id, selected)
|
||||
assert caught.value.code == 'quick_run_uncertain'
|
||||
assert journal.get(run_id) == before
|
||||
assert case['calls'] == ['OLD-OK', 'OLD-BAD']
|
||||
|
||||
|
||||
def test_incident_rechecks_sibling_under_dispatch_lease(confirmed_incident_batch, monkeypatch):
|
||||
from dx_productivity.trial_task_center.netlist_verification import NetlistVerification
|
||||
|
||||
case, held = confirmed_incident_batch
|
||||
held['value'] = False
|
||||
before_task = NetlistVerification.before_task
|
||||
|
||||
def expose_interruption(self, *args, **kwargs):
|
||||
result = before_task(self, *args, **kwargs)
|
||||
held['value'] = True
|
||||
return result
|
||||
|
||||
monkeypatch.setattr(NetlistVerification, 'before_task', expose_interruption)
|
||||
result = incident(case)
|
||||
assert result['retry_error']['code'] == 'quick_run_uncertain'
|
||||
assert case['calls'] == ['OLD-OK', 'OLD-BAD']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('damage', ['delete', 'tamper'])
|
||||
def test_rule_retry_rechecks_failure_proof_without_spending_or_dispatching(rule_run, damage):
|
||||
case = rule_run()
|
||||
@@ -192,10 +325,11 @@ def test_legacy_rule_retry_cannot_create_a_replacement_before_baseline(rule_run)
|
||||
assert receipt['execution_status'] == 'completed' and receipt['acceptance']['status'] == 'unavailable'
|
||||
|
||||
|
||||
def test_retry_receipt_refresh_preserves_other_task_without_dispatch(tmp_path, monkeypatch):
|
||||
def test_retry_receipt_refresh_preserves_other_task_without_dispatch(tmp_path, monkeypatch, request):
|
||||
from types import SimpleNamespace as NS
|
||||
from dx_productivity.dsh.execution_runs import execute_incident_retry
|
||||
from dx_productivity.dsh.execution_runs import _finish_execution_run, execute_incident_retry
|
||||
from dx_productivity.trial_task_center import netlist_verification, task_queue
|
||||
from dx_productivity.trial_task_center.verification.service import VerificationService
|
||||
selected, other, run_id = 'a' * 32, 'b' * 32, 'c' * 32
|
||||
hashes = {selected: 'd' * 64, other: 'e' * 64}
|
||||
monkeypatch.setattr(task_queue, '_plan_hash', lambda child, key: hashes[key])
|
||||
@@ -206,22 +340,32 @@ def test_retry_receipt_refresh_preserves_other_task_without_dispatch(tmp_path, m
|
||||
def execute(key, **options):
|
||||
dispatch.append(key)
|
||||
return NS(paused=False)
|
||||
service = NS(for_project_task=lambda key: service, task_context=context, execute_quick_run_queue=execute)
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
request.addfinalizer(store.close)
|
||||
verification_service = VerificationService(store, tmp_path)
|
||||
service = NS(for_project_task=lambda key: service, task_context=context, execute_quick_run_queue=execute,
|
||||
verification=verification_service)
|
||||
class Checks:
|
||||
def __init__(self, *args): self.tasks = {}
|
||||
def __enter__(self): return self
|
||||
def __exit__(self, *args): pass
|
||||
def before_task(self, child, key, *, existing_only): assert existing_only
|
||||
def after_task(self, key, **options): assert key == selected
|
||||
def finish(self): return {selected: {'status': 'verified', 'verified': True, 'report_path': 'new.json'}}
|
||||
def finish(self):
|
||||
return {selected: {'status': 'verified', 'verified': True, 'report_path': 'new.json',
|
||||
'execution': {'state': 'completed', 'saved_items': 1}}}
|
||||
monkeypatch.setattr(netlist_verification, 'NetlistVerification', Checks)
|
||||
journal = RunJournal(tmp_path)
|
||||
journal.begin(run_id, [selected, other], hashes)
|
||||
old_other = {'task_id': other, 'state': 'completed', 'message': 'original saved result'}
|
||||
old_report = {'status': 'verified', 'verified': True, 'report_path': 'original.json'}
|
||||
journal.finish(run_id, {'status': 'failed', 'entries': [
|
||||
{'task_id': selected, 'state': 'failed', 'message': 'safe failure'}, old_other],
|
||||
'netlist_verification': {other: old_report}})
|
||||
old_report = {'status': 'verified', 'verified': True, 'report_path': 'original.json',
|
||||
'execution': {'state': 'completed', 'saved_items': 1}}
|
||||
initial = task_queue.TaskQueueResult(run_id, (
|
||||
task_queue.TaskQueueEntry(selected, 'failed', 'safe failure'),
|
||||
task_queue.TaskQueueEntry(**old_other)), False, netlist_verification={other: old_report})
|
||||
_finish_execution_run(service, tmp_path, [selected, other], Event(), run_id, initial, baseline={})
|
||||
verification_task = verification_service.list_tasks()['tasks'][0]['task_id']
|
||||
assert verification_service.read_task(verification_task)['summary']['total'] == 1
|
||||
checkpoint = tmp_path / 'task-queues' / (run_id + '.json')
|
||||
checkpoint.parent.mkdir()
|
||||
checkpoint.write_text(json.dumps({'version': 1, 'phase': 'finished', 'task_ids': [selected, other],
|
||||
@@ -234,6 +378,7 @@ def test_retry_receipt_refresh_preserves_other_task_without_dispatch(tmp_path, m
|
||||
assert next(row for row in receipt['entries'] if row['task_id'] == other) == old_other
|
||||
assert receipt['netlist_verification'][other] == old_report
|
||||
assert json.loads(checkpoint.read_text())['entries'][other] == {'state': 'completed', 'message': 'original saved result'}
|
||||
assert {row['item_key'] for row in verification_service.read_task(verification_task)['items']} == {selected, other}
|
||||
|
||||
|
||||
@pytest.mark.parametrize('scheduled', [False, True])
|
||||
|
||||
@@ -0,0 +1,385 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.dsh import execution_runs
|
||||
from dx_productivity.dsh.run_journal import RunJournal
|
||||
from dx_productivity.trial_task_center import batch_resources
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
from dx_productivity.trial_task_center.logging_setup import configure_logging
|
||||
from dx_productivity.trial_task_center.service import TaskCenterService
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
from dx_productivity.trial_task_center.task_queue import TaskQueueEntry, TaskQueueResult
|
||||
|
||||
|
||||
RUN_ID = '1' * 32
|
||||
BATCH_ID = '2' * 32
|
||||
TASK_ID = 'a' * 32
|
||||
SKIPPED_ID = 'b' * 32
|
||||
PLAN_HASHES = {TASK_ID: 'a' * 64}
|
||||
|
||||
|
||||
def test_known_manifest_run_cannot_resume_through_legacy_path_when_manifest_is_missing(batch):
|
||||
service, child, data, report, admission = batch
|
||||
journal = RunJournal(data)
|
||||
journal.begin(RUN_ID, [TASK_ID], PLAN_HASHES)
|
||||
batch_resources.write_record(data / 'task-queues' / (RUN_ID + '.json'),
|
||||
{'manifest_digest': admission['manifest_digest']})
|
||||
with pytest.raises(TaskCenterError) as caught:
|
||||
execution_runs.execute_confirmed_run(service, data, [TASK_ID], report, Event(), RUN_ID,
|
||||
resume={'run_id': RUN_ID})
|
||||
assert caught.value.code == 'batch_manifest'
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def batch(tmp_path, monkeypatch):
|
||||
report = {'fingerprint': 'frozen', 'plan_hashes': PLAN_HASHES}
|
||||
admission = {'candidate_task_ids': [SKIPPED_ID, TASK_ID],
|
||||
'runnable_task_ids': [TASK_ID], 'plan_hashes': PLAN_HASHES,
|
||||
'execution_report': report, 'manifest_digest': 'd' * 64, 'policy_version': 1,
|
||||
'candidate_fingerprint': 'f' * 64, 'decisions': [
|
||||
{'task_id': SKIPPED_ID, 'classification': 'skipped', 'message': 'no plan'},
|
||||
{'task_id': TASK_ID, 'classification': 'executable'}]}
|
||||
data = tmp_path / 'data'
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
service = TaskCenterService(store, configure_logging(data))
|
||||
child_db = tmp_path / 'child.db'
|
||||
child = TaskStore(child_db)
|
||||
service.for_project_task = lambda key: type('Child', (), {'_store': child})()
|
||||
service.task_context = lambda key: type('Context', (), {
|
||||
'task': type('Task', (), {'name': key}), 'progress': type('Progress', (), {
|
||||
'saved_items': 1, 'failed_items': 0, 'no_match_items': 0, 'queue_complete': True}),
|
||||
'interrupted': False})()
|
||||
monkeypatch.setattr(execution_runs.tasks, 'fingerprint', lambda *_: 'frozen')
|
||||
monkeypatch.setattr(execution_runs, 'validate_batch_admission', lambda *_: report)
|
||||
try:
|
||||
yield service, child, data, report, admission
|
||||
finally:
|
||||
child.close()
|
||||
store.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('resource_state, outcome', [('released', 'completed'), ('isolated', 'paused')])
|
||||
def test_bound_receipt_preserves_verified_result_and_checks_resource_state(batch, monkeypatch, resource_state, outcome):
|
||||
service, child, data, report, admission = batch
|
||||
directory = data / 'batch-runs' / RUN_ID
|
||||
dispatches = []
|
||||
|
||||
def dispatch(current_service, scope, **kwargs):
|
||||
assert json.loads((directory / 'manifest.json').read_bytes())['candidate_task_ids'] == [SKIPPED_ID, TASK_ID]
|
||||
kwargs['revalidate']()
|
||||
dispatches.append(scope)
|
||||
assert RunJournal(data).get(RUN_ID)['task_ids'] == [TASK_ID]
|
||||
with child.transaction():
|
||||
child._connection.execute('INSERT INTO execution_rounds (task_id,round_id) VALUES (?,?)', (TASK_ID, 'round'))
|
||||
child._connection.execute('INSERT INTO execution_operations VALUES (?,?,?,?,?,?,?,?)',
|
||||
(TASK_ID, 'round', 'key', json.dumps({'target_scope': 'targets',
|
||||
'project_path': 'board.prj', 'schematic_name': 'MAIN', 'sheet_number': '1',
|
||||
'target_selectors': 'uid1\x1fR1'}), 'verified', 'a', 1, '{}'))
|
||||
current_service._last_supervisor_batch_id = BATCH_ID
|
||||
record = {'version': 1, 'session_id': BATCH_ID, 'kind': 'task_queue',
|
||||
'generation': 1, 'desktop': 'dx-' + BATCH_ID, 'state': resource_state, 'processes': [],
|
||||
'cad_pid': None, 'cad_guid': None, 'checkpoints': {}, 'retries': {}, 'timings': [],
|
||||
'release_proof': {'generation': 1, 'desktop_not_acquired': True},
|
||||
'cleanup': {'desktop_not_acquired': True, 'desktop_handle_closed': True,
|
||||
'owned_cleanup_complete': True}}
|
||||
batch_resources.write_record(data / 'batch-resources' / BATCH_ID / 'session.json', record)
|
||||
from dx_productivity.trial_task_center.supervisor_protocol import VERSION
|
||||
batch_resources.write_record(data / 'batch-resources' / BATCH_ID / 'supervisor.json',
|
||||
{'version': VERSION, 'batch_id': BATCH_ID, 'state': 'finished', 'outcome': 'ok',
|
||||
'operation': 'execute_task_queue', 'task_ids': [TASK_ID], 'attempt_id': '3' * 32,
|
||||
'request_sha256': '0' * 64, 'parent_process': {'pid': 1, 'creation_time': 'test'}})
|
||||
return TaskQueueResult(RUN_ID, (TaskQueueEntry(TASK_ID, 'completed'),), False,
|
||||
netlist_verification={TASK_ID: {'status': 'verified', 'verified': True}})
|
||||
|
||||
monkeypatch.setattr(execution_runs, 'execute_task_queue', dispatch)
|
||||
receipt = execution_runs.execute_confirmed_run(service, data, (TASK_ID,), report, Event(),
|
||||
RUN_ID, admission=admission)
|
||||
summary = json.loads((directory / 'batch-receipt.json').read_bytes())
|
||||
assert dispatches == [(TASK_ID,)]
|
||||
assert receipt['summary'] == summary
|
||||
assert summary['manifest_digest'] == admission['manifest_digest']
|
||||
assert summary['operation_counts']['saved'] == 1
|
||||
assert summary['task_counts']['skipped'] == 1
|
||||
assert summary['execution_status'] == 'completed'
|
||||
assert summary['acceptance_status'] == 'verified'
|
||||
assert summary['resource_state'] == resource_state
|
||||
assert summary['status'] == RunJournal(data).get(RUN_ID)['result']['status'] == outcome
|
||||
if resource_state == 'isolated':
|
||||
session = data / 'batch-resources' / BATCH_ID / 'session.json'
|
||||
record = json.loads(session.read_bytes())
|
||||
batch_resources.write_record(session, dict(record, state='released'))
|
||||
execution_runs.recover_batch_receipts(service, data)
|
||||
reconciled = json.loads((directory / 'batch-receipt.json').read_bytes())
|
||||
assert dispatches == [(TASK_ID,)]
|
||||
assert reconciled['revision'] == summary['revision'] + 1
|
||||
assert reconciled['operation_counts'] == summary['operation_counts']
|
||||
assert reconciled['resource_state'] == 'released'
|
||||
assert reconciled['status'] == 'completed'
|
||||
|
||||
|
||||
def test_interrupted_receipt_recovery_after_export_failure_dispatches_once(batch, monkeypatch):
|
||||
service, _, data, report, admission = batch
|
||||
dispatches = []
|
||||
directory = data / 'batch-runs' / RUN_ID
|
||||
atomic_write = batch_resources.write_record
|
||||
|
||||
def dispatch(*args, **kwargs):
|
||||
kwargs['revalidate']()
|
||||
dispatches.append(True)
|
||||
checkpoint = data / 'task-queues' / (RUN_ID + '.json')
|
||||
atomic_write(checkpoint, {'task_ids': [TASK_ID], 'plan_hashes': PLAN_HASHES,
|
||||
'entries': {TASK_ID: {'state': 'blocked', 'message': 'needs save verification'}}})
|
||||
raise TaskCenterError('supervisor_interrupted', 'owner exited')
|
||||
|
||||
def write_failure(path, value):
|
||||
if Path(path).name == 'batch-receipt.json':
|
||||
raise OSError('fixture unavailable')
|
||||
atomic_write(path, value)
|
||||
|
||||
monkeypatch.setattr(execution_runs, 'execute_task_queue', dispatch)
|
||||
monkeypatch.setattr(batch_resources, 'write_record', write_failure)
|
||||
with pytest.raises(TaskCenterError, match='owner exited'):
|
||||
execution_runs.execute_confirmed_run(service, data, (TASK_ID,), report, Event(),
|
||||
RUN_ID, admission=admission)
|
||||
assert not (directory / 'batch-receipt.json').exists()
|
||||
durable = RunJournal(data).batch_summary(RUN_ID)
|
||||
assert durable['reporting_errors'][-1]['code'] == 'batch_receipt_export_unavailable'
|
||||
monkeypatch.setattr(batch_resources, 'write_record', atomic_write)
|
||||
execution_runs.recover_batch_receipts(service, data)
|
||||
summary = json.loads((directory / 'batch-receipt.json').read_bytes())
|
||||
assert dispatches == [True]
|
||||
assert summary == RunJournal(data).batch_summary(RUN_ID)
|
||||
assert summary['task_counts']['blocked'] == 1
|
||||
assert summary['stop_reason'] == 'supervisor_interrupted'
|
||||
|
||||
|
||||
def test_confirmed_scope_change_keeps_manifest_and_records_zero_dispatch(batch, monkeypatch):
|
||||
service, _, data, report, admission = batch
|
||||
directory = data / 'batch-runs' / RUN_ID
|
||||
dispatches = []
|
||||
|
||||
def validate(current_service, frozen):
|
||||
assert json.loads((directory / 'manifest.json').read_bytes())['manifest_digest'] == frozen['manifest_digest']
|
||||
raise TaskCenterError('assistant_stale', 'scope changed')
|
||||
|
||||
def dispatch(*args, **kwargs):
|
||||
kwargs['revalidate']()
|
||||
dispatches.append(True)
|
||||
|
||||
monkeypatch.setattr(execution_runs, 'validate_batch_admission', validate)
|
||||
monkeypatch.setattr(execution_runs, 'execute_task_queue', dispatch)
|
||||
with pytest.raises(TaskCenterError, match='scope changed'):
|
||||
execution_runs.execute_confirmed_run(service, data, (TASK_ID,), report, Event(),
|
||||
RUN_ID, admission=admission)
|
||||
summary = json.loads((directory / 'batch-receipt.json').read_bytes())
|
||||
assert not dispatches
|
||||
assert RunJournal(data).get(RUN_ID) is None
|
||||
assert summary['status'] == 'rejected'
|
||||
assert summary['dispatch_count'] == 0 and summary['queue_id'] is None
|
||||
|
||||
|
||||
def test_restart_rebuilds_summary_after_sqlite_publish_error(batch, monkeypatch):
|
||||
service, _, data, report, admission = batch
|
||||
directory = data / 'batch-runs' / RUN_ID
|
||||
dispatches = []
|
||||
save_summary = RunJournal.save_batch_summary
|
||||
|
||||
def dispatch(*args, **kwargs):
|
||||
kwargs['revalidate']()
|
||||
dispatches.append(True)
|
||||
checkpoint = data / 'task-queues' / (RUN_ID + '.json')
|
||||
batch_resources.write_record(checkpoint, {'task_ids': [TASK_ID], 'plan_hashes': PLAN_HASHES,
|
||||
'entries': {TASK_ID: {'state': 'failed', 'message': 'failed safely'}}})
|
||||
return TaskQueueResult(RUN_ID, (TaskQueueEntry(TASK_ID, 'failed'),), False)
|
||||
|
||||
def fail_summary(*args, **kwargs):
|
||||
raise OSError('fixture unavailable')
|
||||
|
||||
monkeypatch.setattr(RunJournal, 'save_batch_summary', fail_summary)
|
||||
monkeypatch.setattr(execution_runs, 'execute_task_queue', dispatch)
|
||||
receipt = execution_runs.execute_confirmed_run(service, data, (TASK_ID,), report, Event(),
|
||||
RUN_ID, admission=admission)
|
||||
assert receipt['reporting_errors'][-1]['code'] == 'batch_summary_unavailable'
|
||||
assert RunJournal(data).get(RUN_ID)['result']['reporting_errors'] == receipt['reporting_errors']
|
||||
assert not (directory / 'batch-receipt.json').exists()
|
||||
monkeypatch.setattr(RunJournal, 'save_batch_summary', save_summary)
|
||||
execution_runs.recover_batch_receipts(service, data)
|
||||
summary = json.loads((directory / 'batch-receipt.json').read_bytes())
|
||||
assert dispatches == [True]
|
||||
assert summary['task_counts']['failed'] == 1 and summary['status'] == 'failed'
|
||||
assert summary['reporting_errors'][-1]['code'] == 'batch_summary_unavailable'
|
||||
|
||||
|
||||
def _durable_supervisor_result(data, result, *, stopping_reason=None, batch_id=BATCH_ID, resumed=False):
|
||||
from hashlib import sha256
|
||||
from dx_productivity.trial_task_center.supervisor_protocol import VERSION, encode
|
||||
|
||||
directory = data / 'batch-resources' / batch_id
|
||||
attempt_id = '3' * 32
|
||||
request_path = directory / 'request.json'
|
||||
batch_resources.write_record(request_path, {'version': VERSION, 'batch_id': batch_id,
|
||||
'attempt_id': attempt_id, 'root': str(data), 'operation': 'execute_task_queue',
|
||||
'task_ids': [TASK_ID], 'arguments': encode({'task_ids': (TASK_ID,),
|
||||
('queue_id' if resumed else 'checkpoint_id'): RUN_ID,
|
||||
'expected_plan_hashes': PLAN_HASHES, 'manifest_digest': 'd' * 64})})
|
||||
batch_resources.write_record(directory / 'supervisor.json',
|
||||
{'version': VERSION, 'batch_id': batch_id, 'state': 'finished', 'outcome': 'ok',
|
||||
'operation': 'execute_task_queue', 'task_ids': [TASK_ID], 'attempt_id': attempt_id,
|
||||
'started_at': 2 if resumed else 1,
|
||||
'stopping_reason': stopping_reason, 'business_idle_timeout_seconds': 150,
|
||||
'request_sha256': sha256(request_path.read_bytes()).hexdigest(),
|
||||
'parent_process': {'pid': 1, 'creation_time': 'test'}})
|
||||
batch_resources.write_record(directory / 'result.json', {'version': VERSION, 'batch_id': batch_id,
|
||||
'attempt_id': attempt_id, 'generation': 1, 'sequence': 1, 'type': 'result',
|
||||
'payload': {'status': 'ok', 'business_succeeded': True, 'result': encode(result)}})
|
||||
batch_resources.write_record(directory / 'session.json', {'version': 1, 'session_id': batch_id,
|
||||
'kind': 'task_queue', 'generation': 1, 'desktop': 'dx-' + batch_id, 'state': 'released', 'processes': [],
|
||||
'cad_pid': None, 'cad_guid': None, 'checkpoints': {}, 'retries': {}, 'timings': [],
|
||||
'release_proof': {'generation': 1, 'desktop_not_acquired': True},
|
||||
'cleanup': {'desktop_not_acquired': True, 'desktop_handle_closed': True, 'owned_cleanup_complete': True}})
|
||||
|
||||
|
||||
def test_restart_recovers_business_and_netlist_before_first_journal_finish(batch, monkeypatch):
|
||||
service, _, data, _, admission = batch
|
||||
checkpoint = {'task_ids': [TASK_ID], 'plan_hashes': PLAN_HASHES, 'manifest_digest': 'd' * 64,
|
||||
'entries': {TASK_ID: {'state': 'completed', 'message': 'saved'}}}
|
||||
directory = data / 'batch-runs' / RUN_ID
|
||||
batch_resources.write_record(directory / 'manifest.json', dict(admission, run_id=RUN_ID))
|
||||
batch_resources.write_record(data / 'task-queues' / (RUN_ID + '.json'), checkpoint)
|
||||
journal = RunJournal(data)
|
||||
journal.begin(RUN_ID, [TASK_ID], PLAN_HASHES)
|
||||
result = TaskQueueResult(RUN_ID, (TaskQueueEntry(TASK_ID, 'completed', 'saved'),), False,
|
||||
netlist_verification={TASK_ID: {'status': 'verified', 'verified': True}})
|
||||
_durable_supervisor_result(data, result)
|
||||
monkeypatch.setattr(execution_runs, 'execute_task_queue',
|
||||
lambda *args, **kwargs: pytest.fail('receipt recovery dispatched CAD'))
|
||||
execution_runs.recover_batch_receipts(service, data)
|
||||
summary = json.loads((directory / 'batch-receipt.json').read_bytes())
|
||||
assert summary['status'] == 'completed'
|
||||
assert summary['execution_status'] == 'completed'
|
||||
assert summary['acceptance_status'] == 'verified'
|
||||
assert journal.get(RUN_ID)['result']['netlist_verification'] == result.netlist_verification
|
||||
|
||||
|
||||
def test_cleanup_only_stop_reason_resolves_without_replay(batch, monkeypatch):
|
||||
service, _, data, report, admission = batch
|
||||
directory = data / 'batch-runs' / RUN_ID
|
||||
|
||||
def dispatch(*args, **kwargs):
|
||||
kwargs['revalidate']()
|
||||
result = TaskQueueResult(RUN_ID, (TaskQueueEntry(TASK_ID, 'completed', 'saved'),), False,
|
||||
netlist_verification={TASK_ID: {'status': 'verified', 'verified': True}})
|
||||
_durable_supervisor_result(data, result)
|
||||
session = data / 'batch-resources' / BATCH_ID / 'session.json'
|
||||
batch_resources.write_record(session, dict(json.loads(session.read_bytes()), state='isolated'))
|
||||
raise batch_resources.BatchResourceCleanupError('resources held', completed_result=result)
|
||||
|
||||
monkeypatch.setattr(execution_runs, 'execute_task_queue', dispatch)
|
||||
with pytest.raises(batch_resources.BatchResourceCleanupError):
|
||||
execution_runs.execute_confirmed_run(service, data, (TASK_ID,), report, Event(),
|
||||
RUN_ID, admission=admission)
|
||||
summary = json.loads((directory / 'batch-receipt.json').read_bytes())
|
||||
assert summary['stop_reason'] == 'resource_pending'
|
||||
assert summary['status'] == 'paused'
|
||||
session = data / 'batch-resources' / BATCH_ID / 'session.json'
|
||||
batch_resources.write_record(session, dict(json.loads(session.read_bytes()), state='released'))
|
||||
execution_runs.recover_batch_receipts(service, data)
|
||||
summary = json.loads((directory / 'batch-receipt.json').read_bytes())
|
||||
assert summary['stop_reason'] is None and summary['status'] == 'completed'
|
||||
|
||||
|
||||
def test_bound_incident_retry_refreshes_original_receipt(batch):
|
||||
service, _, data, _, admission = batch
|
||||
directory = data / 'batch-runs' / RUN_ID
|
||||
batch_resources.write_record(directory / 'manifest.json', dict(admission, run_id=RUN_ID))
|
||||
journal = RunJournal(data)
|
||||
journal.begin(RUN_ID, [TASK_ID], PLAN_HASHES)
|
||||
receipt = {'status': 'failed', 'execution_status': 'failed', 'queue_id': RUN_ID,
|
||||
'entries': [{'task_id': TASK_ID, 'state': 'failed', 'message': 'retry failed safely'}]}
|
||||
journal.finish(RUN_ID, receipt)
|
||||
execution_runs._republish_incident_batch_summary(service, data, RUN_ID, receipt)
|
||||
readback = json.loads((directory / 'batch-receipt.json').read_bytes())
|
||||
assert readback['manifest_digest'] == 'd' * 64
|
||||
assert readback['task_counts']['failed'] == readback['task_counts']['skipped'] == 1
|
||||
|
||||
|
||||
def test_current_lookup_problem_codes_are_exported(batch):
|
||||
service, child, data, _, admission = batch
|
||||
directory = data / 'batch-runs' / RUN_ID
|
||||
batch_resources.write_record(directory / 'manifest.json', dict(admission, run_id=RUN_ID))
|
||||
journal = RunJournal(data)
|
||||
journal.begin(RUN_ID, [TASK_ID], PLAN_HASHES)
|
||||
with child.transaction():
|
||||
child._connection.execute('INSERT INTO execution_rounds (task_id,round_id) VALUES (?,?)', (TASK_ID, 'r'))
|
||||
for index, code in enumerate(('target_not_found', 'lookup_unavailable')):
|
||||
key = str(index)
|
||||
child._connection.execute('INSERT INTO execution_operations VALUES (?,?,?,?,?,?,?,?)',
|
||||
(TASK_ID, 'r', key, '{"target_scope":"all"}', 'failed', 'a', 1, '{}'))
|
||||
child._connection.execute('''INSERT INTO execution_problems
|
||||
(task_id,round_id,problem_key,operation_key,classification,state,code,message,rule_version)
|
||||
VALUES (?,?,?,?,?,?,?,?,?)''', (TASK_ID, 'r', key, key, 'action_required', 'open',
|
||||
code, 'Native lookup report', 'test'))
|
||||
journal.finish(RUN_ID, {'status': 'failed', 'entries': [{'task_id': TASK_ID, 'state': 'failed'}]})
|
||||
execution_runs.recover_batch_receipts(service, data)
|
||||
summary = json.loads((directory / 'batch-receipt.json').read_bytes())
|
||||
assert summary['failure_code_counts'] == {'target_not_found': 1, 'lookup_unavailable': 1}
|
||||
assert {item['code'] for item in summary['operation_failures']} == {'target_not_found', 'lookup_unavailable'}
|
||||
assert all(item['message'] == 'Native lookup report' and item['round_id'] == 'r'
|
||||
for item in summary['operation_failures'])
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reason', ['user_pause', 'inactivity'])
|
||||
def test_restart_keeps_supervisor_stop_cause(batch, reason):
|
||||
service, _, data, _, admission = batch
|
||||
checkpoint = {'task_ids': [TASK_ID], 'plan_hashes': PLAN_HASHES, 'manifest_digest': 'd' * 64,
|
||||
'entries': {TASK_ID: {'state': 'paused', 'message': 'paused'}}}
|
||||
directory = data / 'batch-runs' / RUN_ID
|
||||
batch_resources.write_record(directory / 'manifest.json', dict(admission, run_id=RUN_ID))
|
||||
batch_resources.write_record(data / 'task-queues' / (RUN_ID + '.json'), checkpoint)
|
||||
journal = RunJournal(data)
|
||||
journal.begin(RUN_ID, [TASK_ID], PLAN_HASHES)
|
||||
result = TaskQueueResult(RUN_ID, (TaskQueueEntry(TASK_ID, 'paused', 'paused'),), True)
|
||||
_durable_supervisor_result(data, result, stopping_reason=reason)
|
||||
execution_runs.recover_batch_receipts(service, data)
|
||||
summary = json.loads((directory / 'batch-receipt.json').read_bytes())
|
||||
assert summary['stop_reason'] == reason
|
||||
assert journal.get(RUN_ID)['result']['user_pause_requested'] is (reason == 'user_pause')
|
||||
assert summary['resource']['generations'][0]['business_idle_timeout_seconds'] == 150
|
||||
|
||||
|
||||
def test_restart_recovers_new_supervisor_result_after_resumed_run(batch, monkeypatch):
|
||||
service, _, data, _, admission = batch
|
||||
directory = data / 'batch-runs' / RUN_ID
|
||||
checkpoint_path = data / 'task-queues' / (RUN_ID + '.json')
|
||||
checkpoint = {'task_ids': [TASK_ID], 'plan_hashes': PLAN_HASHES, 'manifest_digest': 'd' * 64,
|
||||
'entries': {TASK_ID: {'state': 'paused', 'message': 'first attempt paused'}}}
|
||||
batch_resources.write_record(directory / 'manifest.json', dict(admission, run_id=RUN_ID))
|
||||
batch_resources.write_record(checkpoint_path, checkpoint)
|
||||
journal = RunJournal(data)
|
||||
journal.begin(RUN_ID, [TASK_ID], PLAN_HASHES)
|
||||
_durable_supervisor_result(data, TaskQueueResult(RUN_ID,
|
||||
(TaskQueueEntry(TASK_ID, 'paused', 'first attempt paused'),), True), stopping_reason='user_pause')
|
||||
monkeypatch.setattr(execution_runs, 'execute_task_queue',
|
||||
lambda *args, **kwargs: pytest.fail('receipt recovery dispatched CAD'))
|
||||
execution_runs.recover_batch_receipts(service, data)
|
||||
previous = journal.batch_summary(RUN_ID)
|
||||
assert previous['status'] == 'paused'
|
||||
assert journal.resume(RUN_ID)['result']['summary'] == previous
|
||||
|
||||
new_result = TaskQueueResult(RUN_ID, (TaskQueueEntry(TASK_ID, 'completed', 'resumed and saved'),), False,
|
||||
netlist_verification={TASK_ID: {'status': 'verified', 'verified': True}})
|
||||
_durable_supervisor_result(data, new_result, batch_id='4' * 32, resumed=True)
|
||||
checkpoint.update(entries={TASK_ID: {'state': 'completed', 'message': 'resumed and saved'}},
|
||||
netlist_verification=new_result.netlist_verification)
|
||||
batch_resources.write_record(checkpoint_path, checkpoint)
|
||||
execution_runs.recover_batch_receipts(service, data)
|
||||
|
||||
summary = journal.batch_summary(RUN_ID)
|
||||
assert summary['revision'] == previous['revision'] + 1
|
||||
assert summary['status'] == 'completed' and summary['acceptance_status'] == 'verified'
|
||||
assert summary['stop_reason'] is None
|
||||
assert summary == json.loads((directory / 'batch-receipt.json').read_bytes())
|
||||
assert journal.get(RUN_ID)['result']['netlist_verification'] == new_result.netlist_verification
|
||||
@@ -96,6 +96,47 @@ def test_inspect_accepts_frozen_workspace_checkpoint(project_service):
|
||||
assert result['remaining_task_ids'] == ids
|
||||
|
||||
|
||||
def test_inspect_restores_a_determined_resource_pause_only_from_its_original_batch(project_service, monkeypatch):
|
||||
import hashlib
|
||||
from dx_productivity.trial_task_center import batch_resources
|
||||
from dx_productivity.trial_task_center.supervisor_protocol import encode
|
||||
|
||||
service, _, data, ids, hashes = project_service
|
||||
journal = RunJournal(data)
|
||||
token, batch_id, attempt = 'a' * 32, 'b' * 32, 'c' * 32
|
||||
journal.begin(token, ids, hashes)
|
||||
evidence(service, ids[0])
|
||||
checkpoint(data, token, ids, hashes, {ids[0]: 'completed'})
|
||||
path = data / 'task-queues' / (token + '.json')
|
||||
state = json.loads(path.read_bytes())
|
||||
directory = data / 'batch-resources' / batch_id
|
||||
identity = {'pid': 17, 'creation_time': 'worker'}
|
||||
binding = {'version': 1, 'batch_id': batch_id, 'attempt_id': attempt}
|
||||
request = dict(binding, operation='execute_task_queue', root=str(data),
|
||||
arguments=encode({'task_ids': tuple(ids), 'queue_id': None, 'checkpoint_id': token,
|
||||
'expected_plan_hashes': hashes, 'manifest_digest': 'e' * 64}))
|
||||
batch_resources.write_record(directory / 'request.json', request)
|
||||
request_digest = hashlib.sha256((directory / 'request.json').read_bytes()).hexdigest()
|
||||
batch_resources.write_record(directory / 'supervisor.json', dict(binding,
|
||||
operation='execute_task_queue', task_ids=ids, state='finished', process=identity,
|
||||
parent_process=identity, request_sha256=request_digest))
|
||||
paused = TaskQueueResult(token, tuple(TaskQueueEntry(item, row['state'])
|
||||
for item, row in state['entries'].items()), True, ids[0])
|
||||
batch_resources.write_record(directory / 'result.json', dict(binding, generation=1, sequence=1, type='result',
|
||||
payload={'business_succeeded': True, 'status': 'ok', 'result': encode(paused)}))
|
||||
state.update(phase='primary', manifest_digest='e' * 64, resource_pause={'task_id': ids[0], 'batch_id': batch_id,
|
||||
'business_determined': True, 'manifest_digest': 'e' * 64, 'sources': {item: [item] for item in ids}})
|
||||
batch_resources.write_record(path, state)
|
||||
monkeypatch.setattr(batch_resources, 'observe_process_identity', lambda _: {'state': 'gone'})
|
||||
journal.finish(token, {'status': 'paused', 'paused': True, 'user_pause_requested': False})
|
||||
inspected = journal.inspect(service, token)
|
||||
assert inspected['resource_batch_id'] == batch_id
|
||||
assert inspected['isolated_task_ids'] == []
|
||||
assert inspected['remaining_task_ids'] == ids[1:]
|
||||
journal.finish(token, {'status': 'paused', 'paused': True, 'user_pause_requested': True})
|
||||
assert journal.inspect(service, token)['resource_batch_id'] is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('interrupted', [False, True])
|
||||
def test_shared_safe_primary_failure_can_hold_remaining_commands_on_resume(project_service, monkeypatch, interrupted):
|
||||
from dataclasses import replace
|
||||
|
||||
@@ -798,6 +798,50 @@ Require QP_App.UndoCount=0,"launch failure invoked undo"
|
||||
''', routines_transform=replace_shell)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('exit_code,may_write,expected_code', [
|
||||
(4, False, 'lookup_unavailable'),
|
||||
(1, False, '-2147220665'),
|
||||
(4, True, '-2147220665'),
|
||||
])
|
||||
def test_native_lookup_timeout_code_reaches_status_tsv(tmp_path, exit_code, may_write, expected_code):
|
||||
def replace_native_shell(routines):
|
||||
start = routines.index('Sub QPNativeReplace(')
|
||||
end = routines.index('End Sub', start)
|
||||
return (routines[:start] + routines[start:end].replace(
|
||||
'Set Shell = CreateObject("WScript.Shell")', 'Set Shell = New NativeResultShell')
|
||||
+ routines[end:] + f'''
|
||||
Class NativeResultShell
|
||||
Public Function Run(ByVal CommandLine, ByVal WindowStyle, ByVal Wait)
|
||||
Run={exit_code}
|
||||
End Function
|
||||
End Class
|
||||
''')
|
||||
|
||||
if may_write:
|
||||
(tmp_path / 'snapshot-value-job.tsv.native.json').write_text(
|
||||
'{"stage": "native_replace_started"}', encoding='utf-8')
|
||||
mutation_possible = 'True' if may_write else 'False'
|
||||
run_vbs(tmp_path, 'part_number', f'''
|
||||
Dim FailureSource, FailureDetail, StatusPath
|
||||
QP_HelperExecutable=WScript.FullName
|
||||
QP_HelperScript=""
|
||||
QP_BatchMode=True
|
||||
On Error Resume Next
|
||||
QPAutomaticReplaceAndRestore Command,SnapshotPath
|
||||
Failure=Err.Number: FailureSource=Err.Source: FailureDetail=Err.Description
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
Require Failure<>0,"native failure did not reach status writer"
|
||||
Require QP_NativeMutationPossible={mutation_possible},"native mutation evidence was lost or invented"
|
||||
Require QP_App.UndoCount=0,"batch failure invoked undo"
|
||||
QPFail QP_Root,"batch_failed",Failure,FailureSource,FailureDetail
|
||||
StatusPath=QP_Fso.BuildPath(QP_Root,"status.tsv")
|
||||
Require QPReadState(StatusPath,"value-job")="batch_failed","failure state was lost"
|
||||
''', routines_transform=replace_native_shell)
|
||||
rows = (tmp_path / 'status.tsv').read_text(encoding='utf-8-sig').splitlines()
|
||||
assert rows[-1].split('\t')[:3] == ['value-job', 'batch_failed', expected_code]
|
||||
|
||||
|
||||
def test_main_continues_after_zero_match_without_calling_native_helper(tmp_path):
|
||||
run_vbs(tmp_path, 'preserve', r'''
|
||||
QP_Fso.DeleteFile SnapshotPath
|
||||
|
||||
Loaded 100 of 166 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user