Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
471401db7d | ||
|
|
e772723b4e | ||
|
|
65f3a9c728 | ||
|
|
8395d7cff2 | ||
|
|
a23e980b4f | ||
|
|
c25db8ca25 | ||
|
|
2a89d6fdd4 | ||
|
|
392ae365da | ||
|
|
0b7f3e5c4a | ||
|
|
f80127e7bd | ||
|
|
ec2591ac75 | ||
|
|
22442e03ae | ||
|
|
9d9b316634 | ||
|
|
6d45ea1fa0 | ||
|
|
d0bbc73da3 | ||
|
|
650dfd5491 | ||
|
|
ba69f86628 | ||
|
|
63999b7bfd |
No files matched your search
@@ -101,6 +101,8 @@ jobs:
|
||||
tests/v1_1/test_workspace_execution.py
|
||||
tests/v1_1/test_nonblocking_bom_values.py
|
||||
tests/v1_1/test_value_readback.py
|
||||
tests/v1_1/test_ui_batch_retry.py
|
||||
tests/v1_1/test_deep_scan_archive_paths.py
|
||||
tests/dsh/test_run_journal.py
|
||||
tests/dsh/test_incident_admission.py
|
||||
tests/dsh/test_native_runtime.py
|
||||
|
||||
@@ -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,63 @@
|
||||
# PR #47 审计 649:核对与整改
|
||||
|
||||
日期:2026-11-27。审计来源:[评论 649](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/pulls/47#issuecomment-649)。审计基线 `f80127e`,被审计提交 `392ae365`。本次在原 PR 分支上整改,不合并、不关闭 #44。
|
||||
|
||||
## P1 逐项结论
|
||||
|
||||
| 项 | 核对结论 | 整改 |
|
||||
| --- | --- | --- |
|
||||
| 1 非监督批次恒 paused | 成立 | 由实际拥有本地 BatchCadRuntime 的队列记录运行身份;只有上下文退出且租约、桌面、写进程证明完整才发布释放。没有 supervisor 不再等同未知,也不直接视作成功。实际 UI 完成态用例通过。 |
|
||||
| 2 资源分支遮住异常 shutdown | 成立,按 P0 处理 | 先确定应用退出结论,再处理资源待释放;`application_shutdown_failed` 持久化并贯穿资源重查、自动续跑和回执恢复。资源消失不能把异常退出升级成完成。 |
|
||||
| 3 安全失败被改 uncertain | 成立 | 从绑定的最终监督结果恢复确定性业务失败。有效 error 不是“没有最终结果”;缺失或损坏结果仍保护,不删除原 uncertain 证据。 |
|
||||
| 4 UI 缓存/DB 范围不同 | 成立 | 在后台从新数据库快照解析初始批次;显式所选以所选任务所属批次为准,详情焦点不充当选集。确认后仍严格核对冻结范围,不能扩大。 |
|
||||
| 5 dirty 提示破坏未启动契约 | 成立 | 候选编辑未保存时明确显示“未启动执行”,保留原控制和授权,零派发。 |
|
||||
| 6 legacy isolated/interrupted 放行 | 与已确认业务规则冲突 | 保留“写入未知整批暂停,即使资源释放仍需核验并重新确认”。旧用例现在断言待核验分支不准入、零 CAD;同一用例的确定性安全失败分支继续验证正常接续,未删保护断言换绿。 |
|
||||
| 7 默认套件新增失败 | 审计所报统计作为输入保留 | 定向复现已点名的受影响功能并分类;真实回归修代码,旧隔离/未知续跑断言改为更严格策略。未重跑全量,不能据此宣称默认套件零失败或把原环境问题计作本轮修复。 |
|
||||
|
||||
## P2 摘选逐项处理
|
||||
|
||||
| 审计指出的现象 | 处理 |
|
||||
| --- | --- |
|
||||
| already_completed 未核对当前验收 | 已保存任务需要匹配当前计划和当前轮次的独立网表核验;失败、缺失或不能关联的验收进入 held,不能当作已验收成功。无保存的 no-match 不强求保存网表。 |
|
||||
| 重复工程登记受完成状态影响 | 在完成/配置等分类之前登记规范化工程身份,不因首项已完成而漏掉重复;重复任务不派发。 |
|
||||
| 所选范围取焦点 group_id | 改从显式选集的数据库任务解析批次;跨批显式选择仍拒绝。 |
|
||||
| 启动/清理回执恢复覆盖提示 | 回执修复不占用前台操作提示,资源重启指引和原始错误保留。另复现并修复后台回执读取抢占“确认强制结束”的竞争,读通道结束后按原确认执行一次。 |
|
||||
| 重试 republish 耗时归零 | 沿用持久化的批次耗时;既有回执没有摘要时也保留已有 elapsed_seconds。 |
|
||||
| 同 revision 固化瞬时快照不稳定 | 不复用带 batch_snapshot_unstable 的暂时摘要,重新读取生产证据后发布新版本;不重复执行业务。 |
|
||||
| 代次 state 直接采用自报 released | 当前及历史代次都验证释放证明、租约和资源观察,不凭字符串发布成功。 |
|
||||
| 重建遗漏已关联 quick-run 资源 | 监督重试在创建工作进程之前绑定请求摘要;本地重试在取得 CAD 资源之前绑定实际运行会话。重建核对原 scope、身份和释放证明,诊断 ZIP 包含被引用的归属记录。 |
|
||||
| pending_save 不进入问题计数 | 纳入问题项、待核验数量和任务内重试阻断;界面显示“保存待核验”,不提供重试勾选。 |
|
||||
| 已打开句柄后 WinError 87 被当 gone | 在被审计提交中已经返回 unknown;保留实现并新增此边界的回归。只有 OpenProcess 未找到原 PID 或已证实身份复用等原证明能判 gone。 |
|
||||
| desktop_lease_pending 可发布 released | 持续阻断直到取得该代租约归还及物理消失证明;历史证明不足不能自行补造归还。 |
|
||||
| 外层 150 秒与 worker 预算不同 | 外层采用现有活动 worker 报告的更长预算,短预算仍由原 worker 看门狗负责;不新增配置页面或第二套独立计时器。 |
|
||||
|
||||
审计评论称 13 项 P2,但公开正文使用“摘选”,可直接定位的是上表内容;本记录不声称已处理未给出位置和触发条件的其他项。
|
||||
|
||||
## 本地增量验证
|
||||
|
||||
只运行新增缺陷及直接受影响的用例;首次反例先红,修改后验证相同边界,不重复全量验收。以下集合有交集,不累加为去重总数。
|
||||
|
||||
- 监督/资源定向 45 项通过,含真实 Windows 子进程崩溃、Job 收尾、活动 worker 超时、未归还租约和异常退出禁止自动续跑。
|
||||
- 回执/运行时/导出定向 40 项通过,含本地真实 PrivateDesktop、generation-zero 从未取得桌面、回执恢复和实际 ZIP 内容;事件重试专项另有 33 项通过。
|
||||
- 五个旧策略测试文件的 19 个受影响场景通过:损坏交接/缺少证明不重放,后续工程不派发;显式模拟验证后只处理剩余工程。
|
||||
- UI 缓存、显式批次、pending_save、dirty、重启提示与实际非监督批次完成态 6 项通过。
|
||||
- 自动诊断 stop/force 交接、导入预检和启动资源重查 11 项通过。旧同步测试替身现在正确完成新增异步预检生命周期;局部批次测试使用显式所选入口,不伪造数据库范围。
|
||||
- 重复工程和已完成任务验收两个实际缺陷已复现并修复;当前轮次通过/失败的双向用例通过。
|
||||
- 后台回执读取与强制结束确认的竞争已复现,修改后竞争用例与 6 种已有完成/确认顺序共 7 项通过。
|
||||
|
||||
## 独立复审补充
|
||||
|
||||
复审进一步指出四个证据缺口,继续按原保护规则整改:
|
||||
|
||||
- 旧监督记录即使标记 completed,也检查实际 CAD shutdown;强制结束记录不能用于接续。
|
||||
- 资源暂停的实际续跑必须有匹配会话和结果代次的完整物理释放证明,不能将缺失的 session.json 当作释放。
|
||||
- 已保存任务缺少当前 round_id 时保持 held,不能用同计划历史验收替代当前轮次。
|
||||
- 事件重试在启动监督进程之前持久化原运行归属,关联写入失败时零启动。本地重试沿用 local-resource 记录绑定自己的实际运行会话;原批已释放、重试桌面仍被外部句柄持有时保持 isolated。
|
||||
|
||||
前三项新增反例已先复现失败,修改后含对应正常路径共 13 项通过;运行日志接续正例补齐物理证明后 1 项通过。
|
||||
|
||||
重试启动和本地归属最终窄组 5 项通过:监督启动前中断、关联写盘失败零启动、本地首份业务回执失败、明确前置拒绝的零代关闭、原批释放而重试桌面仍被真实 Windows 外部句柄持有。两个相邻的既有事件重试回归此前也通过。最终命令使用 `-k 'local_retry or incident_supervisor_launch'`,显式附带的两个既有事件节点被该过滤条件排除,因此最终 5 项不重复计入它们;两次命令合计覆盖 7 个不同节点。
|
||||
|
||||
最终独立只读复审核对了以上四个缺口的实际入口和对应回归;本次限定范围内未发现剩余 P0/P1。27 个修改或新增 Python 文件 AST 可解析;Markdown 代码块成对,差异检查无空白错误。
|
||||
|
||||
原 ETHERNET_1G 工程和配对 scope/effective 报告仍缺,不放宽其身份一致性校验;本轮没有真实 Mentor 换料、六卷评分、100 工程或冻结包复测。本地重试零代运行遇到明确前置错误且正常关闭后记录未获取资源;进程硬退出、关闭异常或释放证明不足时保留 unknown,不认作成功。
|
||||
@@ -0,0 +1,40 @@
|
||||
# Issue #45:整改与增量验收
|
||||
|
||||
日期:2026-11-30。分支:`codex/issue45-ui-remediation`;基线:PR #47 合并提交 `8395d7c`。
|
||||
|
||||
本轮依据八项初步核对和用户确认实施。料号规则由用户明确选择“按上述常见格式校验”;本地只验收新增行为及直接受影响的回归。
|
||||
|
||||
## 整改结果
|
||||
|
||||
| 项目 | 最终行为与证据 |
|
||||
| --- | --- |
|
||||
| D6 料号 | CSV、直接规则写入、位号计划编译/存储、Excel/BOM 导入共用校验。新料号去除首尾空白后限 1–128 字符,包含字母或数字,允许 Unicode 字母数字及 `-_./+()[]`;内部空白、控制字符、`!@#` 等拒绝。未启用但填写了目标料号的行也校验。非法草稿留在表格,高亮并提示具体行;修正后可保存。旧库存源料号保持可读,Value/Cell 保留原有规则,多位号共用目标料号合法。 |
|
||||
| E4 未保存保护 | 切换任务和新建后跳转复用“保存全部/放弃/取消”。保存成功后导航;失败保留当前文本、隐藏草稿与 BOM 批次。放弃恢复已保存行。同任务刷新先提交活跃编辑器再锁模型,避免慢读取期间关闭/切换保存漏掉文本。无法提交编辑器时停止保存/切换/关闭,保留输入,不绕过只读门禁。 |
|
||||
| A5 DPI/窗口 | 首次启动与恢复都按逻辑工作区和原生边框夹取,最小尺寸也受工作区限制。首次显示后再次适配边框;延迟处理只在窗口几何和状态未改变时执行,不覆盖随后设置的尺寸/最大化状态。保留已有几何持久化。 |
|
||||
| A8 日志窗口 | 保留已有独立窗口,验证打开、关闭、重开与新内容呈现。补齐切换“完整日志”后才创建的日志控件可访问名称。 |
|
||||
| D1 选择计数 | 排序保留可见多选,清空后全选覆盖全部可见项;Ctrl 取消唯一选中后,排序/筛选/刷新仍保留空选择。任务列表多选、计划启用数和数据库工程绑定继续按各自含义处理,不因清空列表选择解除工程绑定。 |
|
||||
| F2 快捷键 | F2 在任务导航内复用编辑按钮门禁,表格 F2 编辑保留;F5 复用当前工程刷新按钮门禁。补“更多操作 → 快捷键说明”和菜单快捷键标记,不重复注册已有 Ctrl+Shift+D 等动作。 |
|
||||
| F4 可访问性 | 为核心搜索、批量料号、表格、编辑器和纯图标动作补业务名称,使用实际 QAccessible 名称验证;保留动态 AI 状态名和表单原生标签。动态创建的业务对话框也应用名称。 |
|
||||
| G2 列布局 | 保留已有双表表头宽度、列序及排序持久化。补坏配置类型保护与失败回退,损坏字符串或 QByteArray 不导致启动崩溃。 |
|
||||
|
||||
## 本地验收策略与执行记录
|
||||
|
||||
使用项目已有 Python/pytest-qt 和真实 Qt 控件,`QT_QPA_PLATFORM=offscreen`,临时数据库/文件;不连接 CAD。测试先覆盖实际错误触发路径,再跑直接调用方邻近回归。后续发现的新问题仅补测相关增量。以下结果存在重叠,不相加为一个总通过数。
|
||||
|
||||
| 范围 | 记录 |
|
||||
| --- | --- |
|
||||
| D6 新增校验与 UI | 新增测试初次 19 failed / 6 passed;实现和边界修正后两个校验模块 33 passed。直接输入、目标表、Excel/BOM 邻近回归 59 passed;最后存储 trim 增量由新增测试覆盖。 |
|
||||
| E4 首轮 | 新增导航/关闭/草稿测试 11 passed。直接相关旧模块初次 42 passed / 4 failed;两项 BOM 测试调整初始化,避免依赖静默切换脏任务,其余工作流用例分别复核通过,未放宽超时。 |
|
||||
| D1/F2/F4 | 首轮新增及 UI 邻近 35 passed,#44 选择范围/顺序的四个直接相关节点 4 passed。审查复现 Ctrl 取消后重选后,真实鼠标用例及邻近项 5 passed。 |
|
||||
| A5/G2/A8 | 几何新增先复现首次窗口与边框越界;最终原跨进程几何持久化 + 四个受控缩放工作区用例 5 passed。坏表头类型、旧坏几何和小窗口按钮邻近组中 6 passed,唯一几何持久化失败由前述最终组修复。双表表头恢复已通过。日志完整标签可访问名称先 RED,修复后独立窗口重开用例 1 passed。 |
|
||||
| 审查复核 | D1 空选择和 G2 坏配置独立窄复核 3 passed;D6 数据边界读审与编辑器 Enter/Tab/Escape/组合框探针未发现新增问题。E4 慢刷新数据丢失审查项增加永久回归,后续结果见收尾记录。 |
|
||||
| E4 收尾 | 慢刷新导致关闭/切换保存丢文本的两个用例先 RED;只读编辑器拒绝提交的关闭/切换/保存三个用例也先 RED。修复后 8 个最邻近集成场景 passed,helper/UI 校验模块 7 passed;审查者已经启动的五项独立复核也 passed,未再扩大执行。 |
|
||||
| 最终读审与静态检查 | 审查发现的 E4 P1、D1 P2、F4 P2 均已修复;最终读审未发现未解决的 P0/P1/P2。22 个新增/修改 Python 文件 AST 解析通过,差异空白检查通过。 |
|
||||
|
||||
主要新增用例位于 `tests/v1_1/test_issue45_validation.py`、`tests/v1_1/test_issue45_layout.py`、`tests/ui/test_issue45_validation.py`、`tests/ui/test_issue45_unsaved.py`、`tests/ui/test_issue45_access_keys.py`。每个模块可单独通过 pytest 执行;本次不再为汇总计数重跑已通过组。
|
||||
|
||||
## 验收边界
|
||||
|
||||
125%/150% 使用受控逻辑工作区和模拟显示后边框验证,另以子进程更换 Qt 缩放验证恢复;不等同于物理 Windows 双 DPI 桌面验收。没有重跑默认全量、整套 DSH、六卷、100 工程、打包或真实 Mentor 操作。
|
||||
|
||||
本轮保持 #44 的未知写入暂停整批与资源释放核验门禁。尚未据本轮局部验收宣称第五卷达到 90 分,也不自动关闭 #45 或合并其 PR。
|
||||
@@ -0,0 +1,29 @@
|
||||
# Issue #45:UI 通用体验初步核对
|
||||
|
||||
日期:2026-11-30。来源:[Issue #45](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/issues/45)。
|
||||
|
||||
PR #47 已合并至 main,合并提交 `8395d7cff209447cf0e2dc2a25531ab6799b1b85`。合并前精确 head `a23e980b` 的 push/pull_request 两套 Python 与 JavaScript 检查全部 success,最新审计 662 代码层通过。合并后的文件树与该 head 相同,未重复验收。#44 仍为 open。
|
||||
|
||||
下一项按顺序选择 #45,未发现该 Issue 评论或其他开放 PR 声明正在处理。新分支 `codex/issue45-ui-remediation` 从上述 main 建立,复用现有隔离工作区。本轮只核对内容和准备整改依据,未修改业务代码、未创建新 PR,也未关闭 #45。
|
||||
|
||||
## 八项现状
|
||||
|
||||
| 编号 | 当前核对 | 处理建议 |
|
||||
| --- | --- | --- |
|
||||
| D6 料号校验 | 明确缺口。公共 `validate_mapping_pairs` 接受 `BAD PART !!@#`,实际调用已验证;它只做非空、相等、重复源、链/环校验。TargetPlanRow 仅限制文本类型、模式和 TSV 控制字符。界面已有编辑 delegate,不能再称“无 delegate”,但没有相应料号格式校验。 | 优先统一服务/存储/导入/表格的料号规则,错误行可定位,保存整体拒绝并保留草稿。合法 PN 字符集需以工程/库实际数据为依据,不把 Value 或 Cell 套用同一规则;多个位号共用目标料号是合法场景,不能按目标 PN 重复拒绝。 |
|
||||
| E4 未保存保护 | 部分已有。ProjectPlanPanel 按 task_id 缓存 dirty rows;关闭时已有保存全部/放弃/取消及失败保留。任务切换本身没有相同确认,活跃编辑器尚未提交到模型时的保护需验证。不能据旧版报告直接认定当前仍丢全部草稿。 | 先复现“正在编辑未提交 → 切换 → 返回”和启用数 5→0 的真实路径;确保当前编辑器和隐藏批次都纳入保护,取消留在原任务,保存失败不清草稿。复用既有缓存和事务,不重建草稿系统。 |
|
||||
| A5 DPI/几何 | 有夹取但存在明确边界。无已保存几何时 `_restore_window_geometry` 直接返回,默认 1280×880 不按当前工作区夹取;恢复时又以 minimumSize 重新扩大,980×700 最小窗口在较小逻辑工作区可能仍越界。 | 覆盖首次启动与恢复两条路径,验证 125%/150%、工作区边界和框架尺寸;内容不足时保持滚动或可达,不能只保证左上角可见。与已有几何持久化实现合并,不再写第二套恢复逻辑。 |
|
||||
| A8 独立日志窗口 | 已有实现。RunPanel 创建 TaskLogDialog,TaskLogPresenter 更新内容和关闭状态。旧报告“只有内嵌面板”已不符合当前代码。 | 核验可达入口、父子窗口关闭/重开、运行期间刷新和最小窗口可达性;只有反例成立才修复,不重复创建日志窗口。 |
|
||||
| D1 选择计数 | 需要先校准范围。任务列表计数来自 selectedItems;计划中的替换/保留数量来自 TargetPlanModel.enabled_count;DB projects.selected 表示任务工程绑定。三者并非同一个选择对象。 | 检查全选/清空/筛选/排序后的列表选择和可见计数,另外核对计划启用数。不能为了“DB 数量相等”把清空任务多选变成取消工程绑定;整批/所选执行范围继续遵守 #44 的冻结规则。 |
|
||||
| F2 快捷键 | 部分缺口。Ctrl+Shift+D 已注册;计划内已有 Ctrl+F/Ctrl+S/F3。未找到 F2/F5 集中动作或快捷键说明入口。 | 复用已有动作及 enabled 门禁,补缺失动作和说明,明确焦点作用域;避免全局 F2 抢占表格自身编辑,避免重复注册 Ctrl+Shift+D。 |
|
||||
| F4 可访问名称 | 明确缺口。仅少量 AI 状态、状态分类和分页控件显式命名,搜索/批量料号等核心控件未提供对应显式名称。 | 为业务输入与纯图标动作补清晰名称和说明,保留已有动态状态名称;用可访问接口核对用户真正获得的名称,不将 objectName 当作 accessibleName。 |
|
||||
| G2 列宽/列序持久化 | 已有实现。`_layout_widgets` 包含 rules/targets 的 horizontalHeader,关闭保存 saveState,启动 restoreState;不是只有 tasks/sort。 | 先验证两张表“调宽/调序 → 关闭 → 新进程重启”的实际效果,以及损坏配置、列模式变化和绑定后的状态。若证实已有功能正常,只保留证据;发现具体覆盖/恢复失败才改。 |
|
||||
|
||||
## 建议顺序与验收范围
|
||||
|
||||
1. D6/E4 数据安全:先拒绝不合法保存,证明编辑器/草稿不会因切换或保存失败丢失。
|
||||
2. A5 可达性和 D1 计数:覆盖首次启动/DPI 与各选择范围,保留 #44 的执行范围和止写规则。
|
||||
3. F2/F4 补缺失动作、说明和可访问名称;复用已有入口,避免新增相互冲突的快捷键。
|
||||
4. A8/G2 先验证已有实现,避免重复改造。没有真实反例,不按旧版截图重写当前功能。
|
||||
|
||||
本轮仅执行了一次无 CAD 的公共校验调用,确认非法示例被接受;其余是源码核对,尚未完成 #45 的 Qt 行为和 DPI 验收。后续按增量功能及直接受影响的回归验证,不重复默认全量、六卷、100 工程或真实 Mentor 换料,不据源码核对声明本卷已达 90 分。
|
||||
@@ -0,0 +1,31 @@
|
||||
# PR #48:审计评论 #667 整改
|
||||
|
||||
日期:2026-12-01。审查基线:`65f3a9c`;来源:[评论 #667](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/pulls/48#issuecomment-667)。远端没有更新代码提交,本轮处理该新增审查。
|
||||
|
||||
## 逐项分析与处置
|
||||
|
||||
| 审计项 | 核实与最终处理 |
|
||||
| --- | --- |
|
||||
| 1 删除绕过草稿决策 | 成立。将原切换任务的保存/放弃/取消流程复用于删除与归档,保存失败不进入移除操作。软删除和永久删除成功后都清理被移除任务的编辑器与草稿;取消保留输入,放弃不污染已保存计划。 |
|
||||
| 2 任务列表名称 | 部分描述需校正:实际 QListWidget 已叫 `taskList` 且有名称,未命名的是外层 `taskNavigation`。新增外层名称,保留内层,分别用 QAccessible 验证。 |
|
||||
| 3 刷新提交失败 | 成立。提交失败会取消旧查询、清旧 context、标记读取失败并停止执行;F5 在启动后台刷新前先提交编辑器。读取重试保留锁住的编辑器,待新上下文恢复编辑门禁后再保存,不通过强制解锁写入。永久回归覆盖“失败 → 重试读取 → 保存原输入”,避免失败状态造成无法恢复。 |
|
||||
| 4 BOM 预览异常 | 成立。预览提交失败时走现有错误展示并返回失败,保留输入、草稿和批次;部分通过工程的确认路径只有在预览成功后才更新选择状态。 |
|
||||
| 5 无效编辑索引 | 成立。当前代码实际上保留了无效索引的跟踪;现改为显式取消并关闭编辑器、清理跟踪,避免悬挂控件。 |
|
||||
| 6 兼容性 | 新料号要求文本是有意的 API 约束,继续拒绝数值/None,避免隐式转换破坏型号和前导零。接受已有非法目标 PN 应能停用的建议:仅允许原样停用已存在的规则;批次停用在各原工程内处理,既不复制非法 PN,也不绕过冻结成员检查。重新启用或修改为其他非法 PN 仍拒绝。原有逐行编辑可修正合法 PN,不新增批量迁移功能。 |
|
||||
| 7 停用规则高亮 | 非空的非法停用料号仍应提示,与目标计划一致;只修复未启用空料号被标错的情况。校验规则未因停用而普遍放宽。 |
|
||||
| 8 筛选后的多选 | 保留此前明确采用的“仅可见所选项”范围,不自动恢复隐藏项选择。搜索、状态筛选和所选执行入口增加说明:筛选取消隐藏项选择,清空筛选不恢复,请重新勾选。执行范围仍经 #44 确认与冻结。 |
|
||||
| 9 更小工作区 | 受控 640×344 工作区复现了执行按钮裁切;外层窗口本身已能放入工作区。为任务工作区增加滚动兜底,显式保留紧凑布局的最小内容尺寸,避免自然布局提示使原 980×700 窗口也出现不必要的裁切。小工作区能滚动到保存/执行/新建及运行中的暂停/强制结束;原 980×700 的直接可达性仍通过。 |
|
||||
|
||||
## 本地增量验收
|
||||
|
||||
使用项目现有 Python 与真实 Qt 控件、offscreen 平台、临时数据库。没有重跑审计者已运行的默认全量,也未重跑整套 DSH、六卷、100 工程、打包或真实 CAD。
|
||||
|
||||
- 新增 `tests/ui/test_pr48_audit667.py`,17 个场景分批通过:删除三种选择与保存失败、归档取消/放弃、刷新失败恢复、预览错误保留、无效索引清理、双层可访问名称、停用空值、旧规则停用/禁止非法重写、非文本输入、筛选提示、冻结成员与小屏止写按钮可达性。
|
||||
- 新增小工作区几何用例先复现裁切;五个缩放工作区用例通过。外层滚动首次实现引出两个 980×700 邻近回归,已修复;这两项、小工作区及刷新恢复的窄组 **4 passed**。
|
||||
- 未保存/永久删除/工作区/原几何的直接邻近组初次 **29 passed / 2 failed**,两项失败就是上面的布局回归;修复后只重验这两项及受影响边界。
|
||||
- 批次规则、归档、BOM 邻近及新增边界组 **23 passed**。
|
||||
- 最后几何(含跨进程持久化)、失败保存保留草稿与非法目标写入边界组 **9 passed**。
|
||||
- 最后补充 640×344 运行期间暂停/强制结束按钮可滚动到达,**1 passed**。
|
||||
- 继续核对旧非法规则从服务/UI 调用方逐行修复时,复现跨工程补齐误复制其他已停用非法行;修复为隔离行留在原工程、修正行仅复制合法新值。该用例与批次规则/Cell 类型邻近 **11 passed**;Cell 跨工程传播与料号变更清理 **1 passed**。
|
||||
|
||||
各组有重叠,不相加为总数;未为获得一个汇总数字重复验收。测试中的保存失败通过受控错误回调隔离 DSH,无延长全局超时。尚未执行物理 Windows DPI 或真实 CAD 验收,不据这些局部结果关闭 #45、宣称第五卷达 90 分或合并 PR。
|
||||
@@ -0,0 +1,25 @@
|
||||
# PR #48:增量复审 #669 整改
|
||||
|
||||
2026-12-01,基线 `e772723`。来源:[评论 #669](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/pulls/48#issuecomment-669)。仅处理增量行为与直接邻近回归;同时包含等待新评论期间独立复现的三处边界,详见同日 `pr48-followup-edges` 记录。
|
||||
|
||||
| 项目 | 核实与处置 |
|
||||
| --- | --- |
|
||||
| 1 读取失败门禁 | 原 `_show_error` 实际间接刷新门禁,但失败路径依赖错误渲染成功不够稳固。现在 `_task_context_failed` 先明确刷新门禁再展示错误。新测试从执行/保存按钮已经启用的状态出发,替换错误渲染器仍能证明按钮收紧,并保留草稿。 |
|
||||
| 2 部分绑定失败 | 已复现 `pending_bom` 读取抛错留下新 task_id 与旧行。将服务读取和保留行计算放在发布计划绑定之前,读取失败不发布半套绑定;主窗体也在面板绑定成功后才发布 READY context。失败门禁禁用编辑与保存,保存入口自身检查可编辑状态。 |
|
||||
| 3 确认顺序 | 先解决保存/放弃/取消,再弹删除/归档确认。草稿取消时不会弹破坏性确认。保存失败仍不执行删除或归档,既有永久删除确认保护保留。 |
|
||||
| 4 FAILED 重试编辑保护 | 未发现绕过门禁。新增“读取失败 → 工程变为 RUNNING → 重试成功”用例:保留活动输入,但面板只读、保存/执行禁用;依然通过正常上下文状态恢复门禁,不强制解锁编辑器。 |
|
||||
| 5 其他工作区滚动 | 将已有滚动容器移到整个内容栈外层,任务中心、历史、校验共用。保留内容栈各页身份与导航接口;历史/校验按本页最小布局提示设置可滚动内容大小,任务中心保留 980×700 的直接按钮可达性。受控 640×344 工作区验证三个页面按钮可达。 |
|
||||
| 6 旧规则混合状态/返回值 | 补了有效/非法混合批次,正常停用返回选中 RuleRecord,原地禁用且不复制非法 PN。RUNNING/COMPLETED/BLOCKED 三种冻结同组成员均拒绝并保持全部规则不变;第二成员写入失败会事务回滚。未复现返回 None,无需为不成立的分支新增迁移机制。 |
|
||||
| 7 关闭抖动 | 产品关闭在所有确认分支通过后,取消 context/task/feedback 读取并等待 worker 收尾,再标记关闭;等待期间禁用界面,防止新增编辑。原抖动还涉及 pytest-qt 的销毁顺序,见下文。 |
|
||||
|
||||
## 验收与关闭抖动根因
|
||||
|
||||
新增 `tests/ui/test_pr48_audit669.py` 覆盖 13 个参数化场景,按增量分组验证通过。最初用例复现 5 处失败;修复后 8 项通过。加强其他页面验证为“确为滚动内容后代 + 整窗框在工作区”后,两项先 RED,修复后与原最小窗口/历史/校验导航邻近共 **6 passed**。混合规则与删除/归档/永久删除邻近共 **12 passed**。
|
||||
|
||||
关闭邻近组最初 8 项功能断言通过,但两条 teardown 超时仍可复现。用 faulthandler 检查超时时没有后台读取线程,进一步核对 pytest-qt:其 teardown hook 在 fixture finalizer 前对登记窗口 `close()`、`deleteLater()`,忽略被拒绝的关闭;完成信号接收对象先被销毁,Python 中 active 字典因无法收到 finished 信号残留。修复该 fixture 为使用 pytest-qt 的 `before_close_func`,在对象销毁前等待实际关闭。原三个抖动参数及关闭/取消/失败保存邻近 **7 passed**,未延长超时。
|
||||
|
||||
随后保存、慢刷新、只读提交、最小窗口和几何持久化的直接邻近组 **13 passed / 1 failed**。唯一失败是旧慢刷新关闭测试把读线程 release 写在“窗口已经关闭”之后,与新增等待收尾规则形成测试自锁;调整为先证明编辑已持久化且窗口尚未关闭,再放行读线程并确认关闭,该节点 **1 passed**,仍使用原 3 秒等待。
|
||||
|
||||
独立慢读取测试还验证关闭请求发出取消、worker 未退出时窗口不宣告关闭、退出后 query.busy 为 False。各组存在重叠,不相加为总数,不为汇总数字重跑已通过组。
|
||||
|
||||
没有重跑默认全量、整套 DSH、六卷、100 工程或打包;没有真实 Windows DPI/CAD 验收。不据局部检查关闭 #45 或合并 PR。
|
||||
@@ -0,0 +1,13 @@
|
||||
# PR #48:补充边界整改
|
||||
|
||||
2026-12-01,以 `e772723` 为基线再次检查。两次读取远端均未发现比审计 #667 更新的评论或 review;基线四项 CI 已通过。本轮未重复默认全量,只核对真实界面边界。
|
||||
|
||||
发现并修复:
|
||||
|
||||
1. 搜索或分类筛选把所有所选任务隐藏后,清空筛选会因默认选择回退而重新选中当前任务,与“隐藏项取消选择、不自动恢复”的提示矛盾。现在渲染丢失全部所选项时记住空选择;清空、排序保持空集,明确全选或新任务导航仍可正常选择。
|
||||
2. BOM 报告校验通过但活动编辑器无法提交时,预览未暂存,报告详情却宣称“已暂存预览”。现在保留校验报告并明确写出未暂存及重试方式;恢复可编辑状态、重新导入成功后清除此提示,显示真实暂存状态。原有输入和预览不受失败影响。
|
||||
3. 按需打开的 BOM 详情正文未经过主窗口命名初始化,QAccessible 名称为空。直接在该控件创建时命名为“BOM 导入报告”。
|
||||
|
||||
`tests/ui/test_pr48_followup_edges.py` 的搜索/分类两条、预览失败提示一条均先 RED;修复后连同空选择/多选/预览失败邻近节点 **7 passed**。BOM 详情实际 QAccessible 名称也先 RED,修复后与 BOM 报告归属/新尝试两项邻近检查 **3 passed**。未相加重复计数,未重跑已通过的大组。
|
||||
|
||||
保持 #44 执行范围确认和资源核验规则。未做物理 Windows DPI、真实 CAD、打包、六卷或 100 工程验收,不据本轮结果关闭 #45 或合并 PR。
|
||||
@@ -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,167 @@
|
||||
# PR #47 最新审计整改方案
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [x]`) syntax for tracking.
|
||||
|
||||
**Goal:** 同步残余测试契约,并补齐资源、历史任务和回执的安全恢复通道。
|
||||
|
||||
**Architecture:** 继续使用现有队列、DesktopSlot、RunJournal、归档和诊断接口。先修复测试与测量工具的旧契约,再修复证据恢复;不增加执行器,不通过删除保护记录解除阻断。
|
||||
|
||||
**Tech Stack:** Python、SQLite、PySide6/pytest-qt、Windows Desktop/Job/Mutex、pytest。
|
||||
|
||||
**Spec:** [Issue #44 已确认设计](../specs/2026-11-27-issue44-batch-remediation-design.md)。审计输入:[评论 657](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/pulls/47#issuecomment-657)、[评论 651](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/pulls/47#issuecomment-651)。
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- 方案形成时,分析基线与远端 PR HEAD 均为 `2a89d6fdd4196834efb7e95c4bfaf787daa09964`;当时只新增本地方案文件。用户随后授权修复,实施结果另记于 `docs/testing/2026-11-30-pr47-audit657-acceptance.md`。
|
||||
- 不可执行配置项在确认清单中说明原因,只执行已确认的合法子集。
|
||||
- isolated/unknown 阻断所有新写入,直到物理释放证明成立。
|
||||
- 写入结果不确定则暂停整批;释放资源不能代替原工程核验及重新确认。
|
||||
- 只验收增量实际功能和直接受影响的回归;不自行重跑默认全量、六卷、100 工程、冻结包或真实 Mentor 换料。
|
||||
- 保留 CI 中现有测试,不删除、跳过或放宽断言换取通过。不合并 PR,不关闭 #44。
|
||||
|
||||
## 核对结论
|
||||
|
||||
最新评论确认此前 P1-1~P1-6 整改成立,未发现新增 P0/P1。它报告当前默认套件为 14 failed / 2732 passed / 2 errors,其中相对基线新增 5 个失败用例和 1 个 teardown error。这些是审计执行结果,本次未重复该套件,也未宣称 CI 已绿。
|
||||
|
||||
| 审计项 | 源码核对与根因 | 建议 |
|
||||
| --- | --- | --- |
|
||||
| 5 个残余失败 | 两个 UI 用例在异步预检结束前断言;三个场景仍要求写入不确定后继续。BOM 用例还修改 `_tasks` 伪造执行范围,测量工具内部也有旧断言。 | 同步测试、夹具和工具;保留零后继派发、零重放和证据守恒。 |
|
||||
| P2-1 pending 租约不可恢复 | `batch_resources.py:366` 在观察进程和桌面前直接拒绝。DesktopSlot 的废弃租约接管能力在 acquire 路径内,普通资源重查没有衔接。 | 独立恢复原租约归还证明;不领取新租约,不直接清 pending。 |
|
||||
| P2-2 历史 completed 被 held | `_completed_acceptance_verified` 要求当前轮次和 DSH 验收关联,旧任务可能缺少这类证据。 | 保留保护,给出缺证据原因和定向安全归档入口;只有原始证据完整才允许建立历史关联。 |
|
||||
| P2-3 重复工程全局阻断 | 工程身份在分类前登记,重复成员进入全局 blocker。 | 本轮保留:不能因另一别名 completed 而隐藏 held/不确定结果。改善清单说明,不自动任选一个可写别名。 |
|
||||
| P2-4 缺失执行证据摘要固化 | `execution_runs.py` 同 revision 快捷路径只排除 `batch_snapshot_unstable`,`operation_evidence_missing` 或 round unknown 仍可能只刷新资源。 | 不完整业务证据也进入只读重建;内容未变时保持幂等。 |
|
||||
| P2-5 未上报预算时回退 150 秒 | 外层只在活动 job 上报预算后采用较长预算。 | 在阻塞操作开始前绑定该操作的有限预算,区分启动和执行阶段。先验证实际未上报区间,不能整体禁用停滞保护。 |
|
||||
| P2-6 本地零代异常收尾缺口 | 整批 `task_queue` 的 never_acquired 写在正常返回后;事件重试 `service` 已用 ExitStack 处理普通异常,两条路径不一致。 | 整批复用同样的关闭后收尾规则;硬退出、关闭异常仍 unknown。首次 revalidate 失败发生在写绑定之前,不能笼统归因于“revalidate 前异常”。 |
|
||||
| P2-7 旧队列升级说明 | 属已确认的保护规则。 | 写明中断/隔离且证据不足的旧队列不能自动继续;仍保留有完整证据的确定性安全失败接续。 |
|
||||
| P2-8 同 stage 计数重置 | ProgressWatch 的业务进展判断不以 total 变化或 done 回退为依据。 | 先核对生产端是否存在合法重复 pass;优先让新 pass 使用新的 current_job_id,不能把心跳或总数抖动无条件当进展。 |
|
||||
| P2-9 三个 DSH 编码问题 | 评论说明基线也失败,未给本 PR 新回归证据。 | 单独记录环境/编码问题,不计入本轮新增缺陷修复。 |
|
||||
| P2-10 导出包含工程绝对路径 | `_scrub_text` 会处理用户主目录和凭据,但保留其他工程路径;界面只写“脱敏诊断包”。 | 在导出界面说明仍含工程路径和标识;保留排障证据以及原凭据过滤。 |
|
||||
|
||||
本次仅做了两个无 CAD、无文件修改的时钟反例:同 job/stage 的 total 从 10 变 20、done 仍为 1 时,last_business_progress 保持 1,在 t=151 请求停止;无预算时,外层心跳也不会延长 t=151 的业务停滞期限。这证明机制存在,不等同于已复现真实 CAD 长加载误停。
|
||||
|
||||
## Task 1:同步 5 个残余用例及测量工具
|
||||
|
||||
**Files:** `tests/v1_1/test_target_cell_rules.py`、`test_bom_pending.py`、`test_multi_project_regression.py`、`test_nonblocking_acceptance.py`、`test_project_session_health.py`;`tools/measure_task_queue.py`。CI 配置只核对,不修改测试清单。
|
||||
|
||||
**接口与结果:** 保留生产 `_execute_project_tasks()` 异步生命周期;测量工具 `run_scenario(..., behavior='uncertain_stop')` 输出暂停与真实调用数。
|
||||
|
||||
- [x] 两个 UI 用例等待确认实际出现且 `_workers` 清空,再核对取消确认后零执行;使用 qtbot 条件等待,不加 sleep。
|
||||
|
||||
```python
|
||||
qtbot.waitUntil(lambda: len(confirmations) == 1 and not window._workers)
|
||||
assert not errors and window._batch_stop is None
|
||||
```
|
||||
|
||||
- [x] BOM 用例移除 `_tasks = (...)`,使用数据库中的真实批次;未启用计划的兄弟任务应显示 skipped,确认中保留两个目标和 R2 来源。
|
||||
- [x] 同时修测量工具内部与调用测试的 uncertain_stop 期望。当前三工程夹具首项即不确定,预期 1 次调用、0 次已核验模型变更,后两工程未启动。
|
||||
|
||||
```python
|
||||
assert report['executed_steps'] == 1
|
||||
assert report['changed_components'] == 0
|
||||
assert report['result']['paused'] is True
|
||||
assert [row['state'] for row in report['result']['entries']] == ['blocked', 'pending', 'pending']
|
||||
```
|
||||
|
||||
- [x] 100 UID 用例保留已有 93 verified 和 5 failed,C 的 1 个 UID 不确定后 D 不启动;因此当前夹具预期 99 次调用、1 条 uncertain,而非旧的 100 次调用和 2 条 uncertain。直接恢复原队列不得增加调用数,重开数据库后 93 条 verified 不丢失。
|
||||
- [x] 工程源改变用例预期 blocked/pending、只发生第一工程首个 UID 调用,恢复仍不得派发剩余 UID 或下一工程。
|
||||
- [x] 仅运行这 5 个受影响节点及必要的同文件正常相邻参数,记录 teardown 是否消失,提交测试/工具同步变更。不得改产品逻辑恢复旧放行。
|
||||
|
||||
## Task 2:补齐 pending 原租约恢复
|
||||
|
||||
**Files:** `desktop_slot.py`、`isolated_desktop.py`、`batch_runtime.py`、`batch_resources.py`;`tests/v1_1/test_desktop_slot.py`、`test_pr47_audit_resources.py`。
|
||||
|
||||
**拟议接口:** `desktop_slot.recover_abandoned_lease(binding: dict) -> dict`,返回与 `returned_lease_intact` 兼容的不可变归还回执。binding 含原 slot 路径、scope、name、lease_id、owner PID/creation_time,并由资源记录绑定 session_id/generation。它只恢复原租约,不调用 acquire 创建新租约。
|
||||
|
||||
- [x] 先加失主退出后仍被 pending 永久拒绝的反例,与失主 alive/unknown、Job 非空和租约被新 owner 替换的反例。
|
||||
- [x] 在取得租约后、允许任何 CAD/worker 派发前持久化原租约绑定;磁盘写入失败不得继续派发。slot 的 lease_id 与资源 generation 是不同身份,不能互相替代。
|
||||
- [x] 恢复时取得原命名 Mutex,校验当前登录上下文、slot 和绑定一致;所有原写进程身份明确 gone、所有命名 Job 为空,才能为原 lease 写归还回执。对完整且已存在的历史归还回执直接验证复用,重复执行不覆盖新租约。
|
||||
- [x] 新 owner 已取代原 lease 时,不改 slot、不打开或终止新 owner;只有独立的原归还回执可用于原代次。历史记录缺少可验证映射时保留阻断,显示缺失字段及导出指引,不指导删除证据。
|
||||
- [x] 归还证明成立后仍独立观察桌面:外部句柄存在则 isolated 并阻断新写入;物理消失且写进程证明完整才 released。lease 恢复本身不核验或重放业务。
|
||||
|
||||
```python
|
||||
assert not blocking_resources(root) # 仅原租约可核对、Job 空、桌面物理消失的正例
|
||||
assert calls == [] # 恢复过程没有 CAD/换料派发
|
||||
```
|
||||
|
||||
- [x] 运行新反例、原租约幂等/新 owner 保护用例和一个真实 Windows 外部句柄生命周期用例,提交资源恢复变更。
|
||||
|
||||
## Task 3:给历史 completed 提供安全处置
|
||||
|
||||
**Files:** `batch_admission.py`、`task_archive.py`、`ui/main_window.py`;`tests/ui/test_pr47_audit_ui.py`、`tests/v1_1/test_task_archive.py`。
|
||||
|
||||
**拟议接口:** `_completed_acceptance_verified(service, context)` 保持严格布尔契约;另向 admission 决策提供缺失原因。`archive_completed_session(service, *, task_ids=None)` 可选择明确任务子集,默认值保持现有正常关闭行为,结果仍为 ArchiveReport。
|
||||
|
||||
- [x] 区分缺 DSH 关联、缺当前 round、已有验收失败三种原因,不能把它们都改为 already_completed。
|
||||
- [x] held 清单提供查看既有证据和定向安全归档操作;复用现有归档事务、资源阻断和中断保护,软归档保留数据库记录、日志和工程文件。
|
||||
- [x] 仅当原报告能同时证明工程、计划、原轮次及独立验收时建立带来源的历史关联;缺替换前基准时不得事后补造。无完整证据则解释限制,允许安全归档后由用户另行建立新的明确任务,不自动重放原换料。
|
||||
- [x] 验证归档只影响所选安全历史任务;恢复归档记录后保护仍有效,不确定任务和未释放资源不能归档绕过保护。
|
||||
|
||||
```python
|
||||
assert report.archived_ids == (safe_legacy_id,)
|
||||
assert uncertain_id in report.retained_ids
|
||||
assert cad_calls == []
|
||||
```
|
||||
|
||||
- [x] 只验证历史证据关联/缺失/失败、定向归档与原归档正常相邻路径,提交历史任务处置变更。
|
||||
|
||||
## Task 4:重读不完整回执并统一零代收尾
|
||||
|
||||
**Files:** `dsh/execution_runs.py`、`batch_summary.py`、`task_queue.py`;`tests/dsh/test_pr47_audit_receipts.py`。参考现有 `service.py` 本地重试 ExitStack 行为。
|
||||
|
||||
- [x] 加两组反例:同 revision 的 operation_evidence_missing 在数据源恢复后仍不重建;本地整批绑定已经写入、generation=0 时遇到普通前置异常,正常关闭后却没有 never_acquired 证明。
|
||||
- [x] 同 revision 快捷路径同时排除业务证据缺失和 round unknown,重建只读源;数据仍缺时继续暂停,不推测成功。按源摘要和内容决定是否发布新版本,连续读取同样缺失不反复涨 revision。
|
||||
- [x] 保留原 verified、耗时、验收和归属证据;资源恢复与业务证据恢复互不替代,恢复不派发 CAD。
|
||||
- [x] 整批采用关闭后收尾规则:绑定已写、runtime 正常退出且 generation=0 才能写 never_acquired;普通业务前置异常可触发收尾,BaseException/硬退出和资源清理失败不得解除 unknown。
|
||||
|
||||
```python
|
||||
assert repaired['operation_evidence_missing'] == []
|
||||
assert repaired['revision'] == previous['revision'] + 1
|
||||
assert second_read['revision'] == repaired['revision']
|
||||
assert cad_calls == []
|
||||
```
|
||||
|
||||
- [x] 运行上述新边界,以及已有本地重试普通异常/硬退出和绑定范围变化的直接相邻用例,提交回执恢复变更。
|
||||
|
||||
## Task 5:核实并修正超时预算和重复阶段进展
|
||||
|
||||
**Files:** `batch_supervisor.py`、`batch_worker.py`、`worker_monitor.py`,及定位到的实际进度生产端;`tests/v1_1/test_pr47_audit_resources.py`、`tests/v1_1/test_issue44_stall_policy.py`、`tests/trial_task_center/test_worker_monitor.py`。
|
||||
|
||||
- [x] 先记录启动、加载、保存期间首次活动 job/预算上报的时点,定位无预算的实际区间;保留当前纯时钟机制反例,不能将它写成真实 Mentor 误停结论。
|
||||
- [x] 活动阻塞操作开始前传递并验证其有限预算,拒绝 bool、负数、NaN、无穷;外层使用与内层同源的操作预算。缺预算阶段有明确启动边界和有限时限,不靠心跳无限延长,也不把所有阶段统一加大常量。
|
||||
- [x] 对同 stage 合法重复 pass 优先复用现有 current_job_id 边界;生产端重置 done 时提供新子作业身份。仅 total 变化、重复帧或序号增长不视作已完成工作。
|
||||
- [x] 用模拟时钟覆盖:长预算内不误停、真停滞一次请求停止、无预算启动超时、重复心跳不续命、新 pass 进展有效;先证明真实生产端缺口再改协议,不为假设加新配置面板。
|
||||
|
||||
```python
|
||||
assert requests == [] # 已绑定长预算且仍在预算内
|
||||
assert requests == ['inactivity'] # 真停滞到期,只请求一次合作停止
|
||||
```
|
||||
|
||||
- [x] 只验收发生变化的预算/进度路径与原合作停止相邻场景,提交明确成立的修正;未证实生产缺口则保留分析和反例,不改状态机。
|
||||
|
||||
## Task 6:升级说明、重复任务说明和诊断导出提示
|
||||
|
||||
**Files:** 新增 `docs/testing/2026-11-30-issue44-upgrade-notes.md`;修改 `ui/main_window.py`、`diagnostics_bundle.py`;测试 `tests/ui/test_pr47_audit_ui.py`、`tests/v1_1/test_diagnostics_bundle.py`、`tests/v1_1/test_issue44_batch_bundle.py`。
|
||||
|
||||
- [x] 说明升级后中断/isolated 且证据不足的旧队列须先核验、重新确认;列出资源释放与业务核验两个步骤,不能概括为所有旧队列都无法继续。
|
||||
- [x] 重复工程保持当前阻断规则,清单指出冲突任务和工程身份;只有用户明确重新选定无歧义范围且不存在同批未核验写入,才重新预检。
|
||||
- [x] 导出入口写明“已过滤凭据和用户信息,仍含工程路径、任务标识及执行日志”,不虚称全面匿名;保留既有脱敏和允许列表。提示融入现有导出交互,不新增泛化审批流程。
|
||||
- [x] 验证可见提示及实际 ZIP 仍过滤凭据、保留必要工程关联。基线编码问题独立记录,不作为本 PR 新增修复计数。
|
||||
|
||||
## 验收与交付顺序
|
||||
|
||||
1. Task 1 先解除已知的测试契约不一致,保留 CI 原测试入口。
|
||||
2. Task 2、3、4 解决有具体代码证据的恢复缺口,分别增量验收,避免交叉误计。
|
||||
3. Task 5 先证实生产触发路径,再决定是否改预算和进度协议;Task 6 与对应功能一起更新说明。
|
||||
4. 每项只跑新增反例和直接受影响的正常相邻用例;本次分析不重复审计已经做过的默认全量。最终逐项记录命令、实际 pass/fail 和未验证范围,静态检查修改文件与 git diff --check。
|
||||
5. 定向通过只证明相应增量功能;实际 CI 状态需看后续运行结果,不能由本地窄组替代。没有真实现场核验依据,不声明卷四达标,不关闭 #44。
|
||||
|
||||
## 本方案自审
|
||||
|
||||
10 项 P2 均有处置:1/2/4/6 有恢复改动,5/8 先证实触发路径,3 保持严格重复保护,7/10 改说明,9 归既有环境问题。五项失败覆盖到测试、夹具和测量工具,没有修改产品安全契约。方案形成时仅新增本文件;后续实施以验收记录为准。
|
||||
|
||||
## 实施裁决
|
||||
|
||||
- 旧 pending 缺精确原租约映射时,不靠同名桌面补造证据;新原租约回执必须覆盖所有资源 writer 根,才能补足历史树关闭证明。它不替代桌面物理消失核验。
|
||||
- 不自动导入缺来源的历史网表报告。现有严格的计划/轮次/报告关联保留,为缺证据的安全已完成任务提供定向归档替代路径,归档不等于验收通过。
|
||||
- 重复阶段在真实 VBS 调用路径成立;采用监控快照 business_sequence 传递已证明进展,保留现有 job/VBS 协议和默认超时,避免为每次重复读取重建执行作业。
|
||||
- 复审新增的跨轮次借证据风险纳入 Task 4:回执恢复必须引用原运行绑定的 round_id;未知或冲突身份不能从当前新轮次补造。
|
||||
@@ -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,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,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,65 @@
|
||||
# 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 的现场缺陷仍需原现场证据;本轮仅处理共同的整批准入、写入保护、入口反馈与回执。
|
||||
|
||||
本地分支保留,可继续定位剩余现场问题。没有推送、合并、发布或向远端工单发送消息。
|
||||
|
||||
后续已按要求提交 PR #47。评论 649 引发的增量整改、策略分歧和定向验证另记于 [PR 审计整改记录](../reviews/2026-11-27-pr47-audit-649.md);以上为首次验收当时的记录。
|
||||
@@ -0,0 +1,29 @@
|
||||
# Issue #44 升级与恢复说明
|
||||
|
||||
本次升级保留“写入结果待核验则暂停整批”的保护。不能通过隔离任务、归档任务或清理资源自动跳过未知写入,也不会自动重放原换料。
|
||||
|
||||
## 旧队列与资源恢复
|
||||
|
||||
- 中断、隔离且证据不足的旧队列,需要先核验原工程,再重新确认继续。有完整证明的确定性安全失败仍按已有规则接续,不能概括为所有旧队列都禁止恢复。
|
||||
- “重试释放资源”只处理资源证据。原租约失主已退出、Job 为空且身份可精确关联时,可恢复该租约的归还证明;同名桌面已经由新 owner 租用时不会操作新 owner。
|
||||
- 租约归还与桌面物理释放分别核验。桌面仍被外部句柄持有时保持隔离,并阻断新 CAD 写入。释放成功也不代表原换料结果核验通过。
|
||||
- 历史记录缺少可验证的原租约绑定、原进程身份或代次关联时,继续保护并显示具体缺证据原因。请导出诊断保留现场,不删除 session/slot 文件解除保护。
|
||||
- 从 `2a89d6f` 时代升级的在途 manifest 批次,检查点可能没有原 `round_ids`。这类回执会按缺少轮次归属显示 unknown/paused,目标计数不能认证;先核验原工程并重新确认。不得从后来新轮次的 SQL 记录补造原批次身份,也不自动重放。
|
||||
|
||||
## 历史已完成任务
|
||||
|
||||
旧版本的 completed 状态不能替代当前计划、当前轮次的独立验收。批次清单会区分缺执行轮次、缺匹配运行记录和已有验收未通过,显示查看执行日志与导出诊断的路径。
|
||||
|
||||
不再参与当前批次的安全历史任务,可在“任务管理 → 归档当前已完成任务”中单独归档。它移至回收站,保留原计划、工程、日志、SQL 执行记录和验收证据;可以恢复。归档不会把未知或失败的验收改成通过,也不会自动建立新一轮换料。
|
||||
|
||||
存在 prepared、pending_save、uncertain 或未完成作业、中断保护、活动工程和归属未释放资源的任务不会被此入口归档。恢复历史任务后仍使用相同的验收和止写规则。
|
||||
|
||||
同一工程的重复任务仍会阻断批次。清单指出冲突任务和工程;先核对原任务及其待核验结果,再明确选择无歧义的范围重新预检,不自动任选一个别名执行。
|
||||
|
||||
## 诊断导出
|
||||
|
||||
导出会按现有规则过滤凭据、用户名等信息,仍保留工程路径、任务标识、执行日志和资源关联,便于排查现场问题。诊断包不包含原工程文件、中心库、BOM 或完整任务数据库。分享前应了解其中仍有工程相关信息。
|
||||
|
||||
## 验证范围
|
||||
|
||||
本轮按增量功能及直接受影响的回归验证。默认全量套件、真实 Mentor 换料、六卷评分、100 工程和冻结包没有重复验收。现场 ETHERNET_1G 原工程与配对报告仍缺,不据此关闭 #44 或声明卷四达标。
|
||||
@@ -0,0 +1,48 @@
|
||||
# PR #47 审计 657:增量修复与验收
|
||||
|
||||
日期:2026-11-30。修复基线:`2a89d6fdd4196834efb7e95c4bfaf787daa09964`。输入:[评论 657](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/pulls/47#issuecomment-657)、[整改方案](../superpowers/plans/2026-11-30-pr47-audit657-remediation.md)。
|
||||
|
||||
## 修改结果
|
||||
|
||||
- 五个残余失败的测试契约及测量工具同步:异步预检按实际完成等待,不再修改 UI 缓存伪造范围;不确定写入暂停整批,后续工程未启动。100 UID 场景保留 93 verified、5 failed,出现一条 uncertain 后停止,D 不派发,调用总数为 99。
|
||||
- 原 pending 租约可凭精确 lease/session/generation 绑定恢复不可变归还回执。原 owner 明确退出、命名 Job 为空、原回执覆盖全部 writer 根才可证明进程树关闭;不领取新租约,不操作后来的 owner,不伪造 owned_cleanup_complete。外部桌面句柄仍存在时保持 isolated,句柄关闭并核验消失后才 released。
|
||||
- 历史 completed 缺证据时给出缺轮次、缺匹配运行记录、验收未通过等具体原因。“任务管理 → 归档当前已完成任务”只软归档明确选中的安全完成任务;重新检查 SQL pending/prepared/pending_save/uncertain、中断、活动工程和资源归属,保留原计划与证据。
|
||||
- 不完整回执会重新读取原业务证据,内容不变不空转增加 revision。整批零代普通异常在正常关闭后补未获取资源证明;BaseException、清理失败和未写入绑定的路径仍保护。
|
||||
- 复审发现并关闭跨轮借证据风险:原回执、原持久摘要和原队列检查点一致的轮次身份才可使用;首次发布也不例外。新队列实际执行时记录 round_ids;身份缺失或冲突保持 unknown。历史 SQL 只按原 round 查询,旧验收不能认证后来同计划的新轮;准入也拒绝轮次未知或作业证据缺失的已完成结果。
|
||||
- 修复实际重复语义读取阶段被外层最高值忽略的问题:worker 快照提供单调业务序号,真实阶段边界和进展才递增;计数回退、total 抖动、重复快照和心跳不续期。创建进程前先发布有效预算,拒绝非法预算,保留默认超时和原有 120 秒 bootstrap 限期。
|
||||
- 补充[升级说明](2026-11-30-issue44-upgrade-notes.md)和导出提示:诊断仍含工程路径与任务标识。导出过滤与 ZIP 格式未改,不重复运行上轮已验收的导出全组。
|
||||
|
||||
## 定向验证证据
|
||||
|
||||
以下集合存在交集,不累加为总测试数。除新增反例先复现失败、修复后验证,以及新变更直接影响的相邻场景外,没有重复宽范围验收。
|
||||
|
||||
| 范围 | 最终证据 |
|
||||
| --- | --- |
|
||||
| 原五项失败、测试夹具、测量工具 | 五函数共 10 个不同节点最终通过;含两个 UI 正常参数及 success/failure_continue/pause_resume 正常邻接。真实数据库批次、兄弟任务 skipped、原队列恢复零重放与 SQL/源文件守恒均保留。 |
|
||||
| 原租约与树关闭证明 | 新反例先 RED;新资源组 10 passed,资源/slot 邻接组 10 passed,实际正常发布/现存活租约 2 passed,最后多 worker/精确绑定/真实 Windows 外部句柄窄组 6 passed。集合有交集。 |
|
||||
| 归档、历史验收原因及 UI | 归档及原准入/归档邻接组 18 passed;一个测试夹具实际缺 round 而非缺 DSH DB,拆为两种实际缺证据分支后 2 passed。新增“不完整证据不能认证”两反例先 RED,修后连同当前轮次有效验收正例 3 passed。 |
|
||||
| 回执缺证据、零代及跨轮归属 | 最终 `tests/dsh/test_pr47_audit657_receipts.py`:12 passed。包含原 r1/新 r2、无身份、身份冲突、首次发布缺绑定/缺检查点、幂等重建及正常异常/硬退出/清理失败。 |
|
||||
| 实际 UI 非监督完成与原回执相邻回归 | 最终 3 passed,14.36 秒。真实两任务顺序、调用数、no-match 及 completed 断言保留。第一次 UI 用例在 5 秒通用 settle 窗口超时,实际日志已经生成 completed;仅该用例增加明确的“预期调用已发生且后台 worker 结束”条件等待,上限 10 秒,不修改产品超时或通用夹具。 |
|
||||
| 进展与预算 | 新反例先 RED,worker/外层看门狗与原生进度邻接组 14 passed;runtime 实际 JSON 转发单例 1 passed,覆盖 15 个不同节点。 |
|
||||
| 独立限定复审 | 原租约桥接、归档、异步生命周期、预算及最终轮次绑定复核通过;复审发现的跨轮风险已经关闭,无遗留可确认问题。复审只读,没有另跑宽测试。 |
|
||||
| 静态检查 | 27 个修改或新增 Python 文件 AST 可解析,修改的 Markdown 空白/代码块检查及 git diff --check 通过。 |
|
||||
|
||||
最后回执及实际 UI 两次命令:
|
||||
|
||||
```powershell
|
||||
$env:PYTHONPATH = (Resolve-Path src).Path
|
||||
$env:PYTHONUTF8 = '1'
|
||||
$env:QT_QPA_PLATFORM = 'offscreen'
|
||||
$py = 'F:/Sync Tool Skyworth/Work Maps/dxdesigner-part-replacement/.venv/Scripts/python.exe'
|
||||
& $py -X utf8 -m pytest tests/dsh/test_pr47_audit657_receipts.py tests/ui/test_trial_task_center_workflow.py::test_native_batch_records_complete_order_and_actual_results -q --tb=short
|
||||
# 12 passed,1 个 UI 条件等待超时;业务日志已完成。
|
||||
& $py -X utf8 -m pytest tests/ui/test_trial_task_center_workflow.py::test_native_batch_records_complete_order_and_actual_results tests/dsh/test_pr47_audit_receipts.py::test_recovery_retries_a_previously_unstable_snapshot_at_the_same_revision 'tests/dsh/test_pr47_audit_receipts.py::test_local_manifest_run_completes_from_its_actual_runtime_release[False]' -q --tb=short
|
||||
# 收紧完成条件、给予该功能用例合理等待窗口后,3 passed。
|
||||
```
|
||||
|
||||
## 支持边界
|
||||
|
||||
- 缺少精确原租约映射的旧 pending 记录仍保留保护及缺证据诊断,不凭同名桌面收养资源。没有原轮次身份的旧回执也不按当前 SQL 补造归属。
|
||||
- 没有原始可证明匹配的历史报告时,不自动导入或补造验收;提供安全归档替代路径,归档不表示验收通过。
|
||||
- 没有重跑默认全量,也没有删除/跳过 CI 原有测试。五个已知残余失败的定向通过不能代替整条 CI 的实际运行结果。
|
||||
- 未执行真实 Mentor 换料、六卷评分、100 工程或冻结包复测。原 ETHERNET_1G 工程及配对报告仍缺,本 PR 不关闭 #44,不声明卷四达标。
|
||||
@@ -0,0 +1,44 @@
|
||||
# PR #47 审计 660:增量修复与验收
|
||||
|
||||
日期:2026-11-30。修复基线:`c25db8ca25884c339b169facace4b0001c26434e`。输入:[评论 660](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/pulls/47#issuecomment-660)。
|
||||
|
||||
## 修复
|
||||
|
||||
- `task_queue.bind_task_round` 对没有 `_store` 的队列适配器跳过轮次认证,不再因 AttributeError 将任务误判为 blocked。适配器可以完成其执行契约,但回执保留 operation_evidence_missing 和未知轮次,不补造原运行身份。
|
||||
- `task_archive` 的轻量 facade 缺 `_store` 时使用服务实际主存储查询作业问题,再检查中断与原 uncertain.flag。没有按审计建议直接跳过 SQL,prepared、pending_save、uncertain 仍能阻止归档。
|
||||
- 假执行器在模拟实际完成的路径记录匹配的原 SQL round 和检查点 round_ids,修复六个 DSH 回执用例。未执行、缺绑定和跨轮反例不补造证据,生产 collector 不放宽。
|
||||
- `DesktopSlot.acquire` 统一核验旧桌面物理消失。正常归还或恢复归还只证明原租约已归还;即使 slot 是 idle,桌面仍被外部句柄持有时也不能领取新租约。观察 unknown/异常时同样拒绝,原 slot 和独立归还回执保持不变。消失后允许领取同 scope 的新 lease_id。
|
||||
- worker 创建失败、process 尚未建立时,只删除属于本次 token 的初始进度快照;不删除其他 token 的快照,也不改变原始启动错误。
|
||||
- CI 文件清单加入两个回归文件 `test_ui_batch_retry.py`、`test_deep_scan_archive_paths.py`;未删除或跳过旧测试。
|
||||
- [升级说明](2026-11-30-issue44-upgrade-notes.md)补充 `2a89d6f` 时代在途 manifest 检查点缺 round_ids 的边界:按缺原轮次归属保护,不采用当前新轮次补造身份。
|
||||
|
||||
## 定向证据
|
||||
|
||||
集合有交集,不能相加为总数。只运行本轮反例及直接相关正常相邻路径,不重复默认全量、整组 DSH 或先前已通过的广泛验收。
|
||||
|
||||
| 范围 | 证据 |
|
||||
| --- | --- |
|
||||
| 两个适配器回归 | 原节点先 2 failed;修复后 retry 两种参数、深路径两节点、SQL 未核验三种状态共 7 passed,6.32 秒。主 SQL 检查在 facade 无 store 时仍保留。 |
|
||||
| 适配器证据守恒 | 增加实际 UI 回执 assertion 后,重跑对应单节点 1 passed,2.67 秒;明确 round unknown 和两任务 evidence_missing,不能因执行恢复就伪称验收完整。该节点与上组重叠。 |
|
||||
| DSH 回执测试夹具 | 原文件 6 failed / 7 passed;补匹配轮次绑定后该文件 13 passed,5.56 秒。生产范围、轮次、恢复和验收代码未改。 |
|
||||
| Slot 物理门 | 新四反例在原实现全失败;修后新例与直接相关 fixture 10 passed,8.04 秒,含真实 Windows 外部句柄;再验证其余 acquire 相邻保护 11 passed / 2 deselected,0.63 秒,合计 21 个不同节点。 |
|
||||
| 未启动的进度快照 | 原反例 1 failed / 1 passed;修后两个快照归属分支及原启动前预算单例 3 passed,0.74 秒。 |
|
||||
| 静态及限定复审 | 12 个修改或新增 Python 文件 AST、Markdown 格式及差异检查通过;独立只读复审核对统一物理门、主存储保护、适配器证据、测试夹具和 CI 清单,未发现遗留需修复问题。 |
|
||||
|
||||
复现/主要绿色命令使用本项目虚拟环境、`PYTHONPATH=src`、`PYTHONUTF8=1`,UI 使用 `QT_QPA_PLATFORM=offscreen`:
|
||||
|
||||
```powershell
|
||||
$env:PYTHONPATH = (Resolve-Path src).Path
|
||||
$env:PYTHONUTF8 = '1'
|
||||
$env:QT_QPA_PLATFORM = 'offscreen'
|
||||
$py = 'F:/Sync Tool Skyworth/Work Maps/dxdesigner-part-replacement/.venv/Scripts/python.exe'
|
||||
& $py -X utf8 -m pytest tests/v1_1/test_ui_batch_retry.py::test_retry_preparation_rebuilds_batch_only_after_success tests/v1_1/test_deep_scan_archive_paths.py tests/v1_1/test_pr47_audit657_archive.py::test_selected_archive_retains_unresolved_sql_evidence -q --tb=short
|
||||
& $py -X utf8 -m pytest tests/dsh/test_issue44_batch_receipt.py -q --tb=short
|
||||
& $py -X utf8 -m pytest tests/v1_1/test_pr47_audit660_progress.py tests/v1_1/test_pr47_audit657_stall.py::test_initial_worker_budget_is_published_before_process_creation -q --tb=short
|
||||
```
|
||||
|
||||
## 保留的保护与限制
|
||||
|
||||
isolated/unknown 阻断新写入;资源释放不能替代业务核验。写入不确定仍暂停整批,不自动隔离后推进,也不重放换料。旧记录缺原 lease 或 round 身份仍保留保护。绑定落盘失败仍按证据不足处理,不为使状态好看而假称成功。
|
||||
|
||||
没有重跑默认全量或整个 tests/dsh,也没有执行真实 Mentor 换料、六卷、100 工程或冻结包复测;不能据定向用例宣称完整 CI 已绿。ETHERNET_1G 原工程与配对报告仍缺,不关闭 #44。
|
||||
@@ -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,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
|
||||
}
|
||||
@@ -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
|
||||
@@ -1646,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 _
|
||||
@@ -1669,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
|
||||
@@ -3995,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,19 +1,32 @@
|
||||
"""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, _incident_resource_binding, _incident_resource_path, _queue_request_matches,
|
||||
_supervisor_request, collect_batch_summary, refresh_batch_resources,
|
||||
)
|
||||
from ..trial_task_center.errors import TaskCenterError
|
||||
from ..trial_task_center.path_access import internal_path
|
||||
from ..trial_task_center.task_queue import execute_task_queue
|
||||
|
||||
|
||||
def _failure_evidence(service, journal, run_id, baseline):
|
||||
evidence = {key: baseline[key] for key in ('tasks', 'entries', 'retry', 'netlist_verification') if key in baseline}
|
||||
evidence = {key: baseline[key]
|
||||
for key in ('tasks', 'entries', 'retry', 'netlist_verification', 'elapsed_seconds') if key in baseline}
|
||||
if not baseline:
|
||||
return evidence
|
||||
try:
|
||||
@@ -37,7 +50,67 @@ 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()
|
||||
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, round(monotonic() - start, 3))
|
||||
raise
|
||||
return _finish_batch_summary(service, root, journal, manifest, receipt, round(monotonic() - start, 3))
|
||||
|
||||
|
||||
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 +120,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 +133,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 +146,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 +180,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 +206,34 @@ 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': '请按每项实际计数判断;未命中不表示已替换保存。'}
|
||||
if 'elapsed_seconds' in baseline:
|
||||
receipt['elapsed_seconds'] = baseline['elapsed_seconds']
|
||||
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.
|
||||
@@ -169,6 +285,252 @@ def _finish_execution_run(service, root, task_ids, stop, run_id, result, *, base
|
||||
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):
|
||||
records = []
|
||||
for path in internal_path(root / 'batch-resources').glob('*/request.json'):
|
||||
try:
|
||||
batch_id = path.parent.name
|
||||
journal, arguments = _supervisor_request(root, batch_id)
|
||||
if _queue_request_matches(manifest, journal, arguments):
|
||||
records.append((journal.get('started_at') or 0, batch_id))
|
||||
except (OSError, ValueError, TypeError, KeyError, AttributeError):
|
||||
continue
|
||||
return [batch_id for _, batch_id in sorted(records)]
|
||||
|
||||
|
||||
def _receipt_resource_batches(root, manifest, main_batches, previous):
|
||||
directory = internal_path(root / 'batch-runs' / manifest['run_id'])
|
||||
linked = [path.stem.removeprefix('incident-resource-')
|
||||
for path in sorted(directory.glob('incident-resource-*.json'))]
|
||||
local = [path.stem.removeprefix('local-resource-')
|
||||
for path in sorted(directory.glob('local-resource-*.json'))]
|
||||
return list(dict.fromkeys(batch_id for batch_id in
|
||||
[*main_batches, *(previous or {}).get('resource_batch_ids', ()), *linked, *local]
|
||||
if isinstance(batch_id, str) and re.fullmatch('[0-9a-f]{32}', batch_id)))
|
||||
|
||||
|
||||
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())
|
||||
if supervisor.get('business_uncertain') is True:
|
||||
return {}
|
||||
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, elapsed):
|
||||
run_id = manifest['run_id']
|
||||
log = service._logging.logger
|
||||
receipt = {**receipt, 'elapsed_seconds': elapsed}
|
||||
has_run = False
|
||||
try:
|
||||
has_run = journal.get(run_id) is not None
|
||||
previous_summary = journal.batch_summary(run_id)
|
||||
batch_ids = _receipt_resource_batches(root, manifest, _bound_supervisors(root, manifest),
|
||||
previous_summary)
|
||||
summary = collect_batch_summary(service, root, manifest, receipt,
|
||||
batch_ids=batch_ids, elapsed_seconds=elapsed, no_dispatch=not has_run,
|
||||
prior_summary=previous_summary)
|
||||
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 _record_incident_resource_link(root, run_id, batch_id, task_id, expected_item, *, local=False,
|
||||
manifest_digest=None):
|
||||
path = internal_path(root / 'batch-runs' / run_id / 'manifest.json')
|
||||
try:
|
||||
manifest = json.loads(path.read_bytes())
|
||||
if (manifest['run_id'] != run_id or task_id not in manifest['runnable_task_ids']
|
||||
or (manifest_digest is not None and manifest['manifest_digest'] != manifest_digest)):
|
||||
raise ValueError('incident resource run identity changed')
|
||||
if local:
|
||||
from ..trial_task_center.task_queue import _local_resource_path
|
||||
path = root / _local_resource_path(run_id, batch_id)
|
||||
binding = {'version': 1, 'session_id': batch_id, 'queue_id': run_id, 'kind': 'quick_run_queue',
|
||||
'manifest_digest': manifest['manifest_digest'], 'task_ids': manifest['runnable_task_ids'],
|
||||
'plan_hashes': manifest['plan_hashes'], 'task_id': task_id, 'never_acquired': False}
|
||||
batch_resources.write_record(path, binding)
|
||||
return lambda: batch_resources.write_record(path, dict(binding, never_acquired=True))
|
||||
supervisor, arguments = _supervisor_request(root, batch_id)
|
||||
binding = _incident_resource_binding(manifest, supervisor, arguments)
|
||||
if binding['task_id'] != task_id or arguments.get('expected_item') != expected_item:
|
||||
raise ValueError('incident resource request selection changed')
|
||||
batch_resources.write_record(root / _incident_resource_path(manifest, batch_id), binding)
|
||||
except (OSError, ValueError, TypeError, KeyError, AttributeError) as error:
|
||||
raise TaskCenterError('incident_resource_link_unavailable',
|
||||
'无法记录本次重试与原批次的资源关联,未启动后台执行。') from error
|
||||
|
||||
|
||||
def _republish_incident_batch_summary(service, root, run_id, receipt):
|
||||
"""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 {}
|
||||
elapsed = previous.get('elapsed_seconds',
|
||||
receipt.get('elapsed_seconds', (run['result'] or {}).get('elapsed_seconds', 0)))
|
||||
return _finish_batch_summary(service, root, journal, manifest, receipt, elapsed)
|
||||
|
||||
|
||||
def _publish_batch_summary(root, journal, summary, receipt, *, has_run):
|
||||
run_id = summary['run_id']
|
||||
receipt = dict(receipt, elapsed_seconds=summary['elapsed_seconds'])
|
||||
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'
|
||||
summary_linked = (not running and durable
|
||||
and receipt.get('summary', {}).get('revision') == durable['revision'])
|
||||
if (summary_linked and not durable.get('operation_evidence_missing')
|
||||
and not any(row.get('state') == 'unknown'
|
||||
for row in durable['source_versions']['rounds'].values())
|
||||
and not any(row.get('code') == 'batch_snapshot_unstable'
|
||||
for row in durable['reporting_errors'])):
|
||||
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
|
||||
main_batches = _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 main_batches 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', (durable or {}).get('elapsed_seconds', 0))
|
||||
batch_ids = _receipt_resource_batches(root, manifest, main_batches, durable)
|
||||
summary = collect_batch_summary(service, root, manifest, receipt, elapsed_seconds=elapsed,
|
||||
batch_ids=batch_ids, prior_summary=durable)
|
||||
if summary_linked and summary == {key: value for key, value in durable.items() if key != 'revision'}:
|
||||
try:
|
||||
if json.loads(output.read_bytes()) == durable:
|
||||
continue
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
batch_resources.write_record(output, durable)
|
||||
continue
|
||||
_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)
|
||||
@@ -230,6 +592,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]):
|
||||
@@ -254,7 +617,15 @@ 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)
|
||||
controls = {}
|
||||
if revalidate is not None:
|
||||
def bind_request(batch_id, *, local=False):
|
||||
return _record_incident_resource_link(root, run_id, batch_id, task_id, expected_item,
|
||||
local=local, manifest_digest=checkpoint.get('manifest_digest'))
|
||||
|
||||
controls.update(revalidate=revalidate, before_launch=bind_request)
|
||||
outcome = service.execute_quick_run_queue(task_id, expected_item=expected_item, stop_event=stop_event,
|
||||
**controls)
|
||||
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
|
||||
@@ -310,7 +681,9 @@ 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:
|
||||
receipt = _republish_incident_batch_summary(service, root, run_id, receipt)
|
||||
verification.update(run_receipt_updated=True, run_status=receipt['status'])
|
||||
return outcome, current, verification
|
||||
except Exception as error:
|
||||
@@ -329,4 +702,10 @@ 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:
|
||||
try:
|
||||
_republish_incident_batch_summary(service, root, run_id, failure)
|
||||
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)
|
||||
|
||||
@@ -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],
|
||||
|
||||
@@ -23,6 +23,21 @@ class InputError(ValueError):
|
||||
_MAPPING_HEADER = ("old_part_number", "new_part_number")
|
||||
|
||||
|
||||
def validate_part_number(value: str) -> str:
|
||||
"""Normalize a newly assigned PN; legacy source inventory stays readable."""
|
||||
if not isinstance(value, str):
|
||||
raise InputError("invalid_part_number", "新料号必须是文本")
|
||||
value = value.strip()
|
||||
if not value:
|
||||
raise InputError("blank_part_number", "新料号不能为空")
|
||||
if len(value) > 128:
|
||||
raise InputError("invalid_part_number", "新料号最多允许 128 个字符")
|
||||
if (not any(char.isalnum() for char in value)
|
||||
or any(not char.isalnum() and char not in "-_./+()[]" for char in value)):
|
||||
raise InputError("invalid_part_number", "新料号须包含字母或数字;允许中文和 -_./+()[],不能包含内部空白、控制字符或其他符号(如 !@#)")
|
||||
return value
|
||||
|
||||
|
||||
def _mapping_rows(data: bytes, source: Path) -> list[dict[str, str | None]]:
|
||||
try:
|
||||
with io.StringIO(data.decode("utf-8-sig"), newline="") as handle:
|
||||
@@ -79,6 +94,10 @@ def parse_mapping_bytes(data: bytes, source: Path) -> tuple[MappingRule, ...]:
|
||||
new = (row.get("new_part_number") or "").strip()
|
||||
if not old or not new:
|
||||
raise InputError("blank_part_number", f"mapping row {row_number} has a blank part number")
|
||||
try:
|
||||
new = validate_part_number(new)
|
||||
except InputError as error:
|
||||
raise InputError(error.code, f"mapping row {row_number}: {error.message}") from error
|
||||
old_identity = old.casefold()
|
||||
new_identity = new.casefold()
|
||||
if old_identity == new_identity:
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
"""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 _completed_acceptance_verified(service, context):
|
||||
return _completed_acceptance_problem(service, context) is None
|
||||
|
||||
|
||||
def _completed_acceptance_problem(service, context):
|
||||
if not context.progress.saved_items:
|
||||
return None # A certified no-match result requires no saved-netlist acceptance.
|
||||
from ..dsh.run_journal import RunJournal
|
||||
from .task_queue import _plan_hash
|
||||
task_id = context.task.task_id
|
||||
root = service.layout_settings_path.parent
|
||||
if not (root / 'dsh-state.sqlite3').is_file():
|
||||
return 'acceptance_history_missing', '历史结果缺少可关联的运行验收记录。'
|
||||
child = service.for_project_task(task_id)
|
||||
current_hash = _plan_hash(child, task_id)
|
||||
with child._store._lock:
|
||||
current = child._store._connection.execute(
|
||||
'SELECT round_id FROM execution_rounds WHERE task_id=?', (task_id,)).fetchone()
|
||||
if current is None or not current[0]:
|
||||
return 'acceptance_round_missing', '已保存结果缺少当前执行轮次,不能沿用历史验收。'
|
||||
for run in RunJournal(root).list_runs(limit=1000):
|
||||
if task_id not in run['task_ids'] or run['plan_hashes'].get(task_id) != current_hash:
|
||||
continue
|
||||
result = run['result'] or {}
|
||||
summary = result.get('summary') or {}
|
||||
round_source = summary.get('source_versions', {}).get('rounds', {}).get(task_id, {})
|
||||
if (round_source.get('state') == 'unknown'
|
||||
or task_id in summary.get('operation_evidence_missing', ())):
|
||||
return 'acceptance_evidence_unavailable', '原运行的轮次或作业证据尚未完整核对,不能认证当前结果。'
|
||||
if round_source.get('round_id') != current[0]:
|
||||
return 'acceptance_round_mismatch', '现有验收不属于当前执行轮次。'
|
||||
report = (result.get('netlist_verification') or {}).get(task_id) or {}
|
||||
if run['status'] != 'running' and report.get('status') == 'verified' and report.get('verified') is True:
|
||||
return None
|
||||
if report and report.get('status') not in {'unavailable', 'not_required'}:
|
||||
return 'acceptance_failed', '当前轮次的独立网表验收未通过。'
|
||||
return 'acceptance_report_missing', '当前轮次缺少完整的独立网表验收。'
|
||||
return 'acceptance_history_missing', '历史结果缺少与当前计划匹配的运行验收记录。'
|
||||
|
||||
|
||||
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 = [], [], [], {}, []
|
||||
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)
|
||||
task = context.task
|
||||
fingerprints.append(asdict(context))
|
||||
row['project'] = str(context.project.path) if context.project else ''
|
||||
if context.project is not None:
|
||||
path_key = str(context.project.path.resolve(strict=False)).casefold()
|
||||
if path_key in paths:
|
||||
blockers.append('本批重复包含同一个工程,请核对任务绑定。')
|
||||
row.update(reason_code='project_duplicate',
|
||||
message=f'与任务“{paths[path_key]}”重复绑定工程:{context.project.path};请核对原任务及待核验结果。')
|
||||
continue
|
||||
paths[path_key] = task.name
|
||||
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):
|
||||
problem = _completed_acceptance_problem(service, context)
|
||||
if problem is not None:
|
||||
row.update(classification='held', reason_code='acceptance_unverified',
|
||||
acceptance_reason=problem[0], message=problem[1] +
|
||||
'请查看执行日志或导出诊断;可在“任务管理”中归档当前已完成任务,原结果和证据保留。')
|
||||
blockers.append(f'{task.name}:{row["message"]}')
|
||||
continue
|
||||
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
|
||||
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'
|
||||
@@ -103,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', {})
|
||||
@@ -141,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):
|
||||
@@ -166,6 +164,27 @@ def writer_identities(record):
|
||||
return identities
|
||||
|
||||
|
||||
def _lease_writer_trees_closed(record):
|
||||
"""A bound immutable lease return certifies every covered named Job empty."""
|
||||
try:
|
||||
from .desktop_slot import returned_lease_intact
|
||||
binding = record['desktop_lease_binding']
|
||||
receipt = record['cleanup']['desktop_lease']
|
||||
if (binding['session_id'] != record['session_id'] or binding['generation'] != record['generation']
|
||||
or binding['name'] != record['desktop'] or binding['lease_id'] != receipt['lease_id']
|
||||
or binding['scope'] != receipt['scope']
|
||||
or not returned_lease_intact(receipt, record['desktop'])):
|
||||
return False
|
||||
returned = json.loads(internal_path(receipt['path']).read_bytes())
|
||||
if returned['owner'] != binding['owner'] or returned['context'] != binding['context']:
|
||||
return False
|
||||
roots = [launch['process'] for launch in returned['launches'] if launch.get('process')]
|
||||
identities = writer_identities(record)
|
||||
return bool(identities) and all(identity in roots for identity in identities)
|
||||
except (OSError, ValueError, KeyError, TypeError, AttributeError):
|
||||
return False
|
||||
|
||||
|
||||
def isolation_proof(record):
|
||||
"""Certify handle closure and exact writer exit, never a desktop disappearance."""
|
||||
cleanup = record.get('cleanup') or {}
|
||||
@@ -176,7 +195,7 @@ def isolation_proof(record):
|
||||
if not returned_lease_intact(cleanup['desktop_lease'], record['desktop']):
|
||||
raise ValueError('Managed desktop return proof changed')
|
||||
if (cleanup.get('desktop_handle_closed') is not True
|
||||
or cleanup.get('owned_cleanup_complete') is not True):
|
||||
or not (cleanup.get('owned_cleanup_complete') is True or _lease_writer_trees_closed(record))):
|
||||
raise ValueError('Owned resource cleanup is not proven')
|
||||
identities = writer_identities(record)
|
||||
if not all(_process_gone(item) for item in identities):
|
||||
@@ -201,6 +220,8 @@ def _released_evidence(record):
|
||||
"""A state label alone must never reopen the physical resource gate."""
|
||||
proof = record.get('release_proof', {})
|
||||
cleanup = record.get('cleanup') or {}
|
||||
if cleanup.get('desktop_lease_pending') is True:
|
||||
return False
|
||||
if (proof.get('generation') == record['generation'] and proof.get('desktop_not_acquired') is True
|
||||
and cleanup.get('desktop_not_acquired') is True and cleanup.get('desktop_handle_closed') is True
|
||||
and cleanup.get('owned_cleanup_complete') is True and not cleanup.get('errors')
|
||||
@@ -219,12 +240,18 @@ def _released_evidence(record):
|
||||
last = releases[-1]
|
||||
cleanup = last.get('cleanup') or {}
|
||||
return (last.get('generation') == record['generation'] and last.get('desktop') == record['desktop']
|
||||
and cleanup.get('desktop_lease_pending') is not True
|
||||
and cleanup.get('desktop_handle_closed') is True and not cleanup.get('errors')
|
||||
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('上一批资源尚未确认释放;请先重试释放资源,再开始新批次。')
|
||||
|
||||
|
||||
@@ -237,31 +264,49 @@ 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 _lease_writer_trees_closed(record):
|
||||
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']]:
|
||||
@@ -353,6 +398,16 @@ 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 (record.get('cleanup') or {}).get('desktop_lease_pending') is True:
|
||||
binding = record.get('desktop_lease_binding') or {}
|
||||
if (binding.get('session_id') != record['session_id']
|
||||
or binding.get('generation') != record['generation']
|
||||
or binding.get('name') != record['desktop']):
|
||||
raise ValueError('缺少本会话和代次的原桌面租约绑定,请保留记录并导出诊断')
|
||||
from .desktop_slot import recover_abandoned_lease
|
||||
receipt = recover_abandoned_lease(binding)
|
||||
record['cleanup'] = dict(record['cleanup'], desktop_lease=receipt, desktop_lease_pending=False)
|
||||
write_record(path, {key: value for key, value in record.items() if key != 'record_path'})
|
||||
if not _historical_writer_trees_closed(record, path):
|
||||
log('failed', '缺少历史写入进程树退出证明')
|
||||
continue
|
||||
@@ -366,7 +421,7 @@ def cleanup_pending_resources(root, *, logging_context=None, retry_failed=False)
|
||||
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
|
||||
@@ -385,12 +440,11 @@ def cleanup_pending_resources(root, *, logging_context=None, retry_failed=False)
|
||||
return True
|
||||
|
||||
if not _observe_release(observe, record):
|
||||
# A residual desktop name is only a warning after owned
|
||||
# handle closure and independently revalidated writer exit.
|
||||
# Keep the closed writer proof while the desktop still blocks admission.
|
||||
proof = isolation_proof(record)
|
||||
record.pop('record_path', None)
|
||||
warning = '桌面仍在或同名桌面正在使用,未取得桌面消失证明'
|
||||
record.update(state='isolated', blocking=False, isolation_proof=proof,
|
||||
record.update(state='isolated', blocking=True, isolation_proof=proof,
|
||||
isolation_warning=warning)
|
||||
write_record(path, record)
|
||||
log('isolated', warning)
|
||||
|
||||
@@ -3,7 +3,7 @@ from dataclasses import replace
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .models import TaskStatus
|
||||
from .rule_validation import validate_mapping_pairs
|
||||
from .rule_validation import validate_mapping_pairs, validate_target_part_number
|
||||
|
||||
|
||||
def members(store, task_id):
|
||||
@@ -118,11 +118,26 @@ def mutate_batch_rules(service, task_id, operation, *, rule_id=None, offset=0, *
|
||||
selected = store.get_rule(rule_id) if rule_id else None
|
||||
selected_key = selected.old_part_number.casefold() if selected else None
|
||||
if operation == 'update':
|
||||
if not isinstance(options['new_part_number'], str):
|
||||
validate_target_part_number(options['new_part_number'])
|
||||
if options.get('target_cell') is None:
|
||||
options['target_cell'] = selected.target_cell if options['new_part_number'].strip() == selected.new_part_number else ''
|
||||
for field in ('custom_value_enabled', 'custom_value', 'sync_nc'):
|
||||
if options.get(field) is None:
|
||||
options[field] = getattr(selected, field)
|
||||
if options == (_options(selected) | {'enabled': False}):
|
||||
try:
|
||||
validate_target_part_number(selected.new_part_number)
|
||||
except TaskCenterError:
|
||||
# Disable legacy defaults in place; never copy invalid PN to another project.
|
||||
chosen = None
|
||||
for member in tasks:
|
||||
for prior in before[member.task_id]:
|
||||
if prior.old_part_number.casefold() == selected_key:
|
||||
result = store.update_rule(prior.rule_id, **(_options(prior) | {'enabled': False}))
|
||||
if prior.rule_id == rule_id:
|
||||
chosen = result
|
||||
return chosen
|
||||
union = {}
|
||||
# Existing per-project rules are merged when unambiguous. An explicit
|
||||
# edit/delete may resolve its own old-number conflict, never other keys.
|
||||
@@ -155,7 +170,13 @@ def mutate_batch_rules(service, task_id, operation, *, rule_id=None, offset=0, *
|
||||
if key not in local:
|
||||
settings = _options(rule)
|
||||
if key == selected_key and operation == 'update':
|
||||
settings['enabled'] = False
|
||||
settings.update(options, old_part_number=rule.old_part_number, enabled=False)
|
||||
elif not rule.enabled:
|
||||
try:
|
||||
validate_target_part_number(rule.new_part_number)
|
||||
except TaskCenterError:
|
||||
# Quarantined legacy rows stay at their original project until repaired.
|
||||
continue
|
||||
local[key] = store.add_rule(member.task_id, **settings)
|
||||
# Historical per-project additions may have different positions.
|
||||
# Normalize to the same batch order before applying a relative move.
|
||||
|
||||
@@ -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,
|
||||
desktop_lease_binding=None,
|
||||
release_rechecks=[],
|
||||
release_state={'mentor': 'not_started', 'desktop': 'pending'})
|
||||
self.generation = generation
|
||||
@@ -229,6 +232,9 @@ class BatchCadRuntime:
|
||||
LIVE_RESOURCES[str(self.path)] = self
|
||||
started = time.monotonic()
|
||||
try:
|
||||
if isinstance(self.desktop, PrivateDesktop):
|
||||
self.desktop.on_lease_acquired = lambda binding: self._save(
|
||||
desktop_lease_binding=dict(binding, session_id=self.session_id, generation=generation))
|
||||
self.desktop.__enter__()
|
||||
except Exception:
|
||||
if getattr(self.desktop, '_slot', None) is not None and not self.desktop._slot_acquired:
|
||||
@@ -358,7 +364,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', 'token', 'business_sequence', 'stage', 'done', 'total', 'safe_stop',
|
||||
'stop_requested', 'stopping_reason', 'idle_timeout_seconds', 'failure_completion_grace_seconds')}
|
||||
except (OSError, ValueError, TypeError):
|
||||
return None
|
||||
|
||||
@@ -571,7 +578,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'):
|
||||
@@ -1134,7 +1141,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:
|
||||
@@ -1189,7 +1196,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,467 @@
|
||||
"""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 re
|
||||
import sqlite3
|
||||
|
||||
from . import batch_resources
|
||||
from .execution_journal import ExecutionJournal, _targets
|
||||
from .path_access import canonical_path, 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, round_ids=None):
|
||||
rows, versions, missing = [], {}, []
|
||||
for task_id in task_ids:
|
||||
round_id = round_ids.get(task_id) if round_ids is not None else None
|
||||
try:
|
||||
if round_ids is not None and not round_id:
|
||||
raise LookupError('original execution round is not bound')
|
||||
store = service.for_project_task(task_id)._store
|
||||
with store._lock:
|
||||
current = store._connection.execute(
|
||||
'SELECT * FROM execution_rounds WHERE task_id=?', (task_id,)).fetchone()
|
||||
if round_ids is None and not current:
|
||||
versions[task_id] = {'round_id': None}
|
||||
continue
|
||||
round_id = round_id or current['round_id']
|
||||
is_current = current is not None and current['round_id'] == round_id
|
||||
round_row = dict(current) if is_current else {'round_id': 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))]
|
||||
if not is_current and not raw_rows and not commits:
|
||||
raise LookupError('original round evidence is unavailable')
|
||||
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 = (is_current and 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', **({'round_id': round_id} if round_id else {})}
|
||||
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 _supervisor_request(root, batch_id):
|
||||
from .supervisor_protocol import VERSION, decode, valid_journal
|
||||
|
||||
if not isinstance(batch_id, str) or not re.fullmatch('[0-9a-f]{32}', batch_id):
|
||||
raise ValueError('invalid supervisor identifier')
|
||||
directory = internal_path(root / 'batch-resources' / batch_id)
|
||||
raw = (directory / 'request.json').read_bytes()
|
||||
request = json.loads(raw)
|
||||
supervisor = json.loads((directory / 'supervisor.json').read_bytes())
|
||||
if (not valid_journal(supervisor, batch_id) or sha256(raw).hexdigest() != supervisor['request_sha256']
|
||||
or request['version'] != VERSION or canonical_path(request['root']) != canonical_path(root)
|
||||
or request['batch_id'] != batch_id or request['attempt_id'] != supervisor['attempt_id']
|
||||
or request['operation'] != supervisor['operation'] or request['task_ids'] != supervisor['task_ids']):
|
||||
raise ValueError('supervisor request identity changed')
|
||||
return supervisor, decode(request['arguments'])
|
||||
|
||||
|
||||
def _queue_request_matches(manifest, supervisor, arguments):
|
||||
scope = manifest['runnable_task_ids']
|
||||
return (supervisor['operation'] == 'execute_task_queue' and supervisor['task_ids'] == scope
|
||||
and (arguments.get('queue_id') or arguments.get('checkpoint_id')) == manifest['run_id']
|
||||
and list(arguments.get('task_ids', ())) == scope
|
||||
and arguments.get('expected_plan_hashes') == manifest['plan_hashes']
|
||||
and arguments.get('manifest_digest') == manifest['manifest_digest'])
|
||||
|
||||
|
||||
def _incident_resource_path(manifest, batch_id):
|
||||
return Path('batch-runs') / manifest['run_id'] / f'incident-resource-{batch_id}.json'
|
||||
|
||||
|
||||
def _incident_resource_binding(manifest, supervisor, arguments):
|
||||
task_id = arguments.get('task_id')
|
||||
if (supervisor['operation'] != 'execute_quick_run_queue' or supervisor['task_ids'] != [task_id]
|
||||
or task_id not in manifest['runnable_task_ids']):
|
||||
raise ValueError('incident resource request scope changed')
|
||||
return {'manifest_digest': manifest['manifest_digest'], 'task_id': task_id,
|
||||
'request_sha256': supervisor['request_sha256']}
|
||||
|
||||
|
||||
def _resource_source(root, batch_ids, *, manifest, no_dispatch):
|
||||
from .batch_supervisor import _abnormal_shutdown, pending_supervisors
|
||||
from .task_queue import _local_resource_path
|
||||
|
||||
references, generations, states = [], [], []
|
||||
supervisor_outcomes = {}
|
||||
try:
|
||||
related = batch_resources.pending_resources(root)
|
||||
supervisors = pending_supervisors(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')
|
||||
try:
|
||||
local_kind = None
|
||||
local_path = _local_resource_path(manifest['run_id'], batch_id)
|
||||
if internal_path(root / local_path).is_file():
|
||||
references.append(local_path.as_posix())
|
||||
local = json.loads(internal_path(root / local_path).read_bytes())
|
||||
expected = {'version': 1, 'session_id': batch_id, 'queue_id': manifest['run_id'],
|
||||
'manifest_digest': manifest['manifest_digest'],
|
||||
'task_ids': manifest['runnable_task_ids'], 'plan_hashes': manifest['plan_hashes']}
|
||||
if any(local.get(key) != value for key, value in expected.items()):
|
||||
raise ValueError('local runtime scope changed')
|
||||
local_kind = local.get('kind', 'task_queue')
|
||||
if (local_kind not in {'task_queue', 'quick_run_queue'}
|
||||
or local_kind == 'quick_run_queue' and local.get('task_id') not in manifest['runnable_task_ids']):
|
||||
raise ValueError('local runtime task scope changed')
|
||||
if local.get('never_acquired') is True and not record_path.is_file():
|
||||
states.append('released' if not related and not supervisors else 'unknown')
|
||||
continue
|
||||
supervisor = {}
|
||||
else:
|
||||
supervisor, arguments = _supervisor_request(root, batch_id)
|
||||
if supervisor['operation'] == 'execute_quick_run_queue':
|
||||
binding = _incident_resource_binding(manifest, supervisor, arguments)
|
||||
binding_path = _incident_resource_path(manifest, batch_id)
|
||||
if internal_path(root / binding_path).is_file():
|
||||
references.append(binding_path.as_posix())
|
||||
if json.loads(internal_path(root / binding_path).read_bytes()) != binding:
|
||||
raise ValueError('incident resource binding changed')
|
||||
# Previously published receipt IDs predate the dedicated binding file.
|
||||
elif not _queue_request_matches(manifest, supervisor, arguments):
|
||||
raise ValueError('resource request scope changed')
|
||||
supervisor_outcomes[batch_id] = supervisor.get('outcome')
|
||||
record = json.loads(record_path.read_bytes())
|
||||
if (not batch_resources._valid_record(record, record_path)
|
||||
or local_kind and record['kind'] != local_kind
|
||||
or local_kind == 'quick_run_queue' and record.get('log_task_ids') != [local['task_id']]):
|
||||
raise ValueError('resource record scope changed')
|
||||
if _abnormal_shutdown(record_path.parent):
|
||||
supervisor_outcomes[batch_id] = 'application_shutdown_failed'
|
||||
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())
|
||||
for release in record.get('generation_releases', ()):
|
||||
generation = release['generation']
|
||||
if generation == record['generation']:
|
||||
continue
|
||||
historical = {**record, **release, 'release_proof': {}, 'processes': [],
|
||||
'generation_releases': [release]}
|
||||
released = (batch_resources._valid_record(historical, record_path)
|
||||
and batch_resources._released_evidence(historical)
|
||||
and not any(item.get('generation') == generation for item in matching))
|
||||
states.append('released' if released else 'unknown')
|
||||
generations.append({'session_id': batch_id, 'generation': generation,
|
||||
'state': 'released' if released else 'unknown', 'reason': release.get('reason')})
|
||||
declared = record['state']
|
||||
proven = (declared == 'released' and batch_resources._released_evidence(record)
|
||||
and not any(item.get('generation') == record['generation'] for item in matching))
|
||||
generation_state = 'unknown' if declared == 'released' and not proven else declared
|
||||
if generation_state == 'unknown':
|
||||
states.append('unknown')
|
||||
if not matching:
|
||||
states.append('released' if proven else 'unknown')
|
||||
generations.append({'session_id': batch_id, 'generation': record['generation'],
|
||||
'state': generation_state, 'supervisor_status': supervisor_outcomes[batch_id],
|
||||
'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 supervisors:
|
||||
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,
|
||||
'supervisor_outcomes': supervisor_outcomes}
|
||||
|
||||
|
||||
def _original_rounds(task_ids, checkpoint, receipt, prior_summary):
|
||||
histories = [summary.get('source_versions', {}).get('rounds', {})
|
||||
for summary in (receipt.get('summary') or {}, prior_summary or {})]
|
||||
bound, conflicts = {}, set()
|
||||
for task_id in task_ids:
|
||||
records = [previous.get(task_id, {}) for previous in histories]
|
||||
candidates = {value for value in [checkpoint.get('round_ids', {}).get(task_id),
|
||||
*(old.get('round_id') for old in records)]
|
||||
if isinstance(value, str) and value}
|
||||
if any(old.get('round_conflict') for old in records) or len(candidates) > 1:
|
||||
conflicts.add(task_id)
|
||||
bound[task_id] = next(iter(candidates)) if len(candidates) == 1 and task_id not in conflicts else None
|
||||
return bound, conflicts
|
||||
|
||||
|
||||
def collect_batch_summary(service, root, manifest, receipt, *, batch_ids, elapsed_seconds, no_dispatch=False,
|
||||
prior_summary=None):
|
||||
"""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():
|
||||
checkpoint, checkpoint_digest, path, error = _checkpoint_source(root, manifest)
|
||||
bound, conflicts = _original_rounds(task_ids, checkpoint, receipt, prior_summary)
|
||||
rows, rounds, missing = _operation_sources(service, task_ids, bound)
|
||||
for task_id in conflicts:
|
||||
rounds[task_id]['round_conflict'] = True
|
||||
resource = _resource_source(root, batch_ids, manifest=manifest, 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 = [row for row in receipt.get('reporting_errors', ())
|
||||
if row.get('code') != 'batch_snapshot_unstable']
|
||||
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 == 'application_shutdown_failed'
|
||||
or 'application_shutdown_failed' in resource['supervisor_outcomes'].values()):
|
||||
stop_reason = 'application_shutdown_failed'
|
||||
if summary['execution_status'] == 'completed':
|
||||
summary['status'] = 'failed'
|
||||
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 not batch_ids or (summary['resource_state'] == 'released' and 'supervisor_outcomes' in summary['resource']):
|
||||
return summary
|
||||
resource = _resource_source(root, batch_ids, manifest=manifest, no_dispatch=False)
|
||||
shutdown_failed = 'application_shutdown_failed' in resource['supervisor_outcomes'].values()
|
||||
if resource['state'] != 'released' and not shutdown_failed:
|
||||
return summary
|
||||
status = summary['status']
|
||||
stop_reason = summary['stop_reason']
|
||||
if shutdown_failed:
|
||||
stop_reason = 'application_shutdown_failed'
|
||||
if summary['execution_status'] == 'completed':
|
||||
status = 'failed'
|
||||
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
|
||||
if resource == summary['resource'] and status == summary['status'] and stop_reason == summary['stop_reason']:
|
||||
return summary
|
||||
return {**summary, 'status': status, 'stop_reason': stop_reason, 'resource_state': resource['state'],
|
||||
'resource': resource,
|
||||
'source_versions': {**summary['source_versions'], 'resource_digest': _digest(resource)},
|
||||
'evidence': {**summary['evidence'], 'resource_records': resource['evidence']}}
|
||||
@@ -4,6 +4,7 @@ from __future__ import annotations
|
||||
from contextlib import contextmanager
|
||||
import json
|
||||
import hashlib
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import queue
|
||||
@@ -29,14 +30,43 @@ class BusinessProgressWatch:
|
||||
"""Control-channel liveness cannot certify forward business progress."""
|
||||
def __init__(self, started, idle_timeout=150):
|
||||
self.last_progress = started
|
||||
self.fallback_idle_timeout = idle_timeout
|
||||
self.idle_timeout = idle_timeout
|
||||
self.signatures = {}
|
||||
self.stage_progress = {}
|
||||
self.business_sequences = {}
|
||||
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'))
|
||||
timeout = progress.get('idle_timeout_seconds')
|
||||
self.idle_timeout = self.fallback_idle_timeout
|
||||
if (progress.get('job_id') and type(timeout) in (int, float)
|
||||
and 0 < timeout < math.inf):
|
||||
self.idle_timeout = max(self.fallback_idle_timeout, timeout)
|
||||
token, business_sequence = progress.get('token'), progress.get('business_sequence')
|
||||
if (isinstance(token, str) and len(token) == 32
|
||||
and all(character in '0123456789abcdef' for character in token)
|
||||
and isinstance(progress.get('job_id'), str) and progress['job_id']
|
||||
and type(business_sequence) is int and business_sequence > 0):
|
||||
binding = (token, progress['job_id'])
|
||||
if business_sequence > self.business_sequences.get(binding, 0):
|
||||
self.business_sequences[binding] = business_sequence
|
||||
self.last_progress = now
|
||||
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 +77,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 +97,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 +313,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 +327,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)
|
||||
@@ -307,6 +345,7 @@ def reconcile_supervisors(root):
|
||||
"""Recheck orphan ownership only; this never launches or replays a job."""
|
||||
from .batch_resources import _process_gone, blocking_resources, write_record
|
||||
from .read_recovery import process_tree_exited
|
||||
from .supervisor_result import validated_outcome
|
||||
physical = blocking_resources(root)
|
||||
for record in pending_supervisors(root):
|
||||
owner = (_LIVE_SUPERVISORS.get(canonical_path(record['record_path']))
|
||||
@@ -314,14 +353,25 @@ 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)):
|
||||
continue
|
||||
if record.get('outcome') not in {'interrupted', 'completed_resources_pending'}:
|
||||
_mark_interrupted(root, record, 'Supervisor ended without a reconciled final result')
|
||||
if any(item.get('session_id') == record['batch_id'] or not item.get('session_id') for item in physical):
|
||||
if (not record.get('batch_id')
|
||||
or (record.get('process_observation') or {}).get('state') == 'unknown'
|
||||
or (identity and not _process_gone(identity))):
|
||||
continue
|
||||
path = Path(record.pop('record_path'))
|
||||
outcome = 'completed' if record.get('outcome') == 'completed_resources_pending' else 'interrupted'
|
||||
related = _related_resources(physical, record['batch_id'])
|
||||
if record.get('outcome') != 'interrupted':
|
||||
try:
|
||||
response, _ = _read_final_response(path.parent, record)
|
||||
validated_outcome(record['operation'], response)
|
||||
except (OSError, ValueError, KeyError, TypeError, AttributeError):
|
||||
_mark_interrupted(root, record, 'Supervisor ended without a reconciled final result')
|
||||
else:
|
||||
_record_response_outcome(record, response, path.parent, related)
|
||||
if related:
|
||||
write_record(path, record)
|
||||
if related:
|
||||
continue
|
||||
outcome = 'completed' if record['outcome'] == 'ok' else record['outcome']
|
||||
if outcome == 'interrupted':
|
||||
from .task_queue import reconcile_interrupted_queue
|
||||
reconcile_interrupted_queue(root, record)
|
||||
@@ -346,63 +396,101 @@ def _environment():
|
||||
return environment
|
||||
|
||||
|
||||
def _finish_response(root, journal, response, context):
|
||||
"""A supervisor exit may release its last USER reference. Never repeat work."""
|
||||
from .batch_resources import cleanup_pending_resources, resource_blockers, 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')
|
||||
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()}
|
||||
write_record(Path(root) / 'batch-resources' / journal['batch_id'] / 'supervisor.json', journal)
|
||||
if blockers:
|
||||
raise resource_pending_error(journal['operation'], result, error, primary)
|
||||
for failure in (error, primary):
|
||||
if failure is not None:
|
||||
failure.resources_released = not warnings
|
||||
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:
|
||||
write_record(Path(root) / 'batch-resources' / journal['batch_id'] / 'supervisor.json', journal)
|
||||
except OSError as record_error:
|
||||
context.logger.error('supervisor_shutdown_record_failed batch_id=%s error=%s',
|
||||
journal['batch_id'], record_error)
|
||||
journal['shutdown_record_error'] = str(record_error)
|
||||
def shutdown_failure():
|
||||
failure = application_shutdown_error(result, error, primary)
|
||||
failure.resources_released = not warnings
|
||||
failure.owned_writers_exited = True
|
||||
failure.resource_warnings = warnings
|
||||
return failure
|
||||
def _read_final_response(directory, journal, gate=None):
|
||||
saved_only = False
|
||||
try:
|
||||
resource = json.loads(resource_path.read_text(encoding='utf-8'))
|
||||
response = json.loads(internal_path(directory / 'result.json').read_bytes())
|
||||
except FileNotFoundError:
|
||||
resource = {}
|
||||
except (OSError, ValueError, TypeError) as failure:
|
||||
journal.update(state='blocked', shutdown_record_error=str(failure))
|
||||
preserve_shutdown_failure(failure)
|
||||
raise shutdown_failure() from failure
|
||||
response = json.loads(internal_path(directory / 'business-result.json').read_bytes())
|
||||
if response['payload'].get('business_succeeded') is not True:
|
||||
raise ValueError('Untrusted saved business result')
|
||||
response = dict(response, type='result', sequence=(gate.sequence if gate else 0) + 1)
|
||||
saved_only = True
|
||||
minimum_sequence = max(1, gate.sequence) if gate else 1
|
||||
minimum_generation = gate.generation if gate else 1
|
||||
if (response.get('version') != VERSION or response.get('batch_id') != journal['batch_id']
|
||||
or response.get('attempt_id') != journal['attempt_id'] or response.get('type') != 'result'
|
||||
or type(response.get('sequence')) is not int or response['sequence'] < minimum_sequence
|
||||
or type(response.get('generation')) is not int or response['generation'] < minimum_generation):
|
||||
raise ValueError('stale or invalid final supervisor result')
|
||||
return response['payload'], saved_only
|
||||
|
||||
|
||||
def _related_resources(pending, batch_id):
|
||||
return tuple(item for item in pending if item.get('session_id') == batch_id or not item.get('session_id'))
|
||||
|
||||
|
||||
def _abnormal_shutdown(directory):
|
||||
resource_path = internal_path(directory / 'session.json')
|
||||
try:
|
||||
resource = json.loads(resource_path.read_bytes())
|
||||
except FileNotFoundError:
|
||||
return False
|
||||
shutdown = resource.get('cad_shutdown') if isinstance(resource, dict) else None
|
||||
if shutdown is None and isinstance(resource, dict):
|
||||
shutdown = {}
|
||||
return False
|
||||
if (not isinstance(shutdown, dict)
|
||||
or not isinstance(shutdown.get('cleanup_errors', ()), (list, tuple))
|
||||
or any(not isinstance(item, dict) for item in shutdown.get('cleanup_errors', ()))):
|
||||
journal.update(state='blocked', shutdown_record_error='invalid shutdown record shape')
|
||||
preserve_shutdown_failure('invalid shutdown record shape')
|
||||
raise shutdown_failure()
|
||||
if (shutdown.get('orderly_shutdown') is False or shutdown.get('forced_termination')
|
||||
or shutdown.get('diagnostic_errors')
|
||||
or any(item.get('stage') != 'desktop_release' for item in shutdown.get('cleanup_errors', ()))):
|
||||
raise shutdown_failure()
|
||||
raise ValueError('invalid shutdown record shape')
|
||||
return (shutdown.get('orderly_shutdown') is False or bool(shutdown.get('forced_termination'))
|
||||
or bool(shutdown.get('diagnostic_errors'))
|
||||
or any(item.get('stage') != 'desktop_release' for item in shutdown.get('cleanup_errors', ())))
|
||||
|
||||
|
||||
def _record_response_outcome(journal, response, directory, related, *, ownership_pending=False):
|
||||
from .batch_resources import _isolation_evidence
|
||||
|
||||
isolated = tuple(item for item in related if item.get('state') == 'isolated' and _isolation_evidence(item))
|
||||
pending = bool(related) or ownership_pending
|
||||
writers_exited = not ownership_pending and len(related) == len(isolated)
|
||||
try:
|
||||
abnormal_shutdown = _abnormal_shutdown(directory)
|
||||
except (OSError, ValueError, TypeError) as failure:
|
||||
journal['shutdown_record_error'] = str(failure)
|
||||
abnormal_shutdown = True
|
||||
journal['state'] = 'blocked' if pending or journal.get('shutdown_record_error') else 'finished'
|
||||
if abnormal_shutdown or journal.get('outcome') == 'application_shutdown_failed':
|
||||
journal['outcome'] = 'application_shutdown_failed'
|
||||
elif response['business_succeeded']:
|
||||
journal['outcome'] = 'completed_resources_pending' if pending else 'ok'
|
||||
else:
|
||||
journal['outcome'] = 'error'
|
||||
journal['resource_recheck'] = {'pending': pending, 'warnings': list(isolated),
|
||||
'desktop_released': not pending, 'owned_writers_exited': writers_exited, 'checked_at': time.time()}
|
||||
return isolated
|
||||
|
||||
|
||||
def _finish_response(root, journal, response, context, *, transport_error=None, ownership_pending=False):
|
||||
"""A supervisor exit may release its last USER reference. Never repeat work."""
|
||||
from .batch_resources import cleanup_pending_resources, pending_resources, write_record
|
||||
from .supervisor_result import validated_outcome, resource_pending_error, application_shutdown_error
|
||||
result, error, primary = validated_outcome(journal['operation'], response)
|
||||
if transport_error is None:
|
||||
pending = cleanup_pending_resources(root, logging_context=context)
|
||||
related = _related_resources(pending, journal['batch_id'])
|
||||
else:
|
||||
related = pending_resources(root)
|
||||
journal['error'] = str(transport_error)
|
||||
path = Path(root) / 'batch-resources' / journal['batch_id'] / 'supervisor.json'
|
||||
isolated = _record_response_outcome(journal, response, path.parent, related, ownership_pending=ownership_pending)
|
||||
write_record(path, journal)
|
||||
recheck = journal['resource_recheck']
|
||||
if journal['outcome'] == 'application_shutdown_failed':
|
||||
failure = application_shutdown_error(result, transport_error or error, primary)
|
||||
elif recheck['pending'] or transport_error is not None:
|
||||
failure = resource_pending_error(journal['operation'], result, transport_error or error, primary or error)
|
||||
else:
|
||||
failure = None
|
||||
if failure is not None:
|
||||
failure.resources_released = recheck['desktop_released']
|
||||
failure.owned_writers_exited = recheck['owned_writers_exited']
|
||||
failure.resource_warnings = isolated
|
||||
raise failure
|
||||
for failure in (error, primary):
|
||||
if failure is not None:
|
||||
failure.resources_released = True
|
||||
failure.owned_writers_exited = True
|
||||
if response.get('business_succeeded'):
|
||||
if response.get('error'):
|
||||
context.logger.info('supervisor_resource_recovery_passed batch_id=%s business_replayed=false', journal['batch_id'])
|
||||
@@ -416,7 +504,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, before_launch=None):
|
||||
from .batch_resources import write_record, process_identity
|
||||
from .isolated_desktop import _Win32Api
|
||||
from .stop_control import StopControl
|
||||
@@ -438,6 +527,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
|
||||
@@ -460,7 +556,18 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
|
||||
'operation': operation, 'arguments': encode(arguments), 'task_ids': journal['task_ids'],
|
||||
'interactive_stop': isinstance(stop_event, StopControl)})
|
||||
journal['request_sha256'] = hashlib.sha256(internal_path(request).read_bytes()).hexdigest()
|
||||
write_record(directory / 'supervisor.json', journal)
|
||||
journal_path = directory / 'supervisor.json'
|
||||
write_record(journal_path, journal)
|
||||
if before_launch is not None:
|
||||
try:
|
||||
before_launch(batch_id)
|
||||
except Exception as error:
|
||||
journal.update(state='finished', outcome='prelaunch_rejected', error=str(error))
|
||||
try:
|
||||
write_record(journal_path, journal)
|
||||
except OSError:
|
||||
service._logging.logger.exception('supervisor_prelaunch_rejection_unavailable batch_id=%s', batch_id)
|
||||
raise
|
||||
from .supervisor_evidence import LifecycleEvidence
|
||||
lifecycle = LifecycleEvidence(directory)
|
||||
lifecycle.try_append('supervisor_starting', operation=operation)
|
||||
@@ -475,6 +582,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 +635,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 +651,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 +683,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
|
||||
@@ -661,22 +784,11 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
|
||||
raise resource_pending_error(operation, None, ownership_cleanup_error, failure)
|
||||
raise failure
|
||||
try:
|
||||
try:
|
||||
response = json.loads(internal_path(directory / 'result.json').read_text(encoding='utf-8'))
|
||||
except FileNotFoundError:
|
||||
saved = json.loads(internal_path(directory / 'business-result.json').read_text(encoding='utf-8'))
|
||||
if (saved.get('version') != VERSION or saved.get('batch_id') != batch_id
|
||||
or saved.get('attempt_id') != attempt_id or not saved['payload'].get('business_succeeded')):
|
||||
raise ValueError('Untrusted saved business result')
|
||||
response = dict(saved, type='result', sequence=gate.sequence + 1)
|
||||
response, saved_only = _read_final_response(directory, journal, gate)
|
||||
if saved_only:
|
||||
service._logging.logger.warning('supervisor_final_missing_saved_result_retained batch_id=%s', batch_id)
|
||||
if (response.get('version') != VERSION or response.get('batch_id') != batch_id
|
||||
or response.get('attempt_id') != attempt_id or response.get('type') != 'result'
|
||||
or type(response.get('sequence')) is not int or response['sequence'] < gate.sequence
|
||||
or type(response.get('generation')) is not int or response['generation'] < gate.generation):
|
||||
raise ValueError('stale or invalid final supervisor result')
|
||||
from .supervisor_result import validated_outcome, resource_pending_error
|
||||
decoded_result, decoded_error, decoded_primary = validated_outcome(operation, response['payload'])
|
||||
from .supervisor_result import validated_outcome
|
||||
validated_outcome(operation, response)
|
||||
except (OSError, ValueError, KeyError, TypeError, AttributeError) as error:
|
||||
from .supervisor_evidence import MissingSupervisorResult, InvalidSupervisorResult
|
||||
failure_type = MissingSupervisorResult if isinstance(error, FileNotFoundError) else InvalidSupervisorResult
|
||||
@@ -710,20 +822,9 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
|
||||
failure.owned_writers_exited = (not resource_blockers(outstanding) and ownership_cleanup_error is None
|
||||
and (process is None or process_tree_exited(process)))
|
||||
raise failure from (transport_error or error)
|
||||
ownership_pending = False
|
||||
if transport_error is not None:
|
||||
if response['payload']['business_succeeded']:
|
||||
journal.update(state='blocked', outcome='completed_resources_pending', error=str(transport_error))
|
||||
write_record(directory / 'supervisor.json', journal)
|
||||
else:
|
||||
_mark_interrupted(root, journal, transport_error)
|
||||
failure = resource_pending_error(operation, decoded_result, transport_error, decoded_primary)
|
||||
from .batch_resources import pending_resources, resource_blockers
|
||||
from .read_recovery import process_tree_exited
|
||||
pending = pending_resources(root)
|
||||
failure.resources_released = (ownership_cleanup_error is None and not pending
|
||||
and process is not None and process_tree_exited(process))
|
||||
failure.owned_writers_exited = (ownership_cleanup_error is None and not resource_blockers(pending)
|
||||
and process is not None and process_tree_exited(process))
|
||||
failure.resource_warnings = tuple(row for row in pending if row not in resource_blockers(pending))
|
||||
raise failure
|
||||
return _finish_response(root, journal, response['payload'], service._logging)
|
||||
ownership_pending = ownership_cleanup_error is not None or process is None or not process_tree_exited(process)
|
||||
return _finish_response(root, journal, response, service._logging,
|
||||
transport_error=transport_error, ownership_pending=ownership_pending)
|
||||
@@ -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')
|
||||
@@ -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)
|
||||
|
||||
@@ -143,6 +143,54 @@ def observe_current_desktop_name(name):
|
||||
return managed_desktop_disappeared({'scope': slot.scope, 'name': slot.name})
|
||||
|
||||
|
||||
def recover_abandoned_lease(binding, *, root=None, context=None, backend=None):
|
||||
"""Return only an exactly bound orphan lease, without acquiring a new one."""
|
||||
slot = DesktopSlot(root=root, context=context, backend=backend)
|
||||
try:
|
||||
if (binding.get('version') != 1 or binding.get('context') != slot.context
|
||||
or binding.get('scope') != slot.scope or binding.get('name') != slot.name
|
||||
or canonical_path(binding['path']) != slot.path
|
||||
or not re.fullmatch('[0-9a-f]{32}', binding.get('lease_id', ''))):
|
||||
_fail('原桌面租约归属不完整,请导出诊断;保留资源保护。')
|
||||
return_path = slot.path.parent / 'leases' / (binding['lease_id'] + '.json')
|
||||
|
||||
def receipt(record, raw):
|
||||
if (record.get('context') != slot.context or record.get('owner') != binding['owner']
|
||||
or record.get('lease_id') != binding['lease_id']):
|
||||
_fail('原桌面租约身份已变化,保留资源保护。')
|
||||
value = dict(returned=True, name=slot.name, scope=slot.scope, lease_id=binding['lease_id'],
|
||||
desktop_disappeared=record.get('desktop_disappeared'), path=str(return_path),
|
||||
sha256=hashlib.sha256(raw).hexdigest())
|
||||
if not returned_lease_intact(value, slot.name):
|
||||
_fail('原桌面租约归还记录不完整,保留资源保护。')
|
||||
return value
|
||||
|
||||
if internal_path(return_path).exists():
|
||||
raw = internal_path(return_path).read_bytes()
|
||||
return receipt(json.loads(raw), raw)
|
||||
mutex = slot.backend.lock('Local\\DxPartReplace-Desktop-' + slot.scope)
|
||||
try:
|
||||
original = json.loads(internal_path(slot.path).read_bytes())
|
||||
if (original.get('lease_id') != binding['lease_id']
|
||||
or original.get('owner') != binding['owner']):
|
||||
_fail('原桌面已由其他租约接替,未操作新的持有者。')
|
||||
slot._validate(original)
|
||||
if not slot.backend.process_gone(original['owner']):
|
||||
_fail('原租约持有者尚未确认退出,保留资源保护。')
|
||||
returned = dict(original, state='idle', writers_exited=True,
|
||||
desktop_disappeared=not slot.backend.desktop_exists(slot.name), recovered=True)
|
||||
write_record(return_path, returned)
|
||||
write_record(slot.path, returned)
|
||||
return receipt(returned, internal_path(return_path).read_bytes())
|
||||
finally:
|
||||
slot.backend.unlock(mutex)
|
||||
except TaskCenterError:
|
||||
raise
|
||||
except (OSError, ValueError, KeyError, TypeError, AttributeError) as error:
|
||||
raise TaskCenterError('desktop_slot_busy',
|
||||
'无法核对原桌面租约,请保留记录并导出诊断;未解除资源保护。') from error
|
||||
|
||||
|
||||
class DesktopSlot:
|
||||
def __init__(self, *, root=None, context=None, backend=None):
|
||||
self.context = _context() if context is None else context
|
||||
@@ -164,6 +212,12 @@ class DesktopSlot:
|
||||
write_record(self.path, record)
|
||||
self.record = record
|
||||
|
||||
def binding(self):
|
||||
if self.handle is None or self.receipt is not None:
|
||||
_fail('桌面租约尚未领取或已经归还。')
|
||||
return dict(version=1, path=str(self.path), context=dict(self.context), scope=self.scope,
|
||||
name=self.name, lease_id=self.lease_id, owner=dict(self.record['owner']))
|
||||
|
||||
def _validate(self, record):
|
||||
if (record.get('version') != 1 or record.get('context') != self.context
|
||||
or record.get('name') != self.name or record.get('scope') != self.scope
|
||||
@@ -193,6 +247,8 @@ class DesktopSlot:
|
||||
self._validate(previous)
|
||||
if previous['state'] == 'leased' and not self.backend.process_gone(previous['owner']):
|
||||
_fail('前批桌面持有者尚未退出,保留原租用。')
|
||||
if self.backend.desktop_exists(self.name):
|
||||
_fail('前批桌面尚未确认物理释放,请先释放残留句柄再领取新租约。')
|
||||
elif self.backend.desktop_exists(self.name):
|
||||
_fail('同名桌面缺少归属记录,未收养现有桌面。')
|
||||
self._save(dict(version=1, context=self.context, name=self.name, scope=self.scope,
|
||||
|
||||
@@ -56,6 +56,10 @@ 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'}
|
||||
or bool(re.fullmatch(r'(?:local|incident)-resource-[0-9a-f]{32}\.json', parts[2]))))
|
||||
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 +78,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 +124,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)
|
||||
|
||||
@@ -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',
|
||||
@@ -120,11 +121,11 @@ class ExecutionProblems:
|
||||
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.rowid''',
|
||||
(task_id, current[0])).fetchall() if current else ()
|
||||
blocked = any(row['state'] in {'pending', 'prepared', 'uncertain'} for row in rows)
|
||||
blocked = any(row['state'] in {'pending', 'prepared', 'pending_save', 'uncertain'} for row in rows)
|
||||
items = []
|
||||
for row in rows:
|
||||
if row['state'] == 'superseded' or (not row['problem_key'] and row['state'] not in
|
||||
{'pending', 'prepared', 'uncertain', 'failed'}):
|
||||
{'pending', 'prepared', 'pending_save', 'uncertain', 'failed'}):
|
||||
continue
|
||||
command = json.loads(row['command_json'])
|
||||
targets = [selector.split('\x1f') for selector in
|
||||
@@ -142,7 +143,7 @@ class ExecutionProblems:
|
||||
return dict(round_id=current[0] if current else None, items=tuple(items),
|
||||
failed=sum(item['state'] == 'failed' for item in items),
|
||||
held=sum(item['state'] == 'pending' for item in items),
|
||||
uncertain=sum(item['state'] in {'prepared', 'uncertain'} for item in items),
|
||||
uncertain=sum(item['state'] in {'prepared', 'pending_save', 'uncertain'} for item in items),
|
||||
resolved=sum(item['problem_state'] == 'resolved' for item in items))
|
||||
|
||||
def validate_selection(self, task_id, keys, round_id, generations):
|
||||
|
||||
@@ -605,6 +605,7 @@ class PrivateDesktop:
|
||||
self.cleanup_record = None
|
||||
self._desktop_handle_history = []
|
||||
self._process_history = []
|
||||
self.on_lease_acquired = None
|
||||
|
||||
def __enter__(self) -> "PrivateDesktop":
|
||||
if not self.enabled:
|
||||
@@ -613,6 +614,8 @@ class PrivateDesktop:
|
||||
self._slot.acquire()
|
||||
self._slot_acquired = True
|
||||
try:
|
||||
if self._slot is not None and self.on_lease_acquired is not None:
|
||||
self.on_lease_acquired(self._slot.binding())
|
||||
self._create()
|
||||
if self._slot is not None and hasattr(self._api, 'validate_desktop_owner'):
|
||||
self._api.validate_desktop_owner(self._handle, self._slot.context['sid'])
|
||||
|
||||
@@ -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
|
||||
@@ -379,7 +384,7 @@ def load_databook_target(snapshot, report, target, *, controls, browse, filter_p
|
||||
load['retry'] = retry
|
||||
save_report(snapshot, report)
|
||||
if not retry:
|
||||
raise
|
||||
raise DxDataBookLookupTimeout(str(error)) from error
|
||||
if candidates:
|
||||
close_dialog(candidates[0])
|
||||
load['closed_dialog'] = candidates[0]['hwnd']
|
||||
@@ -1220,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)
|
||||
@@ -1243,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,10 +3,17 @@ import csv
|
||||
import io
|
||||
from pathlib import Path
|
||||
|
||||
from dx_productivity.part_replace.inputs import InputError, parse_mapping_bytes
|
||||
from dx_productivity.part_replace.inputs import InputError, parse_mapping_bytes, validate_part_number
|
||||
from .errors import TaskCenterError
|
||||
|
||||
|
||||
def validate_target_part_number(value):
|
||||
try:
|
||||
return validate_part_number(value)
|
||||
except InputError as error:
|
||||
raise TaskCenterError(error.code, error.message) from error
|
||||
|
||||
|
||||
def validate_mapping_pairs(pairs):
|
||||
output = io.StringIO(newline='')
|
||||
writer = csv.writer(output, lineterminator='\n')
|
||||
|
||||
@@ -245,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)
|
||||
@@ -278,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)
|
||||
|
||||
@@ -290,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 {}))
|
||||
@@ -879,30 +881,57 @@ class TaskCenterService:
|
||||
continue_after_backup_failure: bool = False,
|
||||
reuse_project_session: bool = True,
|
||||
runtime=None,
|
||||
revalidate=None,
|
||||
before_launch=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 {}),
|
||||
**({'before_launch': before_launch} if before_launch 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:
|
||||
from .batch_runtime import BatchCadRuntime, BatchResourceCleanupError
|
||||
mark_never_acquired = None
|
||||
|
||||
def finish_local_binding(error_type, _error, _traceback):
|
||||
orderly = error_type is None or (
|
||||
issubclass(error_type, Exception) and not issubclass(error_type, BatchResourceCleanupError))
|
||||
if orderly and mark_never_acquired is not None and owned_runtime.generation == 0:
|
||||
try:
|
||||
mark_never_acquired()
|
||||
except OSError:
|
||||
self._logging.logger.exception('local_incident_release_proof_unavailable task_id=%s', task_id)
|
||||
|
||||
with ExitStack() as ownership:
|
||||
ownership.push(finish_local_binding)
|
||||
owned_runtime = ownership.enter_context(BatchCadRuntime(self._logging.root, 'quick_run_queue', stop_event))
|
||||
owned_runtime.bind_logs(self._logging, (task_id,))
|
||||
|
||||
def bind_local_session():
|
||||
nonlocal mark_never_acquired
|
||||
if revalidate is not None:
|
||||
revalidate()
|
||||
mark_never_acquired = before_launch(owned_runtime.session_id, local=True)
|
||||
|
||||
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=bind_local_session if before_launch is not None else revalidate)
|
||||
owned_runtime.result = result
|
||||
return 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}:
|
||||
|
||||
@@ -14,7 +14,7 @@ import sqlite3
|
||||
import threading
|
||||
from uuid import uuid4
|
||||
|
||||
from .rule_validation import validate_mapping_pairs
|
||||
from .rule_validation import validate_mapping_pairs, validate_target_part_number
|
||||
|
||||
from .store_schema import StoreSchema
|
||||
from .store_target_plan import TargetPlanRepository
|
||||
@@ -609,7 +609,11 @@ class TaskStore:
|
||||
) -> RuleRecord:
|
||||
with self.transaction():
|
||||
prior = self._rule_record(self._rule_row(rule_id))
|
||||
old, new = self._normalized_rule(old_part_number, new_part_number)
|
||||
# Quarantining an unchanged legacy PN cannot introduce a new mapping.
|
||||
disabling_unchanged = (not enabled and old_part_number == prior.old_part_number
|
||||
and new_part_number == prior.new_part_number)
|
||||
old, new = ((prior.old_part_number, prior.new_part_number) if disabling_unchanged
|
||||
else self._normalized_rule(old_part_number, new_part_number))
|
||||
if target_cell is None:
|
||||
target_cell = prior.target_cell if new == prior.new_part_number else ''
|
||||
target_cell = self._normalized_target_cell(target_cell)
|
||||
@@ -623,7 +627,8 @@ class TaskStore:
|
||||
custom_value_enabled = ?, custom_value = ?, sync_nc = ?, target_cell = ? WHERE rule_id = ?""",
|
||||
(old, new, int(bool(enabled)), int(custom_enabled), normalized_value, int(nc_enabled), target_cell, rule_id),
|
||||
)
|
||||
self._validate_enabled_rules(prior.task_id)
|
||||
if not disabling_unchanged:
|
||||
self._validate_enabled_rules(prior.task_id)
|
||||
return self._rule_record(self._rule_row(rule_id))
|
||||
|
||||
def get_rule(self, rule_id: str) -> RuleRecord:
|
||||
@@ -1027,7 +1032,7 @@ class TaskStore:
|
||||
@staticmethod
|
||||
def _normalized_rule(old_part_number: str, new_part_number: str) -> tuple[str, str]:
|
||||
old = str(old_part_number).strip()
|
||||
new = str(new_part_number).strip()
|
||||
new = validate_target_part_number(new_part_number)
|
||||
if not old or not new:
|
||||
raise TaskCenterError("blank_part_number", "part numbers must not be blank")
|
||||
return old, new
|
||||
|
||||
@@ -77,7 +77,7 @@ class TargetPlanRepository:
|
||||
task = self._store.get_task(task_id)
|
||||
if task.status not in {TaskStatus.DRAFT, TaskStatus.READY}:
|
||||
raise TaskCenterError("target_plan_locked", "task plan is locked")
|
||||
rows = tuple(rows)
|
||||
rows = tuple(replace(row, new_part_number=row.new_part_number.strip()) for row in rows)
|
||||
compile_target_rules(rows)
|
||||
identities = ProjectIdentityResolver()
|
||||
projects = self._store.list_projects(task_id)
|
||||
|
||||
@@ -6,6 +6,7 @@ from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .rule_validation import validate_target_part_number
|
||||
|
||||
|
||||
class ProjectIdentityResolver:
|
||||
@@ -75,9 +76,10 @@ class TargetPlanRow:
|
||||
object.__setattr__(self, "value_mode", "custom")
|
||||
if self.value_mode == "custom":
|
||||
object.__setattr__(self, "custom_value_enabled", True)
|
||||
if any(character in value for value in (self.new_part_number, self.custom_value, self.target_cell, self.value_mode)
|
||||
# PN drafts may be invalid; compile/save validates them before persistence.
|
||||
if any(character in value for value in (self.custom_value, self.target_cell, self.value_mode)
|
||||
for character in "\t\r\n"):
|
||||
raise TaskCenterError("target_plan", "Part Number and Value cannot contain TSV controls")
|
||||
raise TaskCenterError("target_plan", "Value and Cell cannot contain TSV controls")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
@@ -123,9 +125,14 @@ def compile_target_rules(rows: tuple[TargetPlanRow, ...], *, default_value_mode:
|
||||
if target_key in seen:
|
||||
raise TaskCenterError("target_overlap", "target reference appears more than once")
|
||||
seen.add(target_key)
|
||||
new = row.new_part_number.strip()
|
||||
if row.enabled or new:
|
||||
try:
|
||||
new = validate_target_part_number(row.new_part_number)
|
||||
except TaskCenterError as error:
|
||||
raise TaskCenterError(error.code, f"{target.schematic_name}:{target.sheet_number} | {target.refdes}:{error.message}") from error
|
||||
if not row.enabled:
|
||||
continue
|
||||
new = row.new_part_number.strip()
|
||||
old = target.old_part_number.strip()
|
||||
if not new or old.casefold() == new.casefold():
|
||||
raise TaskCenterError("mapping_rule", "source and target Part Numbers must differ")
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Recoverable task-list archival performed only during an opted-in normal close."""
|
||||
"""Recoverable archival for normal close and explicit completed-task selection."""
|
||||
from dataclasses import dataclass
|
||||
|
||||
from .models import ProjectStatus, TaskStatus
|
||||
@@ -15,14 +15,16 @@ class ArchiveReport:
|
||||
return tuple(task_id for task_id, _ in self.retained)
|
||||
|
||||
|
||||
def archive_completed_session(service):
|
||||
def archive_completed_session(service, *, task_ids=None):
|
||||
"""Soft-delete safe tasks atomically; preserve recovery tasks and all files."""
|
||||
return service._idle_quick_run_operation('archive_completed_session', None,
|
||||
lambda: _archive(service))
|
||||
lambda: _archive(service, task_ids))
|
||||
|
||||
|
||||
def _archive(service):
|
||||
def _archive(service, requested_ids=None):
|
||||
store = service._store
|
||||
from .errors import TaskCenterError
|
||||
from .execution_problems import ExecutionProblems
|
||||
from .batch_resources import resource_blockers
|
||||
pending = resource_blockers(service.pending_batch_resources())
|
||||
owned = set()
|
||||
@@ -36,12 +38,25 @@ def _archive(service):
|
||||
owned.update(task_ids)
|
||||
retained, safe = [], []
|
||||
with store.transaction():
|
||||
for task in store.list_tasks():
|
||||
tasks = tuple(store.list_tasks())
|
||||
if requested_ids is not None:
|
||||
selected = tuple(requested_ids)
|
||||
if (not selected or len(set(selected)) != len(selected)
|
||||
or not set(selected).issubset(task.task_id for task in tasks)):
|
||||
raise TaskCenterError('archive_scope', '归档范围已变化,请重新选择已完成任务。')
|
||||
tasks = tuple(task for task in tasks if task.task_id in selected)
|
||||
for task in tasks:
|
||||
reason = None
|
||||
child = service._project_task_service(task.task_id)
|
||||
problems = ExecutionProblems(getattr(child, '_store', None) or store).overview(task.task_id)
|
||||
if unknown or task.task_id in owned:
|
||||
reason = '后台资源尚未确认释放;重新打开后使用“重新清理资源”。'
|
||||
elif requested_ids is not None and task.status is not TaskStatus.COMPLETED:
|
||||
reason = '当前任务已不处于已完成状态,未归档。'
|
||||
elif task.status in {TaskStatus.RUNNING, TaskStatus.BLOCKED}:
|
||||
reason = '任务仍在执行状态;重新打开后暂停或核验恢复。'
|
||||
elif problems['uncertain'] or problems['held']:
|
||||
reason = '仍有未执行或待核验作业,请先核验恢复。'
|
||||
elif any(project.status in {ProjectStatus.CAPTURING_BEFORE, ProjectStatus.AWAITING_OPERATOR,
|
||||
ProjectStatus.CAPTURING_AFTER, ProjectStatus.VERIFYING}
|
||||
for project in store.list_projects(task.task_id)):
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""Durable serial scheduling of single-project tasks, above the existing runner."""
|
||||
|
||||
from contextlib import contextmanager
|
||||
from contextlib import ExitStack, contextmanager
|
||||
from dataclasses import asdict, dataclass, is_dataclass
|
||||
import hashlib
|
||||
import inspect
|
||||
@@ -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,101 @@ 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, _released_evidence, _valid_record, blocking_resources
|
||||
from .batch_supervisor import _abnormal_shutdown, 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 journal.get('outcome') == 'application_shutdown_failed'
|
||||
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
|
||||
if _abnormal_shutdown(directory):
|
||||
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
|
||||
if require_released:
|
||||
session_path = directory / 'session.json'
|
||||
session = json.loads(session_path.read_bytes())
|
||||
if (not _valid_record(session, session_path) or session['state'] != 'released'
|
||||
or session['generation'] != message['generation'] or not _released_evidence(session)):
|
||||
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 _local_resource_path(queue_id, session_id):
|
||||
return Path('batch-runs') / queue_id / f'local-resource-{session_id}.json'
|
||||
|
||||
|
||||
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,25 +298,89 @@ 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:
|
||||
from .batch_runtime import BatchCadRuntime, BatchResourceCleanupError
|
||||
from .batch_resources import write_record
|
||||
token = queue_id or checkpoint_id
|
||||
binding = binding_path = None
|
||||
binding_written = False
|
||||
|
||||
def bind_local_session():
|
||||
nonlocal binding_written
|
||||
if revalidate is not None:
|
||||
revalidate()
|
||||
write_record(binding_path, binding)
|
||||
binding_written = True
|
||||
|
||||
def finish_local_binding(error_type, _error, _traceback):
|
||||
orderly = error_type is None or (
|
||||
issubclass(error_type, Exception) and not issubclass(error_type, BatchResourceCleanupError))
|
||||
if orderly and binding_written and owned_runtime.generation == 0:
|
||||
try:
|
||||
write_record(binding_path, dict(binding, never_acquired=True))
|
||||
except OSError as error:
|
||||
service._logging.logger.error('local_resource_release_proof_unavailable queue_id=%s error=%s',
|
||||
token, type(error).__name__)
|
||||
|
||||
with ExitStack() as ownership:
|
||||
ownership.push(finish_local_binding)
|
||||
owned_runtime = ownership.enter_context(BatchCadRuntime(service._logging.root, 'task_queue', stop_event))
|
||||
if manifest_digest is not None:
|
||||
if (not isinstance(token, str) or len(token) != 32
|
||||
or any(char not in '0123456789abcdef' for char in token)):
|
||||
raise TaskCenterError('task_queue_state', '冻结任务队列编号无效。')
|
||||
binding_path = service._logging.root / _local_resource_path(token, owned_runtime.session_id)
|
||||
binding = {'version': 1, 'session_id': owned_runtime.session_id, 'queue_id': token,
|
||||
'manifest_digest': manifest_digest, 'task_ids': list(task_ids),
|
||||
'plan_hashes': expected_plan_hashes, 'never_acquired': False}
|
||||
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=bind_local_session if binding else revalidate,
|
||||
manifest_digest=manifest_digest)
|
||||
owned_runtime.result = result
|
||||
return result
|
||||
return result
|
||||
ids = tuple(task_ids)
|
||||
if not ids or len(set(ids)) != len(ids):
|
||||
raise TaskCenterError('task_queue_selection', '请选择不同的单工程任务。')
|
||||
root = service._logging.root
|
||||
with _queue_lease(root):
|
||||
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 +388,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 +414,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,14 +425,51 @@ 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
|
||||
|
||||
def bind_task_round(task_id):
|
||||
if manifest_digest is None:
|
||||
return
|
||||
child = children[task_id]
|
||||
store = getattr(child, '_store', None)
|
||||
if store is None:
|
||||
return # Adapters without a journal cannot certify a round identity.
|
||||
with store._lock:
|
||||
row = store._connection.execute(
|
||||
'SELECT round_id FROM execution_rounds WHERE task_id=?', (task_id,)).fetchone()
|
||||
if row is not None:
|
||||
known = state.setdefault('round_ids', {}).get(task_id)
|
||||
if known is not None and known != row[0]:
|
||||
raise TaskCenterError('task_queue_state', '原队列执行轮次已变化,不能沿用原验收。')
|
||||
state['round_ids'][task_id] = row[0]
|
||||
_save(path, state)
|
||||
|
||||
from .stop_control import ProjectStopControl
|
||||
parent_control = getattr(runtime, 'stop_event', None)
|
||||
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 +499,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 +514,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)
|
||||
@@ -323,6 +536,7 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||
if hasattr(child, '_quick_run_preparer'):
|
||||
child._quick_run_preparer.reconcile_terminal_receipts(task_id)
|
||||
progress = child.quick_run_progress(task_id)
|
||||
bind_task_round(task_id)
|
||||
if progress.queue_complete:
|
||||
checks.before_task(child, task_id, existing_only=True)
|
||||
entry = {'state': 'failed' if getattr(progress, 'failed_items', 0) else 'completed',
|
||||
@@ -342,6 +556,7 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||
execution_dispatched = True
|
||||
result = execute(task_id, expected_item=expected, stop_event=project_control,
|
||||
**runtime_options)
|
||||
bind_task_round(task_id)
|
||||
if child.has_interrupted_quick_run(task_id) or (
|
||||
result.last_result is not None and result.last_result.state == 'batch_saved_unverified'
|
||||
):
|
||||
@@ -376,32 +591,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 +628,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())):
|
||||
@@ -422,6 +645,7 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||
checks.before_task(children[task_id], task_id)
|
||||
from .problem_pass import run_problem_pass
|
||||
def capture_retry(task_id, result):
|
||||
bind_task_round(task_id)
|
||||
if not result.paused and not children[task_id].has_interrupted_quick_run(task_id):
|
||||
checks.after_task(task_id, execution_state='failed' if result.progress.failed_items else 'completed',
|
||||
refresh=True, execution_summary={key: getattr(result.progress, key, None)
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Names for business inputs and otherwise unnamed public Qt controls."""
|
||||
from PySide6.QtGui import QAccessible
|
||||
from PySide6.QtWidgets import (QAbstractButton, QComboBox, QFormLayout, QLabel,
|
||||
QLineEdit, QPlainTextEdit, QTextEdit, QToolButton, QWidget)
|
||||
|
||||
|
||||
_NAMES = {
|
||||
'taskSearch': '搜索工程任务',
|
||||
'taskList': '工程任务列表',
|
||||
'taskNavigation': '工程任务导航',
|
||||
'taskSort': '任务显示排序',
|
||||
'taskSortMenu': '任务显示排序',
|
||||
'findTargetText': '搜索位号计划',
|
||||
'bulkTargetPart': '批量目标料号',
|
||||
'mappingTable': '料号替换规则',
|
||||
'targetPlanTable': '位号替换计划',
|
||||
'taskDirectory': '工程任务目录',
|
||||
'taskProjectCandidates': '待导入工程列表',
|
||||
'targetCellCombo': '目标封装',
|
||||
'executionResults': '替换结果',
|
||||
'logView': '任务日志',
|
||||
'bomImportReport': 'BOM 导入报告',
|
||||
}
|
||||
|
||||
|
||||
def apply_accessible_names(root):
|
||||
widgets = [root, *root.findChildren(QWidget)]
|
||||
for widget in widgets:
|
||||
if not widget.accessibleName() and widget.objectName() in _NAMES:
|
||||
widget.setAccessibleName(_NAMES[widget.objectName()])
|
||||
for widget in widgets:
|
||||
if widget.accessibleName():
|
||||
continue
|
||||
if isinstance(widget, QToolButton) and isinstance(widget.parentWidget(), QLineEdit):
|
||||
action = widget.defaultAction()
|
||||
parent = widget.parentWidget()
|
||||
if action and action.objectName() == '_q_qlineeditclearaction':
|
||||
name = '清除' + parent.accessibleName()
|
||||
else:
|
||||
name = widget.toolTip().split(' · ', 1)[0]
|
||||
if name:
|
||||
widget.setAccessibleName(name)
|
||||
continue
|
||||
if not isinstance(widget, (QLineEdit, QPlainTextEdit, QTextEdit, QComboBox, QAbstractButton)):
|
||||
continue
|
||||
interface = QAccessible.queryAccessibleInterface(widget)
|
||||
if interface and interface.text(QAccessible.Text.Name):
|
||||
continue
|
||||
name = ''
|
||||
parent = widget.parentWidget()
|
||||
layout = parent.layout() if parent else None
|
||||
if isinstance(layout, QFormLayout):
|
||||
label = layout.labelForField(widget)
|
||||
if isinstance(label, QLabel):
|
||||
name = label.text()
|
||||
if not name and isinstance(widget, (QLineEdit, QPlainTextEdit, QTextEdit)):
|
||||
name = widget.placeholderText()
|
||||
if not name:
|
||||
name = widget.toolTip().splitlines()[0] if widget.toolTip() else ''
|
||||
if name:
|
||||
widget.setAccessibleName(name)
|
||||
@@ -31,7 +31,8 @@ class CommandMenu(QMenu):
|
||||
|
||||
def sync(self):
|
||||
for action,button in self._commands:
|
||||
action.setText(button.text())
|
||||
shortcut = button.property('shortcutLabel')
|
||||
action.setText(button.text() + (f'\t{shortcut}' if shortcut else ''))
|
||||
action.setIcon(button.icon())
|
||||
action.setEnabled(button.isEnabled())
|
||||
action.setVisible(not button.isHidden())
|
||||
|
||||
@@ -96,6 +96,7 @@ class TaskLogDialog(QDialog):
|
||||
else:
|
||||
if self.log_view is None:
|
||||
self.log_view = QPlainTextEdit(objectName='logView')
|
||||
self.log_view.setAccessibleName('任务日志')
|
||||
self.log_view.setReadOnly(True)
|
||||
self._pages[1].addWidget(self.log_view)
|
||||
previous = self.log_view.toPlainText()
|
||||
@@ -126,6 +127,7 @@ class BomReportDialog(QDialog):
|
||||
self.setWindowTitle('本批 BOM 导入校验详情')
|
||||
self.resize(820, 420)
|
||||
self.view = QPlainTextEdit(objectName='bomImportReport')
|
||||
self.view.setAccessibleName('BOM 导入报告')
|
||||
self.view.setReadOnly(True)
|
||||
QVBoxLayout(self).addWidget(self.view)
|
||||
|
||||
|
||||
@@ -4,10 +4,10 @@ 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, QSize, 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)
|
||||
from PySide6.QtWidgets import (QApplication, QCheckBox, QDialog, QFileDialog, QHBoxLayout, QLayout, QMessageBox,
|
||||
QPushButton, QLabel, QScrollArea, QSizePolicy, QSplitter, QStackedWidget, QTabWidget, QToolButton, QVBoxLayout, QWidget)
|
||||
from ..errors import TaskCenterError
|
||||
from ..models import TaskStatus
|
||||
from ..version import VERSION
|
||||
@@ -21,6 +21,7 @@ from .run_panel import RunPanel
|
||||
from .styles import APP_STYLESHEET
|
||||
from .material import AcrylicController, MaterialMainWindow
|
||||
from .icons import apply_icons, icon
|
||||
from .accessibility import apply_accessible_names
|
||||
from .task_list import TaskList
|
||||
from .workers import ServiceWorker
|
||||
from .toggle_switch import ToggleSwitch
|
||||
@@ -122,6 +123,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 = ''
|
||||
@@ -145,10 +149,12 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self.task_list.new_button.clicked.connect(self._new_task)
|
||||
self.task_list.edit_button.clicked.connect(self._edit_task)
|
||||
self.task_list.delete_button.clicked.connect(self._delete_task)
|
||||
self.task_list.archive_button.clicked.connect(self._archive_completed_task)
|
||||
self.task_list.restore_button.clicked.connect(self._restore_task)
|
||||
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)
|
||||
@@ -184,6 +190,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)
|
||||
@@ -192,6 +199,9 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self._material.set_reduced_transparency(self.reduced_transparency_button.isChecked())
|
||||
self.reduced_transparency_button.toggled.connect(self._set_reduced_transparency)
|
||||
apply_icons(self)
|
||||
from .shortcuts import install_window_shortcuts
|
||||
install_window_shortcuts(self)
|
||||
apply_accessible_names(self)
|
||||
self.archive_on_close_check.setChecked(self._layout_settings.value(
|
||||
'tasks/archive_on_close', False, type=bool))
|
||||
self.archive_on_close_check.toggled.connect(self._set_archive_on_close)
|
||||
@@ -201,8 +211,10 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self.task_list.view_changed.connect(self._update_gates)
|
||||
for name, widget in self._layout_widgets().items():
|
||||
saved = self._layout_settings.value(f'single_project/{name}')
|
||||
if saved is not None:
|
||||
widget.restoreState(saved)
|
||||
if isinstance(saved, (QByteArray, bytes, bytearray, memoryview)):
|
||||
default_state = widget.saveState()
|
||||
if not widget.restoreState(saved):
|
||||
widget.restoreState(default_state)
|
||||
from .dsh_operations import DshOperationsController
|
||||
self._dsh_operations = DshOperationsController(self)
|
||||
from .dsh_blockers import DshBlockerCoordinator
|
||||
@@ -214,6 +226,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()
|
||||
@@ -287,9 +300,14 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self.workspace_splitter.setStretchFactor(1, 1)
|
||||
container = QWidget(objectName='taskCenterSurface')
|
||||
layout = QHBoxLayout(container)
|
||||
# Retain the compact layout at 980x700; smaller viewports can scroll it.
|
||||
layout.setSizeConstraint(QLayout.SizeConstraint.SetNoConstraint)
|
||||
container.setMinimumSize(900, 600)
|
||||
layout.setContentsMargins(8, 8, 8, 8)
|
||||
layout.addWidget(self.workspace_splitter)
|
||||
self.content_stack = QStackedWidget()
|
||||
self.content_stack.layout().setSizeConstraint(QLayout.SizeConstraint.SetNoConstraint)
|
||||
self.content_stack.setMinimumSize(900, 600)
|
||||
self.content_stack.addWidget(container)
|
||||
from .operation_history import OperationHistoryPage
|
||||
self.history_panel = OperationHistoryPage(self.service, self)
|
||||
@@ -299,17 +317,37 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
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.workspace_scroll = QScrollArea(objectName='taskWorkspaceScroll')
|
||||
self.workspace_scroll.setAccessibleName('工作区')
|
||||
self.workspace_scroll.setWidgetResizable(True)
|
||||
self.workspace_scroll.setFrameShape(QScrollArea.Shape.NoFrame)
|
||||
self.workspace_scroll.setWidget(self.content_stack)
|
||||
self.setCentralWidget(self.workspace_scroll)
|
||||
self._reset_layout()
|
||||
|
||||
def _workspace_changed(self, index):
|
||||
history = self.content_stack.widget(index) is self.history_panel
|
||||
verification = self.content_stack.widget(index) is self.verification_panel
|
||||
minimum = QSize(900, 600)
|
||||
if history or verification:
|
||||
minimum = minimum.expandedTo(self.content_stack.currentWidget().minimumSizeHint())
|
||||
self.content_stack.setMinimumSize(minimum)
|
||||
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 showEvent(self, event):
|
||||
super().showEvent(event)
|
||||
if not getattr(self, '_initial_geometry_checked', False):
|
||||
self._initial_geometry_checked = True
|
||||
initial = (self.geometry(), self.normalGeometry(), self.windowState())
|
||||
def fit_initial_frame():
|
||||
# A queued fit must not overwrite a resize/maximize after show().
|
||||
if initial == (self.geometry(), self.normalGeometry(), self.windowState()):
|
||||
self._restore_window_geometry(restore_saved=False)
|
||||
QTimer.singleShot(0, self, fit_initial_frame)
|
||||
|
||||
def _history_activity_changed(self):
|
||||
self._update_gates()
|
||||
if self._close_pending and self.history_panel._worker is None and not self._workers and not self._closed:
|
||||
@@ -319,6 +357,38 @@ 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, *, restore_saved=True):
|
||||
saved = self._layout_settings.value('main_window/geometry')
|
||||
if restore_saved and isinstance(saved, QByteArray):
|
||||
self.restoreGeometry(saved)
|
||||
normal = self.normalGeometry()
|
||||
if not normal.isValid():
|
||||
normal = self.geometry()
|
||||
screen = QApplication.screenAt(normal.center())
|
||||
screen = screen or QApplication.primaryScreen()
|
||||
if screen is None:
|
||||
return
|
||||
available = screen.availableGeometry()
|
||||
client, frame = self.geometry(), self.frameGeometry()
|
||||
left, top = max(0, client.left() - frame.left()), max(0, client.top() - frame.top())
|
||||
frame_width, frame_height = max(0, frame.width() - client.width()), max(0, frame.height() - client.height())
|
||||
limit = QSize(max(1, available.width() - frame_width - 16),
|
||||
max(1, available.height() - frame_height - 16))
|
||||
self.setMinimumSize(QSize(980, 700).boundedTo(limit))
|
||||
if (available.contains(frame)
|
||||
and normal.size().boundedTo(limit) == normal.size()
|
||||
and normal.size().expandedTo(self.minimumSize()) == normal.size()):
|
||||
return
|
||||
state = self.windowState()
|
||||
self.setWindowState(Qt.WindowState.WindowNoState)
|
||||
size = normal.size().boundedTo(limit).expandedTo(self.minimumSize())
|
||||
fallback = QRect(available.left() + 8 + left, available.top() + 8 + top, size.width(), size.height())
|
||||
self.setGeometry(fallback)
|
||||
self.setWindowState(state)
|
||||
self.service._logging.logger.info('window_geometry screen=%s dpi=%s scale=%s available=%s client=%s',
|
||||
screen.name(), screen.logicalDotsPerInch(), screen.devicePixelRatio(),
|
||||
available.getRect(), self.geometry().getRect())
|
||||
|
||||
def _reset_layout(self):
|
||||
self.workspace_splitter.setSizes((240, 1040))
|
||||
self.detail_splitter.setSizes((650, 110))
|
||||
@@ -377,11 +447,16 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
return
|
||||
if choice == 'save':
|
||||
event.ignore()
|
||||
try:
|
||||
operation = self.plan_panel.prepare_save_all()
|
||||
except Exception as error:
|
||||
self._show_error(error, auto_intervene=False)
|
||||
return
|
||||
self._close_saving = True
|
||||
def saved(_):
|
||||
self.plan_panel.discard_all()
|
||||
def saved(rows):
|
||||
self.plan_panel.accept_saved_plans(rows)
|
||||
self._close_pending = True
|
||||
self._run_async(self.plan_panel.prepare_save_all(), saved)
|
||||
self._run_async(operation, saved)
|
||||
return
|
||||
if choice != 'discard':
|
||||
event.ignore()
|
||||
@@ -415,10 +490,20 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
event.ignore()
|
||||
QTimer.singleShot(100, self.close)
|
||||
return
|
||||
for query in (self._context_query, self._task_query, self._feedback_query):
|
||||
query.close()
|
||||
if any(query.busy for query in (self._context_query, self._task_query, self._feedback_query)):
|
||||
self._close_pending = True
|
||||
self.setEnabled(False)
|
||||
event.ignore()
|
||||
QTimer.singleShot(100, self, 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()
|
||||
@@ -448,9 +533,14 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
if deleted else self.service.tasks(read_control=control), received, self._show_error, cancellable=True)
|
||||
|
||||
def open_task(self, task_id):
|
||||
if self._workers and self._batch_stop is None:
|
||||
self.task_list.select_task(self._task_id)
|
||||
return
|
||||
if task_id != self._task_id and self.plan_panel.has_unsaved_plans():
|
||||
self.task_list.select_task(self._task_id)
|
||||
self._resolve_unsaved_plans(lambda: self.open_task(task_id))
|
||||
return
|
||||
if not task_id:
|
||||
if self._workers and self._batch_stop is None:
|
||||
return
|
||||
self._task_id = None
|
||||
self.plan_panel.bind_task(None)
|
||||
self.project_summary.populate(None)
|
||||
@@ -459,8 +549,6 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self._log_presenter.bind(None)
|
||||
self._load_task_data()
|
||||
return
|
||||
if self._workers and self._batch_stop is None:
|
||||
return
|
||||
if self._task_id != task_id:
|
||||
self._execution_after_save = None
|
||||
self.plan_panel.bind_task(None)
|
||||
@@ -472,7 +560,42 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self._log_presenter.bind(task_id)
|
||||
self._load_task_data()
|
||||
|
||||
def _resolve_unsaved_plans(self, proceed):
|
||||
if not self.plan_panel.has_unsaved_plans():
|
||||
proceed()
|
||||
return
|
||||
choice = self._close_plan_confirmer()
|
||||
if choice == 'save':
|
||||
try:
|
||||
operation = self.plan_panel.prepare_save_all()
|
||||
except Exception as error:
|
||||
self._show_error(error, auto_intervene=False)
|
||||
return
|
||||
saved = False
|
||||
def accepted(rows):
|
||||
nonlocal saved
|
||||
self.plan_panel.accept_saved_plans(rows)
|
||||
saved = True
|
||||
def finished():
|
||||
if saved and not self._closed:
|
||||
proceed()
|
||||
self._run_async(operation, accepted, expected_task_id=self._task_id, on_finished=finished)
|
||||
elif choice == 'discard':
|
||||
self.plan_panel.discard_all()
|
||||
proceed()
|
||||
else:
|
||||
self.task_list.list.setFocus(Qt.FocusReason.OtherFocusReason)
|
||||
|
||||
def _load_task_data(self, *, auto_intervene=True):
|
||||
# Capture editing while the current context still permits model changes.
|
||||
try:
|
||||
# A read retry retains the locked editor until context restores edit gates.
|
||||
if self._context_phase is not ContextReadPhase.FAILED:
|
||||
self.plan_panel.table.commit_editor()
|
||||
except Exception as error:
|
||||
self._context_query.invalidate()
|
||||
self._task_context_failed(error, auto_intervene=False)
|
||||
return False
|
||||
self._context = None
|
||||
self._context_phase = ContextReadPhase.LOADING if self._task_id else ContextReadPhase.IDLE
|
||||
self._update_gates()
|
||||
@@ -481,27 +604,29 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
if not task_id:
|
||||
self._context_query.invalidate()
|
||||
self._apply_task_context(None, auto_intervene=auto_intervene)
|
||||
return
|
||||
return True
|
||||
self.project_summary.state.setText('正在读取任务…')
|
||||
self._context_query.request(lambda control: self.service.task_context(task_id, read_control=control),
|
||||
lambda context: self._apply_task_context(context, auto_intervene=auto_intervene),
|
||||
lambda error: self._task_context_failed(error, auto_intervene=auto_intervene), cancellable=True)
|
||||
return True
|
||||
|
||||
def _task_context_failed(self, error, *, auto_intervene=True):
|
||||
self._execution_after_save = None
|
||||
self._context_phase = ContextReadPhase.FAILED
|
||||
self._context = None
|
||||
self.project_summary.state.setText('任务读取失败,请点击“重试读取任务”。')
|
||||
self._update_gates()
|
||||
self._show_error(error, auto_intervene=auto_intervene)
|
||||
|
||||
def _apply_task_context(self, context, *, auto_intervene=True):
|
||||
try:
|
||||
self._context_phase = ContextReadPhase.READY if context else ContextReadPhase.IDLE
|
||||
self._context = context
|
||||
if context:
|
||||
self._known_task_groups[context.task.task_id] = context.task.group_id
|
||||
self.project_summary.populate(context)
|
||||
self.plan_panel.bind_task(self._task_id, context.targets if context else ())
|
||||
self._context_phase = ContextReadPhase.READY if context else ContextReadPhase.IDLE
|
||||
self._context = context
|
||||
self.project_summary.populate(context)
|
||||
self.mapping_table.populate(context.rules if context else ())
|
||||
with QSignalBlocker(self.run_panel.copy_value_check):
|
||||
self.run_panel.copy_value_check.setChecked(bool(context and context.task.copy_part_number_to_value))
|
||||
@@ -539,6 +664,8 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
dirty=self.plan_panel.table.dirty or self.plan_panel.table.has_pending_editor())
|
||||
group_unsaved = self._group_has_unsaved_plans() if state.editable or state.new_round else False
|
||||
context = self._context
|
||||
self.task_list.archive_button.setEnabled(bool(context and context.task.status is TaskStatus.COMPLETED
|
||||
and not busy and not resources_pending and self._batch_stop is None))
|
||||
save_pending = bool(context and state.editable and
|
||||
(self.plan_panel.table.dirty or self.plan_panel.table.has_pending_editor() or self.plan_panel._active_bom_batch()))
|
||||
self.run_panel.quick_run_button.setText('保存计划以执行' if save_pending else state.execute_text)
|
||||
@@ -598,8 +725,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'
|
||||
@@ -639,6 +768,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
|
||||
def _new_task(self):
|
||||
dialog = DirectoryTaskDialog(self.service, self)
|
||||
apply_accessible_names(dialog)
|
||||
if dialog.exec() == QDialog.DialogCode.Accepted:
|
||||
root, paths = dialog.values()
|
||||
self._run_async(lambda: self.service.create_project_tasks(root, selected_paths=paths),
|
||||
@@ -648,8 +778,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self.task_list.recycle_button.setChecked(False)
|
||||
self._refresh_task_list()
|
||||
if tasks:
|
||||
self._task_id = tasks[0].task_id
|
||||
self._load_task_data()
|
||||
QTimer.singleShot(0, self, lambda: self.open_task(tasks[0].task_id))
|
||||
self._set_operator_message(f'创建 {len(tasks)} 个单工程任务。已有未完成任务的工程不会重复创建。')
|
||||
|
||||
def _refresh_bound_project(self):
|
||||
@@ -658,6 +787,12 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self._set_operator_message('')
|
||||
self._load_task_data()
|
||||
return
|
||||
try:
|
||||
self.plan_panel.table.commit_editor()
|
||||
except Exception as error:
|
||||
self._context_query.invalidate()
|
||||
self._task_context_failed(error, auto_intervene=False)
|
||||
return
|
||||
task_id = self._task_id
|
||||
self._run_async(lambda: self.service.refresh_bound_project(task_id),
|
||||
lambda _: self._load_task_data(), self.project_summary.refresh_button,
|
||||
@@ -668,6 +803,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
return
|
||||
task = self._context.task
|
||||
dialog = _TaskDialog(self, task.name, task.note)
|
||||
apply_accessible_names(dialog)
|
||||
if dialog.exec() == QDialog.DialogCode.Accepted:
|
||||
name, note = dialog.values()
|
||||
self._run_async(lambda: self.service.update_task(task.task_id, name=name, note=note),
|
||||
@@ -682,18 +818,44 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
return
|
||||
task = self._context.task
|
||||
permanent = task.status is TaskStatus.DELETED
|
||||
if QMessageBox.question(self, '彻底删除任务' if permanent else '删除任务',
|
||||
'永久删除任务记录,工程文件和诊断证据保留。此操作不可撤销。' if permanent else '移至已删除,之后可恢复。',
|
||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
|
||||
QMessageBox.StandardButton.No) != QMessageBox.StandardButton.Yes:
|
||||
return
|
||||
operation = (lambda: self.service.purge_task(task.task_id, confirmed=True)) if permanent else (lambda: self.service.delete_task(task.task_id))
|
||||
def done(_):
|
||||
if permanent:
|
||||
self.plan_panel.forget_task(task.task_id)
|
||||
self._task_id = None
|
||||
self.plan_panel.forget_task(task.task_id)
|
||||
self._task_id = None
|
||||
self._context = None
|
||||
self._metadata_changed(None)
|
||||
self._run_async(operation, done, self.task_list.delete_button)
|
||||
def confirmed():
|
||||
if QMessageBox.question(self, '彻底删除任务' if permanent else '删除任务',
|
||||
'永久删除任务记录,工程文件和诊断证据保留。此操作不可撤销。' if permanent else '移至已删除,之后可恢复。',
|
||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
|
||||
QMessageBox.StandardButton.No) == QMessageBox.StandardButton.Yes:
|
||||
self._run_async(operation, done, self.task_list.delete_button)
|
||||
self._resolve_unsaved_plans(confirmed)
|
||||
|
||||
def _archive_completed_task(self):
|
||||
if not self._context or self._workers:
|
||||
return
|
||||
task_id = self._context.task.task_id
|
||||
from ..task_archive import archive_completed_session
|
||||
|
||||
def done(report):
|
||||
if task_id in report.archived_ids:
|
||||
self.plan_panel.forget_task(task_id)
|
||||
self._task_id = None
|
||||
self._context = None
|
||||
self._metadata_changed(None)
|
||||
self._set_operator_message('已归档,原执行结果和证据保留。' if report.archived_ids else
|
||||
'未归档:' + ';'.join(reason for _, reason in report.retained),
|
||||
'success' if report.archived_ids else 'warning')
|
||||
|
||||
def confirmed():
|
||||
if QMessageBox.question(self, '归档当前已完成任务',
|
||||
'归档后移至回收站,可恢复。工程、计划和原执行证据均保留;归档不会将缺失验收变为验收通过。',
|
||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
|
||||
QMessageBox.StandardButton.No) == QMessageBox.StandardButton.Yes:
|
||||
self._run_async(lambda: archive_completed_session(self.service, task_ids=(task_id,)),
|
||||
done, self.task_list.archive_button)
|
||||
self._resolve_unsaved_plans(confirmed)
|
||||
|
||||
def _restore_task(self):
|
||||
if self._task_id:
|
||||
@@ -725,6 +887,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
target_cell='' if rule is None else rule.target_cell,
|
||||
cell_loader=lambda pn: self.service.target_cell_choices(task_id, pn),
|
||||
cell_context=lambda: (self._task_id, self.service.target_cell_projects(task_id)))
|
||||
apply_accessible_names(dialog)
|
||||
if dialog.exec() != QDialog.DialogCode.Accepted:
|
||||
return
|
||||
old, new, enabled, custom_enabled, value, sync_nc = dialog.values()
|
||||
@@ -869,36 +1032,88 @@ 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
|
||||
try:
|
||||
from ..batch_admission import build_batch_admission, resolve_batch_task_ids
|
||||
selection = self.task_list.selected_task_ids() if selected else None
|
||||
queues = dict(self._project_queues)
|
||||
prepared = []
|
||||
def inspect():
|
||||
records = tuple(self.service.tasks())
|
||||
anchor = selection[0] if selection else owner_task_id
|
||||
owner = next((task for task in records if task.task_id == anchor), None)
|
||||
if owner is None:
|
||||
raise TaskCenterError('batch_scope', '候选任务已变化,请重新选择并确认。')
|
||||
group = owner.group_id
|
||||
candidates = resolve_batch_task_ids(records, group, selected_ids=selection)
|
||||
token, ids = queues.get(group, (None, candidates))
|
||||
if token and selected and tuple(ids) != candidates:
|
||||
raise TaskCenterError('batch_scope', '本批有原队列待接续,请按原确认范围继续,或先核验并结束原批次。')
|
||||
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, group, candidates, token, ids
|
||||
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, group, candidates, token, ids = 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)
|
||||
@@ -906,7 +1121,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:
|
||||
@@ -921,8 +1136,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
|
||||
@@ -930,20 +1159,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
|
||||
@@ -1048,14 +1298,23 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
force_started = False
|
||||
def start_force_if_ready():
|
||||
nonlocal force_started
|
||||
if force_confirmed and cleanup_finished and not force_started and not self._close_pending:
|
||||
if force_confirmed and cleanup_finished and not force_started and not self._close_pending and not self._workers:
|
||||
force_started = True
|
||||
self._run_async(lambda: self.service.force_pending_owned_resources(confirmed=True),
|
||||
forced, self.run_panel.cleanup_resources_button)
|
||||
forced, self.run_panel.cleanup_resources_button, on_finished=repair_reports)
|
||||
def after_report():
|
||||
start_force_if_ready()
|
||||
self._resume_resource_queue()
|
||||
def repair_reports():
|
||||
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=after_report)
|
||||
def after_cleanup():
|
||||
nonlocal cleanup_finished
|
||||
cleanup_finished = True
|
||||
start_force_if_ready()
|
||||
if not force_started and not self._workers:
|
||||
repair_reports()
|
||||
def forced(remaining):
|
||||
from ..batch_resources import resource_blockers
|
||||
self._resource_status.refresh()
|
||||
@@ -1099,6 +1358,12 @@ 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 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(automatic=True)
|
||||
@@ -1106,7 +1371,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
def _export_diagnostics(self):
|
||||
from pathlib import Path
|
||||
name = 'DxPartReplace-诊断-' + time.strftime('%Y%m%d-%H%M%S') + '.zip'
|
||||
value, _ = QFileDialog.getSaveFileName(self, '导出脱敏诊断包', name, 'ZIP 文件 (*.zip)')
|
||||
value, _ = QFileDialog.getSaveFileName(self, '导出诊断包(过滤凭据,仍含工程路径和任务标识)', name, 'ZIP 文件 (*.zip)')
|
||||
if not value or self._diagnostic_worker is not None:
|
||||
return
|
||||
# A read-only support export remains available while CAD is waiting.
|
||||
@@ -1151,6 +1416,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
if self._problem_dialog is dialog:
|
||||
self._problem_dialog = None
|
||||
dialog.finished.connect(closed)
|
||||
apply_accessible_names(dialog)
|
||||
dialog.show()
|
||||
self._run_async(lambda: self.service.execution_problem_overview(task_id), loaded,
|
||||
self.run_panel.problems_button, expected_task_id=task_id)
|
||||
@@ -1230,13 +1496,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']} 个器件。")
|
||||
@@ -1465,8 +1739,10 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
owner = expected_task_id or self._active_quick_run_task_id
|
||||
label = button.text() if button is not None else '操作'
|
||||
self._dsh_blockers.watch(worker, label, owner or expected_task_id or self._task_id, operation_area)
|
||||
self.operation_state = OperationState.start(label, owner, operation_area)
|
||||
self._set_operator_message(self.operation_state.message)
|
||||
receipt_recovery = operation_area == 'batch_receipts'
|
||||
if not receipt_recovery:
|
||||
self.operation_state = OperationState.start(label, owner, operation_area)
|
||||
self._set_operator_message(self.operation_state.message)
|
||||
self.plan_panel._summary()
|
||||
operation_error = None
|
||||
def valid():
|
||||
@@ -1475,13 +1751,17 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
nonlocal operation_error
|
||||
if valid():
|
||||
try:
|
||||
self.operation_state = self.operation_state.finish()
|
||||
self._set_operator_message(self.operation_state.message)
|
||||
if self.operation_state.phase is OperationPhase.CANCELLED:
|
||||
return
|
||||
if not receipt_recovery:
|
||||
self.operation_state = self.operation_state.finish()
|
||||
self._set_operator_message(self.operation_state.message)
|
||||
if self.operation_state.phase is OperationPhase.CANCELLED:
|
||||
return
|
||||
callback(result)
|
||||
except Exception as error:
|
||||
operation_error = error
|
||||
if receipt_recovery:
|
||||
self.service._logging.logger.warning('batch_receipt_recovery_unavailable error=%s', type(error).__name__)
|
||||
return
|
||||
self._close_pending = False
|
||||
if execution:
|
||||
# A result renderer is part of the worker lifecycle.
|
||||
@@ -1496,6 +1776,9 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
operation_error = error
|
||||
if not isValid(self) or self._closed:
|
||||
return
|
||||
if receipt_recovery:
|
||||
self.service._logging.logger.warning('batch_receipt_recovery_unavailable error=%s', type(error).__name__)
|
||||
return
|
||||
self.operation_state = self.operation_state.finish(error)
|
||||
if self._close_saving or not (isinstance(error, TaskCenterError) and error.code == 'operation_cancelled'):
|
||||
self._close_pending = False
|
||||
|
||||
@@ -2,7 +2,10 @@
|
||||
from collections.abc import Callable, Iterable
|
||||
|
||||
from PySide6.QtCore import QAbstractTableModel, QModelIndex, Qt, Signal
|
||||
from PySide6.QtGui import QColor
|
||||
from PySide6.QtWidgets import QAbstractItemView, QHeaderView, QTableView
|
||||
from ..errors import TaskCenterError
|
||||
from ..rule_validation import validate_target_part_number
|
||||
|
||||
|
||||
class RuleTableModel(QAbstractTableModel):
|
||||
@@ -29,6 +32,16 @@ class RuleTableModel(QAbstractTableModel):
|
||||
if not index.isValid() or not 0 <= index.row() < len(self.rules):
|
||||
return None
|
||||
rule, column = self.rules[index.row()], index.column()
|
||||
if column == 1 and role in (Qt.ItemDataRole.BackgroundRole, Qt.ItemDataRole.ForegroundRole, Qt.ItemDataRole.ToolTipRole):
|
||||
try:
|
||||
if rule.enabled or rule.new_part_number.strip():
|
||||
validate_target_part_number(rule.new_part_number)
|
||||
except TaskCenterError as error:
|
||||
if role == Qt.ItemDataRole.BackgroundRole:
|
||||
return QColor('#fce8e6')
|
||||
if role == Qt.ItemDataRole.ForegroundRole:
|
||||
return QColor('#9c231b')
|
||||
return f'规则 {index.row() + 1}:{error.message}'
|
||||
if role == Qt.ItemDataRole.UserRole:
|
||||
return rule.rule_id
|
||||
if role == Qt.ItemDataRole.CheckStateRole and column == 4:
|
||||
|
||||
@@ -24,11 +24,11 @@ class ProblemItemsDialog(QDialog):
|
||||
self.table.setHorizontalHeaderLabels(headers)
|
||||
self.table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
|
||||
self.table.setAlternatingRowColors(True)
|
||||
states = {'failed': '失败', 'pending': '尚未执行', 'prepared': '待核验', 'uncertain': '待核验',
|
||||
states = {'failed': '失败', 'pending': '尚未执行', 'prepared': '待核验', 'pending_save': '保存待核验', 'uncertain': '待核验',
|
||||
'verified': '已解决', 'restored': '已解决', 'no_match': '已解决'}
|
||||
for index, row in enumerate(overview['items']):
|
||||
can_retry = allow_retry and row['can_retry']
|
||||
action = ('可勾选手动重试' if can_retry else '先核验并恢复' if row['state'] in {'prepared', 'uncertain'}
|
||||
action = ('可勾选手动重试' if can_retry else '先核验并恢复' if row['state'] in {'prepared', 'pending_save', 'uncertain'}
|
||||
else '继续原队列/工程级重试' if row['state'] in {'pending', 'failed'} else '无需操作')
|
||||
values = ('', states.get(row['state'], row['state']), row['project_path'],
|
||||
f"{row['schematic_name']} / {row['sheet_number']}", row['refdes'], row['uid'],
|
||||
|
||||
@@ -187,6 +187,7 @@ class ProjectPlanPanel(QWidget):
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground,True)
|
||||
self.window = window
|
||||
self.task_id = None
|
||||
self._source_rows = ()
|
||||
self._drafts = {}
|
||||
self._bom_batches = {}
|
||||
self._orphaned_bom_batches = {}
|
||||
@@ -325,17 +326,26 @@ class ProjectPlanPanel(QWidget):
|
||||
self._edit_feedback()
|
||||
|
||||
def bind_task(self, task_id, rows=None):
|
||||
self._restore_bom_report(self._report_scope(task_id))
|
||||
if self.task_id == task_id and self.table.dirty:
|
||||
if self.task_id == task_id and rows is not None:
|
||||
self._source_rows = tuple(rows)
|
||||
if self.task_id == task_id and (self.table.dirty or self.table.has_pending_editor()):
|
||||
self._restore_bom_report(self._report_scope(task_id))
|
||||
return
|
||||
if self.task_id != task_id:
|
||||
self.table.commit_editor()
|
||||
if self.task_id and self.table.dirty:
|
||||
self._drafts[self.task_id] = self.table.rows()
|
||||
self.task_id = task_id
|
||||
if rows is None:
|
||||
rows = self.window.service.target_plan(task_id) if task_id else ()
|
||||
rows = tuple(rows)
|
||||
reader = getattr(self.window.service, 'pending_bom', None)
|
||||
self._pending_bom = reader(task_id) if task_id and reader else ()
|
||||
self._retained_bom = retained_bom_rows(self._pending_bom, rows) if self._pending_bom else ()
|
||||
pending_bom = reader(task_id) if task_id and reader else ()
|
||||
retained = retained_bom_rows(pending_bom, rows) if pending_bom else ()
|
||||
# Publish the binding only after all service reads succeeded.
|
||||
self.task_id = task_id
|
||||
self._source_rows = rows
|
||||
self._pending_bom, self._retained_bom = pending_bom, retained
|
||||
self._restore_bom_report(self._report_scope(task_id))
|
||||
self.pending_table.setRowCount(len(self._pending_bom) + len(self._retained_bom))
|
||||
for index, request in enumerate(self._pending_bom):
|
||||
record = request.record
|
||||
@@ -431,7 +441,7 @@ class ProjectPlanPanel(QWidget):
|
||||
|
||||
def prepare_save_all(self, task_ids=None):
|
||||
# Snapshot widgets only on the GUI thread; the returned operation uses plain data.
|
||||
if self.table.has_pending_editor():self.table.setFocus(Qt.FocusReason.ShortcutFocusReason)
|
||||
self.table.commit_editor()
|
||||
drafts = dict(self._drafts)
|
||||
if self.task_id and self.table.dirty:
|
||||
drafts[self.task_id] = self.table.rows()
|
||||
@@ -455,7 +465,7 @@ class ProjectPlanPanel(QWidget):
|
||||
return self.window.service.save_plan_drafts(pending_batches, standalone)
|
||||
|
||||
def forget_task(self, task_id):
|
||||
"""A confirmed permanent deletion is the only removal that discards its draft."""
|
||||
"""Release a removed task after its drafts have been resolved."""
|
||||
self._drafts.pop(task_id, None)
|
||||
self._bom_imports.pop(self._report_scope(task_id), None)
|
||||
self._restore_bom_report(self._report_scope(self.task_id))
|
||||
@@ -473,7 +483,9 @@ class ProjectPlanPanel(QWidget):
|
||||
scope=scope, projects=projects)
|
||||
self._bom_batches = batches
|
||||
if self.task_id == task_id:
|
||||
self.table.cancel_editor()
|
||||
self.task_id = None
|
||||
self._source_rows = ()
|
||||
self.table.populate(())
|
||||
|
||||
def discard_all(self):
|
||||
@@ -481,8 +493,16 @@ class ProjectPlanPanel(QWidget):
|
||||
self._drafts.clear()
|
||||
self._bom_batches.clear()
|
||||
self._orphaned_bom_batches.clear()
|
||||
self.table.dirty = False
|
||||
self.table.populate(self._source_rows)
|
||||
self._release_bom_previews()
|
||||
self._summary()
|
||||
|
||||
def accept_saved_plans(self, saved):
|
||||
if saved and self.task_id in saved:
|
||||
self._source_rows = tuple(saved[self.task_id])
|
||||
if saved:
|
||||
self._release_bom_previews(saved)
|
||||
self.discard_all()
|
||||
|
||||
def _release_bom_previews(self, saved=None):
|
||||
for machine in self._bom_imports.values():
|
||||
@@ -618,7 +638,7 @@ class ProjectPlanPanel(QWidget):
|
||||
f'原计划保留 {retained} 个,合计 {count + retained} 个;确认执行后仅核验当前工程。')
|
||||
return
|
||||
if batch:
|
||||
self.summary.setText(f'本批 BOM 已匹配 {len(batch.projects)} 个工程;表格显示当前工程,切换任务可编辑,'
|
||||
self.summary.setText(f'本批 BOM 已匹配 {len(batch.projects)} 个工程;表格显示当前工程,'
|
||||
'确认后一次保存本批位号计划。')
|
||||
return
|
||||
if not count:
|
||||
@@ -678,12 +698,18 @@ class ProjectPlanPanel(QWidget):
|
||||
def _saved(self, rows):
|
||||
self._clear_bom_notice()
|
||||
self._drafts.pop(self.task_id, None)
|
||||
self._source_rows = tuple(rows)
|
||||
self.table.populate(rows)
|
||||
self.window._load_task_data()
|
||||
self._summary()
|
||||
|
||||
def save(self):
|
||||
if not self.task_id:
|
||||
if not self.task_id or not self._editable:
|
||||
return
|
||||
try:
|
||||
self.table.commit_editor()
|
||||
except Exception as error:
|
||||
self.window._show_error(error, auto_intervene=False)
|
||||
return
|
||||
batch = self._active_bom_batch()
|
||||
if batch:
|
||||
@@ -787,21 +813,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 ""}'
|
||||
@@ -837,7 +864,10 @@ class ProjectPlanPanel(QWidget):
|
||||
self.window._set_operator_message(summary, 'error' if report.preview is None and not report.deferred else 'info')
|
||||
self._restore_bom_report(scope)
|
||||
if report.preview is not None:
|
||||
self._preview_bom(report.preview)
|
||||
staged = self._preview_bom(report.preview)
|
||||
machine.state = replace(machine.state, notice='' if staged else
|
||||
'本次预览未暂存,原有预览和编辑保留;请恢复可编辑状态后重新导入。')
|
||||
self._restore_bom_report(self._report_scope(self.task_id))
|
||||
elif report.deferred:
|
||||
self.bind_task(self.task_id)
|
||||
self.window._load_task_data()
|
||||
@@ -900,12 +930,18 @@ class ProjectPlanPanel(QWidget):
|
||||
if machine is None or machine.state.busy:
|
||||
return
|
||||
preview = select_passed_projects(machine.state.report, task_ids)
|
||||
self._preview_bom(preview)
|
||||
if not self._preview_bom(preview):
|
||||
return
|
||||
machine.state = replace(machine.state, report=replace(machine.state.report, passed_preview=preview),
|
||||
notice=f'已明确选择 {len(preview.projects)} 个通过工程,待保存原预览行。')
|
||||
self._restore_bom_report(self._report_scope(self.task_id))
|
||||
|
||||
def _preview_bom(self, batch):
|
||||
try:
|
||||
self.table.commit_editor()
|
||||
except Exception as error:
|
||||
self.window._show_error(error, auto_intervene=False)
|
||||
return False
|
||||
if self.task_id and self.table.dirty:
|
||||
self._drafts[self.task_id] = self.table.rows()
|
||||
key = tuple(task_id for task_id, _ in batch.scope)
|
||||
@@ -942,6 +978,7 @@ class ProjectPlanPanel(QWidget):
|
||||
self.table.populate(self._drafts[self.task_id])
|
||||
self.table.dirty = True
|
||||
self._changed()
|
||||
return True
|
||||
|
||||
def _saved_bom_batch(self, saved):
|
||||
self._clear_bom_notice()
|
||||
@@ -952,6 +989,7 @@ class ProjectPlanPanel(QWidget):
|
||||
self._bom_batches = {key: batch for key, batch in self._bom_batches.items()
|
||||
if not all(project.task_id in saved for project in batch.projects)}
|
||||
if self.task_id in saved:
|
||||
self._source_rows = tuple(saved[self.task_id])
|
||||
self.table.populate(saved[self.task_id])
|
||||
self.window._load_task_data()
|
||||
self._summary()
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
"""Explicit single-task execution, recovery and safe pause controls."""
|
||||
from PySide6.QtCore import Signal,Qt
|
||||
from PySide6.QtWidgets import (QCheckBox, QHBoxLayout, QLabel, QProgressBar,
|
||||
from PySide6.QtGui import QKeySequence
|
||||
from PySide6.QtWidgets import (QCheckBox, QDialog, QDialogButtonBox, QHBoxLayout, QLabel, QProgressBar,
|
||||
QPushButton, QToolButton, QVBoxLayout, QWidget)
|
||||
|
||||
from .detail_windows import TaskLogDialog
|
||||
from .command_menu import CommandMenu
|
||||
from .icons import icon
|
||||
from .accessibility import apply_accessible_names
|
||||
|
||||
|
||||
class RunPanel(QWidget):
|
||||
@@ -36,7 +38,7 @@ class RunPanel(QWidget):
|
||||
self.cleanup_resources_button = QPushButton('重新清理资源', objectName='cleanupBatchResources')
|
||||
self.cleanup_resources_button.setToolTip('只释放本程序拥有的后台资源,不执行工程替换。')
|
||||
self.diagnostics_button = QPushButton('导出诊断包', objectName='exportDiagnosticBundle')
|
||||
self.diagnostics_button.setToolTip('导出脱敏日志与资源记录,不包含工程、中心库、BOM 或任务数据库。')
|
||||
self.diagnostics_button.setToolTip('导出时过滤凭据和用户名,仍含工程路径、任务标识及执行日志;不包含工程文件、中心库、BOM 或任务数据库。')
|
||||
self.new_round_button = QPushButton('开始新一轮', objectName='startNewRoundButton')
|
||||
self.history_button = QPushButton('查看轮次证据', objectName='roundHistoryButton')
|
||||
self.copy_value_check = QCheckBox('Value 策略:替换后将 Part Label 写入 Value(逐行自定义优先)', objectName='copyPartNumberToValue')
|
||||
@@ -46,14 +48,19 @@ class RunPanel(QWidget):
|
||||
self.toggle_log_button.setCheckable(True)
|
||||
self.reset_layout_button = QToolButton(objectName='resetLayoutButton')
|
||||
self.reset_layout_button.setText('重置布局')
|
||||
self.shortcut_help_button = QPushButton('快捷键说明', objectName='shortcutHelp')
|
||||
self.shortcut_help_button.setEnabled(False)
|
||||
self.shortcut_help_button.clicked.connect(self._show_shortcuts)
|
||||
self._shortcut_entries = ()
|
||||
self.shortcut_dialog = None
|
||||
self.log_dialog = None
|
||||
self.toggle_log_button.toggled.connect(self._toggle_log)
|
||||
self.more_menu=CommandMenu(self)
|
||||
for button in (self.problems_button,self.diagnostics_button,self.cleanup_resources_button,self.history_button,self.reset_layout_button):
|
||||
for button in (self.problems_button,self.diagnostics_button,self.cleanup_resources_button,self.history_button,self.reset_layout_button,self.shortcut_help_button):
|
||||
self.more_menu.add_button(button)
|
||||
self.more_button=QToolButton(objectName='executionMoreMenu')
|
||||
self.more_button.setText('更多操作')
|
||||
self.more_button.setToolTip('诊断、资源清理、轮次证据与布局')
|
||||
self.more_button.setToolTip('诊断、资源清理、轮次证据、布局与快捷键说明')
|
||||
self.more_button.setIcon(icon('more'))
|
||||
self.more_button.setMenu(self.more_menu)
|
||||
self.more_button.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup)
|
||||
@@ -75,11 +82,35 @@ class RunPanel(QWidget):
|
||||
layout.addWidget(self.busy_indicator)
|
||||
layout.addLayout(buttons)
|
||||
|
||||
def set_shortcut_help(self, entries):
|
||||
self._shortcut_entries = tuple(entries)
|
||||
self.shortcut_help_button.setEnabled(bool(self._shortcut_entries))
|
||||
|
||||
def _show_shortcuts(self):
|
||||
if self.shortcut_dialog is None:
|
||||
self.shortcut_dialog = QDialog(self, objectName='shortcutHelpDialog')
|
||||
self.shortcut_dialog.setWindowTitle('快捷键说明')
|
||||
layout = QVBoxLayout(self.shortcut_dialog)
|
||||
self._shortcut_text = QLabel()
|
||||
self._shortcut_text.setTextFormat(Qt.TextFormat.PlainText)
|
||||
self._shortcut_text.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
|
||||
layout.addWidget(self._shortcut_text)
|
||||
buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Close)
|
||||
buttons.rejected.connect(self.shortcut_dialog.close)
|
||||
layout.addWidget(buttons)
|
||||
self._shortcut_text.setText('\n\n'.join(
|
||||
f'{action.shortcut().toString(QKeySequence.SequenceFormat.NativeText)} · {description}'
|
||||
for action, description in self._shortcut_entries if not action.shortcut().isEmpty()))
|
||||
self.shortcut_dialog.show()
|
||||
self.shortcut_dialog.raise_()
|
||||
self.shortcut_dialog.activateWindow()
|
||||
|
||||
def _toggle_log(self, visible):
|
||||
self.toggle_log_button.setText('收起结果' if visible else '替换结果 / 日志')
|
||||
if visible:
|
||||
if self.log_dialog is None:
|
||||
dialog = TaskLogDialog(self)
|
||||
apply_accessible_names(dialog)
|
||||
self.log_dialog = dialog
|
||||
dialog.finished.connect(lambda _: self._log_finished(dialog))
|
||||
self.log_created.emit(dialog)
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Window shortcut additions and one description of existing command scopes."""
|
||||
from PySide6.QtGui import QAction
|
||||
|
||||
|
||||
def install_window_shortcuts(window):
|
||||
refresh = window.project_summary.refresh_button
|
||||
window.refresh_shortcut = QAction('重新读取当前工程', window)
|
||||
window.refresh_shortcut.setShortcut('F5')
|
||||
window.refresh_shortcut.triggered.connect(lambda: refresh.click()
|
||||
if refresh.isEnabled() and not refresh.isHidden() else None)
|
||||
window.addAction(window.refresh_shortcut)
|
||||
refresh.setProperty('shortcutLabel', 'F5')
|
||||
plan = window.plan_panel
|
||||
plan.find_button.setProperty('shortcutLabel', 'Ctrl+F')
|
||||
plan.find_next_button.setProperty('shortcutLabel', 'F3')
|
||||
plan.save_button.setProperty('shortcutLabel', 'Ctrl+S')
|
||||
entries = [
|
||||
(window.task_list.edit_shortcut, '编辑当前任务(焦点在任务导航内)'),
|
||||
(window.refresh_shortcut, '重新读取当前工程(遵守工程操作门禁)'),
|
||||
(plan.find_shortcut, '定位搜索框(焦点在位号计划内)'),
|
||||
(plan.save_shortcut, '保存当前范围(焦点在位号计划内)'),
|
||||
(plan.next_shortcut, '下一条匹配(焦点在位号计划内)'),
|
||||
]
|
||||
for name in ('dsh_action', 'history_action'):
|
||||
action = getattr(window, name, None)
|
||||
if action is not None:
|
||||
entries.append((action, action.text()))
|
||||
window.run_panel.set_shortcut_help(entries)
|
||||
@@ -1,7 +1,11 @@
|
||||
"""Model-based editable target plan; filtering never changes saved identities."""
|
||||
from dataclasses import replace
|
||||
from PySide6.QtGui import QColor
|
||||
from PySide6.QtCore import QAbstractTableModel, QModelIndex, QSortFilterProxyModel, Qt, Signal,QPersistentModelIndex
|
||||
from PySide6.QtWidgets import QAbstractItemView, QHeaderView, QTableView,QLabel,QStyledItemDelegate,QLineEdit,QAbstractItemDelegate,QComboBox
|
||||
from shiboken6 import isValid
|
||||
from ..errors import TaskCenterError
|
||||
from ..rule_validation import validate_target_part_number
|
||||
|
||||
HEADERS = ('替换', '原理图', '图页', '位号', '旧料号', '原 Value', '新料号', '自定义 Value', '自定义内容', '同步 NC', 'Value 来源')
|
||||
CHECK_FIELDS = {0: 'enabled', 7: 'custom_value_enabled', 9: 'sync_nc'}
|
||||
@@ -48,6 +52,16 @@ class TargetPlanModel(QAbstractTableModel):
|
||||
row = self.rows[index.row()]
|
||||
t = row.target
|
||||
col = index.column()
|
||||
if col == 6 and role in (Qt.ItemDataRole.BackgroundRole, Qt.ItemDataRole.ForegroundRole, Qt.ItemDataRole.ToolTipRole):
|
||||
try:
|
||||
if row.enabled or row.new_part_number.strip():
|
||||
validate_target_part_number(row.new_part_number)
|
||||
except TaskCenterError as error:
|
||||
if role == Qt.ItemDataRole.BackgroundRole:
|
||||
return QColor('#fce8e6')
|
||||
if role == Qt.ItemDataRole.ForegroundRole:
|
||||
return QColor('#9c231b')
|
||||
return f'{error.message}\n{t.schematic_name}:{t.sheet_number} | {t.refdes} | UID {t.uid}'
|
||||
if role == Qt.ItemDataRole.CheckStateRole and col in CHECK_FIELDS:
|
||||
return Qt.CheckState.Checked if getattr(row, CHECK_FIELDS[col]) else Qt.CheckState.Unchecked
|
||||
if role in (Qt.ItemDataRole.DisplayRole, Qt.ItemDataRole.EditRole):
|
||||
@@ -92,11 +106,14 @@ class TargetPlanModel(QAbstractTableModel):
|
||||
self.enabled_count += int(updated.enabled) - int(self.rows[number].enabled)
|
||||
self.rows[number] = updated
|
||||
self.search_text[number] = self.searchable(updated)
|
||||
roles = [role, Qt.ItemDataRole.DisplayRole]
|
||||
roles = [role, Qt.ItemDataRole.DisplayRole, Qt.ItemDataRole.BackgroundRole,
|
||||
Qt.ItemDataRole.ForegroundRole, Qt.ItemDataRole.ToolTipRole]
|
||||
if 'custom_value_enabled' in change:
|
||||
roles.append(Qt.ItemDataRole.CheckStateRole)
|
||||
first, last = (self.index(number, 7), self.index(number, VALUE_MODE_COLUMN)) if 'value_mode' in change else (index, index)
|
||||
self.dataChanged.emit(first, last, roles)
|
||||
if col == 0:
|
||||
self.dataChanged.emit(self.index(number, 6), self.index(number, 6), roles)
|
||||
self.changed.emit()
|
||||
return True
|
||||
|
||||
@@ -121,11 +138,14 @@ class TargetPlanModel(QAbstractTableModel):
|
||||
self.search_text[number] = self.searchable(updated)
|
||||
changed.append(number)
|
||||
if changed:
|
||||
roles = [role, Qt.ItemDataRole.DisplayRole]
|
||||
roles = [role, Qt.ItemDataRole.DisplayRole, Qt.ItemDataRole.BackgroundRole,
|
||||
Qt.ItemDataRole.ForegroundRole, Qt.ItemDataRole.ToolTipRole]
|
||||
if field in {'value_mode', 'custom_value_enabled'}:
|
||||
roles.append(Qt.ItemDataRole.CheckStateRole)
|
||||
first_col, last_col = (7, VALUE_MODE_COLUMN) if field in {'value_mode', 'custom_value_enabled'} else (column, column)
|
||||
self.dataChanged.emit(self.index(min(changed), first_col), self.index(max(changed), last_col), roles)
|
||||
if column == 0:
|
||||
self.dataChanged.emit(self.index(min(changed), 6), self.index(max(changed), 6), roles)
|
||||
self.changed.emit()
|
||||
|
||||
class TargetFilter(QSortFilterProxyModel):
|
||||
@@ -142,6 +162,7 @@ class PlanEditorDelegate(QStyledItemDelegate):
|
||||
def createEditor(self,parent,option,index):
|
||||
if index.column() == VALUE_MODE_COLUMN:
|
||||
editor = QComboBox(parent)
|
||||
editor.setAccessibleName('Value 来源')
|
||||
editor.addItems(VALUE_MODES)
|
||||
view = self.parent()
|
||||
view._active_editor = (editor, QPersistentModelIndex(index))
|
||||
@@ -149,6 +170,9 @@ class PlanEditorDelegate(QStyledItemDelegate):
|
||||
return editor
|
||||
editor=super().createEditor(parent,option,index)
|
||||
if isinstance(editor,QLineEdit):
|
||||
editor.setAccessibleName(HEADERS[index.column()])
|
||||
if index.column() == 6:
|
||||
editor.setAccessibleDescription('输入新料号;错误会在单元格中提示,修正后保存计划。')
|
||||
view=self.parent()
|
||||
view._active_editor=(editor,QPersistentModelIndex(index))
|
||||
editor.textChanged.connect(lambda _:view.editor_activity.emit())
|
||||
@@ -217,11 +241,37 @@ class TargetTable(QTableView):
|
||||
def has_pending_editor(self):
|
||||
if not self._active_editor:return False
|
||||
editor,index=self._active_editor
|
||||
if not isValid(editor):
|
||||
self._active_editor = None
|
||||
return False
|
||||
value = editor.currentText() if isinstance(editor, QComboBox) else editor.text()
|
||||
return index.isValid()and editor.isVisible()and value!=str(index.data(Qt.ItemDataRole.EditRole)or'')
|
||||
def commit_editor(self):
|
||||
"""Capture active text before saving or moving to another task."""
|
||||
if self._active_editor:
|
||||
editor, index = self._active_editor
|
||||
if not isValid(editor):
|
||||
self._active_editor = None
|
||||
return True
|
||||
if not index.isValid():
|
||||
self.cancel_editor()
|
||||
return True
|
||||
if index.isValid():
|
||||
value = editor.currentText() if isinstance(editor, QComboBox) else editor.text()
|
||||
if (value.strip() != str(index.data(Qt.ItemDataRole.EditRole) or '')
|
||||
and not self.model().setData(QModelIndex(index), value, Qt.ItemDataRole.EditRole)):
|
||||
raise TaskCenterError('editor_commit', '当前编辑内容未能写入计划;请恢复可编辑状态后重试。')
|
||||
self._active_editor = None
|
||||
self.itemDelegate().closeEditor.emit(editor, QAbstractItemDelegate.EndEditHint.NoHint)
|
||||
self.editor_activity.emit()
|
||||
return True
|
||||
def cancel_editor(self):
|
||||
if self._active_editor:
|
||||
self.itemDelegate().closeEditor.emit(self._active_editor[0],QAbstractItemDelegate.EndEditHint.RevertModelCache)
|
||||
editor = self._active_editor[0]
|
||||
self._active_editor = None
|
||||
if isValid(editor):
|
||||
self.itemDelegate().closeEditor.emit(editor,QAbstractItemDelegate.EndEditHint.RevertModelCache)
|
||||
self.editor_activity.emit()
|
||||
def rowCount(self):
|
||||
return self.proxy.rowCount()
|
||||
|
||||
|
||||
@@ -6,8 +6,8 @@ from collections.abc import Callable
|
||||
import re
|
||||
from typing import Iterable
|
||||
|
||||
from PySide6.QtCore import Qt, QSignalBlocker, Signal, QSize, QRect
|
||||
from PySide6.QtGui import QColor,QFont,QIcon,QPalette
|
||||
from PySide6.QtCore import Qt, QSignalBlocker, Signal, QSize, QRect, QItemSelectionModel
|
||||
from PySide6.QtGui import QAction,QColor,QFont,QIcon,QPalette
|
||||
from PySide6.QtWidgets import (QAbstractItemView,QComboBox,QHBoxLayout,QLabel,QLineEdit,QListWidget,
|
||||
QListWidgetItem,QPushButton,QVBoxLayout,QWidget,QToolButton,QMenu,
|
||||
QStyledItemDelegate,QStyleOptionViewItem,QStyle,QApplication)
|
||||
@@ -66,10 +66,13 @@ class TaskList(QWidget):
|
||||
self._on_open = on_open
|
||||
self._tasks = ()
|
||||
self._selected_task_id = None
|
||||
self._selection_cleared = False
|
||||
from .icons import icon
|
||||
self._project_icon = icon('project')
|
||||
self.search = QLineEdit(objectName='taskSearch')
|
||||
self.search.setPlaceholderText('搜索任务名称、目录、备注')
|
||||
selection_hint = '筛选仅保留可见任务的选择;清空筛选不恢复隐藏项的选择,请重新勾选。'
|
||||
self.search.setToolTip(selection_hint)
|
||||
self.search.setClearButtonEnabled(True)
|
||||
self.sort = QComboBox(objectName='taskSort')
|
||||
for label, key in (('执行顺序', 'execution'), ('名称 ↑', 'name_asc'), ('名称 ↓', 'name_desc'),
|
||||
@@ -79,6 +82,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'),
|
||||
@@ -87,7 +94,7 @@ class TaskList(QWidget):
|
||||
('失败 / 待重试', 'failed', 'warning')):
|
||||
self.filter.addItem(icon(picture), label, key)
|
||||
self.filter.setAccessibleName('任务状态分类')
|
||||
self.filter.setToolTip('待开始包括待配置和待执行;失败包括已收尾的待重试任务。未完成包括所有尚未完成的任务;分类只筛选显示。')
|
||||
self.filter.setToolTip('待开始包括待配置和待执行;失败包括已收尾的待重试任务。未完成包括所有尚未完成的任务;分类只筛选显示。\n' + selection_hint)
|
||||
self.list = QListWidget(objectName="taskList")
|
||||
self.list.setItemDelegate(TaskItemDelegate(self.list))
|
||||
self.list.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection)
|
||||
@@ -97,10 +104,21 @@ class TaskList(QWidget):
|
||||
self.select_all_button = QPushButton('全选', objectName='selectAllTasks')
|
||||
self.clear_selection_button = QPushButton('清空选择', objectName='clearTaskSelection')
|
||||
self.edit_button = QPushButton("编辑", objectName="editTaskButton")
|
||||
self.edit_shortcut = QAction('编辑任务', self)
|
||||
self.edit_shortcut.setShortcut('F2')
|
||||
self.edit_shortcut.setShortcutContext(Qt.ShortcutContext.WidgetWithChildrenShortcut)
|
||||
self.edit_shortcut.triggered.connect(lambda: self.edit_button.click()
|
||||
if self.edit_button.isEnabled() and not self.edit_button.isHidden() else None)
|
||||
self.addAction(self.edit_shortcut)
|
||||
self.edit_button.setProperty('shortcutLabel', 'F2')
|
||||
self.delete_button = QPushButton("删除", objectName="deleteTaskButton")
|
||||
self.archive_button = QPushButton('归档当前已完成任务', objectName='archiveCompletedTask')
|
||||
self.archive_button.setToolTip('保留原计划、工程和执行证据,移至回收站;待核验作业和未释放资源仍会阻止归档。')
|
||||
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('仅处理列表中可见且明确选中的同批任务,仍按保存的执行顺序;执行前列出逐任务裁决。\n' + selection_hint)
|
||||
self.up_button = QPushButton("上移任务", objectName="moveTaskUp")
|
||||
self.down_button = QPushButton("下移任务", objectName="moveTaskDown")
|
||||
self.new_button.setProperty('appearance','quiet')
|
||||
@@ -112,6 +130,7 @@ class TaskList(QWidget):
|
||||
for button in (self.edit_button,self.restore_button,self.up_button,self.down_button):
|
||||
self.manage_menu.add_button(button)
|
||||
self.manage_menu.addSeparator()
|
||||
self.manage_menu.add_button(self.archive_button)
|
||||
self.manage_menu.add_button(self.delete_button)
|
||||
self.manage_button=QToolButton(objectName='taskManageMenu')
|
||||
self.manage_button.setText('任务管理')
|
||||
@@ -146,10 +165,13 @@ 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():
|
||||
self._selection_cleared = not bool(self.list.selectedItems())
|
||||
task_id = self.current_task_id()
|
||||
if task_id != self._selected_task_id:
|
||||
self._selected_task_id = task_id
|
||||
@@ -166,9 +188,14 @@ 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()}
|
||||
if selected_task_id not in (None, self._selected_task_id):
|
||||
self._selection_cleared = False
|
||||
self._selected_task_id = selected_task_id or self.current_task_id() or self._selected_task_id
|
||||
self._tasks = tuple(tasks)
|
||||
self._render()
|
||||
@@ -182,14 +209,15 @@ class TaskList(QWidget):
|
||||
def select_task(self, task_id: str) -> None:
|
||||
if task_id != self._selected_task_id:
|
||||
self._selected_task_id = task_id
|
||||
self._selection_cleared = False
|
||||
self._render()
|
||||
|
||||
def select_all_tasks(self) -> None:
|
||||
if not self.list.count():
|
||||
return
|
||||
self.list.selectAll()
|
||||
if self.list.currentItem() is None:
|
||||
self.list.setCurrentRow(0)
|
||||
self.list.setCurrentRow(0, QItemSelectionModel.SelectionFlag.NoUpdate)
|
||||
self.list.selectAll()
|
||||
self._update_selection_state()
|
||||
|
||||
def clear_task_selection(self) -> None:
|
||||
@@ -199,22 +227,27 @@ class TaskList(QWidget):
|
||||
for row in range(self.list.count()):
|
||||
self.list.item(row).setSelected(False)
|
||||
self._selected_task_id = None
|
||||
self._selection_cleared = True
|
||||
self._on_open('')
|
||||
self._update_selection_state()
|
||||
self.view_changed.emit()
|
||||
|
||||
def _update_selection_state(self) -> None:
|
||||
selected = len(self.list.selectedItems())
|
||||
total = self.list.count()
|
||||
suffix = f' · 已选 {selected}' if selected else ''
|
||||
current = self.count.text()
|
||||
if ' · 已选 ' in current:
|
||||
current = current.split(' · 已选 ', 1)[0]
|
||||
if current:
|
||||
self.count.setText(current + suffix)
|
||||
self.view_changed.emit()
|
||||
|
||||
def _render(self):
|
||||
selected = self._selected_task_id
|
||||
selected_ids = set(self.selected_task_ids())
|
||||
current = self.current_task_id()
|
||||
if (current is not None and selected != current) or (not selected_ids and not self._selection_cleared):
|
||||
selected_ids = {selected} if selected else set()
|
||||
query = self.search.text().strip().casefold().replace('\\', '/')
|
||||
tasks = [task for task in self._tasks if query in ' '.join(str(getattr(task, name, '') or '')
|
||||
for name in ('name', 'discovery_root', 'note')).casefold().replace('\\', '/')]
|
||||
@@ -252,8 +285,22 @@ class TaskList(QWidget):
|
||||
item.setToolTip(f'{task.name}\n{task.discovery_root or ""}\n{task.note}'.strip())
|
||||
self.list.addItem(item)
|
||||
if getattr(task, "task_id") == selected:
|
||||
self.list.setCurrentItem(item)
|
||||
self.list.setCurrentItem(item, QItemSelectionModel.SelectionFlag.NoUpdate)
|
||||
item.setSelected(str(getattr(task, 'task_id')) in selected_ids)
|
||||
if selected_ids and not self.selected_task_ids():
|
||||
self._selection_cleared = True
|
||||
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()
|
||||
@@ -4,6 +4,7 @@ from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import queue
|
||||
@@ -118,8 +119,8 @@ def cleanup_retained_workers(root, *, force=False):
|
||||
|
||||
class ProgressWatch:
|
||||
def __init__(self, token: str, job_id: str, idle_timeout: float, started: float) -> None:
|
||||
if idle_timeout <= 0:
|
||||
raise ValueError('Idle timeout must be positive')
|
||||
if type(idle_timeout) not in (int, float) or not 0 < idle_timeout < math.inf:
|
||||
raise ValueError('Idle timeout must be finite and positive')
|
||||
self.token = token
|
||||
self.job_id = job_id
|
||||
self.current_job_id = job_id
|
||||
@@ -127,9 +128,13 @@ class ProgressWatch:
|
||||
self.last_progress = started
|
||||
self.last_business_progress = started
|
||||
self.sequence = 0
|
||||
self.business_sequence = 0
|
||||
self.business_done = 0
|
||||
self.native_sequence = 0
|
||||
self.native_business_done = 0
|
||||
self.native_progress_frames = 0
|
||||
self.stop_requested = False
|
||||
self.stopping_reason = ''
|
||||
self.stage = 'starting'
|
||||
self.done = 0
|
||||
self.total = 0
|
||||
@@ -155,8 +160,10 @@ 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)):
|
||||
boundary = (current_job, fields[4]) != (self.current_job_id, self.stage)
|
||||
if boundary or done > self.business_done:
|
||||
self.business_sequence += 1
|
||||
self.business_done = done
|
||||
self.last_business_progress = now
|
||||
self.waiting_for_safe_completion = False
|
||||
if current_job != self.current_job_id:
|
||||
@@ -170,6 +177,7 @@ class ProgressWatch:
|
||||
self.stage_started = now
|
||||
self.sequence = sequence
|
||||
self.native_sequence = 0
|
||||
self.native_business_done = done
|
||||
self.last_progress = now
|
||||
self.stage, self.done, self.total, self.safe_stop = fields[4], done, total, bool(safe)
|
||||
self.unsafe_seen = self.unsafe_seen or not bool(safe)
|
||||
@@ -199,7 +207,9 @@ 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.native_business_done:
|
||||
self.business_sequence += 1
|
||||
self.native_business_done = done
|
||||
self.last_business_progress = now
|
||||
self.waiting_for_safe_completion = False
|
||||
self.done, self.total = done, total
|
||||
@@ -210,6 +220,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
|
||||
@@ -228,10 +239,14 @@ class ProgressWatch:
|
||||
stages = dict(self.stage_seconds)
|
||||
stages[self.stage] = stages.get(self.stage, 0.0) + max(0.0, now - self.stage_started)
|
||||
return {name: getattr(self, name) for name in ('token', 'sequence', 'stage', 'done', 'total', 'safe_stop', 'stop_requested', 'waiting_for_safe_completion')} | {
|
||||
'business_sequence': self.business_sequence,
|
||||
'job_id': self.current_job_id,
|
||||
'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}
|
||||
|
||||
|
||||
@@ -446,6 +461,7 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
stop_warning = ''
|
||||
|
||||
try:
|
||||
_publish_progress(progress_path, watch.snapshot())
|
||||
if process_factory is None:
|
||||
process = subprocess.Popen((*command, token), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
@@ -458,7 +474,6 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
thread = threading.Thread(target=read_stream, args=(stream, channel), daemon=True)
|
||||
thread.start()
|
||||
threads.append(thread)
|
||||
_publish_progress(progress_path, watch.snapshot())
|
||||
_atomic_text(ready, token)
|
||||
while process.poll() is None:
|
||||
if cooperative_abort and owner_loss_path is not None and Path(owner_loss_path).is_file():
|
||||
@@ -468,6 +483,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 +517,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 >=
|
||||
@@ -580,6 +600,12 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
if key not in {'request_bytes', 'marker_bytes'}} | {'worker_tree_exited': True}
|
||||
return result
|
||||
except Exception as error:
|
||||
if process is None:
|
||||
try:
|
||||
if json.loads(progress_path.read_bytes()).get('token') == token:
|
||||
progress_path.unlink()
|
||||
except (OSError, ValueError, AttributeError):
|
||||
pass # Telemetry cleanup must preserve the original launch failure.
|
||||
if process is not None:
|
||||
if (not cooperative_abort and not durable_force_accepted
|
||||
and (not watch.safe_stop or process.poll() is not None)
|
||||
|
||||
@@ -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,151 @@ 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 hashlib import sha256
|
||||
from dx_productivity.dsh.execution_runs import _republish_incident_batch_summary
|
||||
from dx_productivity.trial_task_center.batch_resources import write_record
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
from dx_productivity.trial_task_center.supervisor_protocol import VERSION, encode
|
||||
|
||||
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']()
|
||||
directory = root / 'batch-resources' / batch_id
|
||||
request = directory / 'request.json'
|
||||
header = {'version': VERSION, 'batch_id': batch_id, 'attempt_id': '5' * 32,
|
||||
'operation': 'execute_quick_run_queue', 'task_ids': [item]}
|
||||
write_record(request, dict(header, root=str(root),
|
||||
arguments=encode({'task_id': item, 'expected_item': controls['expected_item']})))
|
||||
write_record(directory / 'supervisor.json', dict(header, state='starting',
|
||||
request_sha256=sha256(request.read_bytes()).hexdigest(),
|
||||
parent_process={'pid': 1, 'creation_time': 'test'}))
|
||||
controls['before_launch'](batch_id)
|
||||
dispatched.append(item)
|
||||
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()
|
||||
|
||||
@@ -0,0 +1,394 @@
|
||||
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 _record_verified_round(child):
|
||||
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, '{}'))
|
||||
return {TASK_ID: 'round'}
|
||||
|
||||
|
||||
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]
|
||||
round_ids = _record_verified_round(child)
|
||||
result = TaskQueueResult(RUN_ID, (TaskQueueEntry(TASK_ID, 'completed'),), False,
|
||||
netlist_verification={TASK_ID: {'status': 'verified', 'verified': True}})
|
||||
batch_resources.write_record(data / 'task-queues' / (RUN_ID + '.json'),
|
||||
{'task_ids': [TASK_ID], 'plan_hashes': PLAN_HASHES, 'manifest_digest': 'd' * 64,
|
||||
'round_ids': round_ids, 'entries': {TASK_ID: {'state': 'completed', 'message': ''}}})
|
||||
_durable_supervisor_result(data, result)
|
||||
path = data / 'batch-resources' / BATCH_ID / 'session.json'
|
||||
record = json.loads(path.read_bytes())
|
||||
batch_resources.write_record(path, dict(record, state=resource_state))
|
||||
return result
|
||||
|
||||
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, child, data, _, admission = batch
|
||||
checkpoint = {'task_ids': [TASK_ID], 'plan_hashes': PLAN_HASHES, 'manifest_digest': 'd' * 64,
|
||||
'round_ids': _record_verified_round(child),
|
||||
'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, child, 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}})
|
||||
batch_resources.write_record(data / 'task-queues' / (RUN_ID + '.json'),
|
||||
{'task_ids': [TASK_ID], 'plan_hashes': PLAN_HASHES, 'manifest_digest': 'd' * 64,
|
||||
'round_ids': _record_verified_round(child),
|
||||
'entries': {TASK_ID: {'state': 'completed', 'message': 'saved'}}})
|
||||
_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'))
|
||||
batch_resources.write_record(data / 'task-queues' / (RUN_ID + '.json'),
|
||||
{'task_ids': [TASK_ID], 'plan_hashes': PLAN_HASHES, 'manifest_digest': 'd' * 64,
|
||||
'round_ids': {TASK_ID: 'r'}, 'entries': {TASK_ID: {'state': 'failed', 'message': 'Native lookup report'}}})
|
||||
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, child, 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,
|
||||
round_ids=_record_verified_round(child))
|
||||
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
|
||||
@@ -0,0 +1,201 @@
|
||||
"""Recovery of incomplete evidence does not repeat engineering work."""
|
||||
import json
|
||||
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, batch_summary, task_queue
|
||||
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime, BatchResourceCleanupError
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
from test_issue44_batch_receipt import BATCH_ID, RUN_ID, TASK_ID, batch
|
||||
from test_pr47_audit_receipts import _start, _supervised_complete
|
||||
from test_run_journal import project_service
|
||||
|
||||
|
||||
def _verified_batch(case):
|
||||
service, child, root, _, admission = case
|
||||
with child.transaction():
|
||||
child._connection.execute('INSERT INTO execution_rounds(task_id,round_id) VALUES (?,?)',
|
||||
(TASK_ID, 'round'))
|
||||
command = {'target_scope': 'targets', 'project_path': 'board.prj',
|
||||
'schematic_name': 'MAIN', 'sheet_number': '1', 'target_selectors': 'uid1\x1fR1'}
|
||||
child._connection.execute('INSERT INTO execution_operations VALUES (?,?,?,?,?,?,?,?)',
|
||||
(TASK_ID, 'round', 'key', json.dumps(command), 'verified', 'attempt', 1, '{}'))
|
||||
journal = _start(root, admission)
|
||||
journal.finish(RUN_ID, dict(_supervised_complete(root), elapsed_seconds=28.125))
|
||||
checkpoint = root / 'task-queues' / (RUN_ID + '.json')
|
||||
batch_resources.write_record(checkpoint,
|
||||
dict(json.loads(checkpoint.read_bytes()), round_ids={TASK_ID: 'round'}))
|
||||
return service, root, journal
|
||||
|
||||
|
||||
def test_same_revision_rebuilds_missing_evidence_without_version_churn(batch, monkeypatch):
|
||||
service, root, journal = _verified_batch(batch)
|
||||
read_sources = batch_summary._operation_sources
|
||||
unavailable = True
|
||||
|
||||
def evidence(*args):
|
||||
if unavailable:
|
||||
return [], {TASK_ID: {'state': 'unknown'}}, [TASK_ID]
|
||||
return read_sources(*args)
|
||||
|
||||
monkeypatch.setattr(batch_summary, '_operation_sources', evidence)
|
||||
monkeypatch.setattr(execution_runs, 'execute_task_queue', lambda *_args, **_kwargs:
|
||||
pytest.fail('receipt recovery dispatched engineering work'))
|
||||
execution_runs.recover_batch_receipts(service, root)
|
||||
first = journal.batch_summary(RUN_ID)
|
||||
assert first['operation_evidence_missing'] == [TASK_ID]
|
||||
assert first['status'] == 'paused' and first['resource_state'] == 'released'
|
||||
execution_runs.recover_batch_receipts(service, root)
|
||||
assert journal.batch_summary(RUN_ID) == first
|
||||
exported = root / 'batch-runs' / RUN_ID / 'batch-receipt.json'
|
||||
exported.write_text('{incomplete export', encoding='utf-8')
|
||||
execution_runs.recover_batch_receipts(service, root)
|
||||
assert journal.batch_summary(RUN_ID) == first
|
||||
assert json.loads(exported.read_bytes()) == first
|
||||
|
||||
unavailable = False
|
||||
execution_runs.recover_batch_receipts(service, root)
|
||||
recovered = journal.batch_summary(RUN_ID)
|
||||
assert recovered['revision'] == first['revision'] + 1
|
||||
assert recovered['operation_evidence_missing'] == []
|
||||
assert recovered['operation_counts']['verified'] == 1
|
||||
assert recovered['status'] == recovered['execution_status'] == 'completed'
|
||||
assert recovered['acceptance'] == first['acceptance']
|
||||
assert recovered['elapsed_seconds'] == first['elapsed_seconds'] == 28.125
|
||||
assert recovered['resource_batch_ids'] == first['resource_batch_ids'] == [BATCH_ID]
|
||||
assert recovered['netlist_verification'] == first['netlist_verification']
|
||||
execution_runs.recover_batch_receipts(service, root)
|
||||
assert journal.batch_summary(RUN_ID) == recovered
|
||||
assert json.loads((root / 'batch-runs' / RUN_ID / 'batch-receipt.json').read_bytes()) == recovered
|
||||
|
||||
|
||||
def test_same_revision_rechecks_unknown_round_even_without_missing_field(batch, monkeypatch):
|
||||
service, root, journal = _verified_batch(batch)
|
||||
execution_runs.recover_batch_receipts(service, root)
|
||||
previous = journal.batch_summary(RUN_ID)
|
||||
previous.update(status='paused', source_versions={**previous['source_versions'],
|
||||
'rounds': {TASK_ID: {'state': 'unknown'}}})
|
||||
journal.save_batch_summary(RUN_ID, previous, journal.get(RUN_ID)['result'], revision=previous['revision'])
|
||||
monkeypatch.setattr(execution_runs, 'execute_task_queue', lambda *_args, **_kwargs:
|
||||
pytest.fail('unknown-round recovery dispatched engineering work'))
|
||||
execution_runs.recover_batch_receipts(service, root)
|
||||
repaired = journal.batch_summary(RUN_ID)
|
||||
assert repaired['status'] == 'completed'
|
||||
assert repaired['source_versions']['rounds'][TASK_ID]['round_id'] == 'round'
|
||||
assert repaired['operation_counts']['verified'] == 1
|
||||
assert repaired['revision'] == previous['revision'] + 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize('bound', [True, False])
|
||||
def test_first_publication_never_lends_a_new_round_to_an_old_report(batch, bound):
|
||||
service, root, journal = _verified_batch(batch)
|
||||
with batch[1].transaction():
|
||||
batch[1]._connection.execute('UPDATE execution_rounds SET round_id=? WHERE task_id=?',
|
||||
('round-2', TASK_ID))
|
||||
if not bound:
|
||||
checkpoint = root / 'task-queues' / (RUN_ID + '.json')
|
||||
state = json.loads(checkpoint.read_bytes())
|
||||
state.pop('round_ids')
|
||||
batch_resources.write_record(checkpoint, state)
|
||||
manifest = json.loads((root / 'batch-runs' / RUN_ID / 'manifest.json').read_bytes())
|
||||
execution_runs._finish_batch_summary(service, root, journal, manifest, journal.get(RUN_ID)['result'], 28.125)
|
||||
summary = journal.batch_summary(RUN_ID)
|
||||
version = summary['source_versions']['rounds'][TASK_ID]
|
||||
if bound:
|
||||
assert version['round_id'] == 'round'
|
||||
assert summary['operation_counts']['verified'] == 1
|
||||
else:
|
||||
assert version['state'] == 'unknown' and 'round_id' not in version
|
||||
assert summary['status'] == 'paused' and summary['operation_evidence_missing'] == [TASK_ID]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('binding', ['checkpoint', 'summary', 'missing', 'conflict'])
|
||||
def test_recovery_never_lends_a_new_round_to_an_old_netlist_report(batch, monkeypatch, binding):
|
||||
service, root, journal = _verified_batch(batch)
|
||||
if binding == 'summary':
|
||||
execution_runs.recover_batch_receipts(service, root)
|
||||
previous = journal.batch_summary(RUN_ID)
|
||||
previous.update(status='paused', operation_evidence_missing=[TASK_ID])
|
||||
journal.save_batch_summary(RUN_ID, previous, journal.get(RUN_ID)['result'], revision=previous['revision'])
|
||||
else:
|
||||
with monkeypatch.context() as unavailable:
|
||||
unavailable.setattr(batch_summary, '_operation_sources',
|
||||
lambda *_args: ([], {TASK_ID: {'state': 'unknown'}}, [TASK_ID]))
|
||||
execution_runs.recover_batch_receipts(service, root)
|
||||
first = journal.batch_summary(RUN_ID)
|
||||
checkpoint = root / 'task-queues' / (RUN_ID + '.json')
|
||||
state = json.loads(checkpoint.read_bytes())
|
||||
if binding in {'missing', 'summary'}:
|
||||
state.pop('round_ids')
|
||||
elif binding == 'conflict':
|
||||
previous = journal.batch_summary(RUN_ID)
|
||||
previous['source_versions']['rounds'][TASK_ID] = {'round_id': 'foreign-round'}
|
||||
journal.save_batch_summary(RUN_ID, previous, journal.get(RUN_ID)['result'], revision=previous['revision'])
|
||||
batch_resources.write_record(checkpoint, state)
|
||||
child = batch[1]
|
||||
with child.transaction():
|
||||
child._connection.execute('UPDATE execution_rounds SET round_id=? WHERE task_id=?', ('round-2', TASK_ID))
|
||||
command = json.loads(child._connection.execute(
|
||||
'SELECT command_json FROM execution_operations WHERE task_id=?', (TASK_ID,)).fetchone()[0])
|
||||
for i in range(2):
|
||||
child._connection.execute('INSERT INTO execution_operations VALUES (?,?,?,?,?,?,?,?)',
|
||||
(TASK_ID, 'round-2', 'new-key-' + str(i), json.dumps(command), 'verified', 'new-attempt', 1, '{}'))
|
||||
execution_runs.recover_batch_receipts(service, root)
|
||||
repaired = journal.batch_summary(RUN_ID)
|
||||
version = repaired['source_versions']['rounds'][TASK_ID]
|
||||
assert version.get('round_id') != 'round-2'
|
||||
assert repaired['netlist_verification'] == first['netlist_verification']
|
||||
if binding in {'checkpoint', 'summary'}:
|
||||
assert version['round_id'] == 'round'
|
||||
assert repaired['operation_counts']['verified'] == 1
|
||||
else:
|
||||
assert version['state'] == 'unknown' and repaired['status'] == 'paused'
|
||||
assert repaired['operation_evidence_missing'] == [TASK_ID]
|
||||
execution_runs.recover_batch_receipts(service, root)
|
||||
assert journal.batch_summary(RUN_ID)['source_versions']['rounds'][TASK_ID] == version
|
||||
|
||||
|
||||
class FatalExit(BaseException):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure', ['ordinary', 'fatal', 'cleanup', 'revalidation'])
|
||||
def test_local_queue_zero_generation_finalizes_only_after_orderly_close(project_service, monkeypatch, failure):
|
||||
service, _, root, ids, hashes = project_service
|
||||
task_id = ids[0]
|
||||
child = service.for_project_task(task_id)
|
||||
validations = []
|
||||
|
||||
def revalidate():
|
||||
validations.append(True)
|
||||
if failure == 'revalidation':
|
||||
raise TaskCenterError('preflight_changed', 'scope changed before binding')
|
||||
|
||||
def fail_before_any_cad(*args):
|
||||
if failure == 'fatal':
|
||||
raise FatalExit('simulated hard boundary interruption')
|
||||
raise TaskCenterError('preflight_changed', 'scope changed after binding')
|
||||
|
||||
monkeypatch.setattr(child, 'get_task', fail_before_any_cad)
|
||||
if failure == 'cleanup':
|
||||
def cannot_close(*args):
|
||||
raise OSError('cleanup was not confirmed')
|
||||
monkeypatch.setattr(BatchCadRuntime, 'close', cannot_close)
|
||||
expected_error = FatalExit if failure == 'fatal' else (
|
||||
BatchResourceCleanupError if failure == 'cleanup' else TaskCenterError)
|
||||
with pytest.raises(expected_error):
|
||||
task_queue.execute_task_queue(service, (task_id,), stop_event=Event(), checkpoint_id=RUN_ID,
|
||||
expected_plan_hashes={task_id: hashes[task_id]}, manifest_digest='d' * 64, revalidate=revalidate)
|
||||
links = list((root / 'batch-runs' / RUN_ID).glob('local-resource-*.json'))
|
||||
assert bool(validations)
|
||||
assert not list((root / 'batch-resources').glob('*/session.json'))
|
||||
if failure == 'revalidation':
|
||||
assert links == []
|
||||
else:
|
||||
assert len(links) == 1
|
||||
binding = json.loads(links[0].read_bytes())
|
||||
assert binding['never_acquired'] is (failure == 'ordinary')
|
||||
assert binding['task_ids'] == [task_id]
|
||||
@@ -0,0 +1,396 @@
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import os
|
||||
import subprocess
|
||||
from threading import Event
|
||||
import zipfile
|
||||
|
||||
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, batch_summary
|
||||
from dx_productivity.trial_task_center.batch_admission import build_batch_admission
|
||||
from dx_productivity.trial_task_center.diagnostics_bundle import export_diagnostic_bundle
|
||||
from dx_productivity.trial_task_center.supervisor_protocol import VERSION, encode
|
||||
from dx_productivity.trial_task_center.task_queue import TaskQueueEntry, TaskQueueResult
|
||||
from test_incident_rule_retry import confirmed_incident_batch, incident, rule_run
|
||||
from test_issue44_batch_receipt import (
|
||||
BATCH_ID, PLAN_HASHES, RUN_ID, TASK_ID, _durable_supervisor_result, batch,
|
||||
)
|
||||
from test_run_journal import project_service
|
||||
|
||||
|
||||
def _complete():
|
||||
return {'status': 'completed', 'execution_status': 'completed', 'queue_id': RUN_ID,
|
||||
'entries': [{'task_id': TASK_ID, 'state': 'completed', 'message': 'done'}],
|
||||
'netlist_verification': {TASK_ID: {'status': 'verified', 'verified': True}}}
|
||||
|
||||
|
||||
def _start(data, admission):
|
||||
batch_resources.write_record(data / 'batch-runs' / RUN_ID / 'manifest.json',
|
||||
dict(admission, run_id=RUN_ID))
|
||||
journal = RunJournal(data)
|
||||
journal.begin(RUN_ID, [TASK_ID], PLAN_HASHES)
|
||||
return journal
|
||||
|
||||
|
||||
def _supervised_complete(data):
|
||||
receipt = _complete()
|
||||
_durable_supervisor_result(data, TaskQueueResult(RUN_ID, (TaskQueueEntry(TASK_ID, 'completed', 'done'),),
|
||||
False, netlist_verification=receipt['netlist_verification']))
|
||||
batch_resources.write_record(data / 'task-queues' / (RUN_ID + '.json'),
|
||||
{'task_ids': [TASK_ID], 'plan_hashes': PLAN_HASHES, 'manifest_digest': 'd' * 64,
|
||||
'entries': {TASK_ID: {'state': 'completed', 'message': 'done'}}})
|
||||
return receipt
|
||||
|
||||
|
||||
def _update_json(path, **changes):
|
||||
batch_resources.write_record(path, dict(json.loads(path.read_bytes()), **changes))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('owns_desktop', [False, pytest.param(True,
|
||||
marks=pytest.mark.skipif(os.name != 'nt', reason='Windows desktop lifetime'))])
|
||||
def test_local_manifest_run_completes_from_its_actual_runtime_release(project_service, monkeypatch, owns_desktop):
|
||||
service, _, root, ids, _ = project_service
|
||||
task_id = ids[0]
|
||||
child = service.for_project_task(task_id)
|
||||
calls = []
|
||||
|
||||
def worker(command, timeout):
|
||||
job = command[-1]
|
||||
calls.append(job)
|
||||
with (Path(command[3]) / 'status.tsv').open('a', encoding='utf-8') as stream:
|
||||
stream.write(f'{job}\tno_match\tbatch_closed\tNo matching components\n')
|
||||
return subprocess.CompletedProcess(command, 0, '', '')
|
||||
|
||||
monkeypatch.setattr(child._quick_run_preparer, '_process_runner', worker)
|
||||
monkeypatch.setattr(child._quick_run_preparer, '_cscript_resolver', lambda: Path('cscript.exe'))
|
||||
if owns_desktop:
|
||||
execute = child.execute_quick_run_queue
|
||||
|
||||
def execute_on_desktop(task_id, *, runtime, **kwargs):
|
||||
runtime._ensure_desktop()
|
||||
return execute(task_id, runtime=runtime, **kwargs)
|
||||
|
||||
monkeypatch.setattr(child, 'execute_quick_run_queue', execute_on_desktop)
|
||||
admission = build_batch_admission(service, [task_id], scope_kind='selected')
|
||||
report = admission['execution_report']
|
||||
result = execution_runs.execute_confirmed_run(service, root, [task_id], report, Event(),
|
||||
RUN_ID, admission=admission)
|
||||
assert len(calls) == 1
|
||||
assert result['execution_status'] == 'completed'
|
||||
assert result['status'] == 'completed' and result['summary']['resource_state'] == 'released'
|
||||
assert result['summary']['resource']['evidence']
|
||||
checkpoint = json.loads((root / 'task-queues' / (RUN_ID + '.json')).read_bytes())
|
||||
with child._store._lock:
|
||||
actual_round = child._store._connection.execute(
|
||||
'SELECT round_id FROM execution_rounds WHERE task_id=?', (task_id,)).fetchone()[0]
|
||||
assert checkpoint['round_ids'][task_id] == actual_round
|
||||
assert result['tasks'][0]['no_match_items'] == 1
|
||||
assert bool(result['summary']['resource']['generations']) is owns_desktop
|
||||
journal = RunJournal(root)
|
||||
assert journal.get(RUN_ID)['status'] == 'completed'
|
||||
if not owns_desktop:
|
||||
proof = result['summary']['resource']['evidence'][0]
|
||||
with zipfile.ZipFile(export_diagnostic_bundle(root, root.parent / 'receipt-support.zip')) as bundle:
|
||||
assert json.loads(bundle.read(proof))['never_acquired'] is True
|
||||
(root / proof).unlink()
|
||||
journal.finish(RUN_ID, {key: value for key, value in result.items() if key != 'summary'})
|
||||
execution_runs.recover_batch_receipts(service, root)
|
||||
rebuilt = journal.batch_summary(RUN_ID)
|
||||
assert rebuilt['resource_state'] == 'unknown' and rebuilt['status'] == 'paused'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('already_summarized', [False, True])
|
||||
def test_incident_publication_preserves_the_recorded_elapsed_time(batch, already_summarized):
|
||||
service, _, data, _, admission = batch
|
||||
journal = _start(data, admission)
|
||||
receipt = _supervised_complete(data)
|
||||
journal.finish(RUN_ID, dict(receipt, elapsed_seconds=28.125))
|
||||
if already_summarized:
|
||||
execution_runs.recover_batch_receipts(service, data)
|
||||
result = execution_runs._republish_incident_batch_summary(service, data, RUN_ID, receipt)
|
||||
assert result['elapsed_seconds'] == result['summary']['elapsed_seconds'] == 28.125
|
||||
assert journal.get(RUN_ID)['result']['elapsed_seconds'] == 28.125
|
||||
|
||||
|
||||
def test_recovery_retries_a_previously_unstable_snapshot_at_the_same_revision(batch, monkeypatch):
|
||||
service, child, data, _, admission = batch
|
||||
journal = _start(data, admission)
|
||||
receipt = _supervised_complete(data)
|
||||
with child.transaction():
|
||||
child._connection.execute('INSERT INTO execution_rounds(task_id,round_id) VALUES (?,?)', (TASK_ID, 'round'))
|
||||
checkpoint = data / 'task-queues' / (RUN_ID + '.json')
|
||||
_update_json(checkpoint, round_ids={TASK_ID: 'round'})
|
||||
journal.finish(RUN_ID, receipt)
|
||||
original = batch_summary._operation_sources
|
||||
generations = iter(range(3))
|
||||
|
||||
def changing(*args):
|
||||
rows, versions, missing = original(*args)
|
||||
return rows, {TASK_ID: {**versions[TASK_ID], 'digest': str(next(generations))}}, missing
|
||||
|
||||
with monkeypatch.context() as unstable:
|
||||
unstable.setattr(batch_summary, '_operation_sources', changing)
|
||||
execution_runs.recover_batch_receipts(service, data)
|
||||
first = journal.batch_summary(RUN_ID)
|
||||
assert first['status'] == 'paused'
|
||||
assert {'code': 'batch_snapshot_unstable'} in first['reporting_errors']
|
||||
execution_runs.recover_batch_receipts(service, data)
|
||||
recovered = journal.batch_summary(RUN_ID)
|
||||
assert recovered['status'] == 'completed'
|
||||
assert recovered['revision'] == first['revision'] + 1
|
||||
assert {'code': 'batch_snapshot_unstable'} not in recovered['reporting_errors']
|
||||
|
||||
|
||||
def test_generation_cannot_publish_released_without_physical_proof(batch):
|
||||
service, _, data, _, admission = batch
|
||||
journal = _start(data, admission)
|
||||
receipt = _supervised_complete(data)
|
||||
session = data / 'batch-resources' / BATCH_ID / 'session.json'
|
||||
_update_json(session, release_proof={}, cleanup={}, generation_releases=[
|
||||
{'generation': 1, 'desktop': 'dx-' + BATCH_ID, 'reason': 'unverified'}], generation=2)
|
||||
journal.finish(RUN_ID, receipt)
|
||||
execution_runs.recover_batch_receipts(service, data)
|
||||
summary = journal.batch_summary(RUN_ID)
|
||||
assert summary['status'] == 'paused'
|
||||
assert {row['generation']: row['state'] for row in summary['resource']['generations']} == {
|
||||
1: 'unknown', 2: 'unknown'}
|
||||
|
||||
|
||||
def _quick_retry(data, retry_id, *, task_id=TASK_ID, expected_item=('p', 's', 'old', 'new')):
|
||||
_durable_supervisor_result(data, None, batch_id=retry_id)
|
||||
directory = data / 'batch-resources' / retry_id
|
||||
request = directory / 'request.json'
|
||||
_update_json(request, operation='execute_quick_run_queue', task_ids=[task_id],
|
||||
arguments=encode({'task_id': task_id, 'expected_item': expected_item}))
|
||||
_update_json(directory / 'supervisor.json', operation='execute_quick_run_queue', task_ids=[task_id],
|
||||
request_sha256=hashlib.sha256(request.read_bytes()).hexdigest())
|
||||
_update_json(directory / 'session.json', kind='quick_run_queue')
|
||||
return request
|
||||
|
||||
|
||||
@pytest.mark.parametrize('damaged_request', ['', 'request', 'request_and_digest'])
|
||||
def test_full_recovery_preserves_and_rechecks_the_bound_quick_run(batch, damaged_request):
|
||||
service, _, data, _, admission = batch
|
||||
journal = _start(data, admission)
|
||||
receipt = _supervised_complete(data)
|
||||
retry_id = '5' * 32
|
||||
retry_request = _quick_retry(data, retry_id)
|
||||
journal.finish(RUN_ID, receipt)
|
||||
execution_runs._record_incident_resource_link(data, RUN_ID, retry_id, TASK_ID, ('p', 's', 'old', 'new'))
|
||||
execution_runs._republish_incident_batch_summary(service, data, RUN_ID, receipt)
|
||||
assert retry_id in journal.batch_summary(RUN_ID)['resource_batch_ids']
|
||||
if damaged_request:
|
||||
_update_json(retry_request, arguments=encode({'task_id': TASK_ID, 'expected_item': ('other',)}))
|
||||
if damaged_request == 'request_and_digest':
|
||||
_update_json(retry_request.with_name('supervisor.json'),
|
||||
request_sha256=hashlib.sha256(retry_request.read_bytes()).hexdigest())
|
||||
journal.finish(RUN_ID, receipt) # No matching receipt revision, so startup rebuilds all sources.
|
||||
execution_runs.recover_batch_receipts(service, data)
|
||||
summary = journal.batch_summary(RUN_ID)
|
||||
assert retry_id in summary['resource_batch_ids']
|
||||
assert summary['resource_state'] == ('unknown' if damaged_request else 'released')
|
||||
if not damaged_request:
|
||||
assert any(row['session_id'] == retry_id for row in summary['resource']['generations'])
|
||||
proof = f'batch-runs/{RUN_ID}/incident-resource-{retry_id}.json'
|
||||
with zipfile.ZipFile(export_diagnostic_bundle(data, data.parent / 'retry-support.zip')) as bundle:
|
||||
assert json.loads(bundle.read(proof))['task_id'] == TASK_ID
|
||||
|
||||
|
||||
def test_receipt_rebuild_preserves_supervisor_shutdown_failure_after_release(batch):
|
||||
service, _, data, _, admission = batch
|
||||
journal = _start(data, admission)
|
||||
_supervised_complete(data)
|
||||
supervisor = data / 'batch-resources' / BATCH_ID / 'supervisor.json'
|
||||
_update_json(supervisor, outcome='application_shutdown_failed')
|
||||
execution_runs.recover_batch_receipts(service, data)
|
||||
summary = journal.batch_summary(RUN_ID)
|
||||
assert summary['execution_status'] == 'completed' and summary['resource_state'] == 'released'
|
||||
assert summary['status'] == 'failed' and summary['stop_reason'] == 'application_shutdown_failed'
|
||||
|
||||
|
||||
def test_recovery_rejects_success_when_the_supervisor_marked_the_business_uncertain(batch):
|
||||
service, _, data, _, admission = batch
|
||||
journal = _start(data, admission)
|
||||
_supervised_complete(data)
|
||||
supervisor = data / 'batch-resources' / BATCH_ID / 'supervisor.json'
|
||||
_update_json(supervisor, outcome='interrupted', business_uncertain=True)
|
||||
execution_runs.recover_batch_receipts(service, data)
|
||||
summary = journal.batch_summary(RUN_ID)
|
||||
assert summary['status'] == 'interrupted'
|
||||
|
||||
|
||||
def test_shutdown_diagnostics_also_protect_old_supervisor_receipts(batch):
|
||||
service, _, data, _, admission = batch
|
||||
journal = _start(data, admission)
|
||||
_supervised_complete(data)
|
||||
session = data / 'batch-resources' / BATCH_ID / 'session.json'
|
||||
_update_json(session, cad_shutdown={'orderly_shutdown': False, 'forced_termination': True})
|
||||
execution_runs.recover_batch_receipts(service, data)
|
||||
summary = journal.batch_summary(RUN_ID)
|
||||
assert summary['execution_status'] == 'completed' and summary['resource_state'] == 'released'
|
||||
assert summary['status'] == 'failed' and summary['stop_reason'] == 'application_shutdown_failed'
|
||||
|
||||
|
||||
def test_local_retry_keeps_its_runtime_after_first_business_receipt_fails(confirmed_incident_batch, monkeypatch):
|
||||
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'))
|
||||
manifest = json.loads((root / 'batch-runs' / run_id / 'manifest.json').read_bytes())
|
||||
checkpoint = root / 'task-queues' / (run_id + '.json')
|
||||
_update_json(checkpoint, manifest_digest=manifest['manifest_digest'])
|
||||
class FatalExit(BaseException):
|
||||
pass
|
||||
|
||||
def fail_first_receipt(*args):
|
||||
raise FatalExit('first business receipt write failed')
|
||||
|
||||
with monkeypatch.context() as damaged:
|
||||
damaged.setattr(RunJournal, 'finish', fail_first_receipt)
|
||||
with pytest.raises(FatalExit):
|
||||
incident(case)
|
||||
execution_runs.recover_batch_receipts(service, root)
|
||||
summary = RunJournal(root).batch_summary(run_id)
|
||||
assert summary['status'] == 'interrupted'
|
||||
retry_id, = summary['resource_batch_ids']
|
||||
evidence = root / summary['resource']['evidence'][0]
|
||||
binding = json.loads(evidence.read_bytes())
|
||||
assert binding['task_id'] == task_id and binding['session_id'] == retry_id
|
||||
assert binding['kind'] == 'quick_run_queue' and binding['never_acquired'] is True
|
||||
assert summary['resource_state'] == 'released'
|
||||
assert case['calls'] == ['OLD-OK', 'OLD-BAD', 'OLD-BAD']
|
||||
|
||||
|
||||
def test_local_retry_records_no_acquisition_after_an_explicit_precondition_error(
|
||||
confirmed_incident_batch, monkeypatch):
|
||||
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'))
|
||||
folder = root / 'batch-runs' / run_id
|
||||
manifest = json.loads((folder / 'manifest.json').read_bytes())
|
||||
_update_json(root / 'task-queues' / (run_id + '.json'), manifest_digest=manifest['manifest_digest'])
|
||||
store = service.for_project_task(task_id)._store
|
||||
original = store.has_active_project
|
||||
monkeypatch.setattr(store, 'has_active_project',
|
||||
lambda: any(folder.glob('local-resource-*.json')) or original())
|
||||
result = incident(case)
|
||||
assert result['retry_error']['code'] == 'active_project_exists'
|
||||
path, = folder.glob('local-resource-*.json')
|
||||
assert json.loads(path.read_bytes())['never_acquired'] is True
|
||||
assert RunJournal(root).batch_summary(run_id)['resource_state'] == 'released'
|
||||
assert case['calls'] == ['OLD-OK', 'OLD-BAD']
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != 'nt', reason='Windows desktop lifetime')
|
||||
def test_local_retry_isolation_cannot_borrow_the_original_batch_release(
|
||||
confirmed_incident_batch, monkeypatch):
|
||||
import sys
|
||||
from dx_productivity.trial_task_center import batch as native_batch
|
||||
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
|
||||
from dx_productivity.trial_task_center.isolated_desktop import _Win32Api, build_startup_info
|
||||
from dx_productivity.trial_task_center.task_queue import _local_resource_path
|
||||
|
||||
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'))
|
||||
manifest = json.loads((root / 'batch-runs' / run_id / 'manifest.json').read_bytes())
|
||||
_update_json(root / 'task-queues' / (run_id + '.json'), manifest_digest=manifest['manifest_digest'])
|
||||
with BatchCadRuntime(root, 'task_queue') as main:
|
||||
main.bind_logs(service._logging, (task_id,))
|
||||
main._ensure_desktop()
|
||||
batch_resources.write_record(root / _local_resource_path(run_id, main.session_id),
|
||||
{'version': 1, 'session_id': main.session_id, 'queue_id': run_id,
|
||||
'manifest_digest': manifest['manifest_digest'], 'task_ids': [task_id],
|
||||
'plan_hashes': manifest['plan_hashes'], 'never_acquired': False})
|
||||
assert main.record['state'] == 'released'
|
||||
execute_batch = native_batch.execute_batch
|
||||
external = None
|
||||
|
||||
def execute_on_retained_desktop(*args, runtime, **kwargs):
|
||||
nonlocal external
|
||||
desktop = runtime._ensure_desktop()
|
||||
external = _Win32Api().create_process((sys.executable, '-u', '-c',
|
||||
'import sys,time,win32service; '
|
||||
'desktop=win32service.OpenDesktop(sys.argv[1],0,False,0x10000000); '
|
||||
'desktop.SetThreadDesktop(); print("ready",flush=True); time.sleep(30)', desktop.name),
|
||||
build_startup_info(desktop.name).lpDesktop, None, None,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
assert external.stdout.readline() == b'ready\r\n'
|
||||
return execute_batch(*args, runtime=runtime, **kwargs)
|
||||
|
||||
monkeypatch.setattr(native_batch, 'execute_batch', execute_on_retained_desktop)
|
||||
try:
|
||||
incident(case)
|
||||
summary = RunJournal(root).batch_summary(run_id)
|
||||
assert summary['execution_status'] == 'completed'
|
||||
assert summary['status'] == 'paused' and summary['resource_state'] == 'isolated'
|
||||
assert {row['state'] for row in summary['resource']['generations']} == {'released', 'isolated'}
|
||||
assert external.poll() is None
|
||||
assert case['calls'] == ['OLD-OK', 'OLD-BAD', 'OLD-BAD']
|
||||
finally:
|
||||
if external is not None:
|
||||
external.close()
|
||||
assert batch_resources.cleanup_pending_resources(root) == ()
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != 'nt', reason='Windows supervisor launch')
|
||||
@pytest.mark.parametrize('link_writable', [True, False])
|
||||
def test_incident_supervisor_launch_requires_its_durable_request_link(
|
||||
confirmed_incident_batch, monkeypatch, link_writable):
|
||||
from dx_productivity.trial_task_center import batch_supervisor
|
||||
from dx_productivity.trial_task_center.isolated_desktop import _Win32Api
|
||||
|
||||
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'))
|
||||
folder = root / 'batch-runs' / run_id
|
||||
manifest = json.loads((folder / 'manifest.json').read_bytes())
|
||||
_update_json(root / 'task-queues' / (run_id + '.json'), manifest_digest=manifest['manifest_digest'])
|
||||
execute = service.execute_quick_run_queue
|
||||
atomic_write = batch_resources.write_record
|
||||
launches = []
|
||||
|
||||
class FatalExit(BaseException):
|
||||
pass
|
||||
|
||||
def supervised_retry(*args, **kwargs):
|
||||
with monkeypatch.context() as mode:
|
||||
mode.setattr(service, '_supervised', True)
|
||||
return execute(*args, **kwargs)
|
||||
|
||||
def write_record(path, value):
|
||||
if not link_writable and Path(path).name.startswith('incident-resource-'):
|
||||
raise OSError('fixture cannot write incident link')
|
||||
return atomic_write(path, value)
|
||||
|
||||
def interrupt_at_create_process(*args, **kwargs):
|
||||
assert link_writable, 'worker launch must wait for durable incident binding'
|
||||
batch_id = service._last_supervisor_batch_id
|
||||
directory = root / 'batch-resources' / batch_id
|
||||
raw = (directory / 'request.json').read_bytes()
|
||||
supervisor = json.loads((directory / 'supervisor.json').read_bytes())
|
||||
link = json.loads((folder / f'incident-resource-{batch_id}.json').read_bytes())
|
||||
assert link == {'manifest_digest': manifest['manifest_digest'], 'task_id': task_id,
|
||||
'request_sha256': hashlib.sha256(raw).hexdigest()}
|
||||
assert supervisor['state'] == 'starting' and supervisor['process'] is None
|
||||
launches.append(batch_id)
|
||||
raise FatalExit('interrupted at native launch boundary')
|
||||
|
||||
monkeypatch.setattr(service, 'execute_quick_run_queue', supervised_retry)
|
||||
monkeypatch.setattr(batch_resources, 'write_record', write_record)
|
||||
monkeypatch.setattr(_Win32Api, 'create_process', interrupt_at_create_process)
|
||||
if link_writable:
|
||||
with pytest.raises(FatalExit):
|
||||
incident(case)
|
||||
execution_runs.recover_batch_receipts(service, root)
|
||||
summary = RunJournal(root).batch_summary(run_id)
|
||||
assert len(launches) == 1 and summary['resource_batch_ids'] == launches
|
||||
assert summary['status'] == 'interrupted' and summary['resource_state'] == 'unknown'
|
||||
else:
|
||||
result = incident(case)
|
||||
assert result['retry_error']['code'] == 'incident_resource_link_unavailable'
|
||||
assert not launches and not batch_supervisor.pending_supervisors(root)
|
||||
assert case['calls'] == ['OLD-OK', 'OLD-BAD']
|
||||
@@ -96,6 +96,51 @@ 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))
|
||||
batch_resources.write_record(directory / 'session.json', dict(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_released': True, 'processes_exited': True}))
|
||||
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
|
||||
@@ -125,7 +170,7 @@ def test_shared_safe_primary_failure_can_hold_remaining_commands_on_resume(proje
|
||||
|
||||
|
||||
@pytest.mark.parametrize('isolated', [True, False])
|
||||
def test_released_isolated_project_does_not_block_resume_of_other_projects(project_service, isolated):
|
||||
def test_released_projects_require_a_verified_result_to_resume_other_projects(project_service, isolated):
|
||||
from dx_productivity.dsh.run_journal import resume_preflight
|
||||
service, _, data, ids, hashes = project_service
|
||||
journal = RunJournal(data)
|
||||
@@ -140,13 +185,21 @@ def test_released_isolated_project_does_not_block_resume_of_other_projects(proje
|
||||
path.write_text(json.dumps({'version': 1, 'task_ids': ids, 'plan_hashes': hashes,
|
||||
'phase': 'primary' if isolated else 'problems', 'entries': entries}))
|
||||
result = journal.inspect(service, 'd' * 32)
|
||||
assert result['queue_available'] and result['resume_ready'], result['blockers']
|
||||
assert result['queue_available']
|
||||
assert result['remaining_task_ids'] == (ids[1:] if isolated else ids)
|
||||
assert result['isolated_task_ids'] == ([ids[0]] if isolated else [])
|
||||
assert result['tasks'][0]['interrupted'] == isolated
|
||||
assert result['tasks'][0]['interrupted'] is isolated
|
||||
if isolated:
|
||||
assert not result['resume_ready'] and 'interrupted' in result['blockers']
|
||||
assert not result['cad_execution_started']
|
||||
with pytest.raises(TaskCenterError) as caught:
|
||||
resume_preflight(service, result)
|
||||
assert caught.value.code == 'run_blocked'
|
||||
return
|
||||
assert result['resume_ready'], result['blockers']
|
||||
report = resume_preflight(service, result)
|
||||
assert report['ready']
|
||||
assert report['tasks'][0]['isolated'] == isolated
|
||||
assert report['tasks'][0]['isolated'] is False
|
||||
|
||||
|
||||
def test_unpaused_blocked_project_is_not_a_completed_run(project_service):
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -33,7 +33,8 @@ def test_manual_confirmation_obeys_fresh_preflight_blockers(ui, batch):
|
||||
confirmations = []
|
||||
window._quick_run_confirmer = lambda *args: confirmations.append(args) or False
|
||||
(window.task_list.queue_button if batch else window.run_panel.quick_run_button).click()
|
||||
assert confirmations == []
|
||||
ui.settle()
|
||||
assert confirmations == ([('batch', 1, 1)] if batch else [])
|
||||
assert not ui.calls and not window._workers
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
"""Incremental scope acceptance through the real task service and Qt controls."""
|
||||
from dataclasses import replace
|
||||
import importlib
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
from dx_productivity.trial_task_center.models import TaskStatus
|
||||
|
||||
|
||||
def admission_module():
|
||||
try:
|
||||
return importlib.import_module('dx_productivity.trial_task_center.batch_admission')
|
||||
except ModuleNotFoundError:
|
||||
pytest.fail('The eligible batch admission path is missing')
|
||||
|
||||
|
||||
def test_selected_scope_uses_saved_order_and_rejects_cross_group(ui):
|
||||
module = admission_module()
|
||||
a, b = ui.tasks
|
||||
assert module.resolve_batch_task_ids(tuple(reversed(ui.tasks)), a.group_id,
|
||||
selected_ids=(b.task_id, a.task_id)) == (a.task_id, b.task_id)
|
||||
with pytest.raises(TaskCenterError):
|
||||
module.resolve_batch_task_ids((a, replace(b, group_id='other')), a.group_id,
|
||||
selected_ids=(a.task_id, b.task_id))
|
||||
|
||||
|
||||
def test_missing_plan_is_listed_without_rejecting_eligible_task(ui):
|
||||
module = admission_module()
|
||||
a, b = ui.tasks
|
||||
ui.store.record_target_inventory(b.task_id, ())
|
||||
report = module.build_batch_admission(ui.service, (a.task_id, b.task_id), scope_kind='batch')
|
||||
assert report['ready']
|
||||
assert report['runnable_task_ids'] == [a.task_id]
|
||||
assert [(d['task_id'], d['classification']) for d in report['decisions']] == [
|
||||
(a.task_id, 'executable'), (b.task_id, 'skipped')]
|
||||
assert report['decisions'][1]['message']
|
||||
assert report['execution_report']['plan_hashes'].keys() == {a.task_id}
|
||||
assert module.validate_batch_admission(ui.service, report)['ready']
|
||||
|
||||
|
||||
def test_confirmation_does_not_silently_admit_a_newly_eligible_task(ui):
|
||||
module = admission_module()
|
||||
a, b = ui.tasks
|
||||
path = ui.service.projects(b.task_id)[0].path
|
||||
backup = path.with_suffix('.prj.saved')
|
||||
path.rename(backup)
|
||||
report = module.build_batch_admission(ui.service, (a.task_id, b.task_id), scope_kind='batch')
|
||||
backup.rename(path)
|
||||
with pytest.raises(TaskCenterError, match='确认|变化'):
|
||||
module.validate_batch_admission(ui.service, report)
|
||||
assert not ui.calls
|
||||
|
||||
|
||||
def test_uncertain_member_stops_entire_batch_even_if_other_member_is_ready(ui):
|
||||
module = admission_module()
|
||||
a, b = ui.tasks
|
||||
ui.store.set_task_status(b.task_id, TaskStatus.BLOCKED, summary='saved but unverified')
|
||||
report = module.build_batch_admission(ui.service, (a.task_id, b.task_id), scope_kind='batch')
|
||||
assert not report['ready']
|
||||
assert report['global_blockers']
|
||||
assert report['decisions'][1]['classification'] == 'held'
|
||||
assert not ui.calls
|
||||
|
||||
|
||||
def test_cancelled_batch_leaves_zero_dispatch_receipt(ui, qtbot):
|
||||
seen = []
|
||||
ui.window._quick_run_confirmer = lambda *args: seen.append(args) or False
|
||||
ui.window.task_list.queue_button.click()
|
||||
qtbot.waitUntil(lambda: bool(seen), timeout=5000)
|
||||
ui.settle()
|
||||
receipts = list((ui.data / 'batch-runs').glob('*/batch-receipt.json'))
|
||||
assert receipts, 'Cancelled confirmations must retain their actual candidate scope'
|
||||
value = json.loads(receipts[-1].read_text(encoding='utf-8'))
|
||||
assert value['status'] == 'cancelled'
|
||||
assert value['dispatch_count'] == 0
|
||||
assert not ui.calls
|
||||
|
||||
|
||||
def test_selected_action_and_confirmation_show_only_explicit_selection(ui, qtbot):
|
||||
action = getattr(ui.window.task_list, 'selected_queue_button', None)
|
||||
assert action is not None, 'Explicit selected-project execution is missing'
|
||||
ui.window.task_list.list.selectAll()
|
||||
ui.settle()
|
||||
seen = []
|
||||
ui.window._quick_run_confirmer = lambda *args: seen.append(
|
||||
(args, ui.window._batch_confirmation_admission)) or False
|
||||
action.click()
|
||||
qtbot.waitUntil(lambda: bool(seen), timeout=5000)
|
||||
assert seen[0][0][1] == 2
|
||||
assert seen[0][1]['scope_kind'] == 'selected'
|
||||
assert seen[0][1]['candidate_task_ids'] == [t.task_id for t in ui.tasks]
|
||||
assert not ui.calls
|
||||
|
||||
|
||||
def test_mixed_eight_projects_dispatch_only_the_confirmed_five(ui, qtbot, tmp_path):
|
||||
from dx_productivity.dsh.run_journal import RunJournal
|
||||
root = tmp_path / 'mixed-eight'
|
||||
for i in range(8):
|
||||
project = root / f'Board-{i}' / 'board.prj'
|
||||
project.parent.mkdir(parents=True)
|
||||
project.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
|
||||
tasks = ui.service.create_project_tasks(root)
|
||||
ui.service.add_rule(tasks[0].task_id, 'OLD', 'NEW')
|
||||
ui.store.record_target_inventory(tasks[5].task_id, ())
|
||||
ui.store.record_target_inventory(tasks[6].task_id, ())
|
||||
ui.service.projects(tasks[7].task_id)[0].path.unlink()
|
||||
ui.window._project_tasks_created(tasks)
|
||||
ui.settle()
|
||||
confirmed = []
|
||||
def confirm(*args):
|
||||
confirmed.append(ui.window._batch_confirmation_admission)
|
||||
return True
|
||||
ui.window._quick_run_confirmer = confirm
|
||||
ui.window.task_list.queue_button.click()
|
||||
qtbot.waitUntil(lambda: len(ui.calls) == 5 or '错误' in ui.window.run_panel.operator_band.text(), timeout=10000)
|
||||
ui.settle()
|
||||
assert len(ui.calls) == 5, ui.window.run_panel.operator_band.text()
|
||||
run = RunJournal(ui.data).list_runs()[0]
|
||||
assert run['task_ids'] == [task.task_id for task in tasks[:5]]
|
||||
assert [d['classification'] for d in confirmed[0]['decisions']] == ['executable'] * 5 + ['skipped'] * 3
|
||||
assert all(ui.service.get_task(task.task_id).status is not TaskStatus.RUNNING for task in tasks)
|
||||
receipt = json.loads((ui.data / 'batch-runs' / run['run_id'] / 'batch-receipt.json').read_text(encoding='utf-8'))
|
||||
assert receipt['task_counts']['skipped'] == 3
|
||||
assert receipt['task_counts']['completed'] == 5
|
||||
assert receipt == ui.window._dsh_last_execution['summary']
|
||||
assert '跳过 3' in ui.window.run_panel.operator_band.text()
|
||||
|
||||
|
||||
def test_plan_change_in_modal_confirmation_produces_no_dispatch(ui, qtbot):
|
||||
def confirm(*_):
|
||||
ui.service.set_copy_part_number_to_value(ui.tasks[0].task_id, True)
|
||||
return True
|
||||
ui.window._quick_run_confirmer = confirm
|
||||
ui.window.task_list.queue_button.click()
|
||||
qtbot.waitUntil(lambda: bool(list((ui.data / 'batch-runs').glob('*/batch-receipt.json'))), timeout=5000)
|
||||
ui.settle()
|
||||
assert not ui.calls
|
||||
assert '变化' in ui.window.run_panel.operator_band.text()
|
||||
|
||||
|
||||
def test_missing_batch_json_is_repaired_on_window_startup_without_dispatch(ui, qtbot):
|
||||
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
|
||||
ui.window._quick_run_confirmer = lambda *_: True
|
||||
ui.window.task_list.queue_button.click()
|
||||
qtbot.waitUntil(lambda: len(ui.calls) == 2, timeout=5000)
|
||||
ui.settle()
|
||||
path = next((ui.data / 'batch-runs').glob('*/batch-receipt.json'))
|
||||
path.unlink()
|
||||
ui.window.close()
|
||||
ui.settle()
|
||||
ui.service._supervised = True
|
||||
second = TrialTaskCenterWindow(ui.service)
|
||||
qtbot.addWidget(second)
|
||||
second.show()
|
||||
try:
|
||||
qtbot.waitUntil(path.is_file, timeout=5000)
|
||||
assert len(ui.calls) == 2, 'Repairing a report must not dispatch replacements'
|
||||
assert json.loads(path.read_text(encoding='utf-8'))['task_counts']['completed'] == 2
|
||||
finally:
|
||||
qtbot.waitUntil(lambda: not second._workers and not second._loading, timeout=5000)
|
||||
second.close()
|
||||
ui.service._supervised = False
|
||||
|
||||
|
||||
def test_changing_explicit_selection_during_confirmation_does_not_dispatch_old_scope(ui, qtbot):
|
||||
ui.window.task_list.list.selectAll()
|
||||
def confirm(*_):
|
||||
item = next(ui.window.task_list.list.item(i) for i in range(ui.window.task_list.list.count())
|
||||
if ui.window.task_list.list.item(i).data(256) == ui.tasks[1].task_id)
|
||||
item.setSelected(False)
|
||||
return True
|
||||
ui.window._quick_run_confirmer = confirm
|
||||
ui.window.task_list.selected_queue_button.click()
|
||||
qtbot.waitUntil(lambda: bool(list((ui.data / 'batch-runs').glob('*/batch-receipt.json'))), timeout=5000)
|
||||
ui.settle()
|
||||
assert not ui.calls
|
||||
assert '范围' in ui.window.run_panel.operator_band.text()
|
||||
|
||||
|
||||
def test_resume_validates_declared_database_source_without_comparing_progress(ui):
|
||||
module = admission_module()
|
||||
ids = tuple(t.task_id for t in ui.tasks)
|
||||
admission = module.build_batch_admission(ui.service, ids, scope_kind='batch')
|
||||
ui.store.set_task_status(ids[0], TaskStatus.RUNNING, summary='legitimate progress')
|
||||
module.validate_batch_resume(ui.service, admission)
|
||||
path = ui.service.projects(ids[1])[0].path
|
||||
path.write_text(path.read_text().replace('"database"', '"different-database"'))
|
||||
with pytest.raises(TaskCenterError, match='写入源'):
|
||||
module.validate_batch_resume(ui.service, admission)
|
||||
assert not ui.calls
|
||||
|
||||
|
||||
def test_resume_of_selected_member_cannot_bypass_uncertain_unselected_sibling(ui):
|
||||
module = admission_module()
|
||||
a, b = ui.tasks
|
||||
admission = module.build_batch_admission(ui.service, (a.task_id,), scope_kind='selected')
|
||||
ui.store.set_task_status(b.task_id, TaskStatus.BLOCKED, summary='saved but unverified')
|
||||
with pytest.raises(TaskCenterError, match='待核验'):
|
||||
module.validate_batch_resume(ui.service, admission)
|
||||
|
||||
|
||||
def test_manual_queue_resume_rejects_a_changed_database_before_second_dispatch(ui, monkeypatch):
|
||||
child = ui.service.for_project_task(ui.tasks[0].task_id)
|
||||
worker = child._quick_run_preparer._process_runner
|
||||
def pause_after_first(command, timeout):
|
||||
completed = worker(command, timeout)
|
||||
ui.window._batch_stop.set()
|
||||
return completed
|
||||
monkeypatch.setattr(child._quick_run_preparer, '_process_runner', pause_after_first)
|
||||
ui.window._quick_run_confirmer = lambda *_: True
|
||||
ui.window.task_list.queue_button.click()
|
||||
ui.settle()
|
||||
assert len(ui.calls) == 1
|
||||
assert ui.window._project_queues
|
||||
path = ui.service.projects(ui.tasks[1].task_id)[0].path
|
||||
path.write_text(path.read_text().replace('"database"', '"different-database"'))
|
||||
ui.window.task_list.queue_button.click()
|
||||
ui.settle()
|
||||
assert len(ui.calls) == 1, 'Resuming must not write a different database under the old authorization'
|
||||
assert '写入源' in ui.window.run_panel.operator_band.text()
|
||||
|
||||
|
||||
def test_selected_execution_uses_saved_order_when_list_display_is_reversed(ui):
|
||||
from dx_productivity.dsh.run_journal import RunJournal
|
||||
ui.window.task_list.sort.setCurrentIndex(ui.window.task_list.sort.findData('name_desc'))
|
||||
ui.window.task_list.list.selectAll()
|
||||
ui.settle()
|
||||
ui.window._quick_run_confirmer = lambda *_: True
|
||||
ui.window.task_list.selected_queue_button.click()
|
||||
ui.settle()
|
||||
assert len(ui.calls) == 2, ui.window.run_panel.operator_band.text()
|
||||
assert RunJournal(ui.data).list_runs()[0]['task_ids'] == [task.task_id for task in ui.tasks]
|
||||
|
||||
|
||||
def test_visible_confirmation_never_names_unselected_sibling_as_execution_scope(ui, monkeypatch):
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
a, b = ui.tasks
|
||||
module = admission_module()
|
||||
admission = module.build_batch_admission(ui.service, (a.task_id,), scope_kind='selected')
|
||||
ui.window._batch_confirmation_admission = admission
|
||||
ui.window._dsh_confirmation_impact = admission['execution_report']['impact']
|
||||
seen = []
|
||||
monkeypatch.setattr(QMessageBox, 'question', lambda *args: seen.append(args[2]) or QMessageBox.StandardButton.No)
|
||||
assert not ui.window._confirm_quick_run('batch', 1, 1)
|
||||
assert a.name in seen[0]
|
||||
assert b.name not in seen[0]
|
||||
@@ -0,0 +1,242 @@
|
||||
"""Keyboard commands, screen-reader names and navigation selection agree with the UI."""
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtGui import QAccessible
|
||||
from PySide6.QtWidgets import QDialog, QHBoxLayout, QLabel, QLineEdit, QTableWidget, QTableWidgetItem, QToolButton, QWidget
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def navigation(qtbot):
|
||||
from dx_productivity.trial_task_center.models import TaskRecord, TaskStatus
|
||||
from dx_productivity.trial_task_center.ui.task_list import TaskList
|
||||
panel = TaskList(lambda _: None)
|
||||
qtbot.addWidget(panel)
|
||||
now = datetime.now(timezone.utc)
|
||||
tasks = tuple(TaskRecord(str(index), name, '', Path('F:/Projects'), TaskStatus.DRAFT,
|
||||
now, now, group_id='batch', group_position=index) for index, name in enumerate(('Board-A', 'Board-B')))
|
||||
panel.populate(tasks, selected_task_id='0')
|
||||
panel.show()
|
||||
return panel, tasks
|
||||
|
||||
|
||||
def accessible_name(widget):
|
||||
return QAccessible.queryAccessibleInterface(widget).text(QAccessible.Text.Name)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def panels(qtbot):
|
||||
from dx_productivity.trial_task_center.ui.task_list import TaskList
|
||||
from dx_productivity.trial_task_center.ui.project_plan import ProjectPlanPanel
|
||||
from dx_productivity.trial_task_center.ui.dsh_status import DshStatusIndicator
|
||||
owner = QWidget()
|
||||
qtbot.addWidget(owner)
|
||||
owner.task_list = TaskList(lambda _: None)
|
||||
owner.plan_panel = ProjectPlanPanel(owner)
|
||||
owner.ai_status_indicator = DshStatusIndicator(owner)
|
||||
layout = QHBoxLayout(owner)
|
||||
layout.addWidget(owner.task_list)
|
||||
layout.addWidget(owner.plan_panel)
|
||||
from dx_productivity.trial_task_center.ui.accessibility import apply_accessible_names
|
||||
apply_accessible_names(owner)
|
||||
owner.show()
|
||||
return owner
|
||||
|
||||
|
||||
def test_task_sort_keeps_selected_rows_and_the_visible_count(navigation):
|
||||
panel, tasks = navigation
|
||||
panel.select_all_button.click()
|
||||
selected = set(panel.selected_task_ids())
|
||||
assert len(selected) == 2
|
||||
panel.sort.setCurrentIndex(panel.sort.findData('name_desc'))
|
||||
assert set(panel.selected_task_ids()) == selected
|
||||
assert panel.count.text().endswith('已选 2')
|
||||
panel.search.setText(tasks[0].name)
|
||||
assert panel.selected_task_ids() == (tasks[0].task_id,)
|
||||
assert panel.count.text().endswith('已选 1')
|
||||
panel.clear_selection_button.click()
|
||||
assert not panel.selected_task_ids()
|
||||
assert '已选' not in panel.count.text()
|
||||
panel.search.clear()
|
||||
assert not panel.selected_task_ids()
|
||||
assert '已选' not in panel.count.text()
|
||||
|
||||
|
||||
def test_f2_edits_only_from_task_navigation_and_respects_button_gate(qtbot):
|
||||
from dx_productivity.trial_task_center.ui.task_list import TaskList
|
||||
owner = QWidget()
|
||||
qtbot.addWidget(owner)
|
||||
navigation = TaskList(lambda _: None)
|
||||
table = QTableWidget(1, 1)
|
||||
table.setItem(0, 0, QTableWidgetItem('OLD'))
|
||||
layout = QHBoxLayout(owner)
|
||||
layout.addWidget(navigation)
|
||||
layout.addWidget(table)
|
||||
owner.show()
|
||||
owner.activateWindow()
|
||||
qtbot.waitUntil(owner.isActiveWindow)
|
||||
clicked = []
|
||||
navigation.edit_button.clicked.connect(lambda: clicked.append(True))
|
||||
navigation.search.setFocus()
|
||||
qtbot.keyClick(navigation.search, Qt.Key.Key_F2)
|
||||
assert clicked == [True]
|
||||
navigation.edit_button.setEnabled(False)
|
||||
qtbot.keyClick(navigation.search, Qt.Key.Key_F2)
|
||||
assert clicked == [True]
|
||||
navigation.edit_button.setEnabled(True)
|
||||
table.setCurrentCell(0, 0)
|
||||
table.setFocus()
|
||||
qtbot.keyClick(table, Qt.Key.Key_F2)
|
||||
assert table.findChild(QLineEdit) is not None
|
||||
assert clicked == [True]
|
||||
|
||||
|
||||
def test_core_inputs_and_sort_icon_have_user_facing_accessible_names(panels):
|
||||
window = panels
|
||||
assert accessible_name(window.task_list.search) == '搜索工程任务'
|
||||
assert accessible_name(window.plan_panel.find_text) == '搜索位号计划'
|
||||
assert accessible_name(window.plan_panel.bulk_part) == '批量目标料号'
|
||||
assert accessible_name(window.findChild(QToolButton, 'taskSortMenu')) == '任务显示排序'
|
||||
assert window.ai_status_indicator.accessibleName()
|
||||
|
||||
|
||||
def test_inline_search_icons_describe_clear_and_find_next(panels):
|
||||
panel = panels.plan_panel
|
||||
panel.find_text.setText('R1')
|
||||
buttons = panel.find_text.findChildren(QToolButton)
|
||||
names = [accessible_name(button) for button in buttons]
|
||||
assert '清除搜索位号计划' in names
|
||||
assert '下一条匹配位号' in names
|
||||
|
||||
|
||||
def test_f5_uses_refresh_button_gate_and_shortcut_help_is_discoverable(panels, qtbot):
|
||||
from dx_productivity.trial_task_center.ui.run_panel import RunPanel
|
||||
from dx_productivity.trial_task_center.ui.project_summary import ProjectSummary
|
||||
from dx_productivity.trial_task_center.ui.shortcuts import install_window_shortcuts
|
||||
panels.project_summary = ProjectSummary(panels)
|
||||
panels.run_panel = RunPanel()
|
||||
panels.layout().addWidget(panels.run_panel)
|
||||
install_window_shortcuts(panels)
|
||||
clicks = []
|
||||
refresh = panels.project_summary.refresh_button
|
||||
refresh.clicked.connect(lambda: clicks.append(True))
|
||||
panels.activateWindow()
|
||||
qtbot.waitUntil(panels.isActiveWindow)
|
||||
panels.plan_panel.find_text.setFocus()
|
||||
qtbot.keyClick(panels.plan_panel.find_text, Qt.Key.Key_F5)
|
||||
assert clicks == [True]
|
||||
refresh.setEnabled(False)
|
||||
qtbot.keyClick(panels.plan_panel.find_text, Qt.Key.Key_F5)
|
||||
assert clicks == [True]
|
||||
refresh.setEnabled(True)
|
||||
refresh.hide()
|
||||
qtbot.keyClick(panels.plan_panel.find_text, Qt.Key.Key_F5)
|
||||
assert clicks == [True]
|
||||
panels.run_panel.more_menu.sync()
|
||||
help_action = next(action for action in panels.run_panel.more_menu.actions() if '快捷键' in action.text())
|
||||
assert help_action.isVisible() and help_action.isEnabled()
|
||||
help_action.trigger()
|
||||
dialog = panels.run_panel.findChild(QDialog, 'shortcutHelpDialog')
|
||||
assert dialog is not None and dialog.isVisible()
|
||||
text = '\n'.join(label.text() for label in dialog.findChildren(QLabel))
|
||||
assert 'F2' in text and 'F5' in text and 'Ctrl+F' in text
|
||||
assert '任务导航' in text and '位号计划' in text
|
||||
dialog.close()
|
||||
|
||||
|
||||
def test_task_menu_displays_f2_without_installing_a_second_shortcut(navigation):
|
||||
from PySide6.QtGui import QAction
|
||||
panel, _ = navigation
|
||||
panel.manage_menu.sync()
|
||||
assert any(action.text().endswith('\tF2') for action in panel.manage_menu.actions())
|
||||
assert sum(action.shortcut().toString() == 'F2' for action in panel.findChildren(QAction)) == 1
|
||||
|
||||
|
||||
def test_select_all_after_clear_selects_every_visible_task(navigation):
|
||||
panel, _ = navigation
|
||||
panel.clear_selection_button.click()
|
||||
panel.select_all_button.click()
|
||||
assert set(panel.selected_task_ids()) == {'0', '1'}
|
||||
assert panel.count.text().endswith('已选 2')
|
||||
|
||||
|
||||
def test_sort_keeps_visible_selection_when_current_task_is_filtered_out(navigation):
|
||||
panel, _ = navigation
|
||||
panel.select_all_button.click()
|
||||
panel.search.setText('Board-B')
|
||||
assert panel.current_task_id() is None
|
||||
assert panel.selected_task_ids() == ('1',)
|
||||
panel.sort.setCurrentIndex(panel.sort.findData('name_desc'))
|
||||
assert panel.selected_task_ids() == ('1',)
|
||||
assert panel.count.text().endswith('已选 1')
|
||||
|
||||
|
||||
def test_ctrl_click_empty_selection_survives_sort_filter_and_refresh(navigation, qtbot):
|
||||
panel, tasks = navigation
|
||||
assert panel.current_task_id() == '0'
|
||||
assert panel.selected_task_ids() == ('0',)
|
||||
position = panel.list.visualItemRect(panel.list.currentItem()).center()
|
||||
qtbot.mouseClick(panel.list.viewport(), Qt.MouseButton.LeftButton,
|
||||
Qt.KeyboardModifier.ControlModifier, position)
|
||||
assert panel.current_task_id() == '0'
|
||||
assert panel.selected_task_ids() == ()
|
||||
panel.sort.setCurrentIndex(panel.sort.findData('name_desc'))
|
||||
assert panel.selected_task_ids() == ()
|
||||
assert '已选' not in panel.count.text()
|
||||
panel.search.setText('Board-B')
|
||||
panel.populate(tasks, selected_task_id='0')
|
||||
panel.search.clear()
|
||||
assert panel.current_task_id() == '0'
|
||||
assert panel.selected_task_ids() == ()
|
||||
assert '已选' not in panel.count.text()
|
||||
panel.select_task('1')
|
||||
assert panel.selected_task_ids() == ('1',)
|
||||
|
||||
|
||||
def test_dialog_form_labels_are_effective_names_and_dynamic_ai_name_survives(panels, qtbot):
|
||||
from dx_productivity.trial_task_center.ui.accessibility import apply_accessible_names
|
||||
from dx_productivity.trial_task_center.ui.dialogs import _MappingDialog
|
||||
dialog = _MappingDialog(panels)
|
||||
qtbot.addWidget(dialog)
|
||||
apply_accessible_names(dialog)
|
||||
assert accessible_name(dialog.old_edit) == '旧物料编码'
|
||||
assert accessible_name(dialog.new_edit) == '新物料编码'
|
||||
assert accessible_name(dialog.custom_value_edit) == 'Value 内容'
|
||||
panels.ai_status_indicator.set_state('working', '执行中', '正在运行')
|
||||
apply_accessible_names(panels)
|
||||
assert accessible_name(panels.ai_status_indicator) == 'AI 自动介入:执行中'
|
||||
|
||||
|
||||
def test_window_shortcuts_use_live_task_gates_and_keep_project_bindings(ui, qtbot):
|
||||
from threading import Event
|
||||
from PySide6.QtGui import QAction
|
||||
window = ui.window
|
||||
assert accessible_name(window.plan_panel.bulk_part) == '批量目标料号'
|
||||
shortcuts = [action.shortcut().toString() for action in window.findChildren(QAction)]
|
||||
assert shortcuts.count('Ctrl+Shift+D') == 1
|
||||
assert shortcuts.count('F5') == 1
|
||||
refresh = window.project_summary.refresh_button
|
||||
clicked = []
|
||||
refresh.clicked.connect(lambda: clicked.append(True))
|
||||
window.activateWindow()
|
||||
qtbot.waitUntil(window.isActiveWindow)
|
||||
window.plan_panel.find_text.setFocus()
|
||||
qtbot.keyClick(window.plan_panel.find_text, Qt.Key.Key_F5)
|
||||
ui.settle()
|
||||
assert clicked == [True]
|
||||
release_worker = Event()
|
||||
window._run_async(lambda: release_worker.wait(5), lambda _: None)
|
||||
try:
|
||||
assert not refresh.isEnabled()
|
||||
qtbot.keyClick(window.plan_panel.find_text, Qt.Key.Key_F5)
|
||||
assert clicked == [True]
|
||||
finally:
|
||||
release_worker.set()
|
||||
ui.settle()
|
||||
window.task_list.clear_selection_button.click()
|
||||
ui.settle()
|
||||
assert not refresh.isEnabled()
|
||||
qtbot.keyClick(window.task_list.search, Qt.Key.Key_F5)
|
||||
assert clicked == [True]
|
||||
assert all(project.selected for task in ui.tasks for project in ui.store.list_projects(task.task_id))
|
||||
@@ -0,0 +1,262 @@
|
||||
"""Task navigation makes an explicit decision for every unsaved plan."""
|
||||
from dataclasses import replace
|
||||
from threading import Event
|
||||
|
||||
import pytest
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtWidgets import QLineEdit
|
||||
|
||||
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow
|
||||
|
||||
|
||||
def seed(ui):
|
||||
task = ui.tasks[0]
|
||||
project = ui.store.list_projects(task.task_id)[0].path
|
||||
rows = tuple(TargetPlanRow(ComponentTarget(project, 'MAIN', '1', f'nav-{i}',
|
||||
f'R{i+1}', 'OLD', '100nF'), False, 'NEW') for i in range(5))
|
||||
ui.store.record_target_inventory(task.task_id, tuple(row.target for row in rows))
|
||||
ui.service.replace_target_plan(task.task_id, rows)
|
||||
rows = ui.service.target_plan(task.task_id)
|
||||
ui.open(task); ui.settle()
|
||||
ui.window.mapping_tabs.setCurrentIndex(1)
|
||||
return ui.window.plan_panel, rows
|
||||
|
||||
|
||||
def edit_cell(panel, text='TYPED'):
|
||||
index = panel.table.model().index(0, 6)
|
||||
panel.table.setCurrentIndex(index)
|
||||
panel.table.setFocus()
|
||||
panel.table.edit(index)
|
||||
editor = panel.table.findChild(QLineEdit)
|
||||
assert editor is not None
|
||||
editor.setText(text)
|
||||
assert panel.table.has_pending_editor()
|
||||
return editor
|
||||
|
||||
|
||||
def test_cancel_task_switch_keeps_five_enabled_rows_and_list_focus(ui):
|
||||
panel, _ = seed(ui)
|
||||
panel.table.select_all_targets(True)
|
||||
choices = []
|
||||
ui.window._close_plan_confirmer = lambda: choices.append('asked') or 'cancel'
|
||||
ui.window.task_list.list.setCurrentRow(1)
|
||||
ui.settle()
|
||||
assert choices == ['asked']
|
||||
assert ui.window._task_id == ui.tasks[0].task_id
|
||||
assert ui.window.task_list.current_task_id() == ui.tasks[0].task_id
|
||||
assert all(row.enabled for row in panel.table.rows())
|
||||
assert panel.has_unsaved_plans()
|
||||
|
||||
|
||||
def test_same_task_refresh_preserves_uncommitted_text_without_prompt(ui):
|
||||
panel, _ = seed(ui)
|
||||
edit_cell(panel)
|
||||
ui.window._close_plan_confirmer = lambda: pytest.fail('metadata refresh is not navigation')
|
||||
ui.open(ui.tasks[0]); ui.settle()
|
||||
assert panel.table.dirty
|
||||
assert panel.table.rows()[0].new_part_number == 'TYPED'
|
||||
ui.window._close_plan_confirmer = lambda: 'cancel'
|
||||
|
||||
|
||||
def test_discard_restores_persisted_rows_before_later_save(ui):
|
||||
panel, original = seed(ui)
|
||||
panel.table.select_all_targets(True)
|
||||
panel.discard_all()
|
||||
assert panel.table.rows() == original
|
||||
assert not panel.has_unsaved_plans()
|
||||
panel.table.model().setData(panel.table.model().index(0, 6), 'LATER')
|
||||
panel.save(); ui.settle()
|
||||
assert not any(row.enabled for row in ui.service.target_plan(ui.tasks[0].task_id))
|
||||
|
||||
|
||||
def test_save_switch_waits_for_atomic_save_including_active_editor(ui, qtbot, monkeypatch):
|
||||
panel, _ = seed(ui)
|
||||
edit_cell(panel)
|
||||
started, release = Event(), Event()
|
||||
original = ui.service.save_plan_drafts
|
||||
def save(batches, standalone):
|
||||
started.set()
|
||||
assert release.wait(5)
|
||||
return original(batches, standalone)
|
||||
monkeypatch.setattr(ui.service, 'save_plan_drafts', save)
|
||||
ui.window._close_plan_confirmer = lambda: 'save'
|
||||
try:
|
||||
ui.window.open_task(ui.tasks[1].task_id)
|
||||
qtbot.waitUntil(started.is_set, timeout=2000)
|
||||
assert ui.window._task_id == ui.tasks[0].task_id
|
||||
assert panel.has_unsaved_plans()
|
||||
finally:
|
||||
release.set()
|
||||
ui.settle()
|
||||
assert ui.window._task_id == ui.tasks[1].task_id
|
||||
assert ui.service.target_plan(ui.tasks[0].task_id)[0].new_part_number == 'TYPED'
|
||||
assert not panel.has_unsaved_plans()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('choice', ['cancel', 'discard'])
|
||||
def test_task_switch_with_active_editor_has_explicit_choice(ui, choice):
|
||||
panel, original = seed(ui)
|
||||
edit_cell(panel)
|
||||
choices = []
|
||||
ui.window._close_plan_confirmer = lambda: choices.append('asked') or choice
|
||||
ui.window.open_task(ui.tasks[1].task_id)
|
||||
ui.settle()
|
||||
assert choices == ['asked']
|
||||
assert ui.window._task_id == ui.tasks[0 if choice == 'cancel' else 1].task_id
|
||||
assert ui.service.target_plan(ui.tasks[0].task_id) == original
|
||||
if choice == 'cancel':
|
||||
assert panel.has_unsaved_plans()
|
||||
assert panel.table.has_pending_editor() or panel.table.rows()[0].new_part_number == 'TYPED'
|
||||
else:
|
||||
assert not panel.has_unsaved_plans()
|
||||
ui.open(ui.tasks[0]); ui.settle()
|
||||
assert panel.table.rows() == original
|
||||
|
||||
|
||||
def test_failed_save_switch_preserves_current_editor_hidden_drafts_and_batches(ui, monkeypatch):
|
||||
from dx_productivity.trial_task_center.bom_batch import BomBatchPreview, BomProjectPreview
|
||||
panel, _ = seed(ui)
|
||||
edit_cell(panel)
|
||||
hidden = ui.tasks[1].task_id
|
||||
panel._drafts[hidden] = ()
|
||||
project = ui.store.list_projects(hidden)[0].path
|
||||
batch = BomBatchPreview(hidden, ((hidden, str(project)),),
|
||||
(BomProjectPreview(hidden, project, (), (), ()),))
|
||||
panel._bom_batches[(hidden,)] = batch
|
||||
calls = []
|
||||
def fail(batches, standalone):
|
||||
calls.append((batches, standalone))
|
||||
raise RuntimeError('controlled save failure')
|
||||
monkeypatch.setattr(ui.service, 'save_plan_drafts', fail)
|
||||
ui.window._close_plan_confirmer = lambda: 'save'
|
||||
ui.window.open_task(hidden)
|
||||
ui.settle()
|
||||
assert len(calls) == 1
|
||||
assert calls[0][0][0][0] == batch
|
||||
assert calls[0][1][ui.tasks[0].task_id][0].new_part_number == 'TYPED'
|
||||
assert ui.window._task_id == ui.tasks[0].task_id
|
||||
assert ui.window.task_list.current_task_id() == ui.tasks[0].task_id
|
||||
assert hidden in panel._drafts
|
||||
assert panel._bom_batches[(hidden,)] == batch
|
||||
assert panel.table.rows()[0].new_part_number == 'TYPED'
|
||||
assert panel.table.dirty
|
||||
assert not ui.calls
|
||||
ui.window._close_plan_confirmer = lambda: 'cancel'
|
||||
|
||||
|
||||
def test_hidden_draft_alone_requires_choice_and_discard_releases_all(ui):
|
||||
panel, _ = seed(ui)
|
||||
panel._drafts[ui.tasks[1].task_id] = ()
|
||||
choices = []
|
||||
ui.window._close_plan_confirmer = lambda: choices.append('asked') or 'discard'
|
||||
ui.open(ui.tasks[1]); ui.settle()
|
||||
assert choices == ['asked']
|
||||
assert not panel.has_unsaved_plans()
|
||||
|
||||
|
||||
def test_save_switch_includes_hidden_draft(ui, monkeypatch):
|
||||
panel, rows = seed(ui)
|
||||
hidden = ui.tasks[1].task_id
|
||||
project = ui.store.list_projects(hidden)[0].path
|
||||
hidden_rows = tuple(replace(row, target=replace(row.target, project_path=project)) for row in rows)
|
||||
ui.store.record_target_inventory(hidden, tuple(row.target for row in hidden_rows))
|
||||
ui.service.replace_target_plan(hidden, hidden_rows)
|
||||
panel._drafts[hidden] = (replace(hidden_rows[0], new_part_number='HIDDEN'),) + hidden_rows[1:]
|
||||
original = ui.service.save_plan_drafts
|
||||
received = []
|
||||
def save(batches, standalone):
|
||||
received.append(set(standalone))
|
||||
return original(batches, standalone)
|
||||
monkeypatch.setattr(ui.service, 'save_plan_drafts', save)
|
||||
ui.window._close_plan_confirmer = lambda: 'save'
|
||||
ui.window.open_task(hidden)
|
||||
ui.settle()
|
||||
assert received == [{hidden}]
|
||||
assert ui.window._task_id == hidden
|
||||
assert ui.service.target_plan(hidden)[0].new_part_number == 'HIDDEN'
|
||||
assert not panel.has_unsaved_plans()
|
||||
|
||||
|
||||
def test_newly_created_task_uses_the_same_unsaved_navigation_decision(ui):
|
||||
panel, _ = seed(ui)
|
||||
panel.table.select_all_targets(True)
|
||||
choices = []
|
||||
ui.window._close_plan_confirmer = lambda: choices.append('asked') or 'cancel'
|
||||
task = ui.service.create_task('New empty task')
|
||||
ui.window._project_tasks_created((task,))
|
||||
ui.settle()
|
||||
assert choices == ['asked']
|
||||
assert ui.window._task_id == ui.tasks[0].task_id
|
||||
assert panel.table.dirty
|
||||
|
||||
|
||||
def test_close_save_commits_active_editor_before_exiting(ui, qtbot):
|
||||
panel, _ = seed(ui)
|
||||
edit_cell(panel)
|
||||
ui.window.archive_on_close_check.setChecked(False)
|
||||
ui.window._close_plan_confirmer = lambda: 'save'
|
||||
ui.window.close()
|
||||
qtbot.waitUntil(lambda: ui.window._closed, timeout=5000)
|
||||
assert ui.service.target_plan(ui.tasks[0].task_id)[0].new_part_number == 'TYPED'
|
||||
assert not panel.has_unsaved_plans()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('destination', ['close', 'switch'])
|
||||
def test_save_during_slow_same_task_refresh_keeps_typed_text(ui, qtbot, monkeypatch, destination):
|
||||
panel, _ = seed(ui)
|
||||
edit_cell(panel, 'REFRESH_TYPED')
|
||||
task = ui.tasks[0]
|
||||
started, release = Event(), Event()
|
||||
original = ui.service.task_context
|
||||
def slow_context(task_id, **kwargs):
|
||||
if task_id == task.task_id and not started.is_set():
|
||||
started.set()
|
||||
assert release.wait(5)
|
||||
return original(task_id, **kwargs)
|
||||
monkeypatch.setattr(ui.service, 'task_context', slow_context)
|
||||
ui.window.archive_on_close_check.setChecked(False)
|
||||
ui.window._close_plan_confirmer = lambda: 'save'
|
||||
try:
|
||||
ui.window.open_task(task.task_id)
|
||||
qtbot.waitUntil(started.is_set, timeout=2000)
|
||||
if destination == 'close':
|
||||
ui.window.close()
|
||||
qtbot.waitUntil(lambda: not ui.window._workers, timeout=3000)
|
||||
assert ui.service.target_plan(task.task_id)[0].new_part_number == 'REFRESH_TYPED'
|
||||
assert not ui.window._closed
|
||||
release.set()
|
||||
qtbot.waitUntil(lambda: ui.window._closed, timeout=3000)
|
||||
else:
|
||||
ui.window.open_task(ui.tasks[1].task_id)
|
||||
qtbot.waitUntil(lambda: not ui.window._workers, timeout=3000)
|
||||
assert ui.window._task_id == ui.tasks[1].task_id
|
||||
assert ui.service.target_plan(task.task_id)[0].new_part_number == 'REFRESH_TYPED'
|
||||
finally:
|
||||
release.set()
|
||||
ui.window._close_plan_confirmer = lambda: 'cancel'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('destination', ['close', 'switch', 'save'])
|
||||
def test_rejected_editor_commit_keeps_text_and_does_not_dispatch_save(ui, monkeypatch, destination):
|
||||
panel, original = seed(ui)
|
||||
edit_cell(panel, 'KEEP_TYPED')
|
||||
panel.table.set_plan_editable(False)
|
||||
errors, writes = [], []
|
||||
monkeypatch.setattr(ui.window, '_show_error', lambda error, **_: errors.append(error))
|
||||
monkeypatch.setattr(ui.service, 'save_plan_drafts', lambda *args: writes.append(args))
|
||||
ui.window._close_plan_confirmer = lambda: 'save'
|
||||
try:
|
||||
if destination == 'close':
|
||||
ui.window.close()
|
||||
elif destination == 'switch':
|
||||
ui.window.open_task(ui.tasks[1].task_id)
|
||||
else:
|
||||
panel.save()
|
||||
assert errors
|
||||
assert not writes and not ui.window._workers
|
||||
assert not ui.window._close_saving and not ui.window._closed
|
||||
assert ui.window._task_id == ui.tasks[0].task_id
|
||||
assert panel.table.has_pending_editor()
|
||||
assert ui.service.target_plan(ui.tasks[0].task_id) == original
|
||||
finally:
|
||||
ui.window._close_plan_confirmer = lambda: 'cancel'
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Invalid Part Number drafts stay editable and identify their offending cell."""
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtWidgets import QLineEdit
|
||||
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow, compile_target_rules
|
||||
from dx_productivity.trial_task_center.ui.mapping_table import MappingTable
|
||||
from dx_productivity.trial_task_center.ui.target_table import TargetTable
|
||||
|
||||
|
||||
def target_row():
|
||||
return TargetPlanRow(ComponentTarget(Path('board.prj'), 'MAIN', '1', 'uid', 'R1', 'OLD', ''), True, 'NEW')
|
||||
|
||||
|
||||
@pytest.mark.parametrize('bulk', [False, True])
|
||||
def test_invalid_pn_highlight_and_tooltip_clear_after_correction(qtbot, bulk):
|
||||
table = TargetTable()
|
||||
qtbot.addWidget(table)
|
||||
table.populate((target_row(),))
|
||||
index = table.model().index(0, 6)
|
||||
if bulk:
|
||||
table.selectRow(0)
|
||||
table.apply_to_selected('BAD PART !!@#')
|
||||
else:
|
||||
assert table.model().setData(index, 'BAD PART !!@#')
|
||||
assert table.rows()[0].new_part_number == 'BAD PART !!@#' and table.dirty
|
||||
assert index.data(Qt.ItemDataRole.BackgroundRole) is not None
|
||||
assert '料号' in index.data(Qt.ItemDataRole.ToolTipRole)
|
||||
assert '空白' in index.data(Qt.ItemDataRole.ToolTipRole)
|
||||
with pytest.raises(TaskCenterError):
|
||||
compile_target_rules(table.rows())
|
||||
assert table.rows()[0].new_part_number == 'BAD PART !!@#'
|
||||
assert table.model().setData(index, 'NEW-OK')
|
||||
assert index.data(Qt.ItemDataRole.BackgroundRole) is None
|
||||
assert compile_target_rules(table.rows())[0].new_part_number == 'NEW-OK'
|
||||
|
||||
|
||||
def test_mapping_pn_error_is_visible_without_flagging_free_value(qtbot):
|
||||
from types import SimpleNamespace
|
||||
table = MappingTable()
|
||||
qtbot.addWidget(table)
|
||||
table.populate((SimpleNamespace(rule_id='rule', old_part_number='OLD', new_part_number='BAD PART !!@#',
|
||||
custom_value_enabled=True, custom_value='free !@#', enabled=True, position=0),))
|
||||
assert table.model().index(0, 1).data(Qt.ItemDataRole.BackgroundRole) is not None
|
||||
assert '空白' in table.model().index(0, 1).data(Qt.ItemDataRole.ToolTipRole)
|
||||
assert table.model().index(0, 2).data(Qt.ItemDataRole.BackgroundRole) is None
|
||||
|
||||
|
||||
def test_part_number_editor_has_an_accessible_name(qtbot):
|
||||
table = TargetTable()
|
||||
qtbot.addWidget(table)
|
||||
table.populate((target_row(),))
|
||||
table.show()
|
||||
table.edit(table.model().index(0, 6))
|
||||
editor = table.findChild(QLineEdit)
|
||||
assert editor is not None and '新料号' in editor.accessibleName()
|
||||
|
||||
|
||||
def test_active_editor_commits_invalid_text_to_draft_without_losing_it(qtbot):
|
||||
table = TargetTable()
|
||||
qtbot.addWidget(table)
|
||||
table.populate((target_row(),))
|
||||
table.show()
|
||||
table.edit(table.model().index(0, 6))
|
||||
editor = table.findChild(QLineEdit)
|
||||
editor.setText('BAD PART !!@#')
|
||||
assert table.has_pending_editor()
|
||||
assert table.commit_editor()
|
||||
assert table.rows()[0].new_part_number == 'BAD PART !!@#' and table.dirty
|
||||
with pytest.raises(TaskCenterError):
|
||||
compile_target_rules(table.rows())
|
||||
assert not table.has_pending_editor()
|
||||
|
||||
|
||||
def test_rejected_readonly_editor_commit_preserves_text_and_allows_retry(qtbot):
|
||||
table = TargetTable()
|
||||
qtbot.addWidget(table)
|
||||
table.populate((target_row(),))
|
||||
table.show()
|
||||
table.edit(table.model().index(0, 6))
|
||||
editor = table.findChild(QLineEdit)
|
||||
editor.setText('PENDING-NEW')
|
||||
table.set_plan_editable(False)
|
||||
with pytest.raises(TaskCenterError, match='editor_commit'):
|
||||
table.commit_editor()
|
||||
assert table.rows()[0].new_part_number == 'NEW'
|
||||
assert table.has_pending_editor() and editor.text() == 'PENDING-NEW' and editor.isVisible()
|
||||
table.set_plan_editable(True)
|
||||
assert table.commit_editor()
|
||||
assert table.rows()[0].new_part_number == 'PENDING-NEW'
|
||||
assert not table.has_pending_editor()
|
||||
|
||||
|
||||
def test_unchanged_after_trim_editor_can_close_without_false_rejection(qtbot):
|
||||
table = TargetTable()
|
||||
qtbot.addWidget(table)
|
||||
table.populate((target_row(),))
|
||||
table.show()
|
||||
table.edit(table.model().index(0, 6))
|
||||
table.findChild(QLineEdit).setText(' NEW ')
|
||||
assert table.commit_editor()
|
||||
assert table.rows()[0].new_part_number == 'NEW' and not table.dirty
|
||||
@@ -63,7 +63,12 @@ def test_last_failed_item_keeps_stop_intent_in_automatic_diagnosis(ui,qtbot,monk
|
||||
monkeypatch.setattr(ui.service.for_project_task(task.task_id)._quick_run_preparer,'_process_runner',executor)
|
||||
monkeypatch.setattr(QMessageBox,'question',lambda *args:QMessageBox.StandardButton.Yes)
|
||||
def dispatch(operation,callback,*args,**kwargs):
|
||||
result=operation();outcomes.append(result);callback(result)
|
||||
result=operation()
|
||||
if kwargs.get('operation_area') == 'batch_preflight':
|
||||
callback(result)
|
||||
kwargs['on_finished']()
|
||||
return
|
||||
outcomes.append(result);callback(result)
|
||||
monkeypatch.setattr(window,'_run_async',dispatch)
|
||||
monkeypatch.setattr(window,'_open_dsh',lambda:None)
|
||||
automation=dsh_automation.DshAutomation(window)
|
||||
@@ -86,7 +91,7 @@ def test_last_failed_item_keeps_stop_intent_in_automatic_diagnosis(ui,qtbot,monk
|
||||
qtbot.waitUntil(finished,timeout=10000)
|
||||
monkeypatch.setattr(dsh_automation,'GitIssuePublisher',lambda *args:lambda *args:{'status':'unavailable'})
|
||||
if scope=='single':window._prepare_quick_run()
|
||||
else:window._execute_project_tasks()
|
||||
else:window._execute_project_tasks(selected=True)
|
||||
assert len(outcomes)==1
|
||||
# A stopped primary pass retains its deferred failures for explicit resume.
|
||||
# Its diagnosis must also retain the original stop/force request.
|
||||
@@ -111,7 +116,7 @@ def test_last_failed_item_keeps_stop_intent_in_automatic_diagnosis(ui,qtbot,monk
|
||||
window._tasks=(ui.service.get_task(task.task_id),)
|
||||
window._update_gates()
|
||||
if scope=='single':window._prepare_quick_run()
|
||||
else:window._execute_project_tasks()
|
||||
else:window._execute_project_tasks(selected=True)
|
||||
wait_for_diagnosis(original_run)
|
||||
ui.settle()
|
||||
# Explicit reauthorization performs the one shared replay. Its second
|
||||
|
||||
@@ -9,11 +9,16 @@ from dx_productivity.trial_task_center.stop_control import StopControl
|
||||
|
||||
@pytest.mark.parametrize('batch', [False, True])
|
||||
@pytest.mark.parametrize('change', ['worker', 'stop', 'closing', 'task', 'dirty', 'dialog'])
|
||||
def test_confirmation_rechecks_admission_before_authorizing_or_replacing_controls(ui, monkeypatch, batch, change):
|
||||
def test_confirmation_rechecks_admission_before_authorizing_or_replacing_controls(ui, monkeypatch, qtbot, batch, change):
|
||||
window = ui.window
|
||||
ui.settle()
|
||||
submitted = []
|
||||
monkeypatch.setattr(window, '_run_async', lambda *args, **kwargs: submitted.append(args))
|
||||
original_run_async = window._run_async
|
||||
def dispatch(*args, **kwargs):
|
||||
if kwargs.get('operation_area') == 'batch_preflight':
|
||||
return original_run_async(*args, **kwargs)
|
||||
submitted.append(args)
|
||||
monkeypatch.setattr(window, '_run_async', dispatch)
|
||||
original_task = window._task_id
|
||||
original_authorization = set(window._dsh_authorized_tasks)
|
||||
original_dialog = window._dsh_operations.dialog
|
||||
@@ -22,7 +27,9 @@ def test_confirmation_rechecks_admission_before_authorizing_or_replacing_control
|
||||
live_worker = object()
|
||||
live_run = {'active': True, 'run_id': 'already-running', 'task_id': 'other-owner'}
|
||||
|
||||
confirmation_seen = []
|
||||
def confirm(*_):
|
||||
confirmation_seen.append(True)
|
||||
if change in {'worker', 'stop'}:
|
||||
window._batch_stop = live_stop
|
||||
window._dsh_run_stop = live_stop
|
||||
@@ -42,6 +49,8 @@ def test_confirmation_rechecks_admission_before_authorizing_or_replacing_control
|
||||
window._quick_run_confirmer = confirm
|
||||
try:
|
||||
(window._execute_project_tasks if batch else window._prepare_quick_run)()
|
||||
if batch:
|
||||
qtbot.waitUntil(lambda: bool(confirmation_seen), timeout=5000)
|
||||
assert not submitted, 'stale confirmation must not submit another execution'
|
||||
assert window._dsh_authorized_tasks == original_authorization
|
||||
assert '未启动' in window.run_panel.operator_band.text()
|
||||
@@ -59,17 +68,24 @@ def test_confirmation_rechecks_admission_before_authorizing_or_replacing_control
|
||||
|
||||
|
||||
@pytest.mark.parametrize('batch', [False, True])
|
||||
def test_idle_confirmation_still_starts_execution_while_read_query_is_busy(ui, monkeypatch, batch):
|
||||
def test_idle_confirmation_still_starts_execution_while_read_query_is_busy(ui, monkeypatch, qtbot, batch):
|
||||
window = ui.window
|
||||
ui.settle()
|
||||
submitted = []
|
||||
monkeypatch.setattr(window, '_run_async', lambda *args, **kwargs: submitted.append(args))
|
||||
original_run_async = window._run_async
|
||||
def dispatch(*args, **kwargs):
|
||||
if kwargs.get('operation_area') == 'batch_preflight':
|
||||
return original_run_async(*args, **kwargs)
|
||||
submitted.append(args)
|
||||
monkeypatch.setattr(window, '_run_async', dispatch)
|
||||
original_query = window._feedback_query
|
||||
window._quick_run_confirmer = lambda *_: True
|
||||
# A background read is not the mutation/execution lane.
|
||||
window._feedback_query = SimpleNamespace(busy=True, invalidate=lambda: None)
|
||||
try:
|
||||
(window._execute_project_tasks if batch else window._prepare_quick_run)()
|
||||
if batch:
|
||||
qtbot.waitUntil(lambda: window._batch_stop is not None, timeout=5000)
|
||||
assert len(submitted) == 1
|
||||
assert isinstance(window._batch_stop, StopControl)
|
||||
assert ui.tasks[0].task_id in window._dsh_authorized_tasks
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
from dataclasses import replace
|
||||
|
||||
import pytest
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
|
||||
from dx_productivity.trial_task_center.batch_admission import build_batch_admission
|
||||
from dx_productivity.trial_task_center.models import TaskStatus
|
||||
|
||||
|
||||
def completed_context(ui, monkeypatch):
|
||||
task_id = ui.tasks[0].task_id
|
||||
ui.store.set_task_status(task_id, TaskStatus.RUNNING)
|
||||
ui.store.set_task_status(task_id, TaskStatus.COMPLETED)
|
||||
original = ui.service.task_context
|
||||
context = original(task_id)
|
||||
context = replace(context, has_evidence=True, progress=replace(context.progress,
|
||||
queue_complete=True, saved_items=1, completed_items=1, total_items=1, next_project_path=None))
|
||||
monkeypatch.setattr(ui.service, 'task_context',
|
||||
lambda key, **kw: context if key == task_id else original(key, **kw))
|
||||
return task_id, context
|
||||
|
||||
|
||||
@pytest.mark.parametrize('missing', ['round', 'history'])
|
||||
def test_legacy_completed_explains_missing_evidence_without_claiming_acceptance(ui, monkeypatch, missing):
|
||||
task_id, _ = completed_context(ui, monkeypatch)
|
||||
if missing == 'history':
|
||||
with ui.store.transaction():
|
||||
ui.store._connection.execute('INSERT INTO execution_rounds(task_id,round_id) VALUES (?,?)', (task_id, 'r'))
|
||||
admission = build_batch_admission(ui.service, tuple(t.task_id for t in ui.tasks), scope_kind='batch')
|
||||
row = admission['decisions'][0]
|
||||
assert row['classification'] == 'held' and not admission['ready']
|
||||
assert row['acceptance_reason'] == f'acceptance_{missing}_missing'
|
||||
assert '归档' in row['message'] and '日志' in row['message']
|
||||
assert not ui.calls
|
||||
|
||||
|
||||
def test_legacy_completed_archive_action_preserves_original_evidence(ui, qtbot, monkeypatch):
|
||||
task_id, context = completed_context(ui, monkeypatch)
|
||||
ui.window._context = context
|
||||
ui.window._update_gates()
|
||||
assert ui.window.task_list.archive_button.isEnabled()
|
||||
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **kw: QMessageBox.StandardButton.Yes)
|
||||
ui.window.task_list.archive_button.click()
|
||||
qtbot.waitUntil(lambda: ui.service.get_task(task_id).status is TaskStatus.DELETED, timeout=5000)
|
||||
ui.settle()
|
||||
assert ui.service.get_task(ui.tasks[1].task_id).status is not TaskStatus.DELETED
|
||||
assert not ui.calls
|
||||
|
||||
|
||||
def test_diagnostics_export_discloses_retained_project_paths(ui):
|
||||
assert '工程路径' in ui.window.run_panel.diagnostics_button.toolTip()
|
||||
assert '凭据' in ui.window.run_panel.diagnostics_button.toolTip()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('missing', ['round_state', 'operations'])
|
||||
def test_incomplete_round_evidence_cannot_certify_a_completed_task(ui, monkeypatch, missing):
|
||||
from dx_productivity.dsh.run_journal import RunJournal
|
||||
from dx_productivity.trial_task_center.task_queue import _plan_hash
|
||||
task_id, _ = completed_context(ui, monkeypatch)
|
||||
with ui.store.transaction():
|
||||
ui.store._connection.execute('INSERT INTO execution_rounds(task_id,round_id) VALUES (?,?)', (task_id, 'r'))
|
||||
source = {'round_id': 'r'}
|
||||
if missing == 'round_state':
|
||||
source['state'] = 'unknown'
|
||||
summary = {'source_versions': {'rounds': {task_id: source}},
|
||||
'operation_evidence_missing': [task_id] if missing == 'operations' else []}
|
||||
journal = RunJournal(ui.data)
|
||||
journal.begin('f' * 32, [task_id], {task_id: _plan_hash(ui.service.for_project_task(task_id), task_id)})
|
||||
journal.finish('f' * 32, {'status': 'completed', 'summary': summary,
|
||||
'netlist_verification': {task_id: {'status': 'verified', 'verified': True}}})
|
||||
result = build_batch_admission(ui.service, tuple(t.task_id for t in ui.tasks), scope_kind='batch')
|
||||
assert not result['ready']
|
||||
assert result['decisions'][0]['acceptance_reason'] == 'acceptance_evidence_unavailable'
|
||||
assert not ui.calls
|
||||
@@ -0,0 +1,108 @@
|
||||
"""Regressions from PR #47 audit 649 at the actual service/UI boundaries."""
|
||||
import json
|
||||
from dataclasses import replace
|
||||
import pytest
|
||||
|
||||
from PySide6.QtCore import QSignalBlocker, Qt
|
||||
|
||||
|
||||
def test_batch_preview_reads_full_group_from_db_when_navigation_cache_is_stale(ui, qtbot):
|
||||
ui.window._tasks = (ui.tasks[0],)
|
||||
seen = []
|
||||
ui.window._quick_run_confirmer = lambda *_: seen.append(ui.window._batch_confirmation_admission) or False
|
||||
ui.window._execute_project_tasks()
|
||||
qtbot.waitUntil(lambda: bool(seen), timeout=5000)
|
||||
ui.settle()
|
||||
assert seen[0]['candidate_task_ids'] == [task.task_id for task in ui.tasks]
|
||||
assert not ui.calls
|
||||
|
||||
|
||||
def test_selected_scope_uses_selected_group_instead_of_detail_focus(ui, qtbot, tmp_path):
|
||||
project = tmp_path / 'other-group' / 'board.prj'
|
||||
project.parent.mkdir()
|
||||
project.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
|
||||
selected, = ui.service.create_project_tasks(project.parent)
|
||||
ui.service.add_rule(selected.task_id, 'OLD', 'NEW')
|
||||
ui.window._tasks = ui.service.tasks()
|
||||
ui.window.task_list.populate(ui.window._tasks, selected_task_id=ui.tasks[0].task_id)
|
||||
with QSignalBlocker(ui.window.task_list.list):
|
||||
ui.window.task_list.list.clearSelection()
|
||||
for row in range(ui.window.task_list.list.count()):
|
||||
item = ui.window.task_list.list.item(row)
|
||||
item.setSelected(item.data(Qt.ItemDataRole.UserRole) == selected.task_id)
|
||||
ui.window._update_gates()
|
||||
seen = []
|
||||
ui.window._quick_run_confirmer = lambda *_: seen.append(ui.window._batch_confirmation_admission) or False
|
||||
ui.window._execute_project_tasks(selected=True)
|
||||
qtbot.waitUntil(lambda: bool(seen), timeout=5000)
|
||||
ui.settle()
|
||||
assert seen[0]['candidate_task_ids'] == [selected.task_id]
|
||||
assert seen[0]['group_id'] == selected.group_id
|
||||
assert not ui.calls
|
||||
|
||||
|
||||
def test_problem_overview_includes_pending_save_and_blocks_failed_retries(ui):
|
||||
from dx_productivity.trial_task_center.execution_problems import ExecutionProblems
|
||||
task_id = ui.tasks[0].task_id
|
||||
with ui.store.transaction():
|
||||
ui.store._connection.execute('INSERT INTO execution_rounds(task_id,round_id) VALUES (?,?)', (task_id, 'r'))
|
||||
for key, state in (('saved-pending', 'pending_save'), ('failed', 'failed')):
|
||||
command = json.dumps({'project_path': str(ui.service.projects(task_id)[0].path),
|
||||
'target_selectors': 'uid\x1fR1', 'schematic_name': 'MAIN', 'sheet_number': '1'})
|
||||
ui.store._connection.execute('INSERT INTO execution_operations VALUES (?,?,?,?,?,?,?,?)',
|
||||
(task_id, 'r', key, command, state, 'attempt', 1, '{}'))
|
||||
overview = ExecutionProblems(ui.store).overview(task_id)
|
||||
assert overview['uncertain'] == 1
|
||||
assert {row['state'] for row in overview['items']} == {'pending_save', 'failed'}
|
||||
assert all(not row['can_retry'] for row in overview['items'])
|
||||
|
||||
|
||||
@pytest.mark.parametrize('verified,has_round', [(False, True), (True, True), (True, False)])
|
||||
def test_completed_tasks_require_current_round_acceptance(ui, monkeypatch, verified, has_round):
|
||||
from dx_productivity.dsh.run_journal import RunJournal
|
||||
from dx_productivity.trial_task_center.batch_admission import build_batch_admission
|
||||
from dx_productivity.trial_task_center.models import TaskStatus
|
||||
from dx_productivity.trial_task_center.task_queue import _plan_hash
|
||||
task_id = ui.tasks[0].task_id
|
||||
ui.store.set_task_status(task_id, TaskStatus.RUNNING)
|
||||
ui.store.set_task_status(task_id, TaskStatus.COMPLETED)
|
||||
original = ui.service.task_context
|
||||
context = original(task_id)
|
||||
completed = replace(context, has_evidence=True, progress=replace(context.progress,
|
||||
queue_complete=True, saved_items=1, completed_items=1, total_items=1, next_project_path=None))
|
||||
monkeypatch.setattr(ui.service, 'task_context', lambda key, **kw: completed if key == task_id else original(key, **kw))
|
||||
if has_round:
|
||||
with ui.store.transaction():
|
||||
ui.store._connection.execute('INSERT INTO execution_rounds(task_id,round_id) VALUES (?,?)', (task_id, 'r'))
|
||||
journal = RunJournal(ui.data)
|
||||
journal.begin('f' * 32, [task_id], {task_id: _plan_hash(ui.service.for_project_task(task_id), task_id)})
|
||||
journal.finish('f' * 32, {'status': 'completed' if verified else 'failed',
|
||||
'acceptance': {'status': 'verified' if verified else 'different'},
|
||||
'summary': {'source_versions': {'rounds': {task_id: {'round_id': 'r'}}}},
|
||||
'netlist_verification': {task_id: {'status': 'verified' if verified else 'different', 'verified': verified}}})
|
||||
admission = build_batch_admission(ui.service, tuple(t.task_id for t in ui.tasks), scope_kind='batch')
|
||||
accepted = verified and has_round
|
||||
assert admission['ready'] is accepted
|
||||
assert admission['decisions'][0]['classification'] == ('already_completed' if accepted else 'held')
|
||||
if not accepted:
|
||||
assert '验收' in admission['decisions'][0]['message']
|
||||
|
||||
|
||||
def test_duplicate_project_is_rejected_even_when_first_task_is_completed(ui, monkeypatch):
|
||||
from dx_productivity.trial_task_center.batch_admission import build_batch_admission
|
||||
from dx_productivity.trial_task_center.models import TaskStatus
|
||||
first, second = ui.tasks
|
||||
project = ui.service.projects(first.task_id)[0]
|
||||
with ui.store.transaction():
|
||||
ui.store._connection.execute('UPDATE projects SET path=? WHERE task_id=?', (str(project.path), second.task_id))
|
||||
ui.store.set_task_status(first.task_id, TaskStatus.RUNNING)
|
||||
ui.store.set_task_status(first.task_id, TaskStatus.COMPLETED)
|
||||
original = ui.service.task_context
|
||||
context = original(first.task_id)
|
||||
completed = replace(context, has_evidence=True, progress=replace(context.progress,
|
||||
queue_complete=True, no_match_items=1, completed_items=1, total_items=1, next_project_path=None))
|
||||
monkeypatch.setattr(ui.service, 'task_context', lambda key, **kw: completed if key == first.task_id else original(key, **kw))
|
||||
admission = build_batch_admission(ui.service, (first.task_id, second.task_id), scope_kind='batch')
|
||||
assert not admission['ready']
|
||||
assert admission['decisions'][1]['reason_code'] == 'project_duplicate'
|
||||
assert not ui.calls
|
||||
@@ -0,0 +1,240 @@
|
||||
"""Incremental regression cases for PR 48 review comment 667."""
|
||||
from dataclasses import replace
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from PySide6.QtCore import QPersistentModelIndex, QRect, Qt
|
||||
from PySide6.QtGui import QAccessible
|
||||
from PySide6.QtWidgets import QApplication, QMessageBox
|
||||
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
from dx_productivity.trial_task_center.models import TaskStatus
|
||||
from tests.ui.test_issue45_unsaved import seed, edit_cell
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def keep_pending_plans_open(ui):
|
||||
ui.window._close_plan_confirmer = lambda: 'cancel'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('choice', ['cancel', 'discard', 'save'])
|
||||
def test_soft_delete_resolves_active_editor_before_removal(ui, monkeypatch, choice):
|
||||
panel, original = seed(ui)
|
||||
task = ui.tasks[0]
|
||||
edit_cell(panel, 'DELETE_TYPED')
|
||||
asked = []
|
||||
ui.window._close_plan_confirmer = lambda: asked.append(True) or choice
|
||||
monkeypatch.setattr(QMessageBox, 'question', lambda *args: QMessageBox.StandardButton.Yes)
|
||||
ui.window._delete_task()
|
||||
ui.settle()
|
||||
assert asked == [True]
|
||||
if choice == 'cancel':
|
||||
assert ui.service.get_task(task.task_id).status is not TaskStatus.DELETED
|
||||
assert panel.has_unsaved_plans()
|
||||
assert panel.table.has_pending_editor() or panel.table.rows()[0].new_part_number == 'DELETE_TYPED'
|
||||
assert ui.service.target_plan(task.task_id) == original
|
||||
else:
|
||||
assert ui.service.get_task(task.task_id).status is TaskStatus.DELETED
|
||||
assert not panel.has_unsaved_plans() and not panel.table._active_editor
|
||||
saved = ui.service.target_plan(task.task_id)
|
||||
assert saved[0].new_part_number == ('DELETE_TYPED' if choice == 'save' else 'NEW')
|
||||
|
||||
|
||||
def test_delete_save_failure_keeps_input_and_task(ui, monkeypatch):
|
||||
panel, _ = seed(ui)
|
||||
edit_cell(panel, 'KEEP_TYPED')
|
||||
ui.window._close_plan_confirmer = lambda: 'save'
|
||||
errors = []
|
||||
monkeypatch.setattr(ui.window, '_show_error', lambda error, **kwargs: errors.append(error))
|
||||
monkeypatch.setattr(QMessageBox, 'question', lambda *args: QMessageBox.StandardButton.Yes)
|
||||
def fail(*args):
|
||||
raise TaskCenterError('controlled_save', 'controlled save failure')
|
||||
monkeypatch.setattr(ui.service, 'save_plan_drafts', fail)
|
||||
ui.window._delete_task()
|
||||
ui.settle()
|
||||
assert ui.service.get_task(ui.tasks[0].task_id).status is not TaskStatus.DELETED
|
||||
assert panel.has_unsaved_plans()
|
||||
assert panel.table.rows()[0].new_part_number == 'KEEP_TYPED'
|
||||
assert errors
|
||||
ui.window._close_plan_confirmer = lambda: 'cancel'
|
||||
|
||||
|
||||
def test_archive_cancel_keeps_active_editor(ui, monkeypatch):
|
||||
panel, _ = seed(ui)
|
||||
edit_cell(panel, 'ARCHIVE_TYPED')
|
||||
ui.window._context = replace(ui.window._context,
|
||||
task=replace(ui.window._context.task, status=TaskStatus.COMPLETED))
|
||||
ui.window._close_plan_confirmer = lambda: 'cancel'
|
||||
calls = []
|
||||
import dx_productivity.trial_task_center.task_archive as archive
|
||||
monkeypatch.setattr(archive, 'archive_completed_session', lambda *a, **k: calls.append(True))
|
||||
monkeypatch.setattr(QMessageBox, 'question', lambda *args: QMessageBox.StandardButton.Yes)
|
||||
ui.window._archive_completed_task()
|
||||
ui.settle()
|
||||
assert not calls
|
||||
assert panel.has_unsaved_plans()
|
||||
assert panel.table.has_pending_editor() or panel.table.rows()[0].new_part_number == 'ARCHIVE_TYPED'
|
||||
|
||||
|
||||
def test_archive_discard_cleans_the_removed_editor(ui, monkeypatch):
|
||||
from dx_productivity.trial_task_center.task_archive import ArchiveReport
|
||||
import dx_productivity.trial_task_center.task_archive as archive
|
||||
panel, _ = seed(ui)
|
||||
task = ui.tasks[0].task_id
|
||||
edit_cell(panel, 'ARCHIVE_TYPED')
|
||||
ui.window._context = replace(ui.window._context,
|
||||
task=replace(ui.window._context.task, status=TaskStatus.COMPLETED))
|
||||
ui.window._close_plan_confirmer = lambda: 'discard'
|
||||
def removed(*args, **kwargs):
|
||||
assert not panel.has_unsaved_plans()
|
||||
ui.service.delete_task(task)
|
||||
return ArchiveReport((task,))
|
||||
monkeypatch.setattr(archive, 'archive_completed_session', removed)
|
||||
monkeypatch.setattr(QMessageBox, 'question', lambda *args: QMessageBox.StandardButton.Yes)
|
||||
ui.window._archive_completed_task()
|
||||
ui.settle()
|
||||
assert ui.service.get_task(task).status is TaskStatus.DELETED
|
||||
assert panel.task_id is None and not panel.has_unsaved_plans()
|
||||
assert panel.table._active_editor is None
|
||||
|
||||
|
||||
def test_failed_refresh_commit_invalidates_context_and_blocks_execution(ui, monkeypatch):
|
||||
from dx_productivity.trial_task_center.ui.operation_state import ContextReadPhase
|
||||
panel, _ = seed(ui)
|
||||
edit_cell(panel, 'KEEP_TYPED')
|
||||
commit = panel.table.commit_editor
|
||||
def fail():
|
||||
raise TaskCenterError('editor_commit', 'controlled commit failure')
|
||||
monkeypatch.setattr(panel.table, 'commit_editor', fail)
|
||||
assert ui.window._load_task_data() is False
|
||||
assert ui.window._context is None
|
||||
assert ui.window._context_phase is ContextReadPhase.FAILED
|
||||
assert not ui.window.run_panel.quick_run_button.isEnabled()
|
||||
assert panel.table.has_pending_editor()
|
||||
monkeypatch.setattr(panel.table, 'commit_editor', commit)
|
||||
ui.window._refresh_bound_project()
|
||||
ui.settle()
|
||||
assert ui.window._context_phase is ContextReadPhase.READY
|
||||
assert panel.table.has_pending_editor()
|
||||
panel.save()
|
||||
ui.settle()
|
||||
assert ui.service.target_plan(ui.tasks[0].task_id)[0].new_part_number == 'KEEP_TYPED'
|
||||
|
||||
|
||||
def test_bom_preview_commit_failure_keeps_editor_and_existing_preview(ui):
|
||||
from dx_productivity.trial_task_center.bom_batch import BomBatchPreview, BomProjectPreview
|
||||
panel, rows = seed(ui)
|
||||
task = ui.tasks[0].task_id
|
||||
project = ui.store.list_projects(task)[0].path
|
||||
preview = BomBatchPreview(task, ((task, str(project)),),
|
||||
(BomProjectPreview(task, project, rows, (), ()),))
|
||||
edit_cell(panel, 'KEEP_TYPED')
|
||||
panel.table.set_plan_editable(False)
|
||||
assert panel._preview_bom(preview) is False
|
||||
assert not panel._bom_batches and not panel._drafts
|
||||
assert panel.table.has_pending_editor()
|
||||
assert '当前编辑内容' in ui.window.run_panel.operator_band.text()
|
||||
|
||||
|
||||
def test_invalid_editor_index_is_cancelled_and_tracking_cleared(ui):
|
||||
panel, _ = seed(ui)
|
||||
editor = edit_cell(panel)
|
||||
panel.table._active_editor = (editor, QPersistentModelIndex())
|
||||
closed = []
|
||||
panel.table.itemDelegate().closeEditor.connect(lambda *args: closed.append(args))
|
||||
panel.table.commit_editor()
|
||||
assert panel.table._active_editor is None
|
||||
assert len(closed) == 1
|
||||
|
||||
|
||||
def test_task_navigation_and_actual_list_have_accessible_names(ui):
|
||||
for widget in (ui.window.task_list, ui.window.task_list.list):
|
||||
interface = QAccessible.queryAccessibleInterface(widget)
|
||||
assert interface.text(QAccessible.Text.Name)
|
||||
|
||||
|
||||
def test_disabled_blank_mapping_has_no_pn_error(ui):
|
||||
rule = ui.store.list_rules(ui.tasks[0].task_id)[0]
|
||||
ui.window.mapping_table.populate((replace(rule, enabled=False, new_part_number=''),))
|
||||
index = ui.window.mapping_table.model().index(0, 1)
|
||||
assert index.data(Qt.ItemDataRole.BackgroundRole) is None
|
||||
|
||||
|
||||
def test_legacy_invalid_rules_can_be_quarantined_but_not_reenabled(ui):
|
||||
task = ui.tasks[0].task_id
|
||||
rules = [ui.store.list_rules(task)[0], ui.store.add_rule(task, 'OTHER', 'NEW-2')]
|
||||
with ui.store.transaction():
|
||||
for rule in rules:
|
||||
ui.store._connection.execute('UPDATE rules SET new_part_number=? WHERE rule_id=?',
|
||||
('LEGACY BAD!', rule.rule_id))
|
||||
for rule in rules:
|
||||
disabled = ui.service.update_rule(rule.rule_id, old_part_number=rule.old_part_number,
|
||||
new_part_number='LEGACY BAD!', enabled=False)
|
||||
assert not disabled.enabled
|
||||
for rule in rules:
|
||||
with pytest.raises(TaskCenterError):
|
||||
ui.store.update_rule(rule.rule_id, old_part_number=rule.old_part_number,
|
||||
new_part_number='LEGACY BAD!', enabled=True)
|
||||
with pytest.raises(TaskCenterError):
|
||||
ui.store.update_rule(rule.rule_id, old_part_number=rule.old_part_number,
|
||||
new_part_number='OTHER BAD!', enabled=False)
|
||||
repaired = ui.service.update_rule(rule.rule_id, old_part_number=rule.old_part_number,
|
||||
new_part_number='REPAIRED', enabled=False)
|
||||
assert repaired.new_part_number == 'REPAIRED'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('value', [123, None])
|
||||
def test_nontext_pn_is_rejected_without_mutating_rules(ui, value):
|
||||
task = ui.tasks[0].task_id
|
||||
original = ui.store.list_rules(task)
|
||||
with pytest.raises(TaskCenterError, match='part_number'):
|
||||
ui.store.add_rule(task, 'OTHER', value)
|
||||
with pytest.raises(TaskCenterError, match='part_number'):
|
||||
ui.service.update_rule(original[0].rule_id, old_part_number='OLD',
|
||||
new_part_number=value, enabled=True)
|
||||
assert ui.store.list_rules(task) == original
|
||||
|
||||
|
||||
def test_filtering_cancels_hidden_selection_with_an_explicit_hint(ui):
|
||||
panel = ui.window.task_list
|
||||
panel.select_all_tasks()
|
||||
panel.search.setText('Board-A')
|
||||
assert len(panel.selected_task_ids()) == 1
|
||||
panel.search.clear()
|
||||
assert len(panel.selected_task_ids()) == 1
|
||||
assert '不恢复' in panel.search.toolTip()
|
||||
assert '可见' in panel.selected_queue_button.toolTip()
|
||||
|
||||
|
||||
def test_legacy_quarantine_still_respects_frozen_batch_members(ui):
|
||||
rule = ui.store.list_rules(ui.tasks[0].task_id)[0]
|
||||
with ui.store.transaction():
|
||||
ui.store._connection.execute('UPDATE rules SET new_part_number=? WHERE rule_id=?',
|
||||
('LEGACY BAD!', rule.rule_id))
|
||||
ui.store.set_task_status(ui.tasks[1].task_id, TaskStatus.READY)
|
||||
ui.store.set_task_status(ui.tasks[1].task_id, TaskStatus.RUNNING)
|
||||
before = tuple(ui.store.list_rules(task.task_id) for task in ui.tasks)
|
||||
with pytest.raises(TaskCenterError):
|
||||
ui.service.update_rule(rule.rule_id, old_part_number='OLD',
|
||||
new_part_number='LEGACY BAD!', enabled=False)
|
||||
assert tuple(ui.store.list_rules(task.task_id) for task in ui.tasks) == before
|
||||
|
||||
|
||||
def test_tiny_workarea_keeps_force_stop_reachable(ui, monkeypatch):
|
||||
window = ui.window
|
||||
screen = SimpleNamespace(availableGeometry=lambda: QRect(0, 0, 640, 344),
|
||||
logicalDotsPerInch=lambda: 288, devicePixelRatio=lambda: 3, name=lambda: 'tiny-workarea')
|
||||
monkeypatch.setattr(QApplication, 'screenAt', lambda _: screen)
|
||||
window._begin_run(ui.tasks[0].task_id)
|
||||
window._update_gates()
|
||||
try:
|
||||
window._restore_window_geometry(restore_saved=False)
|
||||
for button in (window.run_panel.force_stop_button, window.run_panel.stop_queue_button):
|
||||
assert button.isVisible() and button.isEnabled()
|
||||
window.workspace_scroll.ensureWidgetVisible(button, 0, 0)
|
||||
QApplication.processEvents()
|
||||
rect = window.workspace_scroll.viewport().rect()
|
||||
assert rect.contains(button.mapTo(window.workspace_scroll.viewport(), button.rect().bottomRight()))
|
||||
assert screen.availableGeometry().contains(window.frameGeometry())
|
||||
finally:
|
||||
window._finish_run()
|
||||
@@ -0,0 +1,169 @@
|
||||
"""Review 669: failure admission, partial reads and shutdown."""
|
||||
from dataclasses import replace
|
||||
from threading import Event
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from PySide6.QtCore import QRect
|
||||
from PySide6.QtWidgets import QApplication, QMessageBox
|
||||
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
from dx_productivity.trial_task_center.models import TaskStatus
|
||||
from dx_productivity.trial_task_center.ui.operation_state import ContextReadPhase
|
||||
from tests.ui.test_issue45_unsaved import seed, edit_cell
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def retain_drafts(ui):
|
||||
ui.window._close_plan_confirmer = lambda: 'cancel'
|
||||
|
||||
|
||||
def test_context_failure_closes_previously_enabled_gates_without_error_renderer(ui, monkeypatch):
|
||||
panel, _ = seed(ui)
|
||||
panel.table.select_all_targets(True)
|
||||
ui.window._update_gates()
|
||||
assert ui.window.run_panel.quick_run_button.isEnabled()
|
||||
assert panel.save_button.isEnabled() and panel._editable
|
||||
monkeypatch.setattr(ui.window, '_show_error', lambda *args, **kwargs: None)
|
||||
ui.window._task_context_failed(TaskCenterError('read_failed', 'controlled read failure'))
|
||||
assert not ui.window.run_panel.quick_run_button.isEnabled()
|
||||
assert not panel.save_button.isEnabled() and not panel._editable
|
||||
assert panel.table.dirty
|
||||
|
||||
|
||||
def test_pending_bom_read_failure_does_not_publish_new_task_with_old_rows(ui, monkeypatch):
|
||||
panel, old = seed(ui)
|
||||
other = ui.tasks[1].task_id
|
||||
context = ui.service.task_context(other)
|
||||
ui.window._task_id = other
|
||||
def fail(task):
|
||||
raise TaskCenterError('pending_read', 'controlled pending read failure')
|
||||
monkeypatch.setattr(ui.service, 'pending_bom', fail)
|
||||
ui.window._apply_task_context(context, auto_intervene=False)
|
||||
assert ui.window._context_phase is ContextReadPhase.FAILED
|
||||
assert not (panel.task_id == other and panel.table.rows() == old)
|
||||
assert not panel.save_button.isEnabled()
|
||||
writes = []
|
||||
monkeypatch.setattr(ui.service, 'replace_target_plan', lambda *args: writes.append(args))
|
||||
panel.save()
|
||||
assert not writes
|
||||
|
||||
|
||||
@pytest.mark.parametrize('action', ['delete', 'archive'])
|
||||
def test_unsaved_cancel_precedes_destructive_confirmation(ui, monkeypatch, action):
|
||||
panel, _ = seed(ui)
|
||||
edit_cell(panel)
|
||||
if action == 'archive':
|
||||
ui.window._context = replace(ui.window._context,
|
||||
task=replace(ui.window._context.task, status=TaskStatus.COMPLETED))
|
||||
asked = []
|
||||
monkeypatch.setattr(QMessageBox, 'question', lambda *a: asked.append(True) or QMessageBox.StandardButton.Yes)
|
||||
getattr(ui.window, '_delete_task' if action == 'delete' else '_archive_completed_task')()
|
||||
assert not asked
|
||||
assert panel.has_unsaved_plans()
|
||||
|
||||
|
||||
def test_retry_retains_editor_but_respects_new_locked_context(ui):
|
||||
panel, _ = seed(ui)
|
||||
edit_cell(panel, 'LOCKED_TYPED')
|
||||
ui.window._task_context_failed(TaskCenterError('read_failed', 'controlled failure'), auto_intervene=False)
|
||||
ui.store.set_task_status(ui.tasks[0].task_id, TaskStatus.READY)
|
||||
ui.store.set_task_status(ui.tasks[0].task_id, TaskStatus.RUNNING)
|
||||
ui.window._refresh_bound_project()
|
||||
ui.settle()
|
||||
assert ui.window._context_phase is ContextReadPhase.READY
|
||||
assert not panel._editable and not panel.save_button.isEnabled()
|
||||
assert panel.table.has_pending_editor()
|
||||
assert not ui.window.run_panel.quick_run_button.isEnabled()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('page_name,buttons', [
|
||||
('history_panel', ('refresh_button', 'clear_button', 'older_button')),
|
||||
('verification_panel', ('new_button', 'export_button', 'stop_button')),
|
||||
])
|
||||
def test_other_workspaces_can_scroll_all_controls_into_tiny_viewport(ui, monkeypatch, page_name, buttons):
|
||||
window = ui.window
|
||||
screen = SimpleNamespace(availableGeometry=lambda: QRect(0, 0, 640, 344),
|
||||
logicalDotsPerInch=lambda: 288, devicePixelRatio=lambda: 3, name=lambda: 'tiny')
|
||||
monkeypatch.setattr(QApplication, 'screenAt', lambda _: screen)
|
||||
panel = getattr(window, page_name)
|
||||
window.content_stack.setCurrentWidget(panel)
|
||||
window._restore_window_geometry(restore_saved=False)
|
||||
assert window.workspace_scroll.widget().isAncestorOf(panel)
|
||||
assert screen.availableGeometry().contains(window.frameGeometry())
|
||||
for name in buttons:
|
||||
button = getattr(panel, name)
|
||||
window.workspace_scroll.ensureWidgetVisible(button, 0, 0)
|
||||
QApplication.processEvents()
|
||||
point = button.mapTo(window.workspace_scroll.viewport(), button.rect().bottomRight())
|
||||
assert window.workspace_scroll.viewport().rect().contains(point), (page_name, name, point)
|
||||
|
||||
|
||||
def test_close_cancels_context_read_and_waits_for_its_worker(ui, qtbot, monkeypatch):
|
||||
window = ui.window
|
||||
started, release, cancelled = Event(), Event(), Event()
|
||||
original = ui.service.task_context
|
||||
def slow(task_id, *, read_control=None):
|
||||
started.set()
|
||||
try:
|
||||
while not release.wait(.02):
|
||||
if read_control.cancelled:
|
||||
cancelled.set()
|
||||
read_control.checkpoint()
|
||||
return original(task_id, read_control=read_control)
|
||||
finally:
|
||||
cancelled.set()
|
||||
monkeypatch.setattr(ui.service, 'task_context', slow)
|
||||
window.archive_on_close_check.setChecked(False)
|
||||
window._load_task_data()
|
||||
qtbot.waitUntil(started.is_set)
|
||||
try:
|
||||
window.close()
|
||||
qtbot.waitUntil(cancelled.is_set)
|
||||
assert not window._closed
|
||||
finally:
|
||||
release.set()
|
||||
qtbot.waitUntil(lambda: window._closed, timeout=3000)
|
||||
assert not window._context_query.busy
|
||||
|
||||
|
||||
@pytest.mark.parametrize('frozen', [None, TaskStatus.RUNNING, TaskStatus.COMPLETED, TaskStatus.BLOCKED])
|
||||
def test_mixed_legacy_rules_preserve_return_and_frozen_member_contract(ui, frozen):
|
||||
first, second = (ui.store.list_rules(task.task_id)[0] for task in ui.tasks)
|
||||
with ui.store.transaction():
|
||||
ui.store._connection.execute('UPDATE rules SET new_part_number=? WHERE rule_id=?',
|
||||
('LEGACY BAD!', first.rule_id))
|
||||
if frozen:
|
||||
ui.store._connection.execute('UPDATE tasks SET status=? WHERE task_id=?',
|
||||
(frozen.value, ui.tasks[1].task_id))
|
||||
before = tuple(ui.store.list_rules(task.task_id) for task in ui.tasks)
|
||||
def disable():
|
||||
return ui.service.update_rule(first.rule_id, old_part_number=first.old_part_number,
|
||||
new_part_number='LEGACY BAD!', enabled=False)
|
||||
if frozen:
|
||||
with pytest.raises(TaskCenterError):
|
||||
disable()
|
||||
assert tuple(ui.store.list_rules(task.task_id) for task in ui.tasks) == before
|
||||
else:
|
||||
result = disable()
|
||||
assert result.rule_id == first.rule_id and not result.enabled
|
||||
sibling = ui.store.get_rule(second.rule_id)
|
||||
assert not sibling.enabled and sibling.new_part_number == second.new_part_number
|
||||
|
||||
|
||||
def test_mixed_legacy_disable_failure_rolls_back_every_member(ui, monkeypatch):
|
||||
first = ui.store.list_rules(ui.tasks[0].task_id)[0]
|
||||
with ui.store.transaction():
|
||||
ui.store._connection.execute('UPDATE rules SET new_part_number=? WHERE rule_id=?',
|
||||
('LEGACY BAD!', first.rule_id))
|
||||
before = tuple(ui.store.list_rules(task.task_id) for task in ui.tasks)
|
||||
original = ui.store.update_rule
|
||||
def fail(rule_id, **options):
|
||||
if rule_id != first.rule_id:
|
||||
raise TaskCenterError('controlled_rule', 'controlled failure')
|
||||
return original(rule_id, **options)
|
||||
monkeypatch.setattr(ui.store, 'update_rule', fail)
|
||||
with pytest.raises(TaskCenterError):
|
||||
ui.service.update_rule(first.rule_id, old_part_number=first.old_part_number,
|
||||
new_part_number='LEGACY BAD!', enabled=False)
|
||||
assert tuple(ui.store.list_rules(task.task_id) for task in ui.tasks) == before
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Remaining selection and preview presentation boundaries."""
|
||||
import pytest
|
||||
from PySide6.QtGui import QAccessible
|
||||
|
||||
from dx_productivity.trial_task_center.bom_batch import BomBatchPreview, BomProjectPreview
|
||||
from dx_productivity.trial_task_center.bom_import_report import BomImportReport
|
||||
from tests.ui.test_issue45_unsaved import seed, edit_cell
|
||||
|
||||
|
||||
@pytest.mark.parametrize('filter_mode', ['search', 'category'])
|
||||
def test_filtering_every_selected_task_out_does_not_reselect_on_clear(ui, filter_mode):
|
||||
panel = ui.window.task_list
|
||||
panel.select_all_tasks()
|
||||
if filter_mode == 'search':
|
||||
panel.search.setText('no-such-board')
|
||||
else:
|
||||
panel.filter.setCurrentIndex(panel.filter.findData('completed'))
|
||||
assert not panel.selected_task_ids()
|
||||
if filter_mode == 'search':
|
||||
panel.search.clear()
|
||||
else:
|
||||
panel.filter.setCurrentIndex(panel.filter.findData('all'))
|
||||
assert not panel.selected_task_ids()
|
||||
panel.sort.setCurrentIndex(panel.sort.findData('name_desc'))
|
||||
assert not panel.selected_task_ids()
|
||||
panel.select_all_tasks()
|
||||
assert len(panel.selected_task_ids()) == 2
|
||||
|
||||
|
||||
def test_received_bom_report_does_not_claim_failed_preview_was_staged(ui):
|
||||
ui.window._close_plan_confirmer = lambda: 'cancel'
|
||||
panel, rows = seed(ui)
|
||||
task = ui.tasks[0].task_id
|
||||
project = ui.store.list_projects(task)[0].path
|
||||
preview = BomBatchPreview(task, ((task, str(project)),),
|
||||
(BomProjectPreview(task, project, rows, (), ()),))
|
||||
report = BomImportReport((), (), preview=preview)
|
||||
edit_cell(panel, 'KEEP_TYPED')
|
||||
panel.table.set_plan_editable(False)
|
||||
panel._received_bom_report(report)
|
||||
assert not panel._bom_batches
|
||||
assert panel.table.has_pending_editor()
|
||||
machine = panel._bom_imports[panel._report_scope(task)]
|
||||
_, details, _ = panel._format_bom_report(machine.state)
|
||||
assert '未暂存' in details and '已暂存预览' not in details
|
||||
panel.table.set_plan_editable(True)
|
||||
panel._received_bom_report(report)
|
||||
assert panel._bom_batches
|
||||
_, details, _ = panel._format_bom_report(machine.state)
|
||||
assert '已暂存预览' in details and '未暂存' not in details
|
||||
|
||||
|
||||
def test_lazy_bom_report_has_an_accessible_name(ui):
|
||||
panel = ui.window.plan_panel
|
||||
panel._toggle_report(True)
|
||||
try:
|
||||
interface = QAccessible.queryAccessibleInterface(panel.report_dialog.view)
|
||||
assert interface.text(QAccessible.Text.Name) == 'BOM 导入报告'
|
||||
finally:
|
||||
panel._toggle_report(False)
|
||||
@@ -27,6 +27,26 @@ def visible_ids(panel):
|
||||
return [panel.list.item(index).data(Qt.ItemDataRole.UserRole) for index in range(panel.list.count())]
|
||||
|
||||
|
||||
def test_empty_list_explains_search_filter_and_initial_state(navigation, qtbot):
|
||||
panel, tasks, opened = navigation
|
||||
panel.populate(tasks[:1])
|
||||
qtbot.keyClicks(panel.search, 'zzzz_no_match')
|
||||
assert panel.empty_hint.isVisible()
|
||||
assert 'zzzz_no_match' in panel.empty_hint.text()
|
||||
assert '匹配 0 / 共 1 个任务' in panel.count.text()
|
||||
panel.filter.setCurrentIndex(panel.filter.findData('completed'))
|
||||
assert '已完成' in panel.empty_hint.text() and 'zzzz_no_match' in panel.empty_hint.text()
|
||||
panel.search.clear()
|
||||
assert '已完成' in panel.empty_hint.text()
|
||||
panel.filter.setCurrentIndex(panel.filter.findData('all'))
|
||||
assert not panel.empty_hint.isVisible() and len(visible_ids(panel)) == 1
|
||||
panel.populate(())
|
||||
assert '新建任务' in panel.empty_hint.text()
|
||||
panel.recycle_button.setChecked(True)
|
||||
panel.populate(())
|
||||
assert '回收站' in panel.empty_hint.text()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(('category','expected'),[
|
||||
('all',['draft','ready','running','paused','completed','failed','blocked']),
|
||||
('unfinished',['draft','ready','running','paused','failed','blocked']),
|
||||
|
||||
@@ -20,6 +20,7 @@ def test_native_preflight_error_is_visible_and_does_not_start_execution(ui, monk
|
||||
window._prepare_quick_run()
|
||||
else:
|
||||
window._execute_project_tasks()
|
||||
ui.settle()
|
||||
assert '受控预检异常' in window.run_panel.operator_band.text()
|
||||
assert not ui.calls and not window._dsh_authorized_tasks
|
||||
|
||||
@@ -76,11 +77,13 @@ def test_mapping_enable_uses_model_and_persists_without_row_widgets(ui):
|
||||
assert not w.run_panel.quick_run_button.isEnabled()
|
||||
|
||||
|
||||
def test_native_batch_records_complete_order_and_actual_results(ui):
|
||||
def test_native_batch_records_complete_order_and_actual_results(ui, qtbot):
|
||||
from dx_productivity.dsh.run_journal import RunJournal
|
||||
window=ui.window
|
||||
window._quick_run_confirmer=lambda *args:True
|
||||
window._execute_project_tasks();ui.settle()
|
||||
window._execute_project_tasks()
|
||||
qtbot.waitUntil(lambda: len(ui.calls) == len(ui.tasks) and not window._workers, timeout=10000)
|
||||
ui.settle()
|
||||
rows=RunJournal(ui.data).list_runs()
|
||||
assert len(ui.calls)==2 and len(rows)==1
|
||||
assert rows[0]['task_ids']==[task.task_id for task in ui.tasks]
|
||||
|
||||
@@ -26,7 +26,7 @@ def test_task_management_is_a_menu_and_new_task_is_at_the_top(ui):
|
||||
assert panel.new_button.geometry().top()<panel.search.geometry().top()
|
||||
assert not panel.edit_button.isVisible()
|
||||
panel.manage_menu.sync()
|
||||
assert any(action.text()==panel.edit_button.text()for action in panel.manage_menu.actions())
|
||||
assert any(action.text().split('\t')[0]==panel.edit_button.text()for action in panel.manage_menu.actions())
|
||||
assert panel.queue_button.isVisible()
|
||||
assert panel.list.itemDelegate().__class__.__name__=='TaskItemDelegate'
|
||||
|
||||
|
||||
@@ -76,7 +76,8 @@ def test_external_reference_preserves_completed_result_until_resource_only_clean
|
||||
assert json.loads(runtime.path.read_text())['state'] == 'isolated'
|
||||
log = runtime.path.with_name('resource-release.log').read_text(encoding='utf-8')
|
||||
assert 'isolated' in log
|
||||
guard_pending_resources(tmp_path)
|
||||
with pytest.raises(BatchResourceCleanupError):
|
||||
guard_pending_resources(tmp_path)
|
||||
assert not list(Path(tmp_path).rglob('uncertain.flag'))
|
||||
assert current_desktop_name() == before
|
||||
finally:
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from openpyxl import load_workbook
|
||||
from PySide6.QtWidgets import QFileDialog
|
||||
|
||||
from test_bom_batch import batch, records_for
|
||||
from dx_productivity.trial_task_center.bom_plan import write_bom_template
|
||||
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
|
||||
|
||||
|
||||
@pytest.mark.parametrize('case', ['extra', 'near', 'missing', 'header_formula', 'row_formula', 'original'])
|
||||
def test_bom_header_feedback_through_workspace(case, batch, tmp_path, qtbot, monkeypatch):
|
||||
service, _, tasks, targets, inventory_calls = batch
|
||||
task = tasks[0]
|
||||
record = records_for(tasks, targets)[0]
|
||||
source = write_bom_template(tmp_path / f'{case}.xlsx', [record])
|
||||
workbook = load_workbook(source)
|
||||
sheet = workbook.active
|
||||
if case == 'extra':
|
||||
sheet['L1'], sheet['L2'] = '供应商', 'Example supplier'
|
||||
sheet['M1'], sheet['M2'] = '备注', 'Example note'
|
||||
elif case == 'near':
|
||||
sheet['D1'] = '新料号编码'
|
||||
elif case == 'missing':
|
||||
sheet['D1'] = None
|
||||
elif case == 'header_formula':
|
||||
sheet['L1'] = '=1+1'
|
||||
elif case == 'row_formula':
|
||||
sheet['L1'], sheet['L2'] = '备注', '=1+1'
|
||||
workbook.save(source)
|
||||
workbook.close()
|
||||
assert_workspace_import(case, source, task, service, inventory_calls, qtbot, monkeypatch)
|
||||
|
||||
|
||||
def test_field_extra_column_through_workspace(batch, tmp_path, qtbot, monkeypatch):
|
||||
field = os.environ.get('DX_ISSUE33_D5_FIELD')
|
||||
if not field:
|
||||
pytest.skip('set DX_ISSUE33_D5_FIELD to replay the field attachment')
|
||||
service, _, tasks, targets, inventory_calls = batch
|
||||
source = tmp_path / Path(field).name
|
||||
workbook = load_workbook(field)
|
||||
sheet = workbook.active
|
||||
# Rebind to the local fixture project. Keep the original Excel header and BOM cells.
|
||||
sheet['A2'] = tasks[0].name
|
||||
sheet['B2'] = str(targets[tasks[0].task_id][0].project_path)
|
||||
workbook.save(source)
|
||||
workbook.close()
|
||||
assert_workspace_import('field', source, tasks[0], service, inventory_calls, qtbot, monkeypatch)
|
||||
|
||||
|
||||
def assert_workspace_import(case, source, task, service, inventory_calls, qtbot, monkeypatch):
|
||||
window = TrialTaskCenterWindow(service)
|
||||
window.auto_intervention_check.setChecked(False)
|
||||
qtbot.addWidget(window)
|
||||
window.open_task(task.task_id)
|
||||
panel = window.plan_panel
|
||||
qtbot.waitUntil(panel.import_bom_button.isEnabled, timeout=5000)
|
||||
monkeypatch.setattr(QFileDialog, 'getOpenFileNames', lambda *args: ([str(source)], 'Excel (*.xlsx)'))
|
||||
panel.import_bom_button.click()
|
||||
qtbot.waitUntil(lambda: not window._workers, timeout=8000)
|
||||
status = window.run_panel.operator_band.text()
|
||||
print(status)
|
||||
pending = service.pending_bom(task.task_id)
|
||||
assert not inventory_calls
|
||||
if case in {'extra', 'field', 'original', 'near', 'missing', 'header_formula'}:
|
||||
panel.report_toggle.setChecked(True)
|
||||
assert panel.report_dialog is not None
|
||||
details = panel.report_dialog.view.toPlainText()
|
||||
print(details)
|
||||
if case in {'extra', 'field', 'original'}:
|
||||
assert len(pending) == 1
|
||||
assert panel.last_bom_report.failed_rows == 0 and panel.last_bom_report.deferred
|
||||
if case == 'extra':
|
||||
assert '失败 0 行' in status and '警告 2 项' in status
|
||||
assert all(text in details for text in ('已忽略', '供应商', '备注', source.name))
|
||||
assert pending[0].record.new == 'NEW-0'
|
||||
events = (service._logging.root / 'tasks' / task.task_id / 'events.jsonl').read_text(encoding='utf-8')
|
||||
entries = [json.loads(line) for line in events.splitlines()]
|
||||
entry = next(event for event in entries if event['operation'] == 'import_bom_drafts')
|
||||
assert tuple(entry['details']['warnings']) == panel.last_bom_report.warnings
|
||||
elif case == 'field':
|
||||
assert '警告 1 项' in status and 'extra_column' in details
|
||||
else:
|
||||
assert '警告' not in status and '已忽略' not in details
|
||||
else:
|
||||
assert not pending
|
||||
if case == 'near':
|
||||
assert '缺少必需列「新料号」' in status
|
||||
assert '「新料号编码」' in details and '改为「新料号」' in details
|
||||
elif case == 'missing':
|
||||
assert '缺少必需列「新料号」' in status and '新料号' in details
|
||||
elif case == 'header_formula':
|
||||
assert 'BOM 表头不接受公式' in status and 'BOM 表头不接受公式' in details
|
||||
else:
|
||||
assert '第 2 行不接受公式' in status
|
||||
window.close()
|
||||
@@ -389,11 +389,15 @@ def test_confirmation_counts_imported_and_retained_targets(batch, tmp_path, qtbo
|
||||
window._prepare_quick_run()
|
||||
else:
|
||||
qtbot.waitUntil(window.task_list.queue_button.isEnabled)
|
||||
# This confirmation concerns the imported task and its retained R2;
|
||||
# the untouched sibling has no enabled plan to execute.
|
||||
window._tasks = (service.get_task(task_id),)
|
||||
# The real group includes an untouched sibling with no enabled plan.
|
||||
window._execute_project_tasks()
|
||||
qtbot.waitUntil(lambda: len(captured) == 1 and not window._workers)
|
||||
assert captured[0][0] == scope and captured[0][2] == 2
|
||||
if scope == 'batch':
|
||||
admission = window._batch_confirmation_admission
|
||||
assert admission['candidate_task_ids'] == [task.task_id for task in tasks]
|
||||
assert admission['runnable_task_ids'] == [task_id] and captured[0][1] == 1
|
||||
assert admission['decisions'][1]['classification'] == 'skipped'
|
||||
assert not calls and not window._workers
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
text = []
|
||||
|
||||
@@ -9,6 +9,8 @@ from test_bom_batch import batch
|
||||
|
||||
|
||||
def test_real_supervised_sources_roundtrip_origin_metadata_and_preview(batch, tmp_path):
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from dx_productivity.trial_task_center.bom_plan import write_bom_template
|
||||
service, store, tasks, targets, calls = batch
|
||||
for task in tasks:
|
||||
@@ -17,9 +19,14 @@ def test_real_supervised_sources_roundtrip_origin_metadata_and_preview(batch, tm
|
||||
'project_name': task.name, 'project_path': str(targets[task.task_id][0].project_path),
|
||||
'old_part_number': 'OLD', 'new_part_number': 'NEW', 'refdes': 'R1', 'value_mode': 'part_number',
|
||||
},)) for index, task in enumerate(tasks))
|
||||
workbook = load_workbook(sources[0])
|
||||
workbook.active['M1'] = '备注'
|
||||
workbook.save(sources[0])
|
||||
workbook.close()
|
||||
service._supervised = True
|
||||
report = service.preview_bom_sources(tasks[0].task_id, sources)
|
||||
assert report.passed_rows == 2 and report.preview is not None
|
||||
assert report.warnings == ('source-0.xlsx:已忽略未知列「备注」',)
|
||||
assert tuple(row.source_file for row in report.rows) == tuple(str(path.resolve()) for path in sources)
|
||||
assert all(row.source_row == 2 for row in report.rows)
|
||||
assert report.source_map_path.is_file()
|
||||
|
||||
@@ -41,6 +41,11 @@ def test_sequential_leases_reuse_name_but_never_reuse_attempt_identity(tmp_path)
|
||||
name = first.name
|
||||
backend.exists = True # External reference keeps the object after our close.
|
||||
receipt = first.release(desktop_disappeared=False)
|
||||
before = first.path.read_bytes()
|
||||
with pytest.raises(TaskCenterError):
|
||||
slot(tmp_path, backend).acquire()
|
||||
assert first.path.read_bytes() == before and not backend.locked
|
||||
backend.exists = False
|
||||
second = slot(tmp_path, backend).acquire()
|
||||
assert second.name == name
|
||||
assert second.lease_id != first.lease_id
|
||||
@@ -83,6 +88,11 @@ def test_restart_reclaims_dead_owner_only_after_named_job_is_empty(tmp_path):
|
||||
first.launched(job, {'pid': 200, 'creation_time': 'worker-200'})
|
||||
backend.locked = False
|
||||
backend.exists = True
|
||||
before = first.path.read_bytes()
|
||||
with pytest.raises(TaskCenterError):
|
||||
slot(tmp_path, backend).acquire()
|
||||
assert first.path.read_bytes() == before and not backend.locked
|
||||
backend.exists = False
|
||||
second = slot(tmp_path, backend).acquire()
|
||||
assert second.name == first.name
|
||||
second.release(desktop_disappeared=False)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
@@ -116,28 +117,55 @@ def test_manual_failure_cannot_be_completed_by_native_progress(failed_native):
|
||||
service.quick_run_progress(task_id)
|
||||
|
||||
|
||||
def test_uncertain_batch_failed_isolated_before_next_project_in_task_queue(failed_native, tmp_path, monkeypatch):
|
||||
def test_native_uncertainty_holds_batch_until_verified_resume(failed_native, tmp_path, monkeypatch):
|
||||
from threading import Event
|
||||
from test_project_isolation_queue import ReleasedRuntime
|
||||
from dx_productivity.trial_task_center.task_queue import execute_task_queue
|
||||
service, store, task_id, _, _ = failed_native
|
||||
|
||||
service, store, task_id, handoff, report = failed_native
|
||||
other = store.create_task('independent next project')
|
||||
path = tmp_path / 'next.prj'
|
||||
path.touch()
|
||||
path = tmp_path / 'follower' / 'next.prj'
|
||||
path.parent.mkdir()
|
||||
path.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
|
||||
project = store.sync_projects(other.task_id, tmp_path, (path,))[0]
|
||||
store.set_project_selected(project.project_id, True)
|
||||
service.add_rule(other.task_id, 'OLD', 'NEW')
|
||||
store.bind_project_task(other.task_id, project.project_id, 'batch', 1)
|
||||
from test_project_isolation_queue import ReleasedRuntime
|
||||
from dx_productivity.trial_task_center.quick_run_protocol import QuickRunProgress
|
||||
|
||||
calls = []
|
||||
child = service.for_project_task(other.task_id)
|
||||
monkeypatch.setattr(child, 'quick_run_progress', lambda _: calls.append(other.task_id) or QuickRunProgress(
|
||||
0, 0, None, None, None, (path,), True))
|
||||
monkeypatch.setattr(child, 'has_interrupted_quick_run', lambda _: False)
|
||||
child._quick_run_preparer.reconcile_terminal_receipts = lambda _: None
|
||||
original_child = service.for_project_task
|
||||
monkeypatch.setattr(service, 'for_project_task', lambda identifier: child if identifier == other.task_id else original_child(identifier))
|
||||
result = execute_task_queue(service, (task_id, other.task_id), stop_event=Event(), runtime=ReleasedRuntime(service._logging.root))
|
||||
assert not result.paused
|
||||
assert [entry.state for entry in result.entries] == ['blocked', 'completed']
|
||||
assert calls == [other.task_id]
|
||||
assert not (service.for_project_task(other.task_id)._quick_run_preparer.data_root / 'quick-run').exists()
|
||||
|
||||
def worker(command, timeout):
|
||||
root, job = Path(command[3]), command[-1]
|
||||
calls.append(root)
|
||||
with (root / 'status.tsv').open('a', encoding='utf-8') as stream:
|
||||
stream.write(f'{job}\tawaiting_native_replace\t\tcaptured\n'
|
||||
f'{job}\tsaved_ok\tbatch_closed\tverified\n')
|
||||
return subprocess.CompletedProcess(command, 0, '', '')
|
||||
|
||||
original = service.for_project_task(task_id)._quick_run_preparer
|
||||
follower = service.for_project_task(other.task_id)._quick_run_preparer
|
||||
monkeypatch.setattr(original, '_cscript_resolver', lambda: pytest.fail('original operation replayed'))
|
||||
monkeypatch.setattr(follower, '_process_runner', worker)
|
||||
monkeypatch.setattr(follower, '_cscript_resolver', lambda: Path('controlled-cscript'))
|
||||
monkeypatch.setattr(follower, '_sheet_discoverer', lambda _: (('MAIN', '1'),))
|
||||
runtime = ReleasedRuntime(service._logging.root)
|
||||
ids = (task_id, other.task_id)
|
||||
evidence = {file: file.read_bytes() for file in (handoff.command_path, handoff.status_path, report)}
|
||||
first = execute_task_queue(service, ids, stop_event=Event(), runtime=runtime)
|
||||
assert first.paused and first.current_task_id == task_id
|
||||
assert [entry.state for entry in first.entries] == ['blocked', 'pending']
|
||||
assert execute_task_queue(service, ids, stop_event=Event(), runtime=runtime, queue_id=first.queue_id) == first
|
||||
assert calls == [] and not (follower.data_root / 'quick-run').exists()
|
||||
assert all(file.read_bytes() == contents for file, contents in evidence.items())
|
||||
|
||||
job = handoff.command_path.read_text(encoding='utf-8').splitlines()[1].split('\t')[1]
|
||||
with handoff.status_path.open('a', encoding='utf-8') as stream:
|
||||
stream.write(f'{job}\trestored_ok\trecovery_verified\tsaved and verified\n')
|
||||
service.quick_run_progress(task_id)
|
||||
assert not service.has_interrupted_quick_run(task_id)
|
||||
|
||||
resumed = execute_task_queue(service, ids, stop_event=Event(), runtime=runtime, queue_id=first.queue_id)
|
||||
assert not resumed.paused
|
||||
assert [entry.state for entry in resumed.entries] == ['completed', 'completed']
|
||||
assert execute_task_queue(service, ids, stop_event=Event(), runtime=runtime, queue_id=first.queue_id).entries == resumed.entries
|
||||
assert calls == [follower.data_root / 'quick-run']
|
||||
@@ -0,0 +1,22 @@
|
||||
import json
|
||||
import zipfile
|
||||
|
||||
from dx_productivity.trial_task_center.diagnostics_bundle import export_diagnostic_bundle
|
||||
|
||||
|
||||
def test_batch_evidence_uses_existing_redaction_and_allowlist(tmp_path):
|
||||
data = tmp_path / 'data'
|
||||
relative = 'batch-runs/' + 'a' * 32
|
||||
directory = data / relative
|
||||
directory.mkdir(parents=True)
|
||||
(directory / 'manifest.json').write_text(json.dumps({'token': 'private-scope-credential'}))
|
||||
(directory / 'batch-receipt.json').write_text(json.dumps({'manifest_digest': 'bound'}))
|
||||
(directory / 'project.prj').write_text('private CAD')
|
||||
(directory / 'old-receipt.json').write_text('{}')
|
||||
output = export_diagnostic_bundle(data, tmp_path / 'support.zip')
|
||||
with zipfile.ZipFile(output) as bundle:
|
||||
assert b'private-scope-credential' not in bundle.read(f'{relative}/manifest.json')
|
||||
assert json.loads(bundle.read(f'{relative}/batch-receipt.json'))['manifest_digest'] == 'bound'
|
||||
omissions = json.loads(bundle.read('manifest.json'))['omissions']
|
||||
for filename in ('project.prj', 'old-receipt.json'):
|
||||
assert {'path': f'{relative}/{filename}', 'reason': 'outside_allowlist'} in omissions
|
||||
@@ -0,0 +1,88 @@
|
||||
def test_pending_save_is_counted_by_target_and_keeps_batch_blocked():
|
||||
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='job', generation=1,
|
||||
state='pending_save', target_keys=[f'uid:{i}' for i in range(23)],
|
||||
current_round=True)]
|
||||
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['operation_job_count'] == 1
|
||||
assert summary['task_counts']['blocked'] == 1
|
||||
assert summary['status'] == 'blocked'
|
||||
|
||||
|
||||
def test_summary_counts_only_effective_targets_and_conserves_candidate_entries():
|
||||
from dx_productivity.trial_task_center.batch_summary import summarize_batch
|
||||
|
||||
candidates = list('ABCDEFGH')
|
||||
manifest = {'candidate_task_ids': candidates, 'decisions': [
|
||||
{'task_id': key, 'classification': 'executable' if index < 5 else 'skipped',
|
||||
'target_count': 2 if key == 'A' else 0}
|
||||
for index, key in enumerate(candidates)]}
|
||||
queue = {'entries': {key: {'state': 'completed'} for key in candidates[:5]}}
|
||||
rows = [
|
||||
dict(task_id='A', round_id='old', operation_key='old', generation=1,
|
||||
state='verified', target_keys=['historical'], current_round=False),
|
||||
dict(task_id='A', round_id='r', operation_key='gone', generation=1,
|
||||
state='superseded', target_keys=['superseded']),
|
||||
dict(task_id='A', round_id='r', operation_key='job', generation=1,
|
||||
state='failed', target_keys=['ref1', 'ref2']),
|
||||
dict(task_id='A', round_id='r', operation_key='job', generation=2,
|
||||
state='verified', target_keys=['ref1', 'ref2', 'ref2']),
|
||||
dict(task_id='F', round_id='r', operation_key='unrelated', generation=1,
|
||||
state='verified', target_keys=['skipped']),
|
||||
]
|
||||
summary = summarize_batch(manifest, queue, rows,
|
||||
{'state': 'isolated', 'supervisor_status': 'ok'}, elapsed_seconds=18)
|
||||
assert summary['candidate_count'] == sum(summary['task_counts'].values()) == 8
|
||||
assert (summary['task_counts']['completed'], summary['task_counts']['skipped']) == (5, 3)
|
||||
assert summary['operation_counts']['saved'] == 2
|
||||
assert summary['operation_counts']['failed'] == 0
|
||||
assert summary['operation_total'] == 2
|
||||
assert summary['execution_status'] == 'completed'
|
||||
assert summary['status'] == 'paused'
|
||||
|
||||
|
||||
def test_rule_scope_without_native_targets_has_unknown_total():
|
||||
from dx_productivity.trial_task_center.batch_summary import summarize_batch
|
||||
|
||||
manifest = {'candidate_task_ids': ['A'], 'decisions': [
|
||||
{'task_id': 'A', 'classification': 'executable'}]}
|
||||
row = dict(task_id='A', round_id='r', operation_key='rule', generation=1,
|
||||
state='pending', target_keys=None)
|
||||
summary = summarize_batch(manifest, {}, [row], {'state': 'unknown'}, elapsed_seconds=0)
|
||||
assert summary['operation_total'] is None
|
||||
assert summary['operation_job_count'] == 1
|
||||
assert summary['task_counts']['pending'] == 1
|
||||
|
||||
|
||||
def test_native_bom_zero_replacements_is_counted_as_skipped():
|
||||
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': 'skipped', 'message': 'BOM matches'}}}
|
||||
summary = summarize_batch(manifest, queue, [], {'state': 'released'}, elapsed_seconds=1)
|
||||
assert summary['task_counts']['skipped'] == 1
|
||||
assert summary['operation_total'] == 0
|
||||
assert summary['status'] == 'completed'
|
||||
|
||||
|
||||
def test_unresolved_sibling_blocks_every_retry_selection():
|
||||
from dx_productivity.trial_task_center.batch_summary import summarize_batch
|
||||
|
||||
manifest = {'candidate_task_ids': ['A', 'B'], 'decisions': [
|
||||
{'task_id': key, 'classification': 'executable'} for key in ('A', 'B')]}
|
||||
queue = {'entries': {'A': {'state': 'failed'}, 'B': {'state': 'blocked'}}}
|
||||
rows = [
|
||||
dict(task_id='A', round_id='a', operation_key='failed', generation=1,
|
||||
state='failed', target_keys=['A1'], can_retry=True),
|
||||
dict(task_id='B', round_id='b', operation_key='pending', generation=1,
|
||||
state='pending_save', target_keys=['B1']),
|
||||
]
|
||||
summary = summarize_batch(manifest, queue, rows, {'state': 'released'}, elapsed_seconds=1)
|
||||
assert summary['retry_selection'] == []
|
||||
@@ -0,0 +1,57 @@
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
from dx_productivity.trial_task_center import native_helper as native
|
||||
from dx_productivity.trial_task_center.batch_attempt import prepare_attempt, read_attempt
|
||||
from dx_productivity.trial_task_center.execution_problems import classify_execution_failure
|
||||
|
||||
|
||||
def test_empty_databook_timeout_reports_lookup_unavailable_before_writing(tmp_path, monkeypatch):
|
||||
project = tmp_path / 'board.prj'
|
||||
snapshot = tmp_path / 'snapshot-job.tsv'
|
||||
snapshot.write_text(f'M\t{project}\tOLD\tMISSING\tMAIN:1\nC\tuid\tR1\t0\t0\t0\t1\t\n', encoding='utf-8')
|
||||
(tmp_path / 'command.tsv').write_text(
|
||||
f'job_id\ttask_id\tproject_path\njob\ttask\t{project}\n', encoding='utf-8')
|
||||
attempt_path = tmp_path / 'attempt.json'
|
||||
attempt = prepare_attempt(attempt_path, session_id='session', generation=1,
|
||||
job_id='job', task_id='task', project_path=project)
|
||||
for name, value in {
|
||||
'DXPART_DESKTOP': 'dx-test',
|
||||
'DXPART_ATTEMPT_FILE': attempt_path,
|
||||
'DXPART_ATTEMPT_ID': attempt['attempt_id'],
|
||||
'DXPART_BATCH_GENERATION': attempt['generation'],
|
||||
'DXPART_BATCH_SESSION_ID': attempt['session_id'],
|
||||
}.items():
|
||||
monkeypatch.setenv(name, str(value))
|
||||
now = [0.0]
|
||||
monkeypatch.setattr(native, 'time', SimpleNamespace(
|
||||
monotonic=lambda: now[0], sleep=lambda seconds: now.__setitem__(0, now[0] + seconds)))
|
||||
|
||||
def lookup(path, report):
|
||||
native.load_databook_target(path, report, 'MISSING',
|
||||
controls=lambda: (10, 11), browse=lambda: None, filter_part=lambda handle: None,
|
||||
list_rows=lambda handle: [], dialogs=lambda: (), close_dialog=lambda row: None)
|
||||
|
||||
monkeypatch.setattr(native, 'run_native', lookup)
|
||||
assert native.run(snapshot) == 4
|
||||
report_path = snapshot.with_suffix('.tsv.native.json')
|
||||
report = json.loads(report_path.read_bytes())
|
||||
assert (report['ok'], report['stage'], report['code']) == (False, 'preflight', 'lookup_unavailable')
|
||||
assert [load['retry'] for load in report['databook']['loads']] == [True, False]
|
||||
assert report['batch_attempt']['attempt_id'] == attempt['attempt_id']
|
||||
assert read_attempt(attempt_path)['state'] == 'prepared'
|
||||
assert 'MISSING' in snapshot.with_suffix('.tsv.native.error.txt').read_text(encoding='utf-8')
|
||||
|
||||
def unrelated_timeout(path, report):
|
||||
raise TimeoutError('CAD dialog did not open')
|
||||
|
||||
monkeypatch.setattr(native, 'run_native', unrelated_timeout)
|
||||
assert native.run(snapshot) == 1
|
||||
assert 'code' not in json.loads(report_path.read_bytes())
|
||||
|
||||
|
||||
def test_lookup_failure_needs_existing_certification_for_batch_retry():
|
||||
unavailable = classify_execution_failure('lookup_unavailable', 'failed', authorized=True)
|
||||
assert unavailable['retry_allowed'] is False
|
||||
certified = classify_execution_failure('lookup_unavailable', 'failed', certified=True, authorized=True)
|
||||
assert certified['retry_allowed'] is True
|
||||
@@ -0,0 +1,85 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.trial_task_center import batch_resources, batch_supervisor
|
||||
|
||||
|
||||
def test_legacy_nonblocking_isolation_blocks_write(tmp_path, monkeypatch):
|
||||
from test_nonblocking_resources import record_at
|
||||
|
||||
record_at(tmp_path, state='isolated', blocking=False)
|
||||
monkeypatch.setattr(batch_resources, '_isolation_evidence', lambda _: True)
|
||||
with pytest.raises(batch_resources.BatchResourceCleanupError):
|
||||
batch_resources.guard_pending_resources(tmp_path)
|
||||
record = {'state': 'isolated', 'blocking': False}
|
||||
assert batch_resources.resource_blockers((record,)) == (record,)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(('winerror', 'state'), [(5, 'unknown'), (87, 'gone')])
|
||||
def test_process_open_failure_distinguishes_unknown_from_gone(monkeypatch, winerror, state):
|
||||
import pywintypes
|
||||
import win32api
|
||||
|
||||
def open_process(access, inherit, pid):
|
||||
assert (access, inherit, pid) == (0x101000, False, 123)
|
||||
raise pywintypes.error(winerror, 'OpenProcess', 'injected')
|
||||
|
||||
monkeypatch.setattr(win32api, 'OpenProcess', open_process)
|
||||
identity = {'pid': 123, 'creation_time': 'original'}
|
||||
result = batch_resources.observe_process_identity(identity)
|
||||
assert (result['state'], result['error_code']) == (state, winerror)
|
||||
assert batch_resources._process_gone(identity) is (state == 'gone')
|
||||
|
||||
|
||||
@pytest.mark.parametrize(('created', 'wait_result', 'state'), [
|
||||
('original', 258, 'alive'), ('new', 258, 'gone'), ('original', 0, 'gone'), ('original', 9, 'unknown'),
|
||||
])
|
||||
def test_queried_identity_and_liveness_close_handle_once(monkeypatch, created, wait_result, state):
|
||||
import win32api
|
||||
import win32event
|
||||
import win32process
|
||||
|
||||
closed = []
|
||||
handle = SimpleNamespace(Close=lambda: closed.append(True))
|
||||
monkeypatch.setattr(win32api, 'OpenProcess', lambda *args: handle)
|
||||
monkeypatch.setattr(win32process, 'GetProcessTimes', lambda value: {'CreationTime': created})
|
||||
monkeypatch.setattr(win32event, 'WaitForSingleObject', lambda value, timeout: wait_result)
|
||||
observation = batch_resources.observe_process_identity({'pid': 123, 'creation_time': 'original'})
|
||||
assert observation['state'] == state
|
||||
assert closed == [True]
|
||||
|
||||
|
||||
def test_unauthorized_historical_supervisor_is_diagnosable_and_stays_blocked(tmp_path, monkeypatch):
|
||||
import pywintypes
|
||||
import win32api
|
||||
|
||||
def open_process(*args):
|
||||
raise pywintypes.error(5, 'OpenProcess', 'injected')
|
||||
|
||||
monkeypatch.setattr(win32api, 'OpenProcess', open_process)
|
||||
batch = 'b' * 32
|
||||
identity = {'pid': 123, 'creation_time': 'original'}
|
||||
path = tmp_path / 'batch-resources' / batch / 'supervisor.json'
|
||||
batch_resources.write_record(path, {'version': 1, 'batch_id': batch, 'attempt_id': 'a' * 32,
|
||||
'state': 'finished', 'operation': 'probe', 'task_ids': [], 'process': identity,
|
||||
'parent_process': identity, 'request_sha256': 'f' * 64})
|
||||
before = path.read_bytes()
|
||||
pending, = batch_supervisor.reconcile_supervisors(tmp_path)
|
||||
assert pending['state'] == 'blocked'
|
||||
assert pending['process_observation']['state'] == 'unknown'
|
||||
assert pending['process_observation']['error_code'] == 5
|
||||
assert path.read_bytes() == before
|
||||
|
||||
|
||||
def test_live_generation_exempts_only_its_own_healthy_record(tmp_path):
|
||||
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
|
||||
from test_batch_runtime import Desktop
|
||||
from test_nonblocking_resources import record_at
|
||||
|
||||
with BatchCadRuntime(tmp_path, 'execution', desktop_factory=Desktop) as runtime:
|
||||
desktop = runtime._ensure_desktop()
|
||||
assert runtime._ensure_desktop() is desktop
|
||||
record_at(tmp_path, state='isolated', blocking=False)
|
||||
with pytest.raises(batch_resources.BatchResourceCleanupError):
|
||||
runtime._ensure_desktop()
|
||||
@@ -0,0 +1,148 @@
|
||||
from threading import Event
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.trial_task_center.batch_supervisor import BusinessProgressWatch
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
from dx_productivity.trial_task_center.task_queue import execute_task_queue
|
||||
|
||||
from test_project_isolation_queue import ReleasedRuntime
|
||||
from test_task_queue import Service
|
||||
|
||||
|
||||
def test_repeated_state_requests_stop_once_and_real_progress_moves_deadline():
|
||||
watch = BusinessProgressWatch(0)
|
||||
requests = []
|
||||
frame = {'phase': 'ready', 'business_progress': {'job_id': 'one', 'stage': 'save', 'done': 3, 'total': 5}}
|
||||
watch.observe('state', frame, 1)
|
||||
watch.observe('heartbeat', {}, 145)
|
||||
watch.observe('state', {**frame, 'elapsed_seconds': 145}, 145)
|
||||
assert not watch.request_cooperative_stop(150, requests.append)
|
||||
progressed = {**frame, 'business_progress': {**frame['business_progress'], 'done': 4}}
|
||||
watch.observe('state', progressed, 150)
|
||||
watch.observe('state', {**progressed, 'elapsed_seconds': 298}, 298)
|
||||
assert watch.request_cooperative_stop(300, requests.append)
|
||||
assert not watch.request_cooperative_stop(600, requests.append)
|
||||
assert requests == ['inactivity']
|
||||
|
||||
|
||||
def test_outer_watch_respects_worker_stop_already_in_flight():
|
||||
watch = BusinessProgressWatch(0)
|
||||
requests = []
|
||||
watch.observe('state', {'business_progress': {'job_id': 'one', 'stage': 'save',
|
||||
'done': 3, 'total': 5, 'stop_requested': True}}, 10)
|
||||
assert not watch.request_cooperative_stop(200, requests.append)
|
||||
assert requests == []
|
||||
|
||||
|
||||
def test_worker_timeout_publishes_inactivity_without_user_intent():
|
||||
from dx_productivity.trial_task_center.worker_monitor import ProgressWatch
|
||||
|
||||
watch = ProgressWatch('worker', 'job', 150, 0)
|
||||
assert watch.action(150) == 'request_stop'
|
||||
progress = watch.snapshot(now=150)
|
||||
assert progress['stopping_reason'] == 'inactivity'
|
||||
assert progress['idle_timeout_seconds'] == 150
|
||||
|
||||
|
||||
def test_supervisor_delivers_inactivity_stop_without_setting_parent_pause(tmp_path, monkeypatch):
|
||||
import json
|
||||
import sys
|
||||
|
||||
from dx_productivity.trial_task_center import batch_supervisor
|
||||
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.stop_control import StopControl
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
|
||||
probe = tmp_path / 'stall-probe.py'
|
||||
probe.write_text("""
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from dx_productivity.trial_task_center.supervisor_protocol import encode
|
||||
request = Path(sys.argv[1])
|
||||
binding = json.loads(request.read_bytes())
|
||||
envelope = {key: binding[key] for key in ('version', 'batch_id', 'attempt_id')}
|
||||
cancel = request.with_name('cancel.json')
|
||||
deadline = time.monotonic() + 8
|
||||
sequence = 0
|
||||
while not cancel.exists() and time.monotonic() < deadline:
|
||||
sequence += 1
|
||||
print(json.dumps(dict(envelope, type='heartbeat', generation=1, sequence=sequence, payload=None)), flush=True)
|
||||
time.sleep(.02)
|
||||
intent = json.loads(cancel.read_bytes())
|
||||
result = dict(envelope, type='result', generation=1, sequence=sequence + 1,
|
||||
payload={'status': 'ok', 'business_succeeded': True, 'result': encode({'reason': intent['reason']})})
|
||||
request.with_name('result.json').write_text(json.dumps(result), encoding='utf-8')
|
||||
""", encoding='utf-8')
|
||||
monkeypatch.setattr(batch_supervisor, 'BusinessProgressWatch',
|
||||
lambda started: BusinessProgressWatch(started, idle_timeout=.25))
|
||||
monkeypatch.setattr(batch_supervisor, '_command', lambda request: (sys.executable, str(probe), str(request)))
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
try:
|
||||
service = TaskCenterService(store, configure_logging(tmp_path))
|
||||
stop = StopControl()
|
||||
assert batch_supervisor.run_supervised(service, 'probe', {}, stop_event=stop) == {'reason': 'inactivity'}
|
||||
assert not stop.is_set() and not stop.force_event.is_set()
|
||||
journal = next((tmp_path / 'batch-resources').glob('*/supervisor.json'))
|
||||
recorded = json.loads(journal.read_bytes())
|
||||
assert recorded['stopping_reason'] == 'inactivity'
|
||||
assert recorded['business_idle_timeout_seconds'] == .25
|
||||
finally:
|
||||
store.close()
|
||||
|
||||
|
||||
def test_regressing_worker_counters_do_not_extend_supervisor_deadline():
|
||||
watch = BusinessProgressWatch(0)
|
||||
requests = []
|
||||
for now, done in ((1, 4), (100, 3), (149, 4)):
|
||||
watch.observe('state', {'business_progress': {'job_id': 'one', 'stage': 'save', 'done': done}}, now)
|
||||
assert watch.request_cooperative_stop(151, requests.append)
|
||||
assert requests == ['inactivity']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('release_succeeded', [True, False])
|
||||
def test_unknown_save_stops_batch_even_after_resource_release(tmp_path, release_succeeded):
|
||||
service = Service(tmp_path, {'B': TaskCenterError('quick_run_uncertain', 'save outcome unavailable')})
|
||||
runtime = ReleasedRuntime(tmp_path, release_succeeded)
|
||||
result = execute_task_queue(service, ('A', 'B', 'C'), stop_event=Event(), runtime=runtime)
|
||||
assert result.paused and result.current_task_id == 'B'
|
||||
assert [entry.state for entry in result.entries] == ['completed', 'blocked', 'pending']
|
||||
assert service.calls == [('start', 'A'), ('end', 'A'), ('start', 'B')]
|
||||
assert runtime.release_calls == ['quick_run_uncertain']
|
||||
|
||||
|
||||
def test_unknown_write_is_protected_before_cleanup_and_resume_cannot_dispatch(tmp_path):
|
||||
service = Service(tmp_path, {'B': TaskCenterError('quick_run_uncertain', 'save outcome unavailable')})
|
||||
runtime = ReleasedRuntime(tmp_path)
|
||||
release = runtime.release_failed_project
|
||||
|
||||
def guarded_release(error, evidence_root):
|
||||
assert (evidence_root / 'uncertain.flag').read_text(encoding='utf-8')
|
||||
return release(error, evidence_root)
|
||||
|
||||
runtime.release_failed_project = guarded_release
|
||||
result = execute_task_queue(service, ('A', 'B', 'C'), stop_event=Event(), runtime=runtime)
|
||||
assert runtime.release_calls == ['quick_run_uncertain']
|
||||
service.calls.clear()
|
||||
resumed = execute_task_queue(service, ('A', 'B', 'C'), stop_event=Event(), runtime=runtime,
|
||||
queue_id=result.queue_id)
|
||||
assert resumed.paused and resumed.current_task_id == 'B'
|
||||
assert service.calls == []
|
||||
|
||||
|
||||
def test_failed_protection_write_never_runs_owned_cleanup_or_next_project(tmp_path, monkeypatch):
|
||||
from dx_productivity.trial_task_center import stop_control
|
||||
|
||||
def failed_write(*args):
|
||||
raise OSError('disk failure')
|
||||
|
||||
monkeypatch.setattr(stop_control, 'protect_interruption', failed_write)
|
||||
service = Service(tmp_path, {'B': TaskCenterError('quick_run_uncertain', 'save outcome unavailable')})
|
||||
runtime = ReleasedRuntime(tmp_path)
|
||||
with pytest.raises(OSError, match='disk failure'):
|
||||
execute_task_queue(service, ('A', 'B', 'C'), stop_event=Event(), runtime=runtime)
|
||||
assert runtime.release_calls == []
|
||||
assert service.calls == [('start', 'A'), ('end', 'A'), ('start', 'B')]
|
||||
@@ -0,0 +1,96 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from PySide6.QtCore import QRect, QByteArray
|
||||
from PySide6.QtGui import QAccessible
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
from test_ui_remediation import window
|
||||
|
||||
|
||||
@pytest.mark.parametrize('scale,saved,decorated', [(1.25, False, False), (1.5, False, False),
|
||||
(1.5, True, False), (1.5, False, True), (3.0, False, True)])
|
||||
def test_first_and_restored_windows_fit_scaled_workarea(window, qtbot, monkeypatch, scale, saved, decorated):
|
||||
area = QRect(0, 0, int(1920 / scale), int(1032 / scale))
|
||||
screen = SimpleNamespace(availableGeometry=lambda: area, logicalDotsPerInch=lambda: 96 * scale,
|
||||
devicePixelRatio=lambda: scale, name=lambda: 'controlled-scaled-screen')
|
||||
window._layout_settings.remove('main_window/geometry')
|
||||
window.resize(1616, 1100)
|
||||
if saved:
|
||||
window._layout_settings.setValue('main_window/geometry', window.saveGeometry())
|
||||
monkeypatch.setattr(QApplication, 'primaryScreen', lambda: screen)
|
||||
monkeypatch.setattr(QApplication, 'screenAt', lambda _: screen)
|
||||
if decorated:
|
||||
def frame():
|
||||
client = window.geometry()
|
||||
return client.adjusted(-8, -31, 8, 8) if window.isVisible() else client
|
||||
monkeypatch.setattr(window, 'frameGeometry', frame)
|
||||
window._restore_window_geometry()
|
||||
window.show()
|
||||
QApplication.processEvents()
|
||||
assert area.contains(window.frameGeometry()), (area, window.frameGeometry(), window.minimumSize())
|
||||
for button in (window.plan_panel.save_button, window.run_panel.quick_run_button, window.task_list.new_button):
|
||||
if scale == 3.0:
|
||||
window.workspace_scroll.ensureWidgetVisible(button, 0, 0)
|
||||
QApplication.processEvents()
|
||||
point = button.mapTo(window.workspace_scroll.viewport(), button.rect().bottomRight())
|
||||
assert window.workspace_scroll.viewport().rect().contains(point)
|
||||
point = button.mapTo(window, button.rect().bottomRight())
|
||||
assert window.rect().contains(point), (button.objectName(), point, window.size())
|
||||
|
||||
|
||||
def test_both_table_headers_restore_width_order_and_sort(window, qtbot):
|
||||
for table in (window.mapping_table, window.plan_panel.table):
|
||||
header = table.horizontalHeader()
|
||||
header.resizeSection(0, 173)
|
||||
header.moveSection(0, 2)
|
||||
header.setSortIndicator(1, header.sortIndicatorOrder())
|
||||
expected = {name: bytes(widget.saveState()) for name, widget in window._layout_widgets().items()
|
||||
if name in {'rules', 'targets'}}
|
||||
window.close()
|
||||
qtbot.waitUntil(lambda: window._closed)
|
||||
reopened = type(window)(window.service)
|
||||
qtbot.addWidget(reopened)
|
||||
try:
|
||||
reopened.show()
|
||||
qtbot.waitUntil(lambda: not reopened._task_query.busy and not reopened._context_query.busy)
|
||||
for name, data in expected.items():
|
||||
assert bytes(reopened._layout_widgets()[name].saveState()) == data
|
||||
reopened._layout_settings.setValue('single_project/rules', QByteArray(b'broken header'))
|
||||
reopened._layout_settings.sync()
|
||||
finally:
|
||||
reopened.close()
|
||||
|
||||
|
||||
def test_result_log_is_an_independent_reopenable_window(window, qtbot):
|
||||
panel = window.run_panel
|
||||
panel.toggle_log_button.click()
|
||||
first = panel.log_dialog
|
||||
assert first is not None and first.isWindow() and first.isVisible()
|
||||
first.set_content('first evidence', ())
|
||||
first.close()
|
||||
assert panel.log_dialog is None and not panel.toggle_log_button.isChecked()
|
||||
panel.toggle_log_button.click()
|
||||
second = panel.log_dialog
|
||||
assert second is not None and second is not first and second.isWindow()
|
||||
second.set_content('new evidence', ())
|
||||
assert second.log_text == 'new evidence'
|
||||
second.tabs.setCurrentIndex(1)
|
||||
interface = QAccessible.queryAccessibleInterface(second.log_view)
|
||||
assert interface.text(QAccessible.Text.Name) == '任务日志'
|
||||
second.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('corrupt', ['broken header', QByteArray(b'broken header')])
|
||||
def test_invalid_saved_header_types_use_default_layout(window, qtbot, corrupt):
|
||||
window._layout_settings.setValue('single_project/rules', corrupt)
|
||||
window._layout_settings.setValue('single_project/targets', corrupt)
|
||||
window._layout_settings.sync()
|
||||
reopened = type(window)(window.service)
|
||||
qtbot.addWidget(reopened)
|
||||
try:
|
||||
reopened.show()
|
||||
assert reopened.mapping_table.horizontalHeader().sectionSize(0) == 220
|
||||
assert reopened.plan_panel.table.horizontalHeader().sectionSize(0) == 55
|
||||
finally:
|
||||
reopened.close()
|
||||
@@ -0,0 +1,125 @@
|
||||
"""Part Number validation at import, compile and persistence boundaries."""
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from dx_productivity.part_replace.inputs import InputError, parse_mapping_bytes
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
from dx_productivity.trial_task_center.rule_validation import validate_mapping_pairs
|
||||
from dx_productivity.trial_task_center.spreadsheet_plan import export_target_plan, import_target_plan
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow, compile_target_rules
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def plan(tmp_path):
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
try:
|
||||
task = store.create_task('board')
|
||||
path = tmp_path / 'board.prj'
|
||||
store.sync_projects(task.task_id, tmp_path, (path,))
|
||||
targets = tuple(ComponentTarget(path, 'MAIN', '1', f'u{i}', f'R{i}', 'OLD', '') for i in (1, 2))
|
||||
store.record_target_inventory(task.task_id, targets)
|
||||
yield store, task.task_id, targets
|
||||
finally:
|
||||
store.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('bad', ['BAD PART !!@#', 'BAD!PN', 'BAD@PN', 'BAD#PN', 'BAD\x00PN',
|
||||
'BAD PN', 'BAD\u200bPN', 'A' * 129, '---'])
|
||||
def test_mapping_import_and_shared_api_reject_invalid_part_numbers(bad):
|
||||
old, new = 'OLD', bad
|
||||
data = f'old_part_number,new_part_number\n{old},{new}\n'.encode()
|
||||
with pytest.raises(InputError, match='part_number'):
|
||||
parse_mapping_bytes(data, Path('mapping.csv'))
|
||||
with pytest.raises(TaskCenterError, match='part_number'):
|
||||
validate_mapping_pairs(((old, new),))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('enabled', [False, True])
|
||||
def test_direct_rule_add_and_update_reject_bad_pn_atomically(plan, enabled):
|
||||
store, task, _ = plan
|
||||
original = store.add_rule(task, 'OLD', 'NEW')
|
||||
with pytest.raises(TaskCenterError, match='part_number'):
|
||||
store.add_rule(task, 'OTHER', 'BAD PART !!@#', enabled=enabled)
|
||||
with pytest.raises(TaskCenterError, match='part_number'):
|
||||
store.update_rule(original.rule_id, old_part_number='OLD', new_part_number='BAD PART !!@#', enabled=enabled)
|
||||
assert store.list_rules(task) == (original,)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('enabled', [False, True])
|
||||
@pytest.mark.parametrize('bad', ['BAD PART !!@#', 'BAD\tPN', 'BAD\nPN'])
|
||||
def test_invalid_target_draft_can_exist_but_compile_and_save_reject_atomically(plan, enabled, bad):
|
||||
store, task, targets = plan
|
||||
original = store.list_target_plan(task)
|
||||
draft = (replace(original[0], enabled=enabled, new_part_number=bad), original[1])
|
||||
with pytest.raises(TaskCenterError, match='part_number'):
|
||||
compile_target_rules(draft)
|
||||
with pytest.raises(TaskCenterError, match='part_number'):
|
||||
store.replace_target_plan(task, draft)
|
||||
assert draft[0].new_part_number == bad
|
||||
assert store.list_target_plan(task) == original
|
||||
|
||||
|
||||
@pytest.mark.parametrize('enabled', [False, True])
|
||||
def test_excel_import_rejects_invalid_pn_without_changing_saved_plan(plan, tmp_path, enabled):
|
||||
store, task, _ = plan
|
||||
original = store.list_target_plan(task)
|
||||
path = export_target_plan(store, task, tmp_path / 'plan.xlsx')
|
||||
workbook = load_workbook(path)
|
||||
workbook.active['I2'] = enabled
|
||||
workbook.active['J2'] = 'BAD PART !!@#'
|
||||
workbook.save(path)
|
||||
workbook.close()
|
||||
with pytest.raises(TaskCenterError):
|
||||
import_target_plan(store, task, path)
|
||||
assert store.list_target_plan(task) == original
|
||||
|
||||
|
||||
def test_common_target_pn_and_free_value_cell_remain_legal(plan):
|
||||
store, task, targets = plan
|
||||
rows = tuple(TargetPlanRow(target, True, 'NEW-1', custom_value_enabled=True,
|
||||
custom_value='10 kΩ ±1% !@#', target_cell='Cell A!@#') for target in targets)
|
||||
assert len(compile_target_rules(rows)[0].targets) == 2
|
||||
assert store.replace_target_plan(task, rows) == rows
|
||||
|
||||
|
||||
def test_legacy_source_pn_can_be_repaired_without_rejecting_inventory(plan):
|
||||
store, task, targets = plan
|
||||
validate_mapping_pairs((('BAD PART !!@#', 'NEW'),))
|
||||
rule = store.add_rule(task, 'BAD PART !!@#', 'NEW')
|
||||
assert rule.old_part_number == 'BAD PART !!@#'
|
||||
legacy = replace(targets[0], old_part_number='BAD PART !!@#')
|
||||
assert compile_target_rules((TargetPlanRow(legacy, True, 'NEW'),))[0].targets == (legacy,)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('pn', ['ABC-123_1.0/2+(A)[B]', '物料编号-1', 'A' * 128, ' R-01 '])
|
||||
def test_supported_target_pn_spelling_and_length_remain_legal(plan, pn):
|
||||
store, task, targets = plan
|
||||
rule = store.add_rule(task, 'OLD', pn)
|
||||
assert rule.new_part_number == pn.strip()
|
||||
assert compile_target_rules((TargetPlanRow(targets[0], True, pn),))[0].new_part_number == pn.strip()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('enabled', [False, True])
|
||||
def test_bom_import_rejects_invalid_target_pn_atomically(plan, tmp_path, enabled):
|
||||
from dx_productivity.trial_task_center.bom_plan import read_bom_plan, write_bom_template
|
||||
store, task, targets = plan
|
||||
baseline = store.list_target_plan(task)
|
||||
path = write_bom_template(tmp_path / 'bom.xlsx', ({
|
||||
'project_path': str(targets[0].project_path), 'refdes': 'R1',
|
||||
'old_part_number': 'OLD', 'new_part_number': 'BAD PART !!@#', 'enabled': enabled,
|
||||
},))
|
||||
with pytest.raises(TaskCenterError):
|
||||
rows = read_bom_plan(store, task, path)
|
||||
store.replace_target_plan(task, rows)
|
||||
assert store.list_target_plan(task) == baseline
|
||||
|
||||
|
||||
def test_target_plan_save_trims_pn_at_persistence_boundary(plan):
|
||||
store, task, targets = plan
|
||||
rows = (TargetPlanRow(targets[0], True, ' NEW '), TargetPlanRow(targets[1], False, '\t '))
|
||||
saved = store.replace_target_plan(task, rows)
|
||||
assert tuple(row.new_part_number for row in saved) == ('NEW', '')
|
||||
@@ -22,8 +22,11 @@ def test_project_force_observes_user_force_without_leaking_failure_to_parent(tmp
|
||||
|
||||
|
||||
@pytest.mark.parametrize('residual', [False, True])
|
||||
def test_failed_project_retires_proven_exit_despite_shutdown_error(tmp_path, residual):
|
||||
def test_failed_project_requires_physical_release_despite_proven_writer_exit(tmp_path, monkeypatch, residual):
|
||||
import json
|
||||
from test_batch_runtime import Desktop
|
||||
from dx_productivity.trial_task_center import desktop_slot, isolated_desktop
|
||||
|
||||
class OwnedDesktop(Desktop):
|
||||
def close(self):
|
||||
self.cleanup_record = {'desktop_handle_closed': True, 'owned_cleanup_complete': True,
|
||||
@@ -34,12 +37,33 @@ def test_failed_project_retires_proven_exit_despite_shutdown_error(tmp_path, res
|
||||
def cad_exit(*args): raise OSError('shutdown diagnostics failed after exit')
|
||||
runtime.cad = SimpleNamespace(cad=SimpleNamespace(poll=lambda: 0), record={}, __exit__=cad_exit)
|
||||
original = RuntimeError('original failed project')
|
||||
assert runtime.release_failed_project(original, tmp_path / 'failed')
|
||||
assert batch_resources.blocking_resources(tmp_path) == ()
|
||||
assert runtime.record['state'] == ('isolated' if residual else 'released')
|
||||
assert runtime.record['release_results']['desktop_released'] is (not residual)
|
||||
assert runtime.desktop is None and 'shutdown diagnostics failed' in original.shutdown_warning
|
||||
assert (tmp_path / 'failed' / 'uncertain.flag').exists()
|
||||
evidence = tmp_path / 'failed'
|
||||
if residual:
|
||||
with pytest.raises(batch_resources.BatchResourceCleanupError, match='shutdown diagnostics failed'):
|
||||
runtime.release_failed_project(original, evidence)
|
||||
pending, = batch_resources.blocking_resources(tmp_path)
|
||||
assert pending['state'] == 'isolated'
|
||||
assert pending['release_results']['desktop_released'] is False
|
||||
with pytest.raises(batch_resources.BatchResourceCleanupError):
|
||||
batch_resources.guard_pending_resources(tmp_path)
|
||||
original_protection = (evidence / 'uncertain.flag').read_bytes()
|
||||
assert not (evidence / 'project-resource-release.json').exists()
|
||||
|
||||
monkeypatch.setattr(desktop_slot, 'observe_current_desktop_name', lambda _: None)
|
||||
monkeypatch.setattr(isolated_desktop, '_Win32Api',
|
||||
lambda: SimpleNamespace(confirm_desktop_released=lambda _: None))
|
||||
assert batch_resources.cleanup_pending_resources(tmp_path) == ()
|
||||
released = json.loads(runtime.path.read_bytes())
|
||||
assert released['state'] == 'released'
|
||||
assert released['release_proof']['desktop_released'] is True
|
||||
assert (evidence / 'uncertain.flag').read_bytes() == original_protection
|
||||
else:
|
||||
assert runtime.release_failed_project(original, evidence)
|
||||
assert runtime.record['state'] == 'released'
|
||||
assert runtime.record['release_results']['desktop_released'] is True
|
||||
assert runtime.desktop is None and 'shutdown diagnostics failed' in original.shutdown_warning
|
||||
assert (evidence / 'uncertain.flag').exists()
|
||||
batch_resources.guard_pending_resources(tmp_path)
|
||||
|
||||
|
||||
def test_runtime_cleanup_events_record_real_boundaries_and_preserve_error(tmp_path):
|
||||
@@ -56,7 +80,8 @@ def test_runtime_cleanup_events_record_real_boundaries_and_preserve_error(tmp_pa
|
||||
('mentor_exit', 'enter'), ('mentor_exit', 'error'), ('desktop_release', 'enter'), ('desktop_release', 'return')]
|
||||
|
||||
|
||||
def test_workspace_accepts_writer_exit_warning_and_blocks_shared_source_follower(tmp_path, monkeypatch):
|
||||
@pytest.mark.parametrize('shared_source', [False, True])
|
||||
def test_workspace_holds_follower_after_writer_exit_without_verified_result(tmp_path, monkeypatch, shared_source):
|
||||
from test_workspace_execution import service_for
|
||||
from dx_productivity.trial_task_center.workspace_execution import execute_workspace_projects
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
@@ -64,16 +89,22 @@ def test_workspace_accepts_writer_exit_warning_and_blocks_shared_source_follower
|
||||
failure.resources_released = False
|
||||
failure.owned_writers_exited = True
|
||||
service, calls = service_for(tmp_path, monkeypatch, {'A': failure, 'B': 'completed'})
|
||||
result = execute_workspace_projects(service, ('A', 'B'), stop_event=StopControl())
|
||||
assert not result.paused and result.entries[1].state == 'completed'
|
||||
calls.clear()
|
||||
for name in ('A', 'B'):
|
||||
path = tmp_path / name / 'board.prj'
|
||||
path.parent.mkdir(exist_ok=True)
|
||||
path.write_text('KEY iCDBDir "../shared"\n')
|
||||
result = execute_workspace_projects(service, ('A', 'B'), stop_event=StopControl())
|
||||
assert not result.paused and [row.state for row in result.entries] == ['blocked', 'blocked']
|
||||
assert [call[1]['task_ids'][0] for call in calls] == ['A']
|
||||
path.parent.mkdir()
|
||||
source = '../shared' if shared_source else 'database'
|
||||
path.write_text(f'KEY iCDBDir "{source}"\n')
|
||||
ids = ('A', 'B')
|
||||
result = execute_workspace_projects(service, ids, stop_event=StopControl())
|
||||
assert result.paused and result.current_task_id == 'A'
|
||||
assert [entry.state for entry in result.entries] == ['blocked', 'pending']
|
||||
protection = tmp_path / 'tasks' / 'A' / 'quick-run' / 'uncertain.flag'
|
||||
original = protection.read_bytes()
|
||||
resumed = execute_workspace_projects(service, ids, stop_event=StopControl(), queue_id=result.queue_id)
|
||||
assert resumed.paused and resumed.current_task_id == 'A'
|
||||
assert [entry.state for entry in resumed.entries] == ['blocked', 'pending']
|
||||
assert [call[1]['task_ids'] for call in calls] == [('A',)]
|
||||
assert protection.read_bytes() == original
|
||||
|
||||
|
||||
def test_blocked_progress_read_does_not_promote_or_throw(failed_native):
|
||||
|
||||
@@ -25,6 +25,9 @@ def test_managed_desktop_returns_external_residue_and_old_close_cannot_touch_new
|
||||
assert first.cleanup_record['desktop_confirmation']['released'] is False
|
||||
assert first.cleanup_record['desktop_lease']['returned'] is True
|
||||
second = PrivateDesktop('another-task', enabled=True, api=api, slot=slot(tmp_path, backend))
|
||||
with pytest.raises(TaskCenterError):
|
||||
second.__enter__()
|
||||
backend.exists = False
|
||||
second.__enter__()
|
||||
assert second.name == first.name
|
||||
first.close()
|
||||
@@ -102,10 +105,11 @@ def test_mutex_release_error_preserves_the_durably_returned_lease(tmp_path):
|
||||
pass
|
||||
|
||||
record = batch_resources.pending_resources(runtime.root)[0]
|
||||
assert record['state'] == 'isolated' and record['blocking'] is False
|
||||
assert record['state'] == 'isolated' and record['blocking'] is True
|
||||
assert record['cleanup']['desktop_lease']['returned'] is True
|
||||
assert 'mutex release failed' in record['isolation_warning']
|
||||
|
||||
backend.exists = False
|
||||
next_owner = slot(tmp_path / 'slot', backend).acquire()
|
||||
with pytest.raises(OSError, match='mutex release failed'):
|
||||
next_owner.release(desktop_disappeared=False)
|
||||
@@ -113,7 +117,7 @@ def test_mutex_release_error_preserves_the_durably_returned_lease(tmp_path):
|
||||
|
||||
|
||||
def test_failed_lease_return_stays_blocking_until_the_slot_can_be_returned(tmp_path, monkeypatch):
|
||||
from dx_productivity.trial_task_center import batch_resources
|
||||
from dx_productivity.trial_task_center import batch_resources, desktop_slot
|
||||
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
|
||||
|
||||
backend = Backend()
|
||||
@@ -135,6 +139,15 @@ def test_failed_lease_return_stays_blocking_until_the_slot_can_be_returned(tmp_p
|
||||
monkeypatch.undo()
|
||||
batch_resources.cleanup_pending_resources(runtime.root, retry_failed=True)
|
||||
assert not backend.locked
|
||||
pending, = batch_resources.blocking_resources(runtime.root)
|
||||
assert pending['state'] == 'isolated'
|
||||
assert pending['cleanup']['desktop_lease']['returned'] is True
|
||||
assert backend.desktop_exists(pending['desktop'])
|
||||
|
||||
monkeypatch.setattr(desktop_slot, 'managed_desktop_disappeared',
|
||||
lambda receipt: not backend.desktop_exists(receipt['name']))
|
||||
backend.exists = False
|
||||
assert batch_resources.cleanup_pending_resources(runtime.root) == ()
|
||||
assert batch_resources.blocking_resources(runtime.root) == ()
|
||||
|
||||
|
||||
@@ -160,13 +173,17 @@ def test_resource_recheck_never_queries_a_reused_desktop_for_a_returned_lease(tm
|
||||
runtime = BatchCadRuntime(tmp_path / 'data', 'execution', desktop_factory=factory)
|
||||
runtime._ensure_desktop(); runtime.close()
|
||||
assert runtime.record['state'] == 'isolated'
|
||||
with pytest.raises(TaskCenterError):
|
||||
slot(tmp_path / 'slot', backend).acquire()
|
||||
backend.exists = False
|
||||
next_owner = slot(tmp_path / 'slot', backend).acquire()
|
||||
backend.exists = True # A later owner may create a fresh object with the same name.
|
||||
from dx_productivity.trial_task_center import desktop_slot
|
||||
monkeypatch.setattr(desktop_slot, 'managed_desktop_disappeared', lambda receipt: False)
|
||||
def forbidden(*args): pytest.fail('old batch queried the currently leased desktop')
|
||||
monkeypatch.setattr(isolated_desktop, '_Win32Api', forbidden)
|
||||
warnings = batch_resources.cleanup_pending_resources(runtime.root)
|
||||
assert warnings and warnings[0]['blocking'] is False
|
||||
assert warnings and warnings[0]['blocking'] is True
|
||||
next_owner.release(desktop_disappeared=False)
|
||||
|
||||
|
||||
@@ -193,8 +210,8 @@ def test_transient_return_proof_read_failure_can_be_rechecked_without_permanent_
|
||||
monkeypatch.setattr(desktop_slot, 'returned_lease_intact', lambda *args: False)
|
||||
assert batch_resources.cleanup_pending_resources(runtime.root)[0]['blocking'] is True
|
||||
monkeypatch.setattr(desktop_slot, 'returned_lease_intact', original)
|
||||
assert batch_resources.cleanup_pending_resources(runtime.root)[0]['blocking'] is False
|
||||
assert not batch_resources.blocking_resources(runtime.root)
|
||||
assert batch_resources.cleanup_pending_resources(runtime.root)[0]['blocking'] is True
|
||||
assert batch_resources.blocking_resources(runtime.root)
|
||||
|
||||
|
||||
def test_native_job_creation_failure_is_certified_before_process_creation():
|
||||
|
||||
@@ -10,7 +10,7 @@ import pytest
|
||||
@pytest.mark.parametrize('behavior, steps, changed, states', [
|
||||
('success', 24, 24, ['completed', 'completed', 'completed']),
|
||||
('failure_continue', 24, 23, ['failed', 'completed', 'completed']),
|
||||
('uncertain_stop', 17, 16, ['blocked', 'completed', 'completed']),
|
||||
('uncertain_stop', 1, 0, ['blocked', 'pending', 'pending']),
|
||||
('pause_resume', 24, 24, ['completed', 'completed', 'completed']),
|
||||
])
|
||||
def test_multiple_projects_preserve_task_order_scope_results_and_measurements(tmp_path, behavior, steps, changed, states):
|
||||
@@ -24,14 +24,14 @@ def test_multiple_projects_preserve_task_order_scope_results_and_measurements(tm
|
||||
assert report['executed_steps'] == steps
|
||||
assert report['changed_components'] == changed
|
||||
assert report['unselected_components_preserved'] == 12
|
||||
assert report['result']['paused'] is False
|
||||
assert report['result']['paused'] is (behavior == 'uncertain_stop')
|
||||
assert [entry['state'] for entry in report['result']['entries']] == states
|
||||
calls = report['calls']
|
||||
assert len(calls) == steps
|
||||
assert all(len(call['refdes']) == 1 for call in calls)
|
||||
assert len({(call['project'], call['sheet'], call['refdes'][0]) for call in calls}) == steps
|
||||
assert sum(call['state'] == 'saved_ok' for call in calls) == changed
|
||||
assert [call['project'] for call in calls] == (['board-000'] + ['board-001'] * 8 + ['board-002'] * 8 if behavior == 'uncertain_stop' else
|
||||
assert [call['project'] for call in calls] == (['board-000'] if behavior == 'uncertain_stop' else
|
||||
['board-000'] * 8 + ['board-001'] * 8 + ['board-002'] * 8)
|
||||
assert calls[0]['state'] == {'failure_continue': 'batch_failed', 'uncertain_stop': 'batch_saved_unverified'}.get(behavior, 'saved_ok')
|
||||
with sqlite3.connect(output / 'tasks.db') as connection:
|
||||
|
||||
@@ -66,15 +66,21 @@ def test_hundred_uid_batch_keeps_93_verified_items_and_isolates_unknown_writes(t
|
||||
ids = tuple(task.task_id for task in tasks)
|
||||
try:
|
||||
result = execute_task_queue(gui, ids, stop_event=Event())
|
||||
assert not result.paused
|
||||
assert [entry.state for entry in result.entries] == ['failed', 'completed', 'blocked', 'blocked']
|
||||
assert len(calls) == 100 and set(Counter(calls).values()) == {1}
|
||||
assert (tasks[3].task_id, 'u1') in calls
|
||||
assert result.paused and result.current_task_id == tasks[2].task_id
|
||||
assert [entry.state for entry in result.entries] == ['failed', 'completed', 'blocked', 'pending']
|
||||
assert len(calls) == 99 and set(Counter(calls).values()) == {1}
|
||||
assert (tasks[3].task_id, 'u1') not in calls
|
||||
records = dict(store._connection.execute('SELECT state,count(*) FROM execution_operations GROUP BY state'))
|
||||
assert records == {'verified': 93, 'failed': 5, 'uncertain': 2}
|
||||
assert records == {'verified': 93, 'failed': 5, 'uncertain': 1}
|
||||
resumed = execute_task_queue(gui, ids, stop_event=Event(), queue_id=result.queue_id)
|
||||
assert not resumed.paused and resumed.entries[2].state == 'blocked'
|
||||
assert len(calls) == 100
|
||||
assert resumed.paused and resumed.queue_id == result.queue_id
|
||||
assert resumed.current_task_id == tasks[2].task_id
|
||||
assert [(entry.task_id, entry.state) for entry in resumed.entries] == [
|
||||
(entry.task_id, entry.state) for entry in result.entries]
|
||||
assert dict(store._connection.execute(
|
||||
'SELECT state,count(*) FROM execution_operations GROUP BY state')) == records
|
||||
assert engine.has_interrupted_quick_run(tasks[2].task_id)
|
||||
assert len(calls) == 99
|
||||
finally:
|
||||
store.close()
|
||||
reopened = TaskStore(database)
|
||||
|
||||
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user