Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
818fb9a695 |
No files matched your search
@@ -0,0 +1,7 @@
|
|||||||
|
# DxPartReplace 1.3.3-beta.1 实机评分包
|
||||||
|
|
||||||
|
此 Windows x64 便携版包含 #33 的八项修复,供六套固定试卷重新评分。更新内容包括同数据目录单实例、工程路径报错、窗口恢复、搜索空状态、BOM 表头警告,以及 DxDataBook 加载、资源回收和队列续跑。
|
||||||
|
|
||||||
|
退出旧程序后将 ZIP 完整解压到新目录,双击 `启动程序.cmd`。核对窗口标题为 `DxDesigner 器件替换 · 1.3.3-beta.1`。需要复测旧任务时,使用旧 `data` 的备份副本。
|
||||||
|
|
||||||
|
优先用现场库复测 BOB、BOB_Shield 的 `4885-S033D0-M220` 和 WiFi LWB01 的 `4885-S018D0-M220`。记录能否打开工程、加载料号、保存回读及释放桌面。卷四测试 8 工程混合批次,另跑 100 工程队列。卷六记录暂停、跨进程恢复和已保存项的派发次数。原始分数为 373/600,本包成绩以实机逐题结果为准。[实机评分工单 #42](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/issues/42)
|
||||||
@@ -1,107 +0,0 @@
|
|||||||
# 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 身份冲突及客户库确定性不存在仍缺对应现场证据,本轮不关闭工单。
|
|
||||||
@@ -1,250 +0,0 @@
|
|||||||
# 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. 本次规划阶段交付界限
|
|
||||||
|
|
||||||
本计划及配套设计/审查文档完成后,工作停在可评审的方案。正式实施需要用户确定方案;不会因文档内的复选框或提交建议自动开始代码修改。方案审查属于本次工作,未调用其他代理;后续代码评审与实机验收需要单独记录实际执行结果。
|
|
||||||
@@ -1,201 +0,0 @@
|
|||||||
# 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. 评审结论
|
|
||||||
|
|
||||||
建议采用“复用执行链、统一范围和事实契约”的方案。三项核心业务取舍已由用户确定,没有以绕过安全门禁提升通过率。实施前必须把本设计中的提议接口、兼容读取及故障注入用例一起纳入首个代码评审;本次没有声称故障已修复。
|
|
||||||
@@ -1,63 +0,0 @@
|
|||||||
# 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 的现场缺陷仍需原现场证据;本轮仅处理共同的整批准入、写入保护、入口反馈与回执。
|
|
||||||
|
|
||||||
本地分支保留,可继续定位剩余现场问题。没有推送、合并、发布或向远端工单发送消息。
|
|
||||||
@@ -6,7 +6,6 @@ Const VDM_COMPPIN = 4096
|
|||||||
Const VD_ALL = 0
|
Const VD_ALL = 0
|
||||||
Const QP_COMPONENT_COORDINATE_TOLERANCE = 10
|
Const QP_COMPONENT_COORDINATE_TOLERANCE = 10
|
||||||
Const QP_ATTRIBUTE_COORDINATE_TOLERANCE = 10
|
Const QP_ATTRIBUTE_COORDINATE_TOLERANCE = 10
|
||||||
Const QP_DATABOOK_TIMEOUT_EXIT = 4
|
|
||||||
|
|
||||||
Dim QP_Fso
|
Dim QP_Fso
|
||||||
Dim QP_Root
|
Dim QP_Root
|
||||||
@@ -1647,7 +1646,7 @@ Sub QPAutomaticReplaceAndRestore(ByRef Command, ByVal SnapshotPath)
|
|||||||
End Sub
|
End Sub
|
||||||
|
|
||||||
Sub QPNativeReplace(ByRef Command, ByVal SnapshotPath)
|
Sub QPNativeReplace(ByRef Command, ByVal SnapshotPath)
|
||||||
Dim Shell, ExitCode, CommandLine, ErrorPath, ErrorDetail, ErrorSource
|
Dim Shell, ExitCode, CommandLine, ErrorPath, ErrorDetail
|
||||||
QPProgress "before_native", 0, 1
|
QPProgress "before_native", 0, 1
|
||||||
QPInvalidatePinIndex
|
QPInvalidatePinIndex
|
||||||
If Len(QP_HelperExecutable) = 0 Or Not QP_Fso.FileExists(QP_HelperExecutable) Then _
|
If Len(QP_HelperExecutable) = 0 Or Not QP_Fso.FileExists(QP_HelperExecutable) Then _
|
||||||
@@ -1670,18 +1669,15 @@ Sub QPNativeReplace(ByRef Command, ByVal SnapshotPath)
|
|||||||
QPInvalidatePinIndex
|
QPInvalidatePinIndex
|
||||||
QPProgress "native_replace", 1, 1
|
QPProgress "native_replace", 1, 1
|
||||||
If ExitCode <> 0 Then
|
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"
|
ErrorPath = SnapshotPath & ".native.error.txt"
|
||||||
ErrorDetail = ""
|
ErrorDetail = ""
|
||||||
If QP_Fso.FileExists(ErrorPath) Then ErrorDetail = Trim(QPReadUtf8(ErrorPath))
|
If QP_Fso.FileExists(ErrorPath) Then ErrorDetail = Trim(QPReadUtf8(ErrorPath))
|
||||||
If Len(ErrorDetail) > 0 Then
|
If Len(ErrorDetail) > 0 Then
|
||||||
Err.Raise vbObjectError + 839, ErrorSource, _
|
Err.Raise vbObjectError + 839, "QuickPartReplace", _
|
||||||
"automatic native replacement failed: " & ErrorDetail & _
|
"automatic native replacement failed: " & ErrorDetail & _
|
||||||
"; report: " & SnapshotPath & ".native.json"
|
"; report: " & SnapshotPath & ".native.json"
|
||||||
Else
|
Else
|
||||||
Err.Raise vbObjectError + 839, ErrorSource, _
|
Err.Raise vbObjectError + 839, "QuickPartReplace", _
|
||||||
"automatic native replacement failed (exit=" & CStr(ExitCode) & "); see " & SnapshotPath & ".native.json"
|
"automatic native replacement failed (exit=" & CStr(ExitCode) & "); see " & SnapshotPath & ".native.json"
|
||||||
End If
|
End If
|
||||||
End If
|
End If
|
||||||
@@ -3999,12 +3995,9 @@ Sub QPWriteStatus(ByVal Root, ByVal JobId, ByVal State, ByVal Code, ByVal Messag
|
|||||||
End Sub
|
End Sub
|
||||||
|
|
||||||
Sub QPFail(ByVal Root, ByVal State, ByVal Number, ByVal Source, ByVal Description)
|
Sub QPFail(ByVal Root, ByVal State, ByVal Number, ByVal Source, ByVal Description)
|
||||||
Dim Code
|
|
||||||
On Error Resume Next
|
On Error Resume Next
|
||||||
If Len(CStr(QP_CurrentJobId)) > 0 Then
|
If Len(CStr(QP_CurrentJobId)) > 0 Then
|
||||||
Code = CStr(Number)
|
QPWriteStatus Root, QP_CurrentJobId, State, CStr(Number), _
|
||||||
If Source = "QuickPartReplace.DxDataBookLookup" Then Code = "lookup_unavailable"
|
|
||||||
QPWriteStatus Root, QP_CurrentJobId, State, Code, _
|
|
||||||
CStr(Source) & ": " & CStr(Description)
|
CStr(Source) & ": " & CStr(Description)
|
||||||
End If
|
End If
|
||||||
QPLog Root, "ERROR", "stage=" & CStr(QP_Stage) & " number=" & Number & " source=" & Source & _
|
QPLog Root, "ERROR", "stage=" & CStr(QP_Stage) & " number=" & Number & " source=" & Source & _
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# UTF-8
|
# UTF-8
|
||||||
VSVersionInfo(
|
VSVersionInfo(
|
||||||
ffi=FixedFileInfo(
|
ffi=FixedFileInfo(
|
||||||
filevers=(1, 3, 1, 0),
|
filevers=(1, 3, 3, 1),
|
||||||
prodvers=(1, 3, 1, 0),
|
prodvers=(1, 3, 3, 1),
|
||||||
mask=0x3f,
|
mask=0x3f,
|
||||||
flags=0x0,
|
flags=0x0,
|
||||||
OS=0x40004,
|
OS=0x40004,
|
||||||
@@ -15,11 +15,11 @@ VSVersionInfo(
|
|||||||
StringTable('040904B0', [
|
StringTable('040904B0', [
|
||||||
StringStruct('CompanyName', 'DxProductivity'),
|
StringStruct('CompanyName', 'DxProductivity'),
|
||||||
StringStruct('FileDescription', 'DxDesigner Part Replacement'),
|
StringStruct('FileDescription', 'DxDesigner Part Replacement'),
|
||||||
StringStruct('FileVersion', '1.3.1.0'),
|
StringStruct('FileVersion', '1.3.3.1'),
|
||||||
StringStruct('InternalName', 'DxPartReplace'),
|
StringStruct('InternalName', 'DxPartReplace'),
|
||||||
StringStruct('OriginalFilename', 'DxPartReplace.exe'),
|
StringStruct('OriginalFilename', 'DxPartReplace.exe'),
|
||||||
StringStruct('ProductName', 'DxDesigner Part Replacement'),
|
StringStruct('ProductName', 'DxDesigner Part Replacement'),
|
||||||
StringStruct('ProductVersion', '1.3.1')
|
StringStruct('ProductVersion', '1.3.3-beta.1')
|
||||||
])
|
])
|
||||||
]),
|
]),
|
||||||
VarFileInfo([VarStruct('Translation', [1033, 1200])])
|
VarFileInfo([VarStruct('Translation', [1033, 1200])])
|
||||||
|
|||||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "dx-productivity"
|
name = "dx-productivity"
|
||||||
version = "1.3.1"
|
version = "1.3.3b1"
|
||||||
requires-python = ">=3.12,<3.13"
|
requires-python = ">=3.12,<3.13"
|
||||||
dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<1", "openpyxl>=3.1,<4"]
|
dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<1", "openpyxl>=3.1,<4"]
|
||||||
|
|
||||||
|
|||||||
@@ -1,23 +1,14 @@
|
|||||||
"""Execute a natively confirmed frozen scope and persist its actual receipt."""
|
"""Execute a natively confirmed frozen scope and persist its actual receipt."""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from dataclasses import asdict
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
from hashlib import sha256
|
|
||||||
import json
|
import json
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import re
|
|
||||||
from time import monotonic
|
|
||||||
|
|
||||||
from . import task_lifecycle as tasks
|
from . import task_lifecycle as tasks
|
||||||
from .run_journal import RunJournal, _check_scope, _json
|
from .run_journal import RunJournal
|
||||||
from .scheduling import ScheduleStore
|
from .scheduling import ScheduleStore
|
||||||
from .cad_verification import CadVerificationAdapter
|
from .cad_verification import CadVerificationAdapter
|
||||||
from ..trial_task_center import batch_resources
|
|
||||||
from ..trial_task_center.batch_admission import validate_batch_admission
|
|
||||||
from ..trial_task_center.batch_summary import _checkpoint_source, collect_batch_summary, refresh_batch_resources
|
|
||||||
from ..trial_task_center.errors import TaskCenterError
|
from ..trial_task_center.errors import TaskCenterError
|
||||||
from ..trial_task_center.path_access import canonical_path, internal_path
|
|
||||||
from ..trial_task_center.task_queue import execute_task_queue
|
from ..trial_task_center.task_queue import execute_task_queue
|
||||||
|
|
||||||
|
|
||||||
@@ -46,68 +37,7 @@ def _failure_evidence(service, journal, run_id, baseline):
|
|||||||
return evidence
|
return evidence
|
||||||
|
|
||||||
|
|
||||||
def execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, resume=None, schedule=None,
|
def execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, resume=None, schedule=None, automatic=False):
|
||||||
automatic=False, admission=None):
|
|
||||||
root = Path(root)
|
|
||||||
if resume or admission is not None:
|
|
||||||
ids, hashes = _check_scope(run_id, task_ids, report['plan_hashes'])
|
|
||||||
directory = internal_path(root / 'batch-runs' / run_id)
|
|
||||||
manifest_path = directory / 'manifest.json'
|
|
||||||
if admission is not None and not resume:
|
|
||||||
if (list(admission['runnable_task_ids']) != ids or admission['plan_hashes'] != hashes
|
|
||||||
or admission['execution_report'] != report):
|
|
||||||
raise TaskCenterError('run_scope', '已确认的批次范围与执行报告不一致。')
|
|
||||||
manifest = _json({**admission, 'schema_version': 1, 'run_id': run_id,
|
|
||||||
'confirmed_utc': datetime.now(timezone.utc).isoformat()})
|
|
||||||
try:
|
|
||||||
directory.mkdir(parents=True, exist_ok=False)
|
|
||||||
except FileExistsError as error:
|
|
||||||
raise TaskCenterError('run_conflict', '批次已有冻结清单,请读取原执行记录。') from error
|
|
||||||
batch_resources.write_record(manifest_path, manifest)
|
|
||||||
elif manifest_path.is_file():
|
|
||||||
manifest = json.loads(manifest_path.read_bytes())
|
|
||||||
if manifest['run_id'] != run_id or manifest['runnable_task_ids'] != ids or manifest['plan_hashes'] != hashes:
|
|
||||||
raise TaskCenterError('run_scope', '冻结批次的身份或执行计划已变化。')
|
|
||||||
else:
|
|
||||||
if resume and RunJournal(root).batch_retry_revalidator(service, run_id) is not None:
|
|
||||||
raise TaskCenterError('batch_manifest', '原批次的冻结清单缺失,不能按旧版队列继续。')
|
|
||||||
manifest = None
|
|
||||||
else:
|
|
||||||
manifest = None
|
|
||||||
if manifest is None:
|
|
||||||
return _execute_with_schedule(service, root, task_ids, report, stop, run_id,
|
|
||||||
resume=resume, schedule=schedule, automatic=automatic)
|
|
||||||
start = monotonic()
|
|
||||||
original_supervisor = getattr(service, '_last_supervisor_batch_id', None)
|
|
||||||
journal = RunJournal(root)
|
|
||||||
previous_run = journal.get(run_id) if resume else None
|
|
||||||
try:
|
|
||||||
receipt = _execute_with_schedule(service, root, task_ids, report, stop, run_id,
|
|
||||||
resume=resume, schedule=schedule, automatic=automatic, admission=admission,
|
|
||||||
manifest_digest=manifest['manifest_digest'])
|
|
||||||
except Exception as error:
|
|
||||||
current = journal.get(run_id)
|
|
||||||
if resume and current == previous_run:
|
|
||||||
raise
|
|
||||||
receipt = (current or {}).get('result') or {}
|
|
||||||
if not receipt:
|
|
||||||
code = getattr(error, 'code', 'execution_interrupted')
|
|
||||||
receipt = {'status': 'interrupted' if current else
|
|
||||||
'cancelled' if code == 'operation_cancelled' else 'rejected',
|
|
||||||
'paused': bool(current), 'code': code}
|
|
||||||
completed = getattr(error, 'completed_result', None)
|
|
||||||
if current and completed is not None and hasattr(completed, 'netlist_verification'):
|
|
||||||
entries = [asdict(entry) for entry in completed.entries]
|
|
||||||
receipt = {**receipt, 'entries': entries, 'paused': completed.paused,
|
|
||||||
'queue_id': completed.queue_id, 'execution_status': _business_status(entries, completed.paused),
|
|
||||||
'netlist_verification': completed.netlist_verification}
|
|
||||||
_finish_batch_summary(service, root, journal, manifest, receipt, start, original_supervisor)
|
|
||||||
raise
|
|
||||||
return _finish_batch_summary(service, root, journal, manifest, receipt, start, original_supervisor)
|
|
||||||
|
|
||||||
|
|
||||||
def _execute_with_schedule(service, root, task_ids, report, stop, run_id, *, resume=None, schedule=None,
|
|
||||||
automatic=False, admission=None, manifest_digest=None):
|
|
||||||
prior = RunJournal(root).get(run_id) if resume else None
|
prior = RunJournal(root).get(run_id) if resume else None
|
||||||
schedule_id = schedule['schedule_id'] if schedule else (prior or {}).get('schedule_id')
|
schedule_id = schedule['schedule_id'] if schedule else (prior or {}).get('schedule_id')
|
||||||
if schedule_id:
|
if schedule_id:
|
||||||
@@ -117,8 +47,7 @@ def _execute_with_schedule(service, root, task_ids, report, stop, run_id, *, res
|
|||||||
if resume:
|
if resume:
|
||||||
_bound_schedule(schedules, prior)
|
_bound_schedule(schedules, prior)
|
||||||
receipt = _execute_confirmed_run(service, root, task_ids, report, stop, run_id,
|
receipt = _execute_confirmed_run(service, root, task_ids, report, stop, run_id,
|
||||||
resume=resume, schedule=schedule, automatic=automatic, admission=admission,
|
resume=resume, schedule=schedule, automatic=automatic)
|
||||||
manifest_digest=manifest_digest)
|
|
||||||
if resume:
|
if resume:
|
||||||
schedules.finish(schedule_id, 'interrupted' if receipt['status'] in {'paused', 'blocked'} else receipt['status'],
|
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)
|
repair_run_id=run_id, run_id=run_id, receipt=receipt)
|
||||||
@@ -130,12 +59,10 @@ def _execute_with_schedule(service, root, task_ids, report, stop, run_id, *, res
|
|||||||
raise TaskCenterError('schedule_run_conflict', '运行已不再绑定当前排期执行租约。')
|
raise TaskCenterError('schedule_run_conflict', '运行已不再绑定当前排期执行租约。')
|
||||||
_finish_failed_schedule(schedules, RunJournal(root), original)
|
_finish_failed_schedule(schedules, RunJournal(root), original)
|
||||||
raise
|
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,
|
def _execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, resume=None, schedule=None, automatic=False):
|
||||||
automatic=False, admission=None, manifest_digest=None):
|
|
||||||
if tasks.fingerprint(service, task_ids) != report['fingerprint']:
|
if tasks.fingerprint(service, task_ids) != report['fingerprint']:
|
||||||
raise TaskCenterError('assistant_stale', '任务状态已变化,请重新预检后确认。')
|
raise TaskCenterError('assistant_stale', '任务状态已变化,请重新预检后确认。')
|
||||||
journal = RunJournal(root)
|
journal = RunJournal(root)
|
||||||
@@ -143,29 +70,6 @@ def _execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, res
|
|||||||
initialized = False
|
initialized = False
|
||||||
claimed = False
|
claimed = False
|
||||||
baseline = {}
|
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:
|
try:
|
||||||
if schedule:
|
if schedule:
|
||||||
current = next((r for r in schedules.evaluate(service) if r['schedule_id'] == schedule['schedule_id']), None)
|
current = next((r for r in schedules.evaluate(service) if r['schedule_id'] == schedule['schedule_id']), None)
|
||||||
@@ -177,11 +81,10 @@ 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']:
|
if not inspected['resume_ready'] or inspected['plan_hashes'] != report['plan_hashes']:
|
||||||
raise TaskCenterError('run_blocked', '原执行范围或证据已变化,请先核验。')
|
raise TaskCenterError('run_blocked', '原执行范围或证据已变化,请先核验。')
|
||||||
baseline = inspected.get('result') or {}
|
baseline = inspected.get('result') or {}
|
||||||
if not manifest_digest:
|
|
||||||
journal.resume(run_id)
|
journal.resume(run_id)
|
||||||
initialized = True
|
initialized = True
|
||||||
journal.repair_retry_checkpoint(service, run_id)
|
journal.repair_retry_checkpoint(service, run_id)
|
||||||
elif not manifest_digest:
|
else:
|
||||||
journal.begin(run_id, task_ids, report['plan_hashes'], schedule_id=schedule['schedule_id'] if schedule else None)
|
journal.begin(run_id, task_ids, report['plan_hashes'], schedule_id=schedule['schedule_id'] if schedule else None)
|
||||||
initialized = True
|
initialized = True
|
||||||
resource_batch_id = inspected.get('resource_batch_id') if resume else None
|
resource_batch_id = inspected.get('resource_batch_id') if resume else None
|
||||||
@@ -189,9 +92,6 @@ def _execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, res
|
|||||||
expected_plan_hashes=report['plan_hashes'],
|
expected_plan_hashes=report['plan_hashes'],
|
||||||
queue_id=run_id if resume and resume['queue_available'] else None,
|
queue_id=run_id if resume and resume['queue_available'] else None,
|
||||||
checkpoint_id=None if resume and resume['queue_available'] else run_id,
|
checkpoint_id=None if resume and resume['queue_available'] else run_id,
|
||||||
**({'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 {}))
|
**({'resource_batch_id': resource_batch_id} if resource_batch_id else {}))
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
failure = {**(_failure_evidence(service, journal, run_id, baseline) if initialized else {}),
|
failure = {**(_failure_evidence(service, journal, run_id, baseline) if initialized else {}),
|
||||||
@@ -203,20 +103,18 @@ 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)
|
schedules.finish(schedule['schedule_id'], 'interrupted', run_id=run_id, receipt=failure)
|
||||||
raise
|
raise
|
||||||
return _finish_execution_run(service, root, task_ids, stop, run_id, result,
|
return _finish_execution_run(service, root, task_ids, stop, run_id, result,
|
||||||
baseline=baseline, schedule=schedule if claimed else None, resource_report_pending=bool(manifest_digest))
|
baseline=baseline, schedule=schedule if claimed else None)
|
||||||
|
|
||||||
|
|
||||||
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)
|
journal = RunJournal(root)
|
||||||
schedules = ScheduleStore(root) if schedule is not None else None
|
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]
|
entries = [{'task_id': e.task_id, 'state': e.state, 'message': e.message} for e in result.entries]
|
||||||
status = _business_status(entries, result.paused)
|
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')
|
||||||
from ..trial_task_center.netlist_verification import verification_summary
|
from ..trial_task_center.netlist_verification import verification_summary
|
||||||
acceptance = verification_summary(result.netlist_verification)
|
acceptance = verification_summary(result.netlist_verification)
|
||||||
overall = 'failed' if status == 'completed' and acceptance['status'] in {'different', 'unavailable'} else status
|
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,
|
receipt = {'status': overall, 'execution_status': status, 'acceptance': acceptance,
|
||||||
'run_id': run_id, 'queue_id': result.queue_id, 'paused': result.paused,
|
'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()),
|
'user_pause_requested': bool(stop.is_set()), 'awaiting_user_resume': bool(result.paused and stop.is_set()),
|
||||||
@@ -280,220 +178,6 @@ def _finish_execution_run(service, root, task_ids, stop, run_id, result, *, base
|
|||||||
return receipt
|
return receipt
|
||||||
|
|
||||||
|
|
||||||
def _business_status(entries, paused):
|
|
||||||
if any(entry['state'] == 'blocked' for entry in entries):
|
|
||||||
return 'blocked'
|
|
||||||
if paused:
|
|
||||||
return 'paused'
|
|
||||||
return 'failed' if any(entry['state'] == 'failed' for entry in entries) else 'completed'
|
|
||||||
|
|
||||||
|
|
||||||
def _bound_supervisors(root, manifest):
|
|
||||||
from ..trial_task_center.supervisor_protocol import VERSION, decode, valid_journal
|
|
||||||
|
|
||||||
records = []
|
|
||||||
for path in internal_path(root / 'batch-resources').glob('*/request.json'):
|
|
||||||
try:
|
|
||||||
raw = path.read_bytes()
|
|
||||||
request = json.loads(raw)
|
|
||||||
journal = json.loads(path.with_name('supervisor.json').read_bytes())
|
|
||||||
batch_id = path.parent.name
|
|
||||||
if (not valid_journal(journal, batch_id) or sha256(raw).hexdigest() != journal['request_sha256']
|
|
||||||
or request['version'] != VERSION or canonical_path(request['root']) != canonical_path(root)
|
|
||||||
or request['batch_id'] != batch_id or request['attempt_id'] != journal['attempt_id']
|
|
||||||
or request['operation'] != journal['operation'] or journal['operation'] != 'execute_task_queue'
|
|
||||||
or request['task_ids'] != journal['task_ids']
|
|
||||||
or journal['task_ids'] != manifest['runnable_task_ids']):
|
|
||||||
continue
|
|
||||||
arguments = decode(request['arguments'])
|
|
||||||
if ((arguments.get('queue_id') or arguments.get('checkpoint_id')) == manifest['run_id']
|
|
||||||
and list(arguments.get('task_ids', ())) == manifest['runnable_task_ids']
|
|
||||||
and arguments.get('expected_plan_hashes') == manifest['plan_hashes']
|
|
||||||
and arguments.get('manifest_digest') == manifest['manifest_digest']):
|
|
||||||
records.append((journal.get('started_at') or 0, batch_id))
|
|
||||||
except (OSError, ValueError, TypeError, KeyError):
|
|
||||||
continue
|
|
||||||
return [batch_id for _, batch_id in sorted(records)]
|
|
||||||
|
|
||||||
|
|
||||||
def _recover_supervised_business(root, manifest, batch_ids):
|
|
||||||
from ..trial_task_center.supervisor_protocol import MessageGate, VERSION
|
|
||||||
from ..trial_task_center.supervisor_result import validated_outcome
|
|
||||||
|
|
||||||
if not batch_ids:
|
|
||||||
return {}
|
|
||||||
checkpoint, _, _, _ = _checkpoint_source(root, manifest)
|
|
||||||
if checkpoint.get('manifest_digest') != manifest['manifest_digest']:
|
|
||||||
return {}
|
|
||||||
batch_id = batch_ids[-1]
|
|
||||||
directory = internal_path(root / 'batch-resources' / batch_id)
|
|
||||||
try:
|
|
||||||
supervisor = json.loads((directory / 'supervisor.json').read_bytes())
|
|
||||||
attempt_id = supervisor['attempt_id']
|
|
||||||
try:
|
|
||||||
envelope = json.loads((directory / 'result.json').read_bytes())
|
|
||||||
except FileNotFoundError:
|
|
||||||
business = json.loads((directory / 'business-result.json').read_bytes())
|
|
||||||
if business.get('version') != VERSION or business['payload']['business_succeeded'] is not True:
|
|
||||||
return {}
|
|
||||||
envelope = {**business, 'type': 'result', 'sequence': 1}
|
|
||||||
if not MessageGate(batch_id, attempt_id).accept(envelope) or envelope['type'] != 'result':
|
|
||||||
return {}
|
|
||||||
result, _, _ = validated_outcome('execute_task_queue', envelope['payload'])
|
|
||||||
if result is None or result.queue_id != manifest['run_id']:
|
|
||||||
return {}
|
|
||||||
entries = [asdict(entry) for entry in result.entries]
|
|
||||||
if ([entry['task_id'] for entry in entries] != manifest['runnable_task_ids']
|
|
||||||
or any(checkpoint['entries'][entry['task_id']].get('state') != entry['state'] for entry in entries)
|
|
||||||
or (not result.paused and any(entry['state'] in {'pending', 'paused', 'running'} for entry in entries))):
|
|
||||||
return {}
|
|
||||||
netlist = result.netlist_verification or {}
|
|
||||||
if checkpoint.get('netlist_verification', netlist) != netlist:
|
|
||||||
return {}
|
|
||||||
status = _business_status(entries, result.paused)
|
|
||||||
user_paused = supervisor.get('stopping_reason') == 'user_pause'
|
|
||||||
return {'run_id': manifest['run_id'], 'queue_id': result.queue_id, 'entries': entries,
|
|
||||||
'execution_status': status, 'status': status, 'paused': result.paused,
|
|
||||||
'netlist_verification': netlist, 'user_pause_requested': user_paused,
|
|
||||||
'awaiting_user_resume': result.paused and user_paused}
|
|
||||||
except (OSError, ValueError, TypeError, KeyError, AttributeError):
|
|
||||||
return {}
|
|
||||||
|
|
||||||
|
|
||||||
def _finish_batch_summary(service, root, journal, manifest, receipt, start, original_supervisor=None,
|
|
||||||
*, incident_batch_ids=()):
|
|
||||||
run_id = manifest['run_id']
|
|
||||||
elapsed = round(monotonic() - start, 3)
|
|
||||||
log = service._logging.logger
|
|
||||||
receipt = {**receipt, 'elapsed_seconds': elapsed}
|
|
||||||
has_run = False
|
|
||||||
try:
|
|
||||||
has_run = journal.get(run_id) is not None
|
|
||||||
batch_ids = list(dict.fromkeys([*_bound_supervisors(root, manifest), *incident_batch_ids]))
|
|
||||||
current = getattr(service, '_last_supervisor_batch_id', None)
|
|
||||||
if isinstance(current, str) and current != original_supervisor and re.fullmatch('[0-9a-f]{32}', current):
|
|
||||||
has_request = internal_path(root / 'batch-resources' / current / 'request.json').is_file()
|
|
||||||
if not has_request and current not in batch_ids:
|
|
||||||
batch_ids.append(current)
|
|
||||||
summary = collect_batch_summary(service, root, manifest, receipt,
|
|
||||||
batch_ids=batch_ids, elapsed_seconds=elapsed, no_dispatch=not has_run)
|
|
||||||
if not has_run:
|
|
||||||
summary.update(queue_id=None, dispatch_count=0)
|
|
||||||
summary = _publish_batch_summary(root, journal, summary, receipt, has_run=has_run)
|
|
||||||
except Exception as error:
|
|
||||||
receipt.setdefault('reporting_errors', []).append(
|
|
||||||
{'code': 'batch_summary_unavailable', 'error': type(error).__name__})
|
|
||||||
log.warning('batch_summary_unavailable run_id=%s error=%s', run_id, type(error).__name__)
|
|
||||||
if has_run:
|
|
||||||
try:
|
|
||||||
journal.finish(run_id, receipt)
|
|
||||||
except Exception as save_error:
|
|
||||||
log.error('batch_summary_reporting_error_unavailable run_id=%s error=%s',
|
|
||||||
run_id, type(save_error).__name__)
|
|
||||||
return receipt
|
|
||||||
log.info('batch_summary run_id=%s revision=%s status=%s tasks=%s targets=%s',
|
|
||||||
run_id, summary['revision'], summary['status'], summary['task_counts'], summary['operation_total'])
|
|
||||||
return {**receipt, 'status': summary['status'], 'execution_status': summary['execution_status'],
|
|
||||||
'acceptance': summary['acceptance'], 'reporting_errors': summary['reporting_errors'], 'summary': summary}
|
|
||||||
|
|
||||||
|
|
||||||
def _republish_incident_batch_summary(service, root, run_id, receipt, *, batch_id=None):
|
|
||||||
"""Update the original batch revision after an admitted incident retry."""
|
|
||||||
root = Path(root)
|
|
||||||
path = internal_path(root / 'batch-runs' / run_id / 'manifest.json')
|
|
||||||
if not path.is_file():
|
|
||||||
return receipt
|
|
||||||
journal = RunJournal(root)
|
|
||||||
manifest = json.loads(path.read_bytes())
|
|
||||||
run = journal.get(run_id)
|
|
||||||
if (not run or manifest['run_id'] != run_id or manifest['runnable_task_ids'] != run['task_ids']
|
|
||||||
or manifest['plan_hashes'] != run['plan_hashes']):
|
|
||||||
raise TaskCenterError('run_scope', '原批次回执身份变化,无法更新。')
|
|
||||||
previous = journal.batch_summary(run_id) or {}
|
|
||||||
batch_ids = list(previous.get('resource_batch_ids', ()))
|
|
||||||
if isinstance(batch_id, str) and re.fullmatch('[0-9a-f]{32}', batch_id):
|
|
||||||
batch_ids.append(batch_id)
|
|
||||||
return _finish_batch_summary(service, root, journal, manifest, receipt, monotonic(),
|
|
||||||
getattr(service, '_last_supervisor_batch_id', None),
|
|
||||||
incident_batch_ids=batch_ids)
|
|
||||||
|
|
||||||
|
|
||||||
def _publish_batch_summary(root, journal, summary, receipt, *, has_run):
|
|
||||||
run_id = summary['run_id']
|
|
||||||
summary = (journal.save_batch_summary(run_id, summary, receipt) if has_run else dict(summary, revision=1))
|
|
||||||
try:
|
|
||||||
batch_resources.write_record(root / 'batch-runs' / run_id / 'batch-receipt.json', summary)
|
|
||||||
except OSError as error:
|
|
||||||
summary['reporting_errors'].append({'code': 'batch_receipt_export_unavailable', 'error': type(error).__name__})
|
|
||||||
if has_run:
|
|
||||||
journal.save_batch_summary(run_id, summary, receipt, revision=summary['revision'])
|
|
||||||
return summary
|
|
||||||
|
|
||||||
|
|
||||||
def recover_batch_receipts(service, root):
|
|
||||||
"""Rebuild absent or stale JSON from recorded evidence, without dispatch."""
|
|
||||||
from ..trial_task_center.batch_supervisor import mutation_lease
|
|
||||||
|
|
||||||
root = Path(root)
|
|
||||||
paths = internal_path(root / 'batch-runs')
|
|
||||||
if not paths.is_dir():
|
|
||||||
return
|
|
||||||
try:
|
|
||||||
with mutation_lease(root):
|
|
||||||
_recover_batch_receipts(service, root, paths)
|
|
||||||
except TaskCenterError as error:
|
|
||||||
if error.code != 'supervisor_busy':
|
|
||||||
raise
|
|
||||||
|
|
||||||
|
|
||||||
def _recover_batch_receipts(service, root, paths):
|
|
||||||
journal = RunJournal(root)
|
|
||||||
for path in paths.glob('*/manifest.json'):
|
|
||||||
run_id = path.parent.name
|
|
||||||
if not re.fullmatch('[0-9a-f]{32}', run_id):
|
|
||||||
continue
|
|
||||||
try:
|
|
||||||
manifest = json.loads(path.read_bytes())
|
|
||||||
run = journal.get(run_id)
|
|
||||||
output = path.with_name('batch-receipt.json')
|
|
||||||
if (not run or manifest['run_id'] != run_id or manifest['runnable_task_ids'] != run['task_ids']
|
|
||||||
or manifest['plan_hashes'] != run['plan_hashes']):
|
|
||||||
continue
|
|
||||||
receipt = run['result'] or {}
|
|
||||||
durable = journal.batch_summary(run_id)
|
|
||||||
running = run['status'] == 'running'
|
|
||||||
if (not running and durable
|
|
||||||
and receipt.get('summary', {}).get('revision') == durable['revision']):
|
|
||||||
refreshed = refresh_batch_resources(root, manifest, durable)
|
|
||||||
if refreshed is not durable:
|
|
||||||
_publish_batch_summary(root, journal, refreshed, receipt, has_run=True)
|
|
||||||
continue
|
|
||||||
try:
|
|
||||||
if json.loads(output.read_bytes()) == durable:
|
|
||||||
continue
|
|
||||||
except (OSError, ValueError):
|
|
||||||
pass
|
|
||||||
batch_resources.write_record(output, durable)
|
|
||||||
continue
|
|
||||||
batch_ids = _bound_supervisors(root, manifest)
|
|
||||||
if running or not receipt:
|
|
||||||
previous_ids = set((durable or {}).get('resource_batch_ids', ())) if running else set()
|
|
||||||
current_ids = [batch_id for batch_id in batch_ids if batch_id not in previous_ids]
|
|
||||||
recovered = _recover_supervised_business(root, manifest, current_ids)
|
|
||||||
if recovered:
|
|
||||||
receipt = recovered
|
|
||||||
elif running:
|
|
||||||
receipt.update(status='interrupted', execution_status='interrupted', code='execution_interrupted')
|
|
||||||
receipt.setdefault('status', 'interrupted')
|
|
||||||
elapsed = receipt.get('elapsed_seconds') or 0
|
|
||||||
summary = collect_batch_summary(service, root, manifest, receipt, elapsed_seconds=elapsed,
|
|
||||||
batch_ids=batch_ids)
|
|
||||||
_publish_batch_summary(root, journal, summary, receipt, has_run=True)
|
|
||||||
except (OSError, ValueError, KeyError, TypeError, RuntimeError) as error:
|
|
||||||
service._logging.logger.warning('batch_receipt_recovery_unavailable run_id=%s error=%s',
|
|
||||||
run_id, type(error).__name__)
|
|
||||||
|
|
||||||
|
|
||||||
def _persist_execution_receipt(service, journal, run_id, receipt, baseline):
|
def _persist_execution_receipt(service, journal, run_id, receipt, baseline):
|
||||||
try:
|
try:
|
||||||
journal.finish(run_id, receipt)
|
journal.finish(run_id, receipt)
|
||||||
@@ -555,7 +239,6 @@ def _execute_incident_retry(service, root, task_id, run_id, *, expected_item, st
|
|||||||
root = Path(root)
|
root = Path(root)
|
||||||
journal = RunJournal(root)
|
journal = RunJournal(root)
|
||||||
original = journal.get(run_id)
|
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
|
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']
|
if original and (task_id not in original['task_ids']
|
||||||
or _plan_hash(child, task_id) != original['plan_hashes'][task_id]):
|
or _plan_hash(child, task_id) != original['plan_hashes'][task_id]):
|
||||||
@@ -572,8 +255,6 @@ def _execute_incident_retry(service, root, task_id, run_id, *, expected_item, st
|
|||||||
raise TaskCenterError('run_scope', '原队列检查点身份或范围已变化;不执行重试。')
|
raise TaskCenterError('run_scope', '原队列检查点身份或范围已变化;不执行重试。')
|
||||||
retry_run = journal.begin_retry(service, run_id, task_id, operation_keys)
|
retry_run = journal.begin_retry(service, run_id, task_id, operation_keys)
|
||||||
baseline = (retry_run.get('result') or {}) if original else {}
|
baseline = (retry_run.get('result') or {}) if original else {}
|
||||||
before_batch = None
|
|
||||||
retry_dispatched = False
|
|
||||||
try:
|
try:
|
||||||
if original:
|
if original:
|
||||||
checkpoint['entries'][task_id].update(state='running', message='仅执行已预约的原失败项重试。')
|
checkpoint['entries'][task_id].update(state='running', message='仅执行已预约的原失败项重试。')
|
||||||
@@ -582,10 +263,7 @@ def _execute_incident_retry(service, root, task_id, run_id, *, expected_item, st
|
|||||||
with NetlistVerification(root, token, stop_event) as checks:
|
with NetlistVerification(root, token, stop_event) as checks:
|
||||||
# Never capture a partially replaced project as a new "before".
|
# Never capture a partially replaced project as a new "before".
|
||||||
checks.before_task(child, task_id, existing_only=True)
|
checks.before_task(child, task_id, existing_only=True)
|
||||||
before_batch = getattr(service, '_last_supervisor_batch_id', None)
|
outcome = service.execute_quick_run_queue(task_id, expected_item=expected_item, stop_event=stop_event)
|
||||||
retry_dispatched = True
|
|
||||||
outcome = service.execute_quick_run_queue(task_id, expected_item=expected_item, stop_event=stop_event,
|
|
||||||
**({'revalidate': revalidate} if revalidate is not None else {}))
|
|
||||||
current = service.task_context(task_id)
|
current = service.task_context(task_id)
|
||||||
p = current.progress
|
p = current.progress
|
||||||
complete = p.queue_complete and not p.failed_items and not current.interrupted and not outcome.paused
|
complete = p.queue_complete and not p.failed_items and not current.interrupted and not outcome.paused
|
||||||
@@ -641,11 +319,7 @@ def _execute_incident_retry(service, root, task_id, run_id, *, expected_item, st
|
|||||||
result = TaskQueueResult(original['queue_id'], tuple(TaskQueueEntry(**entries[key])
|
result = TaskQueueResult(original['queue_id'], tuple(TaskQueueEntry(**entries[key])
|
||||||
for key in original['task_ids']), outcome.paused, netlist_verification=merged)
|
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,
|
receipt = _finish_execution_run(service, root, original['task_ids'], stop_event, run_id, result,
|
||||||
baseline=baseline, resource_report_pending=revalidate is not None)
|
baseline=baseline)
|
||||||
if revalidate is not None:
|
|
||||||
batch_id = getattr(service, '_last_supervisor_batch_id', None)
|
|
||||||
receipt = _republish_incident_batch_summary(service, root, run_id, receipt,
|
|
||||||
batch_id=batch_id if batch_id != before_batch else None)
|
|
||||||
verification.update(run_receipt_updated=True, run_status=receipt['status'])
|
verification.update(run_receipt_updated=True, run_status=receipt['status'])
|
||||||
return outcome, current, verification
|
return outcome, current, verification
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
@@ -664,12 +338,4 @@ def _execute_incident_retry(service, root, task_id, run_id, *, expected_item, st
|
|||||||
failure['reporting_errors'] = [{'code': 'context_unavailable',
|
failure['reporting_errors'] = [{'code': 'context_unavailable',
|
||||||
'error': type(readback_error).__name__}]
|
'error': type(readback_error).__name__}]
|
||||||
journal.finish(run_id, failure)
|
journal.finish(run_id, failure)
|
||||||
if revalidate is not None:
|
|
||||||
batch_id = getattr(service, '_last_supervisor_batch_id', None)
|
|
||||||
try:
|
|
||||||
_republish_incident_batch_summary(service, root, run_id, failure,
|
|
||||||
batch_id=batch_id if retry_dispatched and batch_id != before_batch else None)
|
|
||||||
except Exception as reporting_error:
|
|
||||||
service._logging.logger.error('incident_batch_receipt_unavailable run_id=%s error=%s',
|
|
||||||
run_id, type(reporting_error).__name__)
|
|
||||||
raise
|
raise
|
||||||
@@ -365,12 +365,6 @@ class IncidentRunner:
|
|||||||
# Consume before entering a service mutation. A crash or changed error
|
# Consume before entering a service mutation. A crash or changed error
|
||||||
# code must never buy another replay of the same authorized run.
|
# code must never buy another replay of the same authorized run.
|
||||||
try:
|
try:
|
||||||
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:
|
if reserve_retry is not None:
|
||||||
reserved = reserve_retry(task_id, source='dsh')
|
reserved = reserve_retry(task_id, source='dsh')
|
||||||
if not reserved:
|
if not reserved:
|
||||||
|
|||||||
@@ -60,8 +60,6 @@ class RunJournal:
|
|||||||
db.execute("""CREATE TABLE IF NOT EXISTS run_journal_receipts (
|
db.execute("""CREATE TABLE IF NOT EXISTS run_journal_receipts (
|
||||||
receipt_id INTEGER PRIMARY KEY AUTOINCREMENT, run_id TEXT NOT NULL,
|
receipt_id INTEGER PRIMARY KEY AUTOINCREMENT, run_id TEXT NOT NULL,
|
||||||
finished_utc TEXT NOT NULL, status TEXT NOT NULL, result 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
|
@contextmanager
|
||||||
def _connect(self):
|
def _connect(self):
|
||||||
@@ -130,33 +128,6 @@ class RunJournal:
|
|||||||
db.execute("COMMIT")
|
db.execute("COMMIT")
|
||||||
return current
|
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):
|
def resume(self, run_id):
|
||||||
"""Mark a natively reconfirmed continuation; keep its last durable receipt."""
|
"""Mark a natively reconfirmed continuation; keep its last durable receipt."""
|
||||||
with self._connect() as db:
|
with self._connect() as db:
|
||||||
@@ -173,53 +144,6 @@ class RunJournal:
|
|||||||
|
|
||||||
def begin_retry(self, service, run_id, task_id, operation_keys):
|
def begin_retry(self, service, run_id, task_id, operation_keys):
|
||||||
"""Persist one reserved retry baseline before its first CAD dispatch."""
|
"""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 ())
|
selected = set(operation_keys or ())
|
||||||
child = service.for_project_task(task_id)
|
child = service.for_project_task(task_id)
|
||||||
store = child._store
|
store = child._store
|
||||||
@@ -413,16 +337,25 @@ class RunJournal:
|
|||||||
isolated.update(key for key in queue.get('isolated_tasks', {})
|
isolated.update(key for key in queue.get('isolated_tasks', {})
|
||||||
if key in queue['entries'] and queue['entries'][key]['state'] == 'blocked')
|
if key in queue['entries'] and queue['entries'][key]['state'] == 'blocked')
|
||||||
receipt = row.get('result') or {}
|
receipt = row.get('result') or {}
|
||||||
pause = queue.get('resource_pause')
|
|
||||||
if (receipt.get('paused') is True and receipt.get('user_pause_requested') is False
|
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 any(entry['state'] == 'blocked' and key not in isolated
|
||||||
and receipt.get('resource_batch_id', pause.get('batch_id')) == pause.get('batch_id')):
|
for key, entry in queue['entries'].items())):
|
||||||
from ..trial_task_center.task_queue import resource_pause_admitted
|
from ..trial_task_center.task_queue import resource_pause_admitted
|
||||||
batch_id = pause.get('batch_id')
|
pause = queue.get('resource_pause') or {}
|
||||||
|
known_batch = receipt.get('resource_batch_id') or pause.get('batch_id')
|
||||||
|
candidates = (known_batch,) if known_batch else (
|
||||||
|
path.parent.name for path in (self.data_root / 'batch-resources').glob('*/result.json'))
|
||||||
|
matches = []
|
||||||
|
for batch_id in candidates:
|
||||||
paused = resource_pause_admitted(self.data_root, batch_id,
|
paused = resource_pause_admitted(self.data_root, batch_id,
|
||||||
tuple(row['task_ids']), row['plan_hashes'])
|
tuple(row['task_ids']), row['plan_hashes'])
|
||||||
if paused and paused.queue_id == run_id:
|
if paused and paused.queue_id == run_id:
|
||||||
resource_batch_id = batch_id
|
matches.append((batch_id, paused))
|
||||||
|
if len(matches) > 1:
|
||||||
|
break
|
||||||
|
if len(matches) == 1:
|
||||||
|
resource_batch_id, paused = matches[0]
|
||||||
|
isolated.add(paused.current_task_id)
|
||||||
released_primary.update(isolated)
|
released_primary.update(isolated)
|
||||||
safe_continuations = set()
|
safe_continuations = set()
|
||||||
for task_id in row["task_ids"]:
|
for task_id in row["task_ids"]:
|
||||||
@@ -448,7 +381,7 @@ class RunJournal:
|
|||||||
for key in ("saved_items", "failed_items", "no_match_items"):
|
for key in ("saved_items", "failed_items", "no_match_items"):
|
||||||
counters[key] += item[key]
|
counters[key] += item[key]
|
||||||
counters["total"] += item["total_items"]
|
counters["total"] += item["total_items"]
|
||||||
if context.interrupted:
|
if context.interrupted and task_id not in isolated:
|
||||||
blockers.append("interrupted")
|
blockers.append("interrupted")
|
||||||
if getattr(progress, "failed_items", 0) and task_id not in released_primary | safe_continuations:
|
if getattr(progress, "failed_items", 0) and task_id not in released_primary | safe_continuations:
|
||||||
blockers.append("failed_items")
|
blockers.append("failed_items")
|
||||||
|
|||||||
@@ -1,167 +0,0 @@
|
|||||||
"""Explicit batch scope and per-project admission; strict single-task checks stay intact."""
|
|
||||||
from dataclasses import asdict
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
from pathlib import Path
|
|
||||||
from uuid import uuid4
|
|
||||||
|
|
||||||
from .errors import TaskCenterError
|
|
||||||
from .models import TaskStatus
|
|
||||||
from ..dsh import task_lifecycle
|
|
||||||
|
|
||||||
_digest = task_lifecycle._digest
|
|
||||||
|
|
||||||
POLICY_VERSION = 'issue44-strict-v1'
|
|
||||||
|
|
||||||
|
|
||||||
def resolve_batch_task_ids(tasks, group_id, *, selected_ids=None):
|
|
||||||
records = {task.task_id: task for task in tasks}
|
|
||||||
members = sorted((task for task in records.values() if task.group_id == group_id
|
|
||||||
and task.status is not TaskStatus.DELETED),
|
|
||||||
key=lambda task: (task.group_position, task.task_id))
|
|
||||||
if not group_id or not members:
|
|
||||||
raise TaskCenterError('batch_scope', '请先选择一个有效的工程批次。')
|
|
||||||
if selected_ids is None:
|
|
||||||
return tuple(task.task_id for task in members)
|
|
||||||
selected = tuple(selected_ids)
|
|
||||||
if (not selected or len(set(selected)) != len(selected)
|
|
||||||
or any(key not in records or records[key].group_id != group_id
|
|
||||||
or records[key].status is TaskStatus.DELETED for key in selected)):
|
|
||||||
raise TaskCenterError('batch_scope', '请选择同一批次中不同的有效任务,跨批任务请分批执行。')
|
|
||||||
return tuple(task.task_id for task in members if task.task_id in selected)
|
|
||||||
|
|
||||||
|
|
||||||
def build_batch_admission(service, task_ids, *, scope_kind):
|
|
||||||
if scope_kind not in {'batch', 'selected'} or not task_ids:
|
|
||||||
raise TaskCenterError('batch_scope', '请选择本批或所选工程范围。')
|
|
||||||
records = tuple(service.tasks())
|
|
||||||
owner = next((task for task in records if task.task_id == task_ids[0]), None)
|
|
||||||
if owner is None:
|
|
||||||
raise TaskCenterError('batch_scope', '任务范围已变化,请重新选择并确认。')
|
|
||||||
ids = resolve_batch_task_ids(records, owner.group_id,
|
|
||||||
selected_ids=tuple(task_ids) if scope_kind == 'selected' else None)
|
|
||||||
if ids != tuple(task_ids):
|
|
||||||
raise TaskCenterError('batch_scope', '本批成员或顺序已变化,请重新确认。')
|
|
||||||
from .batch_resources import resource_blockers
|
|
||||||
blockers, decisions, fingerprints, paths, runnable = [], [], [], set(), []
|
|
||||||
try:
|
|
||||||
if resource_blockers(service.pending_batch_resources()):
|
|
||||||
blockers.append('后台资源尚未确认物理释放,请先重试释放资源。')
|
|
||||||
except Exception as error:
|
|
||||||
blockers.append(f'无法确认后台资源状态:{type(error).__name__}')
|
|
||||||
# Selecting another member cannot bypass an uncertain write in this batch.
|
|
||||||
for task in records:
|
|
||||||
if task.group_id == owner.group_id and task.status is not TaskStatus.DELETED:
|
|
||||||
if task.status is TaskStatus.BLOCKED or service.has_interrupted_quick_run(task.task_id):
|
|
||||||
blockers.append(f'{task.name} 的写入结果待核验,请核验后重新确认本批。')
|
|
||||||
for order, task_id in enumerate(ids):
|
|
||||||
task = next(task for task in records if task.task_id == task_id)
|
|
||||||
row = dict(task_id=task_id, name=task.name, order=order, project='',
|
|
||||||
classification='skipped', reason_code='', message='', enabled_scope=0,
|
|
||||||
component_count=None, target_count=None, verification_pending=False)
|
|
||||||
decisions.append(row)
|
|
||||||
try:
|
|
||||||
context = service.task_context(task_id)
|
|
||||||
fingerprints.append(asdict(context))
|
|
||||||
row['project'] = str(context.project.path) if context.project else ''
|
|
||||||
if context.interrupted or task.status is TaskStatus.BLOCKED:
|
|
||||||
row.update(classification='held', reason_code='quick_run_uncertain', message='写入结果待核验,本批暂停。')
|
|
||||||
continue
|
|
||||||
if (task.status is TaskStatus.COMPLETED and context.progress.queue_complete
|
|
||||||
and not context.progress.failed_items):
|
|
||||||
row.update(classification='already_completed', reason_code='already_completed',
|
|
||||||
message='本轮已有完整执行结果,不重复派发。')
|
|
||||||
continue
|
|
||||||
if context.project is None or not context.project.path.is_file():
|
|
||||||
row.update(reason_code='project_missing', message='工程文件不存在或不可访问。')
|
|
||||||
continue
|
|
||||||
path_key = str(context.project.path.resolve()).casefold()
|
|
||||||
if path_key in paths:
|
|
||||||
blockers.append('本批重复包含同一个工程,请核对任务绑定。')
|
|
||||||
row.update(reason_code='project_duplicate', message='工程在本次范围重复。')
|
|
||||||
continue
|
|
||||||
paths.add(path_key)
|
|
||||||
report = task_lifecycle.preflight(service, [task_id])
|
|
||||||
item = report['tasks'][0]
|
|
||||||
count = item['enabled_rules']
|
|
||||||
exact = bool(task.target_plan_mode) and not context.pending_bom
|
|
||||||
row.update(enabled_scope=count, component_count=count if exact else None,
|
|
||||||
target_count=count if exact else None,
|
|
||||||
verification_pending=item['verification_pending'])
|
|
||||||
if item['blockers']:
|
|
||||||
row.update(reason_code='configuration_blocked', message=';'.join(item['blockers']))
|
|
||||||
continue
|
|
||||||
from .project_isolation import write_sources
|
|
||||||
sources = sorted(write_sources(context.project.path, strict=True))
|
|
||||||
row.update(classification='executable', reason_code='ready', message='可执行。', write_sources=sources)
|
|
||||||
runnable.append(task_id)
|
|
||||||
except (FileNotFoundError, PermissionError, NotADirectoryError) as error:
|
|
||||||
row.update(reason_code='project_unavailable', message=f'工程不可访问:{error}')
|
|
||||||
except Exception as error:
|
|
||||||
# Unreadable execution evidence is not an ordinary configuration skip.
|
|
||||||
row.update(classification='held', reason_code=getattr(error, 'code', 'evidence_unavailable'),
|
|
||||||
message=f'无法核对工程或执行证据:{error}')
|
|
||||||
blockers.append(f'{task.name}:{row["message"]}')
|
|
||||||
report = task_lifecycle.preflight(service, runnable) if runnable and not blockers else None
|
|
||||||
if report is not None and not report['ready']:
|
|
||||||
blockers.append('可执行子集的状态已变化,请重新预检。')
|
|
||||||
result = dict(schema_version=1, policy_version=POLICY_VERSION, scope_kind=scope_kind,
|
|
||||||
group_id=owner.group_id, candidate_task_ids=list(ids), decisions=decisions,
|
|
||||||
runnable_task_ids=runnable, plan_hashes=report['plan_hashes'] if report else {},
|
|
||||||
candidate_fingerprint=_digest(fingerprints), global_blockers=list(dict.fromkeys(blockers)),
|
|
||||||
ready=bool(runnable and not blockers and report and report['ready']), execution_report=report)
|
|
||||||
result['manifest_digest'] = _digest(result)
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
def validate_batch_admission(service, admission):
|
|
||||||
current = build_batch_admission(service, tuple(admission['candidate_task_ids']),
|
|
||||||
scope_kind=admission['scope_kind'])
|
|
||||||
if not current['ready'] or current['manifest_digest'] != admission['manifest_digest']:
|
|
||||||
raise TaskCenterError('assistant_stale', '确认后的任务范围、计划或资源状态已变化,请重新预检并确认。')
|
|
||||||
return current['execution_report']
|
|
||||||
|
|
||||||
|
|
||||||
def validate_batch_resume(service, manifest):
|
|
||||||
"""Check immutable scope and engineering sources without comparing mutable progress."""
|
|
||||||
from .project_isolation import write_sources
|
|
||||||
from .task_queue import _plan_hash
|
|
||||||
payload = {key: value for key, value in manifest.items()
|
|
||||||
if key not in {'manifest_digest', 'run_id', 'confirmed_utc'}}
|
|
||||||
if manifest.get('policy_version') != POLICY_VERSION or _digest(payload) != manifest.get('manifest_digest'):
|
|
||||||
raise TaskCenterError('batch_manifest', '原批次的冻结清单无法核验,请保留证据。')
|
|
||||||
records = tuple(service.tasks())
|
|
||||||
selected = tuple(manifest['candidate_task_ids']) if manifest['scope_kind'] == 'selected' else None
|
|
||||||
ids = resolve_batch_task_ids(records, manifest['group_id'], selected_ids=selected)
|
|
||||||
if ids != tuple(manifest['candidate_task_ids']):
|
|
||||||
raise TaskCenterError('assistant_stale', '原批次成员或顺序已变化,请重新确认。')
|
|
||||||
for task in records:
|
|
||||||
if task.group_id == manifest['group_id'] and task.status is not TaskStatus.DELETED:
|
|
||||||
if task.status is TaskStatus.BLOCKED or service.has_interrupted_quick_run(task.task_id):
|
|
||||||
raise TaskCenterError('quick_run_uncertain', '原批次仍有工程写入结果待核验,不能继续或重试。')
|
|
||||||
for row in manifest['decisions']:
|
|
||||||
if row['classification'] != 'executable':
|
|
||||||
continue
|
|
||||||
task_id = row['task_id']
|
|
||||||
child = service.for_project_task(task_id)
|
|
||||||
if _plan_hash(child, task_id) != manifest['plan_hashes'][task_id]:
|
|
||||||
raise TaskCenterError('assistant_stale', '原批次计划已变化,请重新确认。')
|
|
||||||
projects = child.projects(task_id)
|
|
||||||
if (len(projects) != 1 or str(projects[0].path) != row['project']
|
|
||||||
or sorted(write_sources(projects[0].path, strict=True)) != row.get('write_sources')):
|
|
||||||
raise TaskCenterError('assistant_stale', '原批次工程写入源已变化,请重新确认。')
|
|
||||||
|
|
||||||
|
|
||||||
def write_preflight_receipt(root, admission, status, *, reason=''):
|
|
||||||
if status not in {'rejected', 'cancelled'}:
|
|
||||||
raise ValueError('Only zero-dispatch preflight outcomes are accepted')
|
|
||||||
from .batch_resources import write_record
|
|
||||||
token = uuid4().hex
|
|
||||||
folder = Path(root) / 'batch-runs' / token
|
|
||||||
write_record(folder / 'manifest.json', admission)
|
|
||||||
receipt = dict(schema_version=1, run_id=token, queue_id=None, status=status,
|
|
||||||
manifest_digest=admission['manifest_digest'], dispatch_count=0,
|
|
||||||
candidate_task_ids=admission['candidate_task_ids'], decisions=admission['decisions'],
|
|
||||||
global_blockers=admission['global_blockers'], message=reason,
|
|
||||||
finished_utc=datetime.now(timezone.utc).isoformat())
|
|
||||||
write_record(folder / 'batch-receipt.json', receipt)
|
|
||||||
return folder / 'batch-receipt.json'
|
|
||||||
@@ -103,8 +103,9 @@ def pending_resources(root):
|
|||||||
if not _valid_record(record, path):
|
if not _valid_record(record, path):
|
||||||
raise ValueError('invalid resource ownership record')
|
raise ValueError('invalid resource ownership record')
|
||||||
if record.get('state') != 'released' or not _released_evidence(record):
|
if record.get('state') != 'released' or not _released_evidence(record):
|
||||||
pending.append(dict(record, record_path=str(path), blocking=True))
|
pending.append(dict(record, record_path=str(path),
|
||||||
except (OSError, ValueError, TypeError, KeyError, AttributeError) as error:
|
blocking=not (record.get('state') == 'isolated' and _isolation_evidence(record))))
|
||||||
|
except (OSError, ValueError, TypeError) as error:
|
||||||
pending.append({'state': 'blocked', 'record_path': str(path), 'error': str(error)})
|
pending.append({'state': 'blocked', 'record_path': str(path), 'error': str(error)})
|
||||||
import sys
|
import sys
|
||||||
sessions = getattr(sys.modules.get(__package__ + '.isolated_cad'), 'RETAINED_CAD_SESSIONS', {})
|
sessions = getattr(sys.modules.get(__package__ + '.isolated_cad'), 'RETAINED_CAD_SESSIONS', {})
|
||||||
@@ -140,8 +141,9 @@ def pending_resources(root):
|
|||||||
|
|
||||||
|
|
||||||
def resource_blockers(records):
|
def resource_blockers(records):
|
||||||
"""Pending resources block until physical release is proven."""
|
"""Only a validated isolated desktop warning may leave the resource gate open."""
|
||||||
return tuple(records)
|
return tuple(item for item in records
|
||||||
|
if not (item.get('state') == 'isolated' and item.get('blocking') is False))
|
||||||
|
|
||||||
|
|
||||||
def blocking_resources(root):
|
def blocking_resources(root):
|
||||||
@@ -221,13 +223,8 @@ def _released_evidence(record):
|
|||||||
and (cleanup.get('desktop_confirmation') or {}).get('released') is True)
|
and (cleanup.get('desktop_confirmation') or {}).get('released') is True)
|
||||||
|
|
||||||
|
|
||||||
def guard_pending_resources(root, *, owner=None):
|
def guard_pending_resources(root):
|
||||||
pending = blocking_resources(root)
|
if 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('上一批资源尚未确认释放;请先重试释放资源,再开始新批次。')
|
raise BatchResourceCleanupError('上一批资源尚未确认释放;请先重试释放资源,再开始新批次。')
|
||||||
|
|
||||||
|
|
||||||
@@ -240,41 +237,25 @@ def process_identity(process):
|
|||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
def observe_process_identity(identity):
|
def _process_gone(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 win32api
|
||||||
import win32event
|
import win32event
|
||||||
import win32process
|
import win32process
|
||||||
try:
|
try:
|
||||||
handle = win32api.OpenProcess(0x101000, False, pid) # SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION
|
handle = win32api.OpenProcess(0x101000, False, identity['pid'])
|
||||||
except (OSError, win32api.error) as error:
|
except Exception as error:
|
||||||
code = getattr(error, 'winerror', error.args[0] if error.args and type(error.args[0]) is int else None)
|
code = getattr(error, 'winerror', error.args[0] if error.args else None)
|
||||||
return {'state': 'gone' if code == 87 else 'unknown', 'error': str(error), 'error_code': code}
|
if code == 87:
|
||||||
|
return True
|
||||||
|
raise
|
||||||
try:
|
try:
|
||||||
try:
|
if win32event.WaitForSingleObject(handle, 0) == 0:
|
||||||
actual = win32process.GetProcessTimes(handle).get('CreationTime')
|
return True
|
||||||
if actual is None:
|
created = identity.get('creation_time')
|
||||||
return {'state': 'unknown', 'error': 'Unable to read process creation time', 'error_code': None}
|
# A reused PID is an unrelated process and must never be terminated.
|
||||||
# A reused PID belongs to a different process.
|
return created is not None and str(win32process.GetProcessTimes(handle)['CreationTime']) != created
|
||||||
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:
|
finally:
|
||||||
handle.Close()
|
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):
|
def _historical_writer_trees_closed(record, path):
|
||||||
@@ -385,7 +366,7 @@ def cleanup_pending_resources(root, *, logging_context=None, retry_failed=False)
|
|||||||
absent = _observe_release(lambda: managed_desktop_disappeared(receipt), record)
|
absent = _observe_release(lambda: managed_desktop_disappeared(receipt), record)
|
||||||
if not absent:
|
if not absent:
|
||||||
record.pop('record_path', None)
|
record.pop('record_path', None)
|
||||||
record.update(state='isolated', blocking=True, isolation_proof=proof)
|
record.update(state='isolated', blocking=False, isolation_proof=proof)
|
||||||
write_record(path, record)
|
write_record(path, record)
|
||||||
log('isolated')
|
log('isolated')
|
||||||
continue
|
continue
|
||||||
@@ -404,11 +385,12 @@ def cleanup_pending_resources(root, *, logging_context=None, retry_failed=False)
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
if not _observe_release(observe, record):
|
if not _observe_release(observe, record):
|
||||||
# Keep the closed writer proof while the desktop still blocks admission.
|
# A residual desktop name is only a warning after owned
|
||||||
|
# handle closure and independently revalidated writer exit.
|
||||||
proof = isolation_proof(record)
|
proof = isolation_proof(record)
|
||||||
record.pop('record_path', None)
|
record.pop('record_path', None)
|
||||||
warning = '桌面仍在或同名桌面正在使用,未取得桌面消失证明'
|
warning = '桌面仍在或同名桌面正在使用,未取得桌面消失证明'
|
||||||
record.update(state='isolated', blocking=True, isolation_proof=proof,
|
record.update(state='isolated', blocking=False, isolation_proof=proof,
|
||||||
isolation_warning=warning)
|
isolation_warning=warning)
|
||||||
write_record(path, record)
|
write_record(path, record)
|
||||||
log('isolated', warning)
|
log('isolated', warning)
|
||||||
|
|||||||
@@ -203,14 +203,12 @@ class BatchCadRuntime:
|
|||||||
'generation': self.generation, **details})
|
'generation': self.generation, **details})
|
||||||
|
|
||||||
def _ensure_desktop(self, abort_event=None):
|
def _ensure_desktop(self, abort_event=None):
|
||||||
if self.record['state'] in {'blocked', 'isolated'}:
|
if self.record['state'] == 'blocked':
|
||||||
raise BatchResourceCleanupError('当前批次资源已阻断,不能启动新的工作进程。')
|
raise BatchResourceCleanupError('当前批次资源已阻断,不能启动新的工作进程。')
|
||||||
|
if self.record['state'] == 'isolated':
|
||||||
if self.desktop is not None:
|
if self.desktop is not None:
|
||||||
slot = getattr(self.desktop, '_slot', None)
|
raise BatchResourceCleanupError('隔离桌面已停止使用,请为后续工程创建新的运行会话。')
|
||||||
if (getattr(self.desktop, '_handle', True) is None
|
write_record(self.path.parent / f'isolated-generation-{self.generation}.json', self.record)
|
||||||
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:
|
if self.desktop is None:
|
||||||
check_cancelled(self.stop_event if abort_event is None else abort_event)
|
check_cancelled(self.stop_event if abort_event is None else abort_event)
|
||||||
generation = self.generation + 1
|
generation = self.generation + 1
|
||||||
@@ -360,8 +358,7 @@ class BatchCadRuntime:
|
|||||||
value = json.loads(path.read_text(encoding='utf-8'))
|
value = json.loads(path.read_text(encoding='utf-8'))
|
||||||
if not isinstance(value, dict):
|
if not isinstance(value, dict):
|
||||||
return None
|
return None
|
||||||
return {key: value.get(key) for key in ('job_id', 'stage', 'done', 'total', 'safe_stop',
|
return {key: value.get(key) for key in ('job_id', 'stage', 'done', 'total', 'safe_stop')}
|
||||||
'stop_requested', 'stopping_reason', 'idle_timeout_seconds', 'failure_completion_grace_seconds')}
|
|
||||||
except (OSError, ValueError, TypeError):
|
except (OSError, ValueError, TypeError):
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@@ -574,7 +571,7 @@ class BatchCadRuntime:
|
|||||||
from .isolated_cad import PrivateCadStartupError, is_identity_conflict
|
from .isolated_cad import PrivateCadStartupError, is_identity_conflict
|
||||||
from .worker_monitor import run_monitored_process
|
from .worker_monitor import run_monitored_process
|
||||||
cooperative_abort = cooperative_abort or self.read_only
|
cooperative_abort = cooperative_abort or self.read_only
|
||||||
if abort_event is None:
|
if self.read_only and abort_event is None:
|
||||||
abort_event = self.stop_event
|
abort_event = self.stop_event
|
||||||
root = canonical_path(command[3])
|
root = canonical_path(command[3])
|
||||||
if self.cad is not None and self.record.get('active_project'):
|
if self.cad is not None and self.record.get('active_project'):
|
||||||
@@ -1137,7 +1134,7 @@ class BatchCadRuntime:
|
|||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
phases['desktop'] = 'isolated'
|
phases['desktop'] = 'isolated'
|
||||||
self._save(state='isolated', blocking=True, isolation_proof=proof,
|
self._save(state='isolated', blocking=False, isolation_proof=proof,
|
||||||
isolation_warning='; '.join(errors), release_state=phases, wait_reason='')
|
isolation_warning='; '.join(errors), release_state=phases, wait_reason='')
|
||||||
LIVE_RESOURCES.pop(str(self.path), None)
|
LIVE_RESOURCES.pop(str(self.path), None)
|
||||||
if shutdown_errors:
|
if shutdown_errors:
|
||||||
@@ -1192,7 +1189,7 @@ class BatchCadRuntime:
|
|||||||
self.close(reason='project_failure')
|
self.close(reason='project_failure')
|
||||||
except BatchResourceCleanupError as cleanup:
|
except BatchResourceCleanupError as cleanup:
|
||||||
from .batch_resources import blocking_resources
|
from .batch_resources import blocking_resources
|
||||||
if (self.record['state'] != 'released' or blocking_resources(self.root)
|
if (self.record['state'] not in {'released', 'isolated'} or blocking_resources(self.root)
|
||||||
or not self.owned_processes_exited() or not self._other_writers_exited()):
|
or not self.owned_processes_exited() or not self._other_writers_exited()):
|
||||||
raise
|
raise
|
||||||
cleanup_warning = str(cleanup)
|
cleanup_warning = str(cleanup)
|
||||||
|
|||||||
@@ -1,347 +0,0 @@
|
|||||||
"""Project a frozen batch scope from its current queue and operation evidence."""
|
|
||||||
from collections import Counter
|
|
||||||
from hashlib import sha256
|
|
||||||
import json
|
|
||||||
from pathlib import Path
|
|
||||||
import sqlite3
|
|
||||||
|
|
||||||
from . import batch_resources
|
|
||||||
from .execution_journal import ExecutionJournal, _targets
|
|
||||||
from .path_access import internal_path
|
|
||||||
|
|
||||||
|
|
||||||
_TASK_STATES = ('completed', 'failed', 'blocked', 'skipped', 'already_completed',
|
|
||||||
'pending', 'paused', 'running')
|
|
||||||
_OPERATION_STATES = ('pending', 'prepared', 'running', 'pending_save', 'verified',
|
|
||||||
'no_match', 'failed', 'uncertain', 'restored', 'unknown')
|
|
||||||
|
|
||||||
|
|
||||||
def summarize_batch(manifest, queue, operation_rows, resource_snapshot, *, elapsed_seconds):
|
|
||||||
"""Count engineering entries, jobs and distinct current-round targets."""
|
|
||||||
decisions = {row['task_id']: row for row in manifest['decisions']}
|
|
||||||
entries = {}
|
|
||||||
for task_id in manifest['candidate_task_ids']:
|
|
||||||
decision = decisions[task_id]
|
|
||||||
classification = decision['classification']
|
|
||||||
if classification == 'executable':
|
|
||||||
entry = queue.get('entries', {}).get(task_id, {})
|
|
||||||
state = entry.get('state', 'pending')
|
|
||||||
if state not in _TASK_STATES or state == 'already_completed':
|
|
||||||
state = 'blocked'
|
|
||||||
message = entry.get('message', '')
|
|
||||||
else:
|
|
||||||
state = 'blocked' if classification == 'held' else classification
|
|
||||||
message = decision.get('message') or decision.get('reason') or ''
|
|
||||||
entries[task_id] = {**decision, 'state': state, 'message': message}
|
|
||||||
task_counts = dict.fromkeys(_TASK_STATES, 0)
|
|
||||||
for entry in entries.values():
|
|
||||||
task_counts[entry['state']] += 1
|
|
||||||
|
|
||||||
operation_scope = {key for key, entry in entries.items() if entry['state'] != 'skipped'}
|
|
||||||
effective = {}
|
|
||||||
for row in operation_rows:
|
|
||||||
if (row['task_id'] not in operation_scope or not row.get('current_round', True)
|
|
||||||
or row.get('superseded') or row['state'] == 'superseded'):
|
|
||||||
continue
|
|
||||||
key = (row['task_id'], row['round_id'], row['operation_key'])
|
|
||||||
previous = effective.get(key)
|
|
||||||
if previous is None or row['generation'] >= previous['generation']:
|
|
||||||
effective[key] = row
|
|
||||||
|
|
||||||
job_counts = Counter()
|
|
||||||
unknown_targets = set(queue.get('operation_evidence_missing', ())) & operation_scope
|
|
||||||
targets = {}
|
|
||||||
unsafe = {row['task_id'] for row in effective.values()
|
|
||||||
if row['state'] in {'pending', 'prepared', 'running', 'pending_save', 'uncertain'}}
|
|
||||||
batch_retry_blocked = (bool(task_counts['blocked'] or queue.get('operation_evidence_missing')
|
|
||||||
or manifest.get('global_blockers'))
|
|
||||||
or any(row['state'] in {'prepared', 'running', 'pending_save', 'uncertain', 'unknown'}
|
|
||||||
for row in effective.values()))
|
|
||||||
for row in effective.values():
|
|
||||||
state = row['state'] if row['state'] in _OPERATION_STATES else 'unknown'
|
|
||||||
job_counts[state] += 1
|
|
||||||
if row.get('target_keys') is None:
|
|
||||||
unknown_targets.add(row['task_id'])
|
|
||||||
continue
|
|
||||||
for target in row['target_keys']:
|
|
||||||
key = (row['task_id'], row['round_id'], target)
|
|
||||||
# A verified commit survives a later failed attempt or reporting error.
|
|
||||||
precedence = (state == 'verified', row['generation'])
|
|
||||||
if key not in targets or precedence >= targets[key][0]:
|
|
||||||
targets[key] = (precedence, state)
|
|
||||||
|
|
||||||
counts = Counter(state for _, state in targets.values())
|
|
||||||
targets_by_task = Counter(key[0] for key in targets)
|
|
||||||
jobs_by_task = Counter(row['task_id'] for row in effective.values())
|
|
||||||
for task_id in operation_scope:
|
|
||||||
planned = decisions[task_id].get('target_count')
|
|
||||||
known = targets_by_task[task_id]
|
|
||||||
if type(planned) is int and planned >= known:
|
|
||||||
counts['pending'] += planned - known
|
|
||||||
elif not jobs_by_task[task_id]:
|
|
||||||
unknown_targets.add(task_id)
|
|
||||||
operation_counts = {state: counts[state] for state in _OPERATION_STATES}
|
|
||||||
operation_counts['saved'] = operation_counts['verified']
|
|
||||||
failures = [{**{key: row[key] for key in ('task_id', 'round_id', 'operation_key', 'generation', 'state')},
|
|
||||||
'code': row['code'], 'message': row.get('message') or ''}
|
|
||||||
for row in effective.values()
|
|
||||||
if row['state'] in {'failed', 'uncertain', 'pending_save', 'prepared'} and row.get('code')]
|
|
||||||
|
|
||||||
retry = [
|
|
||||||
{key: row[key] for key in ('task_id', 'round_id', 'operation_key', 'generation')}
|
|
||||||
for row in effective.values()
|
|
||||||
if not batch_retry_blocked and row['state'] == 'failed' and row.get('can_retry') and row['task_id'] not in unsafe
|
|
||||||
and row.get('target_keys')
|
|
||||||
and all(targets[(row['task_id'], row['round_id'], target)][1] == 'failed'
|
|
||||||
for target in row['target_keys'])
|
|
||||||
]
|
|
||||||
if task_counts['blocked'] or any(job_counts[state] for state in ('prepared', 'pending_save', 'uncertain')):
|
|
||||||
execution_status = 'blocked'
|
|
||||||
elif task_counts['paused'] or queue.get('paused'):
|
|
||||||
execution_status = 'paused'
|
|
||||||
elif task_counts['running']:
|
|
||||||
execution_status = 'running'
|
|
||||||
elif task_counts['pending']:
|
|
||||||
execution_status = 'pending'
|
|
||||||
elif task_counts['failed']:
|
|
||||||
execution_status = 'failed'
|
|
||||||
else:
|
|
||||||
execution_status = 'completed'
|
|
||||||
execution_status = queue.get('execution_status') or execution_status
|
|
||||||
if execution_status == 'completed' and any(job_counts[state] for state in ('prepared', 'pending_save', 'uncertain')):
|
|
||||||
execution_status = 'blocked'
|
|
||||||
resource_state = resource_snapshot.get('state')
|
|
||||||
if resource_state not in {'released', 'pending', 'isolated'}:
|
|
||||||
resource_state = 'unknown'
|
|
||||||
acceptance = queue.get('acceptance') or {'status': 'not_required'}
|
|
||||||
status = execution_status
|
|
||||||
if execution_status == 'completed':
|
|
||||||
if acceptance['status'] not in {'verified', 'not_required'}:
|
|
||||||
status = 'failed'
|
|
||||||
elif resource_state != 'released' or queue.get('snapshot_unstable') or queue.get('operation_evidence_missing'):
|
|
||||||
status = 'paused'
|
|
||||||
return {'status': status, 'execution_status': execution_status,
|
|
||||||
'resource_state': resource_state, 'resource': resource_snapshot,
|
|
||||||
'acceptance_status': acceptance['status'], 'acceptance': acceptance,
|
|
||||||
'candidate_count': len(entries), 'entries': list(entries.values()), 'task_counts': task_counts,
|
|
||||||
'operation_job_count': len(effective), 'operation_job_counts': dict(job_counts),
|
|
||||||
'operation_total': None if unknown_targets else sum(counts.values()),
|
|
||||||
'operation_counts': operation_counts, 'operation_evidence_missing': sorted(unknown_targets),
|
|
||||||
'failure_code_counts': dict(Counter(row['code'] for row in failures)),
|
|
||||||
'operation_failures': failures,
|
|
||||||
'retry_selection': retry, 'elapsed_seconds': elapsed_seconds}
|
|
||||||
|
|
||||||
|
|
||||||
def _digest(value):
|
|
||||||
return sha256(json.dumps(value, ensure_ascii=False, sort_keys=True).encode('utf-8')).hexdigest()
|
|
||||||
|
|
||||||
|
|
||||||
def _operation_sources(service, task_ids):
|
|
||||||
rows, versions, missing = [], {}, []
|
|
||||||
for task_id in task_ids:
|
|
||||||
try:
|
|
||||||
store = service.for_project_task(task_id)._store
|
|
||||||
with store._lock:
|
|
||||||
round_row = store._connection.execute(
|
|
||||||
'SELECT * FROM execution_rounds WHERE task_id=?', (task_id,)).fetchone()
|
|
||||||
if not round_row:
|
|
||||||
versions[task_id] = {'round_id': None}
|
|
||||||
continue
|
|
||||||
round_id = round_row['round_id']
|
|
||||||
raw_rows = [dict(row) for row in store._connection.execute('''SELECT o.*,
|
|
||||||
p.classification, p.auto_retries, p.state AS problem_state, p.code, p.message
|
|
||||||
FROM execution_operations o LEFT JOIN execution_problems p
|
|
||||||
ON p.task_id=o.task_id AND p.round_id=o.round_id AND p.operation_key=o.operation_key
|
|
||||||
WHERE o.task_id=? AND o.round_id=? ORDER BY o.operation_key''', (task_id, round_id))]
|
|
||||||
commits = [dict(row) for row in store._connection.execute('''SELECT * FROM execution_project_commits
|
|
||||||
WHERE task_id=? AND round_id=? ORDER BY session_token''', (task_id, round_id))]
|
|
||||||
task_rows = []
|
|
||||||
for row in raw_rows:
|
|
||||||
command = json.loads(row['command_json'])
|
|
||||||
if command.get('target_scope') == 'targets':
|
|
||||||
target_keys = _targets(command)
|
|
||||||
elif command.get('execution_unit') == 'inventory_empty':
|
|
||||||
target_keys = ()
|
|
||||||
else:
|
|
||||||
target_keys = None
|
|
||||||
can_retry = (row['state'] == 'failed' and row['classification'] == 'retryable' and row['problem_state'] == 'open'
|
|
||||||
and not row['auto_retries'] and command.get('execution_unit') == 'component'
|
|
||||||
and not any(commit['state'] in {'verified', 'pending_save'} for commit in commits))
|
|
||||||
if can_retry:
|
|
||||||
receipt = json.loads(row['receipt_json'] or '{}')
|
|
||||||
can_retry = ExecutionJournal(store).failure_certified(task_id,
|
|
||||||
dict(command, task_id=task_id, job_id=receipt.get('job_id')))
|
|
||||||
task_rows.append({**row, 'target_keys': target_keys, 'can_retry': can_retry})
|
|
||||||
rows.extend(task_rows)
|
|
||||||
versions[task_id] = {'round_id': round_id, 'digest': _digest([dict(round_row), task_rows, commits])}
|
|
||||||
except (LookupError, TypeError, ValueError, OSError, RuntimeError, sqlite3.Error):
|
|
||||||
versions[task_id] = {'state': 'unknown'}
|
|
||||||
missing.append(task_id)
|
|
||||||
return rows, versions, missing
|
|
||||||
|
|
||||||
|
|
||||||
def _checkpoint_source(root, manifest):
|
|
||||||
queue_id = manifest['run_id']
|
|
||||||
names = [Path(folder) / f'{queue_id}.json' for folder in ('task-queues', 'workspace-queues')]
|
|
||||||
paths = [name for name in names if internal_path(root / name).is_file()]
|
|
||||||
if len(paths) != 1:
|
|
||||||
return {}, None, None, 'checkpoint_unavailable' if paths else None
|
|
||||||
try:
|
|
||||||
raw = internal_path(root / paths[0]).read_bytes()
|
|
||||||
value = json.loads(raw)
|
|
||||||
scope = manifest['runnable_task_ids']
|
|
||||||
if (value['task_ids'] != scope or value['plan_hashes'] != manifest['plan_hashes']
|
|
||||||
or set(value['entries']) != set(scope)):
|
|
||||||
raise ValueError('checkpoint scope changed')
|
|
||||||
return value, sha256(raw).hexdigest(), paths[0].as_posix(), None
|
|
||||||
except (OSError, ValueError, KeyError, TypeError):
|
|
||||||
return {}, None, None, 'checkpoint_unavailable'
|
|
||||||
|
|
||||||
|
|
||||||
def _resource_source(root, batch_ids, *, scope, no_dispatch):
|
|
||||||
from .batch_supervisor import pending_supervisors
|
|
||||||
from .supervisor_protocol import valid_journal
|
|
||||||
|
|
||||||
references, generations, states = [], [], []
|
|
||||||
try:
|
|
||||||
related = batch_resources.pending_resources(root)
|
|
||||||
if not batch_ids:
|
|
||||||
states.extend('unknown' if record.get('error') else
|
|
||||||
'isolated' if record.get('state') == 'isolated' else 'pending' for record in related)
|
|
||||||
for batch_id in batch_ids:
|
|
||||||
directory = Path('batch-resources') / batch_id
|
|
||||||
for name in ('session.json', 'supervisor.json', 'result.json', 'request.json'):
|
|
||||||
path = directory / name
|
|
||||||
if internal_path(root / path).is_file():
|
|
||||||
references.append(path.as_posix())
|
|
||||||
record_path = internal_path(root / directory / 'session.json')
|
|
||||||
supervisor_path = internal_path(root / directory / 'supervisor.json')
|
|
||||||
try:
|
|
||||||
record = json.loads(record_path.read_bytes())
|
|
||||||
supervisor = json.loads(supervisor_path.read_bytes())
|
|
||||||
if (not batch_resources._valid_record(record, record_path)
|
|
||||||
or not valid_journal(supervisor, batch_id)):
|
|
||||||
raise ValueError('resource record scope changed')
|
|
||||||
tasks = supervisor['task_ids']
|
|
||||||
if not ((supervisor['operation'] == 'execute_task_queue' and tasks == scope)
|
|
||||||
or (supervisor['operation'] == 'execute_quick_run_queue'
|
|
||||||
and len(tasks) == 1 and tasks[0] in scope)):
|
|
||||||
raise ValueError('resource record scope changed')
|
|
||||||
matching = [item for item in related if item.get('session_id') == batch_id
|
|
||||||
or f'/{batch_id}/' in item.get('record_path', '').replace('\\', '/')]
|
|
||||||
states.extend('unknown' if item.get('error') else
|
|
||||||
'isolated' if item.get('state') == 'isolated' else 'pending' for item in matching)
|
|
||||||
for item in matching:
|
|
||||||
name = Path(item['record_path']).name
|
|
||||||
if name.startswith('isolated-generation-'):
|
|
||||||
references.append((directory / name).as_posix())
|
|
||||||
generations.extend({'session_id': batch_id, 'generation': release['generation'],
|
|
||||||
'state': 'released', 'reason': release.get('reason')}
|
|
||||||
for release in record.get('generation_releases', ())
|
|
||||||
if release['generation'] != record['generation'])
|
|
||||||
declared = record['state']
|
|
||||||
if not matching:
|
|
||||||
if declared == 'released' and batch_resources._released_evidence(record):
|
|
||||||
states.append('released')
|
|
||||||
else:
|
|
||||||
states.append('unknown')
|
|
||||||
generations.append({'session_id': batch_id, 'generation': record['generation'],
|
|
||||||
'state': declared, 'supervisor_status': supervisor.get('outcome'),
|
|
||||||
'stopping_reason': supervisor.get('stopping_reason') or record.get('stopping_reason'),
|
|
||||||
'stop_requested_at': supervisor.get('stop_requested_at'),
|
|
||||||
'business_idle_timeout_seconds': supervisor.get('business_idle_timeout_seconds'),
|
|
||||||
'worker_idle_timeout_seconds': supervisor.get('worker_idle_timeout_seconds'),
|
|
||||||
'worker_failure_completion_grace_seconds': supervisor.get('worker_failure_completion_grace_seconds'),
|
|
||||||
'record_digest': _digest(record),
|
|
||||||
'supervisor_digest': _digest(supervisor)})
|
|
||||||
except (OSError, ValueError, TypeError, KeyError, AttributeError):
|
|
||||||
states.append('unknown')
|
|
||||||
for item in pending_supervisors(root):
|
|
||||||
if not batch_ids or item.get('batch_id') in batch_ids:
|
|
||||||
states.append('unknown' if item.get('error') else 'pending')
|
|
||||||
except (OSError, ValueError, TypeError, KeyError, RuntimeError):
|
|
||||||
states.append('unknown')
|
|
||||||
state = next((state for state in ('unknown', 'isolated', 'pending') if state in states),
|
|
||||||
'released' if states or no_dispatch else 'unknown')
|
|
||||||
return {'state': state, 'generations': generations, 'evidence': references}
|
|
||||||
|
|
||||||
|
|
||||||
def collect_batch_summary(service, root, manifest, receipt, *, batch_ids, elapsed_seconds, no_dispatch=False):
|
|
||||||
"""Read versioned sources twice and retry once when writes overlap the read."""
|
|
||||||
from .netlist_verification import verification_summary
|
|
||||||
|
|
||||||
decisions = manifest['decisions']
|
|
||||||
task_ids = [row['task_id'] for row in decisions if row['classification'] != 'skipped']
|
|
||||||
|
|
||||||
def sources():
|
|
||||||
rows, rounds, missing = _operation_sources(service, task_ids)
|
|
||||||
checkpoint, checkpoint_digest, path, error = _checkpoint_source(root, manifest)
|
|
||||||
resource = _resource_source(root, batch_ids, scope=manifest['runnable_task_ids'], no_dispatch=no_dispatch)
|
|
||||||
return rows, missing, checkpoint, resource, path, error, {
|
|
||||||
'rounds': rounds, 'checkpoint_digest': checkpoint_digest, 'resource_digest': _digest(resource)}
|
|
||||||
|
|
||||||
first = sources()
|
|
||||||
current = sources()
|
|
||||||
if first[6] != current[6]:
|
|
||||||
first, current = current, sources()
|
|
||||||
unstable = first[6] != current[6]
|
|
||||||
rows, missing, checkpoint, resource, path, error, versions = current
|
|
||||||
if unstable:
|
|
||||||
rows, missing, resource = [], task_ids, {**resource, 'state': 'unknown'}
|
|
||||||
entries = {row['task_id']: row for row in receipt.get('entries', [])}
|
|
||||||
entries.update(checkpoint.get('entries', {}))
|
|
||||||
execution_status = receipt.get('execution_status') or receipt.get('status')
|
|
||||||
netlist = receipt.get('netlist_verification') or checkpoint.get('netlist_verification') or {}
|
|
||||||
required = {row['task_id'] for row in receipt.get('tasks', ()) if row.get('saved_items')}
|
|
||||||
required.update(row['task_id'] for row in rows if row['state'] == 'verified'
|
|
||||||
and row['task_id'] in manifest['runnable_task_ids'])
|
|
||||||
acceptance = verification_summary(netlist, required_task_ids=required)
|
|
||||||
summary = summarize_batch(manifest, {'entries': entries, 'paused': receipt.get('paused'),
|
|
||||||
'acceptance': acceptance, 'execution_status': execution_status, 'snapshot_unstable': unstable,
|
|
||||||
'operation_evidence_missing': missing}, rows, resource, elapsed_seconds=elapsed_seconds)
|
|
||||||
reporting_errors = list(receipt.get('reporting_errors', ()))
|
|
||||||
if error or unstable:
|
|
||||||
reporting_errors.append({'code': 'batch_snapshot_unstable' if unstable else error})
|
|
||||||
stop_reason = receipt.get('code') or receipt.get('stop_reason')
|
|
||||||
if stop_reason == 'batch_resources_pending' and summary['execution_status'] in {'completed', 'failed'}:
|
|
||||||
stop_reason = 'resource_pending' if summary['resource_state'] != 'released' else None
|
|
||||||
if not stop_reason and receipt.get('user_pause_requested'):
|
|
||||||
stop_reason = 'user_pause'
|
|
||||||
if not stop_reason and summary['status'] in {'paused', 'blocked'}:
|
|
||||||
stopping = [row for row in resource['generations'] if row.get('stopping_reason')]
|
|
||||||
if stopping:
|
|
||||||
stop_reason = max(stopping, key=lambda row: row.get('stop_requested_at') or 0)['stopping_reason']
|
|
||||||
if not stop_reason and summary['status'] in {'paused', 'blocked'}:
|
|
||||||
stop_reason = ('save_unverified' if summary['operation_job_counts'].get('pending_save')
|
|
||||||
or summary['operation_job_counts'].get('uncertain')
|
|
||||||
or summary['operation_job_counts'].get('prepared') else
|
|
||||||
'resource_pending' if summary['resource_state'] != 'released' else 'queue_paused')
|
|
||||||
return {**summary, 'schema_version': 1, 'manifest_digest': manifest['manifest_digest'],
|
|
||||||
'run_id': manifest['run_id'], 'queue_id': receipt.get('queue_id') or manifest['run_id'],
|
|
||||||
'stop_reason': stop_reason,
|
|
||||||
'resource_batch_ids': list(batch_ids), 'reporting_errors': reporting_errors,
|
|
||||||
'netlist_verification': netlist, 'source_versions': versions,
|
|
||||||
'evidence': {'queue_checkpoint': path, 'resource_records': resource['evidence'],
|
|
||||||
'manifest': f"batch-runs/{manifest['run_id']}/manifest.json"}}
|
|
||||||
|
|
||||||
|
|
||||||
def refresh_batch_resources(root, manifest, summary):
|
|
||||||
"""Reconcile resource closure while keeping the durable business snapshot."""
|
|
||||||
batch_ids = summary['resource_batch_ids']
|
|
||||||
if summary['resource_state'] == 'released' or not batch_ids:
|
|
||||||
return summary
|
|
||||||
resource = _resource_source(root, batch_ids, scope=manifest['runnable_task_ids'], no_dispatch=False)
|
|
||||||
if resource['state'] != 'released':
|
|
||||||
return summary
|
|
||||||
status = summary['status']
|
|
||||||
stop_reason = summary['stop_reason']
|
|
||||||
source_unavailable = (any(row.get('state') == 'unknown' for row in summary['source_versions']['rounds'].values())
|
|
||||||
or any(row.get('code') == 'batch_snapshot_unstable' for row in summary['reporting_errors']))
|
|
||||||
if (summary['execution_status'] == 'completed' and summary['acceptance_status'] in {'verified', 'not_required'}
|
|
||||||
and stop_reason == 'resource_pending' and not source_unavailable):
|
|
||||||
status = 'completed'
|
|
||||||
if stop_reason == 'resource_pending':
|
|
||||||
stop_reason = None
|
|
||||||
return {**summary, 'status': status, 'stop_reason': stop_reason, 'resource_state': 'released', 'resource': resource,
|
|
||||||
'source_versions': {**summary['source_versions'], 'resource_digest': _digest(resource)},
|
|
||||||
'evidence': {**summary['evidence'], 'resource_records': resource['evidence']}}
|
|
||||||
@@ -31,25 +31,12 @@ class BusinessProgressWatch:
|
|||||||
self.last_progress = started
|
self.last_progress = started
|
||||||
self.idle_timeout = idle_timeout
|
self.idle_timeout = idle_timeout
|
||||||
self.signatures = {}
|
self.signatures = {}
|
||||||
self.stage_progress = {}
|
|
||||||
self.worker_stop_requested = False
|
|
||||||
self.stop_requested = False
|
|
||||||
|
|
||||||
def observe(self, kind, payload, now):
|
def observe(self, kind, payload, now):
|
||||||
if kind == 'heartbeat':
|
if kind == 'heartbeat':
|
||||||
return
|
return
|
||||||
if kind == 'state':
|
if kind == 'state':
|
||||||
progress = payload.get('business_progress') or {}
|
payload = {key: payload.get(key) for key in ('phase', 'queue', 'batch', 'business_progress', 'active_project')}
|
||||||
self.worker_stop_requested = bool(progress.get('stop_requested') or payload.get('stopping_reason'))
|
|
||||||
payload = {key: payload.get(key) for key in ('phase', 'queue', 'active_project')}
|
|
||||||
payload['business_progress'] = {key: progress.get(key) for key in ('job_id', 'stage')}
|
|
||||||
stage = json.dumps(payload, ensure_ascii=True, sort_keys=True, default=str)
|
|
||||||
done = progress.get('done')
|
|
||||||
done = done if type(done) is int else -1
|
|
||||||
if stage not in self.stage_progress or done > self.stage_progress[stage]:
|
|
||||||
self.stage_progress[stage] = done
|
|
||||||
self.last_progress = now
|
|
||||||
return
|
|
||||||
if kind not in {'state', 'progress', 'phase'}:
|
if kind not in {'state', 'progress', 'phase'}:
|
||||||
return
|
return
|
||||||
signature = json.dumps([kind, payload], ensure_ascii=True, sort_keys=True, default=str)
|
signature = json.dumps([kind, payload], ensure_ascii=True, sort_keys=True, default=str)
|
||||||
@@ -60,17 +47,10 @@ class BusinessProgressWatch:
|
|||||||
def stalled(self, now):
|
def stalled(self, now):
|
||||||
return now - self.last_progress >= self.idle_timeout
|
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):
|
def request_manual_dialog_action(root, binding, dialog, button_hwnd):
|
||||||
"""Publish one explicit UI choice for the current supervisor generation."""
|
"""Publish one explicit UI choice for the current supervisor generation."""
|
||||||
from .batch_resources import write_record, _valid_record, observe_process_identity
|
from .batch_resources import write_record, _valid_record, _process_gone
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
batch_id, attempt_id = binding['batch_id'], binding['attempt_id']
|
batch_id, attempt_id = binding['batch_id'], binding['attempt_id']
|
||||||
if UUID(batch_id).hex != batch_id or UUID(attempt_id).hex != attempt_id:
|
if UUID(batch_id).hex != batch_id or UUID(attempt_id).hex != attempt_id:
|
||||||
@@ -80,8 +60,7 @@ def request_manual_dialog_action(root, binding, dialog, button_hwnd):
|
|||||||
resource = json.loads(internal_path(directory / 'session.json').read_text(encoding='utf-8'))
|
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
|
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 journal['state'] not in {'running', 'blocked'} or not journal.get('process')
|
||||||
or observe_process_identity(journal['process'])['state'] != 'alive'
|
or _process_gone(journal['process']) or not _valid_record(resource, directory / 'session.json')
|
||||||
or not _valid_record(resource, directory / 'session.json')
|
|
||||||
or binding.get('generation') != resource['generation'] or not binding.get('session_token')
|
or binding.get('generation') != resource['generation'] or not binding.get('session_token')
|
||||||
or binding['session_token'] != resource.get('cad_token')
|
or binding['session_token'] != resource.get('cad_token')
|
||||||
or dialog.get('pid') != resource.get('cad_pid') or type(button_hwnd) is not int):
|
or dialog.get('pid') != resource.get('cad_pid') or type(button_hwnd) is not int):
|
||||||
@@ -296,7 +275,7 @@ def mutation_lease(root):
|
|||||||
|
|
||||||
|
|
||||||
def pending_supervisors(root):
|
def pending_supervisors(root):
|
||||||
from .batch_resources import observe_process_identity
|
from .batch_resources import _process_gone
|
||||||
from .read_recovery import process_tree_exited
|
from .read_recovery import process_tree_exited
|
||||||
pending = []
|
pending = []
|
||||||
for path in (internal_path(root) / 'batch-resources').glob('*/supervisor.json'):
|
for path in (internal_path(root) / 'batch-resources').glob('*/supervisor.json'):
|
||||||
@@ -310,15 +289,15 @@ def pending_supervisors(root):
|
|||||||
pending.append(dict(value, record_path=str(canonical_path(path)), state='blocked'))
|
pending.append(dict(value, record_path=str(canonical_path(path)), state='blocked'))
|
||||||
continue
|
continue
|
||||||
identity = value.get('process') or value.get('parent_process')
|
identity = value.get('process') or value.get('parent_process')
|
||||||
observation = observe_process_identity(identity)
|
|
||||||
if value.get('state') == 'finished':
|
if value.get('state') == 'finished':
|
||||||
if value.get('process') is None or observation['state'] == 'gone':
|
if value.get('process') is None or _process_gone(value['process']):
|
||||||
continue
|
continue
|
||||||
elif (value.get('state') in {'starting', 'running'} and observation['state'] == 'alive'
|
pending.append(dict(value, record_path=str(canonical_path(path)), state='blocked'))
|
||||||
and observe_process_identity(value.get('parent_process'))['state'] == 'alive'):
|
|
||||||
continue
|
continue
|
||||||
pending.append(dict(value, record_path=str(canonical_path(path)), state='blocked',
|
if (value.get('state') in {'starting', 'running'} and identity and not _process_gone(identity)
|
||||||
process_observation=observation))
|
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'))
|
||||||
except (OSError, ValueError, TypeError, KeyError) as error:
|
except (OSError, ValueError, TypeError, KeyError) as error:
|
||||||
pending.append({'state': 'blocked', 'record_path': str(canonical_path(path)), 'error': str(error)})
|
pending.append({'state': 'blocked', 'record_path': str(canonical_path(path)), 'error': str(error)})
|
||||||
return tuple(pending)
|
return tuple(pending)
|
||||||
@@ -335,9 +314,7 @@ def reconcile_supervisors(root):
|
|||||||
if owner is not None and not process_tree_exited(owner[1]):
|
if owner is not None and not process_tree_exited(owner[1]):
|
||||||
continue
|
continue
|
||||||
identity = record.get('process')
|
identity = record.get('process')
|
||||||
if (not record.get('batch_id')
|
if not record.get('batch_id') or (identity and not _process_gone(identity)):
|
||||||
or (record.get('process_observation') or {}).get('state') == 'unknown'
|
|
||||||
or (identity and not _process_gone(identity))):
|
|
||||||
continue
|
continue
|
||||||
if record.get('outcome') not in {'interrupted', 'completed_resources_pending'}:
|
if record.get('outcome') not in {'interrupted', 'completed_resources_pending'}:
|
||||||
_mark_interrupted(root, record, 'Supervisor ended without a reconciled final result')
|
_mark_interrupted(root, record, 'Supervisor ended without a reconciled final result')
|
||||||
@@ -371,29 +348,26 @@ def _environment():
|
|||||||
|
|
||||||
def _finish_response(root, journal, response, context):
|
def _finish_response(root, journal, response, context):
|
||||||
"""A supervisor exit may release its last USER reference. Never repeat work."""
|
"""A supervisor exit may release its last USER reference. Never repeat work."""
|
||||||
from .batch_resources import cleanup_pending_resources, _isolation_evidence, write_record
|
from .batch_resources import cleanup_pending_resources, resource_blockers, write_record
|
||||||
from .supervisor_result import validated_outcome, resource_pending_error, application_shutdown_error
|
from .supervisor_result import validated_outcome, resource_pending_error, application_shutdown_error
|
||||||
result, error, primary = validated_outcome(journal['operation'], response)
|
result, error, primary = validated_outcome(journal['operation'], response)
|
||||||
pending = cleanup_pending_resources(root, logging_context=context)
|
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'))
|
related = tuple(item for item in pending if item.get('session_id') == journal['batch_id'] or not item.get('session_id'))
|
||||||
isolated = tuple(item for item in related if item.get('state') == 'isolated' and _isolation_evidence(item))
|
blockers = resource_blockers(related)
|
||||||
writers_exited = len(related) == len(isolated)
|
warnings = tuple(item for item in related if item not in blockers)
|
||||||
journal['state'] = 'blocked' if related else 'finished'
|
journal['state'] = 'blocked' if blockers else 'finished'
|
||||||
journal['outcome'] = ('completed_resources_pending' if related and response.get('business_succeeded')
|
journal['outcome'] = ('completed_resources_pending' if blockers and response.get('business_succeeded')
|
||||||
else response.get('status', 'interrupted'))
|
else response.get('status', 'interrupted'))
|
||||||
journal['resource_recheck'] = {'pending': bool(related), 'warnings': list(isolated),
|
journal['resource_recheck'] = {'pending': bool(blockers), 'warnings': list(warnings),
|
||||||
'desktop_released': not related, 'owned_writers_exited': writers_exited, 'checked_at': time.time()}
|
'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)
|
write_record(Path(root) / 'batch-resources' / journal['batch_id'] / 'supervisor.json', journal)
|
||||||
if related:
|
if blockers:
|
||||||
failure = resource_pending_error(journal['operation'], result, error, primary or error)
|
raise resource_pending_error(journal['operation'], result, error, primary)
|
||||||
failure.resources_released = False
|
|
||||||
failure.owned_writers_exited = writers_exited
|
|
||||||
failure.resource_warnings = isolated
|
|
||||||
raise failure
|
|
||||||
for failure in (error, primary):
|
for failure in (error, primary):
|
||||||
if failure is not None:
|
if failure is not None:
|
||||||
failure.resources_released = True
|
failure.resources_released = not warnings
|
||||||
failure.owned_writers_exited = True
|
failure.owned_writers_exited = True
|
||||||
|
failure.resource_warnings = warnings
|
||||||
resource_path = internal_path(Path(root) / 'batch-resources' / journal['batch_id'] / 'session.json')
|
resource_path = internal_path(Path(root) / 'batch-resources' / journal['batch_id'] / 'session.json')
|
||||||
def preserve_shutdown_failure(detail):
|
def preserve_shutdown_failure(detail):
|
||||||
try:
|
try:
|
||||||
@@ -404,8 +378,9 @@ def _finish_response(root, journal, response, context):
|
|||||||
journal['shutdown_record_error'] = str(record_error)
|
journal['shutdown_record_error'] = str(record_error)
|
||||||
def shutdown_failure():
|
def shutdown_failure():
|
||||||
failure = application_shutdown_error(result, error, primary)
|
failure = application_shutdown_error(result, error, primary)
|
||||||
failure.resources_released = True
|
failure.resources_released = not warnings
|
||||||
failure.owned_writers_exited = True
|
failure.owned_writers_exited = True
|
||||||
|
failure.resource_warnings = warnings
|
||||||
return failure
|
return failure
|
||||||
try:
|
try:
|
||||||
resource = json.loads(resource_path.read_text(encoding='utf-8'))
|
resource = json.loads(resource_path.read_text(encoding='utf-8'))
|
||||||
@@ -441,8 +416,7 @@ def _finish_response(root, journal, response, context):
|
|||||||
raise TaskCenterError('supervisor_interrupted', '批次监督进程异常退出;未重放任务,请检查已有结果和保护记录。')
|
raise TaskCenterError('supervisor_interrupted', '批次监督进程异常退出;未重放任务,请检查已有结果和保护记录。')
|
||||||
|
|
||||||
|
|
||||||
def run_supervised(service, operation, arguments, *, stop_event=None, on_progress=None, on_phase=None,
|
def run_supervised(service, operation, arguments, *, stop_event=None, on_progress=None, on_phase=None):
|
||||||
revalidate=None):
|
|
||||||
from .batch_resources import write_record, process_identity
|
from .batch_resources import write_record, process_identity
|
||||||
from .isolated_desktop import _Win32Api
|
from .isolated_desktop import _Win32Api
|
||||||
from .stop_control import StopControl
|
from .stop_control import StopControl
|
||||||
@@ -464,13 +438,6 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
|
|||||||
_LIVE_SUPERVISORS.pop(key)
|
_LIVE_SUPERVISORS.pop(key)
|
||||||
if operation != 'cleanup_batch_resources' and pending_supervisors(root):
|
if operation != 'cleanup_batch_resources' and pending_supervisors(root):
|
||||||
raise TaskCenterError('batch_resources_pending', '上一监督进程尚未完成资源复核,请先重新清理资源。')
|
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
|
batch_id, attempt_id = uuid4().hex, uuid4().hex
|
||||||
service._last_supervisor_batch_id = batch_id
|
service._last_supervisor_batch_id = batch_id
|
||||||
directory = root / 'batch-resources' / batch_id
|
directory = root / 'batch-resources' / batch_id
|
||||||
@@ -508,16 +475,6 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
|
|||||||
ownership_cleanup_error = None
|
ownership_cleanup_error = None
|
||||||
force_accepted = False
|
force_accepted = False
|
||||||
last_message = None
|
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():
|
def receive():
|
||||||
try:
|
try:
|
||||||
while line := process.stdout.readline(1024 * 1024):
|
while line := process.stdout.readline(1024 * 1024):
|
||||||
@@ -561,7 +518,6 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
|
|||||||
if stalled and not stall_reported:
|
if stalled and not stall_reported:
|
||||||
journal['business_stalled'] = True
|
journal['business_stalled'] = True
|
||||||
journal['business_stalled_at'] = time.time()
|
journal['business_stalled_at'] = time.time()
|
||||||
journal['business_idle_timeout_seconds'] = business_watch.idle_timeout
|
|
||||||
write_record(directory / 'supervisor.json', journal)
|
write_record(directory / 'supervisor.json', journal)
|
||||||
service._logging.logger.warning('supervisor_business_stalled batch_id=%s; owned processes retained', batch_id)
|
service._logging.logger.warning('supervisor_business_stalled batch_id=%s; owned processes retained', batch_id)
|
||||||
stall_reported = True
|
stall_reported = True
|
||||||
@@ -577,14 +533,16 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
|
|||||||
else:
|
else:
|
||||||
force_accepted = True
|
force_accepted = True
|
||||||
break
|
break
|
||||||
if not sent_cancel and process.poll() is None and operation != 'cleanup_batch_resources':
|
if stop_event is not None and stop_event.is_set() and not sent_cancel:
|
||||||
try:
|
try:
|
||||||
if stop_event is not None and stop_event.is_set():
|
write_record(directory / 'cancel.json', {'version': VERSION, 'batch_id': batch_id, 'attempt_id': attempt_id})
|
||||||
publish_cancel('user_pause')
|
journal.setdefault('stop_mode', 'safe')
|
||||||
else:
|
journal.setdefault('stop_requested_at', time.time())
|
||||||
business_watch.request_cooperative_stop(time.monotonic(), publish_cancel)
|
write_record(directory / 'supervisor.json', journal)
|
||||||
|
sent_cancel = True
|
||||||
except OSError as error:
|
except OSError as error:
|
||||||
force_control.control_error = '停止请求尚未成功记录,正在重试:' + str(error)
|
if hasattr(stop_event, 'control_error'):
|
||||||
|
stop_event.control_error = '停止请求尚未成功记录,正在重试:' + str(error)
|
||||||
try:
|
try:
|
||||||
value = messages.get(timeout=.1)
|
value = messages.get(timeout=.1)
|
||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
@@ -609,13 +567,6 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
|
|||||||
state = decode(value['payload'])
|
state = decode(value['payload'])
|
||||||
service._supervisor_state = state
|
service._supervisor_state = state
|
||||||
business_watch.observe('state', state, time.monotonic())
|
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._task_queue_feedback = getattr(service, '_workspace_queue_context', None) or state['queue']
|
||||||
service._batch_feedback = state['batch']
|
service._batch_feedback = state['batch']
|
||||||
service._supervisor_waiting = bool(state.get('waiting_for_resolution')) or stalled
|
service._supervisor_waiting = bool(state.get('waiting_for_resolution')) or stalled
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ def _output_stream():
|
|||||||
|
|
||||||
|
|
||||||
def _admit_request(directory, request, request_bytes):
|
def _admit_request(directory, request, request_bytes):
|
||||||
from .batch_resources import observe_process_identity, process_identity
|
from .batch_resources import _process_gone, process_identity
|
||||||
import win32api
|
import win32api
|
||||||
deadline = time.monotonic() + 5
|
deadline = time.monotonic() + 5
|
||||||
while True:
|
while True:
|
||||||
@@ -49,7 +49,7 @@ def _admit_request(directory, request, request_bytes):
|
|||||||
or journal.get('state') not in {'starting', 'running'}
|
or journal.get('state') not in {'starting', 'running'}
|
||||||
or journal.get('request_sha256') != hashlib.sha256(request_bytes).hexdigest()
|
or journal.get('request_sha256') != hashlib.sha256(request_bytes).hexdigest()
|
||||||
or not journal.get('parent_process', {}).get('creation_time')
|
or not journal.get('parent_process', {}).get('creation_time')
|
||||||
or observe_process_identity(journal['parent_process'])['state'] != 'alive'):
|
or _process_gone(journal['parent_process'])):
|
||||||
raise ValueError('Stale or unowned supervisor request')
|
raise ValueError('Stale or unowned supervisor request')
|
||||||
if journal.get('process'):
|
if journal.get('process'):
|
||||||
break
|
break
|
||||||
@@ -183,11 +183,7 @@ def run(request_path):
|
|||||||
cancel = internal_path(directory / 'cancel.json')
|
cancel = internal_path(directory / 'cancel.json')
|
||||||
if cancel.is_file():
|
if cancel.is_file():
|
||||||
value = json.loads(cancel.read_text(encoding='utf-8'))
|
value = json.loads(cancel.read_text(encoding='utf-8'))
|
||||||
binding = {'version': VERSION, 'batch_id': batch_id, 'attempt_id': attempt_id}
|
if value == {'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()
|
stop.set()
|
||||||
consume_manual_dialog_actions(directory, runtime, batch_id, attempt_id)
|
consume_manual_dialog_actions(directory, runtime, batch_id, attempt_id)
|
||||||
emit('heartbeat')
|
emit('heartbeat')
|
||||||
@@ -277,7 +273,7 @@ def run(request_path):
|
|||||||
response['status'] = 'error'
|
response['status'] = 'error'
|
||||||
response.setdefault('error', encode_error(cleanup_error))
|
response.setdefault('error', encode_error(cleanup_error))
|
||||||
if runtime.record.get('state') == 'isolated':
|
if runtime.record.get('state') == 'isolated':
|
||||||
response['resource_warning'] = {'state': 'isolated', 'blocking': True,
|
response['resource_warning'] = {'state': 'isolated', 'blocking': False,
|
||||||
'desktop': runtime.record['desktop'], 'desktop_released': False,
|
'desktop': runtime.record['desktop'], 'desktop_released': False,
|
||||||
'owned_writers_exited': True}
|
'owned_writers_exited': True}
|
||||||
evidence.try_append('worker_closing', status=response.get('status'), business_succeeded=response.get('business_succeeded'))
|
evidence.try_append('worker_closing', status=response.get('status'), business_succeeded=response.get('business_succeeded'))
|
||||||
|
|||||||
@@ -56,9 +56,6 @@ def _scrub_json(value):
|
|||||||
|
|
||||||
|
|
||||||
def _allowed(parts):
|
def _allowed(parts):
|
||||||
if parts[0] == 'batch-runs':
|
|
||||||
return (len(parts) == 3 and bool(re.fullmatch(r'[0-9a-f]{32}', parts[1]))
|
|
||||||
and parts[2] in {'manifest.json', 'batch-receipt.json'})
|
|
||||||
if parts[0] == 'execution-proof' or (len(parts) > 3 and parts[0] == 'tasks' and parts[2] == 'execution-proof'):
|
if parts[0] == 'execution-proof' or (len(parts) > 3 and parts[0] == 'tasks' and parts[2] == 'execution-proof'):
|
||||||
return (parts[-1] == 'completion.json'
|
return (parts[-1] == 'completion.json'
|
||||||
or bool(re.fullmatch(r'project-(?:commit|pause)-[a-f0-9]{32}\.tsv', parts[-1]))
|
or bool(re.fullmatch(r'project-(?:commit|pause)-[a-f0-9]{32}\.tsv', parts[-1]))
|
||||||
@@ -77,8 +74,7 @@ def _allowed(parts):
|
|||||||
if len(parts) == 2 and parts[0] == 'logs':
|
if len(parts) == 2 and parts[0] == 'logs':
|
||||||
return bool(re.fullmatch(r'[^/]+\.log(?:\.\d+)?', parts[-1]))
|
return bool(re.fullmatch(r'[^/]+\.log(?:\.\d+)?', parts[-1]))
|
||||||
if len(parts) == 3 and parts[0] == 'batch-resources':
|
if len(parts) == 3 and parts[0] == 'batch-resources':
|
||||||
return (parts[-1] in _BATCH_NAMES
|
return parts[-1] in _BATCH_NAMES or bool(re.fullmatch(r'manual-dialog-[a-f0-9]{32}\.json', parts[-1]))
|
||||||
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':
|
if len(parts) >= 5 and parts[0] == 'batch-resources' and parts[2] == 'attempts':
|
||||||
return parts[-1].endswith('.json')
|
return parts[-1].endswith('.json')
|
||||||
if len(parts) >= 2 and parts[0] == 'attempts':
|
if len(parts) >= 2 and parts[0] == 'attempts':
|
||||||
@@ -123,7 +119,7 @@ def export_diagnostic_bundle(data_root, destination: Path) -> Path:
|
|||||||
info = entry.lstat()
|
info = entry.lstat()
|
||||||
if stat.S_ISLNK(info.st_mode) or getattr(info, 'st_file_attributes', 0) & 0x400:
|
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'})
|
manifest['omissions'].append({'path': _scrub_text(relative), 'reason': 'link_or_reparse_point'})
|
||||||
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'}:
|
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'}:
|
||||||
manifest['omissions'].append({'path': _scrub_text(relative), 'reason': 'outside_allowlist'})
|
manifest['omissions'].append({'path': _scrub_text(relative), 'reason': 'outside_allowlist'})
|
||||||
else:
|
else:
|
||||||
safe_folders.append(name)
|
safe_folders.append(name)
|
||||||
|
|||||||
@@ -8,8 +8,7 @@ from .errors import TaskCenterError
|
|||||||
RULE_VERSION = 'evidence-prewrite-v2'
|
RULE_VERSION = 'evidence-prewrite-v2'
|
||||||
# Error codes describe causes, never establish absence of a write.
|
# Error codes describe causes, never establish absence of a write.
|
||||||
TRANSIENT_CODES = frozenset({'cad_attachment_failed', 'worker_timeout_before_write',
|
TRANSIENT_CODES = frozenset({'cad_attachment_failed', 'worker_timeout_before_write',
|
||||||
'worker_error', 'worker_timeout', 'timeout', 'lookup_unavailable',
|
'worker_error', 'worker_timeout', 'timeout', 'quick_run_failed', 'execution_failed', 'native_failed'})
|
||||||
'quick_run_failed', 'execution_failed', 'native_failed'})
|
|
||||||
DETERMINISTIC_CODES = frozenset({'target_identity', 'probe_baseline_missing', 'task_not_retryable',
|
DETERMINISTIC_CODES = frozenset({'target_identity', 'probe_baseline_missing', 'task_not_retryable',
|
||||||
'assistant_stale', 'target_cell', 'invalid_target', 'target_not_found'})
|
'assistant_stale', 'target_cell', 'invalid_target', 'target_not_found'})
|
||||||
RESOURCE_UNCERTAIN_CODES = frozenset({'inventory_cleanup', 'quick_run_uncertain',
|
RESOURCE_UNCERTAIN_CODES = frozenset({'inventory_cleanup', 'quick_run_uncertain',
|
||||||
|
|||||||
@@ -19,11 +19,6 @@ import traceback
|
|||||||
|
|
||||||
|
|
||||||
_SNAPSHOT_REFERENCE_KEYS = ContextVar('snapshot_reference_keys', default={})
|
_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
|
@contextmanager
|
||||||
@@ -384,7 +379,7 @@ def load_databook_target(snapshot, report, target, *, controls, browse, filter_p
|
|||||||
load['retry'] = retry
|
load['retry'] = retry
|
||||||
save_report(snapshot, report)
|
save_report(snapshot, report)
|
||||||
if not retry:
|
if not retry:
|
||||||
raise DxDataBookLookupTimeout(str(error)) from error
|
raise
|
||||||
if candidates:
|
if candidates:
|
||||||
close_dialog(candidates[0])
|
close_dialog(candidates[0])
|
||||||
load['closed_dialog'] = candidates[0]['hwnd']
|
load['closed_dialog'] = candidates[0]['hwnd']
|
||||||
@@ -1225,7 +1220,6 @@ def run(snapshot):
|
|||||||
report.update(snapshot=str(snapshot), ok=False)
|
report.update(snapshot=str(snapshot), ok=False)
|
||||||
report.pop("error", None)
|
report.pop("error", None)
|
||||||
report.pop("traceback", None)
|
report.pop("traceback", None)
|
||||||
report.pop("code", None)
|
|
||||||
def timeout():
|
def timeout():
|
||||||
report.update(ok=False, error="Native helper timed out; inspect schematic before retrying")
|
report.update(ok=False, error="Native helper timed out; inspect schematic before retrying")
|
||||||
save_report(snapshot, report)
|
save_report(snapshot, report)
|
||||||
@@ -1249,9 +1243,6 @@ def run(snapshot):
|
|||||||
except Exception as error:
|
except Exception as error:
|
||||||
report["error"] = f"{type(error).__name__}: {error}"
|
report["error"] = f"{type(error).__name__}: {error}"
|
||||||
report["traceback"] = traceback.format_exc()
|
report["traceback"] = traceback.format_exc()
|
||||||
if isinstance(error, DxDataBookLookupTimeout) and report.get("stage") == "preflight":
|
|
||||||
report["code"] = "lookup_unavailable"
|
|
||||||
return _DATABOOK_TIMEOUT_EXIT
|
|
||||||
return 1
|
return 1
|
||||||
finally:
|
finally:
|
||||||
watchdog.cancel()
|
watchdog.cancel()
|
||||||
|
|||||||
@@ -881,34 +881,30 @@ class TaskCenterService:
|
|||||||
continue_after_backup_failure: bool = False,
|
continue_after_backup_failure: bool = False,
|
||||||
reuse_project_session: bool = True,
|
reuse_project_session: bool = True,
|
||||||
runtime=None,
|
runtime=None,
|
||||||
revalidate=None,
|
|
||||||
):
|
):
|
||||||
if runtime is None and self._supervised:
|
if runtime is None and self._supervised:
|
||||||
return self._supervise('execute_quick_run_queue', {'task_id': task_id, 'expected_item': expected_item,
|
return self._supervise('execute_quick_run_queue', {'task_id': task_id, 'expected_item': expected_item,
|
||||||
'continue_after_backup_failure': continue_after_backup_failure,
|
'continue_after_backup_failure': continue_after_backup_failure,
|
||||||
'reuse_project_session': reuse_project_session}, stop_event=stop_event,
|
'reuse_project_session': reuse_project_session}, stop_event=stop_event)
|
||||||
**({'revalidate': revalidate} if revalidate is not None else {}))
|
|
||||||
if runtime is None:
|
if runtime is None:
|
||||||
from .batch_runtime import BatchCadRuntime
|
from .batch_runtime import BatchCadRuntime
|
||||||
with BatchCadRuntime(self._logging.root, 'quick_run_queue', stop_event) as owned_runtime:
|
with BatchCadRuntime(self._logging.root, 'quick_run_queue', stop_event) as owned_runtime:
|
||||||
owned_runtime.bind_logs(self._logging, (task_id,))
|
owned_runtime.bind_logs(self._logging, (task_id,))
|
||||||
result = self.execute_quick_run_queue(task_id, expected_item=expected_item,
|
result = self.execute_quick_run_queue(task_id, expected_item=expected_item,
|
||||||
stop_event=stop_event, continue_after_backup_failure=continue_after_backup_failure,
|
stop_event=stop_event, continue_after_backup_failure=continue_after_backup_failure,
|
||||||
reuse_project_session=reuse_project_session, runtime=owned_runtime, revalidate=revalidate)
|
reuse_project_session=reuse_project_session, runtime=owned_runtime)
|
||||||
owned_runtime.result = result
|
owned_runtime.result = result
|
||||||
return result
|
return result
|
||||||
delegated = self._project_task_service(task_id)
|
delegated = self._project_task_service(task_id)
|
||||||
if delegated is not self:
|
if delegated is not self:
|
||||||
return delegated.execute_quick_run_queue(task_id, expected_item=expected_item,
|
return delegated.execute_quick_run_queue(task_id, expected_item=expected_item,
|
||||||
stop_event=stop_event, continue_after_backup_failure=continue_after_backup_failure,
|
stop_event=stop_event, continue_after_backup_failure=continue_after_backup_failure,
|
||||||
reuse_project_session=reuse_project_session, runtime=runtime, revalidate=revalidate)
|
reuse_project_session=reuse_project_session, runtime=runtime)
|
||||||
from .batch import execute_batch
|
from .batch import execute_batch
|
||||||
from .task_queue import assert_task_queue_idle
|
from .task_queue import assert_task_queue_idle
|
||||||
|
|
||||||
assert_task_queue_idle(self._logging.root)
|
assert_task_queue_idle(self._logging.root)
|
||||||
with _quick_run_lease(self._logging.root):
|
with _quick_run_lease(self._logging.root):
|
||||||
if revalidate is not None:
|
|
||||||
revalidate()
|
|
||||||
if self._store.has_active_project():
|
if self._store.has_active_project():
|
||||||
raise TaskCenterError('active_project_exists', '人工流程已有活动工程,不能同时启动自动队列。')
|
raise TaskCenterError('active_project_exists', '人工流程已有活动工程,不能同时启动自动队列。')
|
||||||
if self._store.get_task(task_id).status not in {TaskStatus.DRAFT, TaskStatus.READY, TaskStatus.RUNNING, TaskStatus.PAUSED}:
|
if self._store.get_task(task_id).status not in {TaskStatus.DRAFT, TaskStatus.READY, TaskStatus.RUNNING, TaskStatus.PAUSED}:
|
||||||
|
|||||||
@@ -141,18 +141,6 @@ def _save(path: Path, state: dict) -> None:
|
|||||||
'task_queue_state', '不能保存任务队列检查点。')
|
'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):
|
def reconcile_interrupted_queue(root, journal):
|
||||||
"""After confirmed supervisor exit, retire only its persisted running entries."""
|
"""After confirmed supervisor exit, retire only its persisted running entries."""
|
||||||
import hashlib
|
import hashlib
|
||||||
@@ -213,8 +201,7 @@ def resource_pause_admitted(root, batch_id, task_ids, plan_hashes, result=None,
|
|||||||
journal = json.loads((directory / 'supervisor.json').read_bytes())
|
journal = json.loads((directory / 'supervisor.json').read_bytes())
|
||||||
if (not valid_journal(journal, batch_id) or journal['state'] not in {'blocked', 'finished'}
|
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['operation'] != 'execute_task_queue' or journal['task_ids'] != list(task_ids)
|
||||||
or not journal['process'] or journal.get('business_uncertain') or 'stop_requested_at' in journal
|
or not journal['process'] or 'stop_requested_at' in journal
|
||||||
or journal.get('stopping_reason')
|
|
||||||
or journal.get('stop_mode') in {'safe', 'forced'} or (directory / 'cancel.json').exists()):
|
or journal.get('stop_mode') in {'safe', 'forced'} or (directory / 'cancel.json').exists()):
|
||||||
return False
|
return False
|
||||||
raw_request = (directory / 'request.json').read_bytes()
|
raw_request = (directory / 'request.json').read_bytes()
|
||||||
@@ -243,25 +230,18 @@ def resource_pause_admitted(root, batch_id, task_ids, plan_hashes, result=None,
|
|||||||
or state['phase'] != 'primary' or set(state['entries']) != set(task_ids)
|
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 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 any(state['entries'][entry.task_id]['state'] != entry.state for entry in result.entries)
|
||||||
or state['entries'][current]['state'] not in {'completed', 'failed'}
|
or state['entries'][current]['state'] != 'blocked'
|
||||||
or any(entry.state in {'paused', 'running'} for entry in result.entries)
|
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:])):
|
or not any(state['entries'][item]['state'] == 'pending' for item in task_ids[task_ids.index(current) + 1:])):
|
||||||
return False
|
return False
|
||||||
if batch_id in state.get('consumed_resource_pauses', {}):
|
if batch_id in state.get('consumed_resource_pauses', {}):
|
||||||
return False
|
return False
|
||||||
|
warning = payload.get('resource_warning') or {}
|
||||||
pause = state.get('resource_pause') or {}
|
pause = state.get('resource_pause') or {}
|
||||||
intended = ((pause.get('task_id'), pause.get('batch_id')) == (current, batch_id)
|
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 isinstance(pause.get('sources'), dict)
|
||||||
and set(pause['sources']) == set(task_ids))
|
and set(pause['sources']) == set(task_ids)
|
||||||
if intended:
|
or not pause and warning.get('state') == 'isolated' and warning.get('owned_writers_exited') is True)
|
||||||
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'
|
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))):
|
and _process_gone(journal['process']) and not blocking_resources(root) and not pending_supervisors(root))):
|
||||||
return result
|
return result
|
||||||
@@ -272,11 +252,8 @@ def resource_pause_admitted(root, batch_id, task_ids, plan_hashes, result=None,
|
|||||||
|
|
||||||
def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||||
queue_id: str | None = None, runtime=None, expected_plan_hashes=None, checkpoint_id=None,
|
queue_id: str | None = None, runtime=None, expected_plan_hashes=None, checkpoint_id=None,
|
||||||
defer_problem_pass=False, resource_batch_id=None, revalidate=None,
|
defer_problem_pass=False, resource_batch_id=None) -> TaskQueueResult:
|
||||||
manifest_digest=None, continuation_revalidate=None) -> TaskQueueResult:
|
|
||||||
"""Execute the frozen order; uncertain state stops before the next project."""
|
"""Execute the frozen order; uncertain state stops before the next project."""
|
||||||
if revalidate is None and resource_batch_id is not None:
|
|
||||||
revalidate = continuation_revalidate
|
|
||||||
if runtime is None and getattr(service, '_supervised', False):
|
if runtime is None and getattr(service, '_supervised', False):
|
||||||
# Existing per-project checkpoints keep their original resume owner.
|
# Existing per-project checkpoints keep their original resume owner.
|
||||||
if (isinstance(queue_id, str) and len(queue_id) == 32
|
if (isinstance(queue_id, str) and len(queue_id) == 32
|
||||||
@@ -285,19 +262,16 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
|||||||
from .workspace_execution import execute_workspace_projects
|
from .workspace_execution import execute_workspace_projects
|
||||||
return execute_workspace_projects(service, task_ids, queue_id=queue_id, stop_event=stop_event,
|
return execute_workspace_projects(service, task_ids, queue_id=queue_id, stop_event=stop_event,
|
||||||
expected_plan_hashes=expected_plan_hashes, checkpoint_id=checkpoint_id,
|
expected_plan_hashes=expected_plan_hashes, checkpoint_id=checkpoint_id,
|
||||||
defer_problem_pass=defer_problem_pass, revalidate=revalidate)
|
defer_problem_pass=defer_problem_pass)
|
||||||
arguments = {'task_ids': tuple(task_ids),
|
arguments = {'task_ids': tuple(task_ids),
|
||||||
'queue_id': queue_id, 'expected_plan_hashes': expected_plan_hashes,
|
'queue_id': queue_id, 'expected_plan_hashes': expected_plan_hashes,
|
||||||
'checkpoint_id': checkpoint_id, 'defer_problem_pass': defer_problem_pass}
|
'checkpoint_id': checkpoint_id, 'defer_problem_pass': defer_problem_pass}
|
||||||
if resource_batch_id:
|
if resource_batch_id:
|
||||||
arguments['resource_batch_id'] = 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()
|
recovered = set()
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
result = service._supervise('execute_task_queue', arguments, stop_event=stop_event, **controls)
|
result = service._supervise('execute_task_queue', arguments, stop_event=stop_event)
|
||||||
except TaskCenterError as error:
|
except TaskCenterError as error:
|
||||||
result = getattr(error, 'completed_result', None)
|
result = getattr(error, 'completed_result', None)
|
||||||
batch_id = getattr(service, '_last_supervisor_batch_id', None)
|
batch_id = getattr(service, '_last_supervisor_batch_id', None)
|
||||||
@@ -312,16 +286,13 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
|||||||
expected_plan_hashes, result)):
|
expected_plan_hashes, result)):
|
||||||
return result
|
return result
|
||||||
recovered.add(result.current_task_id)
|
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)
|
arguments = dict(arguments, queue_id=result.queue_id, checkpoint_id=None, resource_batch_id=batch_id)
|
||||||
if runtime is None:
|
if runtime is None:
|
||||||
from .batch_runtime import BatchCadRuntime
|
from .batch_runtime import BatchCadRuntime
|
||||||
with BatchCadRuntime(service._logging.root, 'task_queue', stop_event) as owned_runtime:
|
with BatchCadRuntime(service._logging.root, 'task_queue', stop_event) as owned_runtime:
|
||||||
result = execute_task_queue(service, task_ids, stop_event=stop_event,
|
result = execute_task_queue(service, task_ids, stop_event=stop_event,
|
||||||
queue_id=queue_id, runtime=owned_runtime, expected_plan_hashes=expected_plan_hashes,
|
queue_id=queue_id, runtime=owned_runtime, expected_plan_hashes=expected_plan_hashes,
|
||||||
checkpoint_id=checkpoint_id, defer_problem_pass=defer_problem_pass,
|
checkpoint_id=checkpoint_id, defer_problem_pass=defer_problem_pass)
|
||||||
resource_batch_id=resource_batch_id, revalidate=revalidate,
|
|
||||||
manifest_digest=manifest_digest)
|
|
||||||
owned_runtime.result = result
|
owned_runtime.result = result
|
||||||
return result
|
return result
|
||||||
ids = tuple(task_ids)
|
ids = tuple(task_ids)
|
||||||
@@ -329,10 +300,6 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
|||||||
raise TaskCenterError('task_queue_selection', '请选择不同的单工程任务。')
|
raise TaskCenterError('task_queue_selection', '请选择不同的单工程任务。')
|
||||||
root = service._logging.root
|
root = service._logging.root
|
||||||
with _queue_lease(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}
|
children = {task_id: service.for_project_task(task_id) for task_id in ids}
|
||||||
project_paths, projects_by_task = [], {}
|
project_paths, projects_by_task = [], {}
|
||||||
sources = {}
|
sources = {}
|
||||||
@@ -368,7 +335,6 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
|||||||
state = json.loads(path.read_text(encoding='utf-8'))
|
state = json.loads(path.read_text(encoding='utf-8'))
|
||||||
if (state['version'] != 1 or state['task_ids'] != list(ids)
|
if (state['version'] != 1 or state['task_ids'] != list(ids)
|
||||||
or state['plan_hashes'] != hashes or set(state['entries']) != set(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 any(not isinstance(entry, dict) or set(entry) != {'state', 'message'}
|
||||||
or entry['state'] not in {'pending', 'running', 'paused', 'blocked', *_TERMINAL}
|
or entry['state'] not in {'pending', 'running', 'paused', 'blocked', *_TERMINAL}
|
||||||
or not isinstance(entry['message'], str)
|
or not isinstance(entry['message'], str)
|
||||||
@@ -379,8 +345,6 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
|||||||
else:
|
else:
|
||||||
state = {'version': 1, 'task_ids': list(ids), 'plan_hashes': hashes, 'phase': 'primary',
|
state = {'version': 1, 'task_ids': list(ids), 'plan_hashes': hashes, 'phase': 'primary',
|
||||||
'entries': {task_id: {'state': 'pending', 'message': ''} for task_id in ids}}
|
'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)
|
_save(path, state)
|
||||||
paused = False
|
paused = False
|
||||||
current = None
|
current = None
|
||||||
@@ -389,20 +353,26 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
|||||||
isolated_tasks = state.setdefault('isolated_tasks', {})
|
isolated_tasks = state.setdefault('isolated_tasks', {})
|
||||||
isolated_sources = state.setdefault('isolated_sources', {})
|
isolated_sources = state.setdefault('isolated_sources', {})
|
||||||
dependency_tasks = state.setdefault('dependency_tasks', {})
|
dependency_tasks = state.setdefault('dependency_tasks', {})
|
||||||
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:
|
if resource_batch_id:
|
||||||
evidence = resource_pause_admitted(root, resource_batch_id, ids, hashes)
|
evidence = resource_pause_admitted(root, resource_batch_id, ids, hashes)
|
||||||
if not evidence or evidence.queue_id != queue_id:
|
if not evidence or evidence.queue_id != queue_id:
|
||||||
raise TaskCenterError('task_queue_state', '原队列的资源释放或阻断回执无法核验。')
|
raise TaskCenterError('task_queue_state', '原队列的资源释放或阻断回执无法核验。')
|
||||||
item = evidence.current_task_id
|
item = evidence.current_task_id
|
||||||
if not frozen_sources or frozen_sources != state['resource_pause']['sources']:
|
if not children[item].has_interrupted_quick_run(item):
|
||||||
|
raise TaskCenterError('task_queue_state', '阻断工程缺少原待核验证据。')
|
||||||
|
pause = state.get('resource_pause')
|
||||||
|
if pause:
|
||||||
|
known_sources = pause['sources']
|
||||||
|
else:
|
||||||
|
before = (state.get('netlist_verification', {}).get(item, {}).get('before') or {})
|
||||||
|
known = [str(Path(name).resolve()).casefold() for name in before.get('source_hashes', {})
|
||||||
|
if Path(name).suffix.casefold() == '.prj' or Path(name).name.casefold() == 'icdb.dat']
|
||||||
|
known_sources = {item: sorted(known)}
|
||||||
|
if not frozen_sources or any(frozen_sources.get(task) != values for task, values in known_sources.items()):
|
||||||
raise TaskCenterError('task_queue_state', '工程写入源已变化或无法核验,须重新确认。')
|
raise TaskCenterError('task_queue_state', '工程写入源已变化或无法核验,须重新确认。')
|
||||||
sources = {task: set(values) for task, values in frozen_sources.items()}
|
sources = {task: set(values) for task, values in frozen_sources.items()}
|
||||||
|
isolated_tasks[item] = state['entries'][item]['message']
|
||||||
|
isolated_sources.update((source, item) for source in sources[item])
|
||||||
state.setdefault('consumed_resource_pauses', {})[resource_batch_id] = item
|
state.setdefault('consumed_resource_pauses', {})[resource_batch_id] = item
|
||||||
state.pop('resource_pause', None)
|
state.pop('resource_pause', None)
|
||||||
_save(path, state)
|
_save(path, state)
|
||||||
@@ -450,8 +420,6 @@ 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))
|
service._task_queue_feedback = (token, task_id, ids.index(task_id) + 1, len(ids))
|
||||||
resolving_bom = False
|
resolving_bom = False
|
||||||
execution_dispatched = False
|
execution_dispatched = False
|
||||||
resource_only = False
|
|
||||||
uncertain_error = None
|
|
||||||
try:
|
try:
|
||||||
if hasattr(runtime, 'begin_task'):
|
if hasattr(runtime, 'begin_task'):
|
||||||
runtime.begin_task(task_id)
|
runtime.begin_task(task_id)
|
||||||
@@ -525,36 +493,32 @@ 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',
|
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}
|
'message': f'{error.code}: {error.message}' if resolving_bom else error.message}
|
||||||
paused = not safe
|
paused = not safe
|
||||||
if (error.code in {'batch_resources_pending', 'application_shutdown_failed'}
|
if not safe and error.code != 'operation_cancelled' and not stop_event.is_set():
|
||||||
and execution_dispatched and hasattr(child, '_store')
|
|
||||||
and not _task_uncertain(root, child, task_id)):
|
|
||||||
try:
|
try:
|
||||||
progress = child.quick_run_progress(task_id)
|
isolated = isolate_project(runtime, child, task_id, error)
|
||||||
if progress.queue_complete:
|
except Exception as cleanup_error:
|
||||||
resource_only = True
|
entry['message'] += '; 资源收尾未确认:' + str(cleanup_error)
|
||||||
entry['state'] = 'failed' if progress.failed_items else 'completed'
|
isolated = False
|
||||||
except (OSError, ValueError, TaskCenterError):
|
if isolated:
|
||||||
pass
|
isolated_tasks[task_id] = entry['message']
|
||||||
if paused and not resource_only and (error.code != 'operation_cancelled'
|
isolated_sources.update((source,task_id) for source in sources[task_id])
|
||||||
or _task_uncertain(root, child, task_id)):
|
paused = False
|
||||||
uncertain_error = error
|
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
entry = {'state': 'blocked', 'message': str(error)}
|
entry = {'state': 'blocked', 'message': str(error)}
|
||||||
paused = True
|
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():
|
if not stop_event.is_set():
|
||||||
try:
|
try:
|
||||||
isolate_project(runtime, child, task_id, uncertain_error)
|
isolated = isolate_project(runtime, child, task_id, error)
|
||||||
except Exception as cleanup_error:
|
except Exception as cleanup_error:
|
||||||
entry['message'] += '; 资源收尾未确认:' + str(cleanup_error)
|
entry['message'] += '; 资源收尾未确认:' + str(cleanup_error)
|
||||||
_save(path, state)
|
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
|
||||||
record_task_outcome(child, task_id, entry['state'], entry['message'])
|
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
|
if (entry['state'] in {'completed', 'failed'} and task_id in checks.tasks
|
||||||
and not child.has_interrupted_quick_run(task_id)):
|
and not child.has_interrupted_quick_run(task_id)):
|
||||||
progress = child.quick_run_progress(task_id)
|
progress = child.quick_run_progress(task_id)
|
||||||
@@ -562,9 +526,10 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
|||||||
execution_summary={key: getattr(progress, key, None)
|
execution_summary={key: getattr(progress, key, None)
|
||||||
for key in ('saved_items', 'failed_items', 'no_match_items')})
|
for key in ('saved_items', 'failed_items', 'no_match_items')})
|
||||||
if paused:
|
if paused:
|
||||||
if resource_only and not stop_event.is_set() and frozen_sources and hasattr(runtime, 'session_id'):
|
if (entry['state'] == 'blocked' and not stop_event.is_set()
|
||||||
|
and frozen_sources and hasattr(runtime, 'session_id')):
|
||||||
state['resource_pause'] = {'task_id': task_id, 'batch_id': runtime.session_id,
|
state['resource_pause'] = {'task_id': task_id, 'batch_id': runtime.session_id,
|
||||||
'sources': frozen_sources, 'business_determined': True, 'manifest_digest': manifest_digest}
|
'sources': frozen_sources}
|
||||||
_save(path, state)
|
_save(path, state)
|
||||||
break
|
break
|
||||||
if (not paused and stop_event.is_set() and state.get('phase') != 'finished'
|
if (not paused and stop_event.is_set() and state.get('phase') != 'finished'
|
||||||
|
|||||||
@@ -122,8 +122,6 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
|||||||
self._batch_stop = None
|
self._batch_stop = None
|
||||||
self._active_quick_run_task_id = None
|
self._active_quick_run_task_id = None
|
||||||
self._project_queues = {}
|
self._project_queues = {}
|
||||||
self._batch_confirmation_admission = None
|
|
||||||
self._receipt_recovery_started = False
|
|
||||||
self._resource_queue_resume = None
|
self._resource_queue_resume = None
|
||||||
self._execution_after_save = None
|
self._execution_after_save = None
|
||||||
self._generation = 0
|
self._generation = 0
|
||||||
@@ -152,7 +150,6 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
|||||||
self.task_list.up_button.clicked.connect(lambda: self._move_project_task(-1))
|
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.down_button.clicked.connect(lambda: self._move_project_task(1))
|
||||||
self.task_list.queue_button.clicked.connect(self._execute_project_tasks)
|
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 = ProjectSummary()
|
||||||
self.project_summary.refresh_button.clicked.connect(self._refresh_bound_project)
|
self.project_summary.refresh_button.clicked.connect(self._refresh_bound_project)
|
||||||
self.mapping_table = MappingTable(self._rule_enabled_changed)
|
self.mapping_table = MappingTable(self._rule_enabled_changed)
|
||||||
@@ -634,10 +631,8 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
|||||||
group_dirty = self.plan_panel.has_unsaved_plan(group_ids)
|
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)
|
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)
|
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 resources_pending)
|
self.task_list.queue_button.setEnabled(bool(batch_pending) and not busy and not group_dirty
|
||||||
selected_ids = self.task_list.selected_task_ids()
|
and not context.interrupted and not resources_pending)
|
||||||
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):
|
for button in (self.task_list.up_button, self.task_list.down_button):
|
||||||
button.setEnabled(grouped and not busy and not group_active
|
button.setEnabled(grouped and not busy and not group_active
|
||||||
and self.task_list.sort.currentData() == 'execution'
|
and self.task_list.sort.currentData() == 'execution'
|
||||||
@@ -907,87 +902,39 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
|||||||
self._bind_dsh_context()
|
self._bind_dsh_context()
|
||||||
self._run_async(execute, done, self.run_panel.quick_run_button, expected_task_id=task_id)
|
self._run_async(execute, done, self.run_panel.quick_run_button, expected_task_id=task_id)
|
||||||
|
|
||||||
def _execute_project_tasks(self, *, resource_resume=False, selected=False):
|
def _execute_project_tasks(self, *, resource_resume=False):
|
||||||
button = self.task_list.selected_queue_button if selected else self.task_list.queue_button
|
if not self.task_list.queue_button.isEnabled():
|
||||||
if not button.isEnabled() or self._context is None:
|
|
||||||
return
|
return
|
||||||
owner_task_id = self._context.task.task_id
|
owner_task_id = self._context.task.task_id
|
||||||
group = self._context.task.group_id
|
group = self._context.task.group_id
|
||||||
from ..batch_admission import build_batch_admission, resolve_batch_task_ids
|
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:
|
try:
|
||||||
candidates = resolve_batch_task_ids(self._tasks, group,
|
|
||||||
selected_ids=self.task_list.selected_task_ids() if selected else None)
|
|
||||||
except TaskCenterError as error:
|
|
||||||
self._show_error(error, owner_task_id=owner_task_id)
|
|
||||||
return
|
|
||||||
token, ids = self._project_queues.get(group, (None, candidates))
|
|
||||||
if token and selected and tuple(ids) != candidates:
|
|
||||||
self._set_operator_message('本批有原队列待接续,请按原确认范围继续,或先核验并结束原批次。', 'warning')
|
|
||||||
return
|
|
||||||
prepared = []
|
|
||||||
def inspect():
|
|
||||||
if token:
|
if token:
|
||||||
from ...dsh.run_journal import resume_preflight
|
from ...dsh.run_journal import resume_preflight
|
||||||
inspected = 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'):
|
if resource_resume and not inspected.get('resource_batch_id'):
|
||||||
return None
|
return
|
||||||
report = resume_preflight(self.service, inspected)
|
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:
|
else:
|
||||||
admission = build_batch_admission(self.service, candidates,
|
report = lifecycle.preflight(self.service, list(ids), allow_completed=True)
|
||||||
scope_kind='selected' if selected else 'batch')
|
except Exception as error:
|
||||||
report = admission['execution_report']
|
self._show_error(error, owner_task_id=ids[0])
|
||||||
return admission, report
|
|
||||||
def collected(value):
|
|
||||||
if value is not None:
|
|
||||||
prepared.append(value)
|
|
||||||
def confirm():
|
|
||||||
if not prepared or self._closed or self._close_pending or self._task_id != owner_task_id:
|
|
||||||
return
|
return
|
||||||
admission, report = prepared[0]
|
if not self._execution_report_ready(report):
|
||||||
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
|
return
|
||||||
if not report or not self._execution_report_ready(report):
|
|
||||||
return
|
|
||||||
self._batch_confirmation_admission = admission
|
|
||||||
self._dsh_confirmation_impact = report.get('impact', {})
|
self._dsh_confirmation_impact = report.get('impact', {})
|
||||||
enabled = report.get('impact', {}).get('enabled_scope', 0)
|
enabled = report.get('impact', {}).get('enabled_scope', 0)
|
||||||
active = tuple(ids) if token else tuple(admission['runnable_task_ids'])
|
if not resource_resume and not self._quick_run_confirmer('batch', len(ids), enabled):
|
||||||
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
|
return
|
||||||
try:
|
if not self._confirmed_execution_allowed(owner_task_id, ids, self.task_list.queue_button):
|
||||||
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
|
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', {})
|
|
||||||
self._dsh_authorized_tasks.update(ids)
|
self._dsh_authorized_tasks.update(ids)
|
||||||
self._begin_run(ids[0])
|
self._begin_run(ids[0])
|
||||||
self._dsh_live_run['task_ids'] = list(ids)
|
self._dsh_live_run['task_ids'] = list(ids)
|
||||||
@@ -995,7 +942,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
|||||||
self._dsh_run_id = run_id
|
self._dsh_run_id = run_id
|
||||||
self._dsh_live_run['run_id'] = run_id
|
self._dsh_live_run['run_id'] = run_id
|
||||||
stop = self._batch_stop
|
stop = self._batch_stop
|
||||||
def done(result, receipt=None):
|
def done(result):
|
||||||
if result.paused:
|
if result.paused:
|
||||||
self._project_queues[group] = (result.queue_id, ids)
|
self._project_queues[group] = (result.queue_id, ids)
|
||||||
else:
|
else:
|
||||||
@@ -1010,20 +957,6 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
|||||||
self._queue_dsh_incident(entry.task_id,
|
self._queue_dsh_incident(entry.task_id,
|
||||||
'task_queue_blocked' if entry.state == 'blocked' else 'execution_failed', entry.message)
|
'task_queue_blocked' if entry.state == 'blocked' else 'execution_failed', entry.message)
|
||||||
self._show_task_log(force=True)
|
self._show_task_log(force=True)
|
||||||
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} 项。',
|
self._set_operator_message(f'本批任务已暂停。失败/阻断 {failures} 项。' if result.paused else f'本批任务已结束。失败 {failures} 项。',
|
||||||
'warning' if result.paused or failures else 'success')
|
'warning' if result.paused or failures else 'success')
|
||||||
def execute():
|
def execute():
|
||||||
@@ -1033,14 +966,14 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
|||||||
if token:
|
if token:
|
||||||
resume = self._dsh_operations.runs.inspect(self.service, token)
|
resume = self._dsh_operations.runs.inspect(self.service, token)
|
||||||
receipt = execute_confirmed_run(self.service, self.service.layout_settings_path.parent,
|
receipt = execute_confirmed_run(self.service, self.service.layout_settings_path.parent,
|
||||||
list(ids), report, stop, run_id, resume=resume, admission=admission)
|
list(ids), report, stop, run_id, resume=resume)
|
||||||
result = TaskQueueResult(receipt['queue_id'], tuple(TaskQueueEntry(**entry) for entry in receipt['entries']),
|
result = TaskQueueResult(receipt['queue_id'], tuple(TaskQueueEntry(**entry) for entry in receipt['entries']),
|
||||||
receipt['paused'])
|
receipt['paused'])
|
||||||
return result, receipt
|
return result, receipt
|
||||||
def completed(value):
|
def completed(value):
|
||||||
if isinstance(value, tuple):
|
if isinstance(value, tuple):
|
||||||
result, receipt = value
|
result, receipt = value
|
||||||
done(result, receipt)
|
done(result)
|
||||||
self._show_receipt_verification(receipt)
|
self._show_receipt_verification(receipt)
|
||||||
self._dsh_last_execution = receipt
|
self._dsh_last_execution = receipt
|
||||||
self._bind_dsh_context()
|
self._bind_dsh_context()
|
||||||
@@ -1049,7 +982,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
|||||||
self._resource_queue_resume = (group, result.queue_id, ids)
|
self._resource_queue_resume = (group, result.queue_id, ids)
|
||||||
else:
|
else:
|
||||||
done(value)
|
done(value)
|
||||||
self._run_async(execute, completed, button, on_finished=self._check_resource_queue)
|
self._run_async(execute, completed, self.task_list.queue_button, on_finished=self._check_resource_queue)
|
||||||
|
|
||||||
def _check_resource_queue(self):
|
def _check_resource_queue(self):
|
||||||
if self._resource_queue_resume and self._resource_status.blocked and not self._workers:
|
if self._resource_queue_resume and self._resource_status.blocked and not self._workers:
|
||||||
@@ -1180,10 +1113,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
|||||||
nonlocal cleanup_finished
|
nonlocal cleanup_finished
|
||||||
cleanup_finished = True
|
cleanup_finished = True
|
||||||
start_force_if_ready()
|
start_force_if_ready()
|
||||||
if not force_started and not self._workers:
|
self._resume_resource_queue()
|
||||||
from ...dsh.execution_runs import recover_batch_receipts
|
|
||||||
self._run_async(lambda: recover_batch_receipts(self.service, self.service.layout_settings_path.parent),
|
|
||||||
lambda _: None, operation_area='batch_receipts', on_finished=self._resume_resource_queue)
|
|
||||||
def forced(remaining):
|
def forced(remaining):
|
||||||
from ..batch_resources import resource_blockers
|
from ..batch_resources import resource_blockers
|
||||||
self._resource_status.refresh()
|
self._resource_status.refresh()
|
||||||
@@ -1227,12 +1157,6 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
|||||||
if self._workers or self._loading or not self._resource_status.known or self._resource_status.busy:
|
if self._workers or self._loading or not self._resource_status.known or self._resource_status.busy:
|
||||||
QTimer.singleShot(250, self._startup_resource_recheck)
|
QTimer.singleShot(250, self._startup_resource_recheck)
|
||||||
return
|
return
|
||||||
if 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:
|
if self._resource_status.records:
|
||||||
self._update_gates()
|
self._update_gates()
|
||||||
self._cleanup_batch_resources(automatic=True)
|
self._cleanup_batch_resources(automatic=True)
|
||||||
@@ -1364,21 +1288,13 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
|||||||
|
|
||||||
def _confirm_quick_run(self, scope, selected_projects, enabled_rules):
|
def _confirm_quick_run(self, scope, selected_projects, enabled_rules):
|
||||||
context = self._context
|
context = self._context
|
||||||
admission = self._batch_confirmation_admission if scope != 'current' else None
|
names = context.project.path if scope == 'current' else '\n'.join(
|
||||||
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))
|
||||||
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')
|
text = (f'执行范围:{names}\n\n' + ('' if scope == 'current' else f'按顺序处理 {selected_projects} 个工程任务。\n')
|
||||||
+ f'勾选目标/规则:{enabled_rules}\n'
|
+ f'勾选目标/规则:{enabled_rules}\n'
|
||||||
+ '逐项执行原生 Replace Part + Library Wins,保留每行 Value/NC 策略;创建备份并自动保存、关闭、重开核验。'
|
+ '逐项执行原生 Replace Part + Library Wins,保留每行 Value/NC 策略;创建备份并自动保存、关闭、重开核验。'
|
||||||
+ '\n默认在受监督的私有桌面执行,结束后释放自有 CAD 会话;主桌面可继续查看其他文件。请确保待处理工程未在其他 CAD 会话中打开。'
|
+ '\n默认在受监督的私有桌面执行,结束后释放自有 CAD 会话;主桌面可继续查看其他文件。请确保待处理工程未在其他 CAD 会话中打开。'
|
||||||
+ '\n确认后连续执行,暂停等待当前步骤收尾;状态不确定时停止。')
|
+ '\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', {})
|
impact = getattr(self, '_dsh_confirmation_impact', {})
|
||||||
if impact:
|
if impact:
|
||||||
text += '\n\n执行影响:' + ('器件数量未知,执行时按实际命中核验。' if impact['component_count'] is None else f"已选中 {impact['component_count']} 个器件。")
|
text += '\n\n执行影响:' + ('器件数量未知,执行时按实际命中核验。' if impact['component_count'] is None else f"已选中 {impact['component_count']} 个器件。")
|
||||||
|
|||||||
@@ -105,8 +105,6 @@ class TaskList(QWidget):
|
|||||||
self.restore_button = QPushButton("恢复", objectName="restoreTaskButton")
|
self.restore_button = QPushButton("恢复", objectName="restoreTaskButton")
|
||||||
self.queue_button = QPushButton("顺序执行本批任务", objectName="executeProjectTasks")
|
self.queue_button = QPushButton("顺序执行本批任务", objectName="executeProjectTasks")
|
||||||
self.queue_button.setToolTip('按保存的执行顺序执行本批全部任务,不受搜索和显示排序影响。')
|
self.queue_button.setToolTip('按保存的执行顺序执行本批全部任务,不受搜索和显示排序影响。')
|
||||||
self.selected_queue_button = QPushButton('顺序执行所选任务', objectName='executeSelectedProjectTasks')
|
|
||||||
self.selected_queue_button.setToolTip('仅处理列表中明确选中的同批任务,仍按保存的执行顺序;执行前列出逐任务裁决。')
|
|
||||||
self.up_button = QPushButton("上移任务", objectName="moveTaskUp")
|
self.up_button = QPushButton("上移任务", objectName="moveTaskUp")
|
||||||
self.down_button = QPushButton("下移任务", objectName="moveTaskDown")
|
self.down_button = QPushButton("下移任务", objectName="moveTaskDown")
|
||||||
self.new_button.setProperty('appearance','quiet')
|
self.new_button.setProperty('appearance','quiet')
|
||||||
@@ -155,7 +153,6 @@ class TaskList(QWidget):
|
|||||||
layout.addWidget(self.empty_hint)
|
layout.addWidget(self.empty_hint)
|
||||||
layout.addWidget(self.list, 1)
|
layout.addWidget(self.list, 1)
|
||||||
layout.addWidget(self.queue_button)
|
layout.addWidget(self.queue_button)
|
||||||
layout.addWidget(self.selected_queue_button)
|
|
||||||
layout.addLayout(footer)
|
layout.addLayout(footer)
|
||||||
def selected():
|
def selected():
|
||||||
task_id = self.current_task_id()
|
task_id = self.current_task_id()
|
||||||
@@ -174,9 +171,6 @@ class TaskList(QWidget):
|
|||||||
item = self.list.currentItem()
|
item = self.list.currentItem()
|
||||||
return str(item.data(Qt.ItemDataRole.UserRole)) if item is not None else None
|
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:
|
def populate(self, tasks: Iterable[object], *, selected_task_id: str | None = None) -> None:
|
||||||
preserve_selection = selected_task_id in (None, self.current_task_id())
|
preserve_selection = selected_task_id in (None, self.current_task_id())
|
||||||
selected_ids = {item.data(Qt.ItemDataRole.UserRole) for item in self.list.selectedItems()}
|
selected_ids = {item.data(Qt.ItemDataRole.UserRole) for item in self.list.selectedItems()}
|
||||||
@@ -223,7 +217,6 @@ class TaskList(QWidget):
|
|||||||
current = current.split(' · 已选 ', 1)[0]
|
current = current.split(' · 已选 ', 1)[0]
|
||||||
if current:
|
if current:
|
||||||
self.count.setText(current + suffix)
|
self.count.setText(current + suffix)
|
||||||
self.view_changed.emit()
|
|
||||||
|
|
||||||
def _render(self):
|
def _render(self):
|
||||||
selected = self._selected_task_id
|
selected = self._selected_task_id
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
VERSION = "1.3.1"
|
VERSION = "1.3.3-beta.1"
|
||||||
@@ -130,7 +130,6 @@ class ProgressWatch:
|
|||||||
self.native_sequence = 0
|
self.native_sequence = 0
|
||||||
self.native_progress_frames = 0
|
self.native_progress_frames = 0
|
||||||
self.stop_requested = False
|
self.stop_requested = False
|
||||||
self.stopping_reason = ''
|
|
||||||
self.stage = 'starting'
|
self.stage = 'starting'
|
||||||
self.done = 0
|
self.done = 0
|
||||||
self.total = 0
|
self.total = 0
|
||||||
@@ -156,7 +155,8 @@ class ProgressWatch:
|
|||||||
return False
|
return False
|
||||||
except (ValueError, UnicodeError):
|
except (ValueError, UnicodeError):
|
||||||
return False
|
return False
|
||||||
if ((current_job, fields[4]) != (self.current_job_id, self.stage) or done > self.done):
|
if ((current_job, fields[4], done, total, bool(safe)) !=
|
||||||
|
(self.current_job_id, self.stage, self.done, self.total, self.safe_stop)):
|
||||||
self.last_business_progress = now
|
self.last_business_progress = now
|
||||||
self.waiting_for_safe_completion = False
|
self.waiting_for_safe_completion = False
|
||||||
if current_job != self.current_job_id:
|
if current_job != self.current_job_id:
|
||||||
@@ -199,7 +199,7 @@ class ProgressWatch:
|
|||||||
self.native_sequence = sequence
|
self.native_sequence = sequence
|
||||||
self.native_progress_frames += 1
|
self.native_progress_frames += 1
|
||||||
self.last_progress = now
|
self.last_progress = now
|
||||||
if done > self.done:
|
if (done, total) != (self.done, self.total):
|
||||||
self.last_business_progress = now
|
self.last_business_progress = now
|
||||||
self.waiting_for_safe_completion = False
|
self.waiting_for_safe_completion = False
|
||||||
self.done, self.total = done, total
|
self.done, self.total = done, total
|
||||||
@@ -210,7 +210,6 @@ class ProgressWatch:
|
|||||||
idle_timeout = self.idle_timeout
|
idle_timeout = self.idle_timeout
|
||||||
if not self.stop_requested and idle >= idle_timeout:
|
if not self.stop_requested and idle >= idle_timeout:
|
||||||
self.stop_requested = True
|
self.stop_requested = True
|
||||||
self.stopping_reason = 'inactivity'
|
|
||||||
return 'request_stop'
|
return 'request_stop'
|
||||||
if self.stop_requested and idle >= idle_timeout * 2:
|
if self.stop_requested and idle >= idle_timeout * 2:
|
||||||
if (self.waiting_for_safe_completion
|
if (self.waiting_for_safe_completion
|
||||||
@@ -233,9 +232,6 @@ class ProgressWatch:
|
|||||||
'native_progress_frames': self.native_progress_frames,
|
'native_progress_frames': self.native_progress_frames,
|
||||||
'business_idle_seconds': max(0.0, now - self.last_business_progress),
|
'business_idle_seconds': max(0.0, now - self.last_business_progress),
|
||||||
'heartbeat_idle_seconds': max(0.0, now - self.last_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}
|
'elapsed_seconds': max(0.0, now - self.started), 'stage_seconds': stages}
|
||||||
|
|
||||||
|
|
||||||
@@ -472,7 +468,6 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
|||||||
read_cancel_started = time.monotonic()
|
read_cancel_started = time.monotonic()
|
||||||
if not watch.stop_requested:
|
if not watch.stop_requested:
|
||||||
watch.stop_requested = True
|
watch.stop_requested = True
|
||||||
watch.stopping_reason = 'owner_loss'
|
|
||||||
request_stop()
|
request_stop()
|
||||||
if time.monotonic() - read_cancel_started >= READ_ONLY_CANCEL_GRACE_SECONDS:
|
if time.monotonic() - read_cancel_started >= READ_ONLY_CANCEL_GRACE_SECONDS:
|
||||||
raise WorkerMonitorCancelled('read owner exited before the read completed', stage=watch.stage)
|
raise WorkerMonitorCancelled('read owner exited before the read completed', stage=watch.stage)
|
||||||
@@ -506,10 +501,6 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
|||||||
# have reached watch yet, so ordinary pause cannot kill here.
|
# have reached watch yet, so ordinary pause cannot kill here.
|
||||||
watch.stop_requested = True
|
watch.stop_requested = True
|
||||||
watch.last_progress = time.monotonic()
|
watch.last_progress = time.monotonic()
|
||||||
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
|
watch.last_business_progress = watch.last_progress
|
||||||
request_stop()
|
request_stop()
|
||||||
_publish_progress(progress_path, watch.snapshot())
|
_publish_progress(progress_path, watch.snapshot())
|
||||||
|
|||||||
@@ -50,22 +50,32 @@ def _token(value):
|
|||||||
return isinstance(value, str) and len(value) == 32 and all(char in '0123456789abcdef' for char in 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,
|
def execute_workspace_projects(service, task_ids, *, stop_event, queue_id=None,
|
||||||
expected_plan_hashes=None, checkpoint_id=None, defer_problem_pass=False,
|
expected_plan_hashes=None, checkpoint_id=None, defer_problem_pass=False):
|
||||||
revalidate=None):
|
from .task_queue import _plan_hash, TaskQueueEntry, TaskQueueResult
|
||||||
from .task_queue import _plan_hash, _task_uncertain, _uncertainty_root, TaskQueueEntry, TaskQueueResult
|
|
||||||
ids = tuple(task_ids)
|
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
|
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):
|
or item in {'.', '..'} for item in ids):
|
||||||
raise TaskCenterError('task_queue_selection', '请选择不同的单工程任务。')
|
raise TaskCenterError('task_queue_selection', '请选择不同的单工程任务。')
|
||||||
root = canonical_path(service._logging.root)
|
root = canonical_path(service._logging.root)
|
||||||
with _lease(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}
|
children = {item: service.for_project_task(item) for item in ids}
|
||||||
projects = [children[item].projects(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()
|
if any(len(rows) != 1 for rows in projects) or len({str(canonical_path(rows[0].path)).casefold()
|
||||||
@@ -109,12 +119,6 @@ def execute_workspace_projects(service, task_ids, *, stop_event, queue_id=None,
|
|||||||
return TaskQueueResult(token, tuple(TaskQueueEntry(item, state['entries'][item]['state'],
|
return TaskQueueResult(token, tuple(TaskQueueEntry(item, state['entries'][item]['state'],
|
||||||
state['entries'][item]['message']) for item in ids), paused, current, verification or None)
|
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):
|
def run_project(item, *, problems=False):
|
||||||
row = state['entries'][item]
|
row = state['entries'][item]
|
||||||
previous = row['state']
|
previous = row['state']
|
||||||
@@ -136,32 +140,31 @@ 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)
|
row.update(state=outcome.entries[0].state, message=outcome.entries[0].message, released=True)
|
||||||
if row['state'] == 'blocked':
|
if row['state'] == 'blocked':
|
||||||
record_task_outcome(children[item], item, 'blocked', row['message'])
|
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)
|
verification = (outcome.netlist_verification or {}).get(item)
|
||||||
if verification:
|
if verification:
|
||||||
row['netlist_verification'] = verification
|
row['netlist_verification'] = verification
|
||||||
write_record(path, state)
|
write_record(path, state)
|
||||||
return outcome.paused or row['state'] == 'blocked'
|
return outcome.paused and row['state'] != 'blocked'
|
||||||
except TaskCenterError as error:
|
except TaskCenterError as error:
|
||||||
from .batch_resources import blocking_resources
|
from .batch_resources import resource_blockers
|
||||||
released = getattr(error, 'resources_released', False) is True and not blocking_resources(root)
|
released = ((getattr(error, 'resources_released', False) is True
|
||||||
saved = getattr(error, 'completed_result', None)
|
or getattr(error, 'owned_writers_exited', False) is True)
|
||||||
if (isinstance(saved, TaskQueueResult) and saved.queue_id == child_id
|
and not resource_blockers(service.pending_batch_resources() if hasattr(service, 'pending_batch_resources') else ()))
|
||||||
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.update(state='blocked', message=error.message, released=released)
|
||||||
row['supervisor_batch_id'] = getattr(service, '_last_supervisor_batch_id', None)
|
row['supervisor_batch_id'] = getattr(service, '_last_supervisor_batch_id', None)
|
||||||
protect_interruption(_uncertainty_root(root, children[item], item), 'project_supervisor_failed: ' + error.message)
|
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)
|
||||||
record_task_outcome(children[item], item, 'blocked', 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)
|
write_record(path, state)
|
||||||
return True
|
return not row['released']
|
||||||
except BaseException:
|
except BaseException:
|
||||||
row['state'] = previous if previous in _TERMINAL else 'blocked'
|
row['state'] = previous if previous in _TERMINAL else 'blocked'
|
||||||
write_record(path, state)
|
write_record(path, state)
|
||||||
@@ -194,7 +197,9 @@ def execute_workspace_projects(service, task_ids, *, stop_event, queue_id=None,
|
|||||||
write_record(path, state)
|
write_record(path, state)
|
||||||
continue
|
continue
|
||||||
if row['state'] in _TERMINAL:
|
if row['state'] in _TERMINAL:
|
||||||
if not row['released']:
|
if row['state'] == 'blocked' and not row['released']:
|
||||||
|
if not _released_after_recheck(root, item, row):
|
||||||
|
return result(True, item)
|
||||||
row['released'] = True
|
row['released'] = True
|
||||||
write_record(path, state)
|
write_record(path, state)
|
||||||
continue
|
continue
|
||||||
|
|||||||
@@ -123,139 +123,6 @@ def incident(case):
|
|||||||
run_id=case['run_id'], execution_authorized=True)
|
run_id=case['run_id'], execution_authorized=True)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def confirmed_incident_batch(rule_run, monkeypatch):
|
|
||||||
from dataclasses import replace
|
|
||||||
from dx_productivity.trial_task_center import batch_admission, batch_resources
|
|
||||||
from dx_productivity.trial_task_center.project_isolation import write_sources
|
|
||||||
|
|
||||||
case = rule_run(initial_saved=False, retry_saved=False)
|
|
||||||
service, task_id, run_id, root = (case[key] for key in ('service', 'task_id', 'run_id', 'root'))
|
|
||||||
task, = service.tasks()
|
|
||||||
sibling_id = 'f' * 32
|
|
||||||
sibling = replace(task, task_id=sibling_id, group_position=task.group_position + 1)
|
|
||||||
monkeypatch.setattr(service, 'tasks', lambda: (task, sibling))
|
|
||||||
original_interrupted = service.has_interrupted_quick_run
|
|
||||||
held = {'value': True}
|
|
||||||
monkeypatch.setattr(service, 'has_interrupted_quick_run',
|
|
||||||
lambda item: held['value'] if item == sibling_id else original_interrupted(item))
|
|
||||||
run = RunJournal(root).get(run_id)
|
|
||||||
project = service.task_context(task_id).project.path
|
|
||||||
manifest = {'schema_version': 1, 'policy_version': batch_admission.POLICY_VERSION, 'scope_kind': 'selected',
|
|
||||||
'group_id': task.group_id, 'candidate_task_ids': [task_id], 'runnable_task_ids': [task_id],
|
|
||||||
'plan_hashes': run['plan_hashes'], 'decisions': [{'task_id': task_id,
|
|
||||||
'classification': 'executable', 'project': str(project), 'write_sources': sorted(write_sources(project, strict=True))}]}
|
|
||||||
batch_resources.write_record(root / 'batch-runs' / run_id / 'manifest.json',
|
|
||||||
dict(manifest, run_id=run_id, manifest_digest=batch_admission._digest(manifest)))
|
|
||||||
return case, held
|
|
||||||
|
|
||||||
|
|
||||||
def test_uncertain_batch_sibling_blocks_incident_before_retry_reservation(confirmed_incident_batch):
|
|
||||||
case, _ = confirmed_incident_batch
|
|
||||||
result = incident(case)
|
|
||||||
assert result['attempts'] == 0
|
|
||||||
assert result['retry_error']['code'] == 'quick_run_uncertain'
|
|
||||||
assert case['calls'] == ['OLD-OK', 'OLD-BAD']
|
|
||||||
assert case['service'].execution_problems(case['task_id'])[0]['auto_retries'] == 0
|
|
||||||
|
|
||||||
|
|
||||||
def test_cleared_sibling_does_not_reopen_a_batch_paused_for_verification(confirmed_incident_batch):
|
|
||||||
case, held = confirmed_incident_batch
|
|
||||||
held['value'] = False
|
|
||||||
journal = RunJournal(case['root'])
|
|
||||||
run = journal.get(case['run_id'])
|
|
||||||
journal.finish(case['run_id'], dict(run['result'], status='blocked', paused=True))
|
|
||||||
result = incident(case)
|
|
||||||
assert result['attempts'] == 0
|
|
||||||
assert result['retry_error']['code'] == 'quick_run_uncertain'
|
|
||||||
assert case['calls'] == ['OLD-OK', 'OLD-BAD']
|
|
||||||
|
|
||||||
|
|
||||||
def test_missing_confirmed_manifest_cannot_fall_back_to_legacy_retry(confirmed_incident_batch):
|
|
||||||
case, held = confirmed_incident_batch
|
|
||||||
held['value'] = False
|
|
||||||
root, run_id = case['root'], case['run_id']
|
|
||||||
folder = root / 'batch-runs' / run_id
|
|
||||||
manifest = json.loads((folder / 'manifest.json').read_bytes())
|
|
||||||
checkpoint = root / 'task-queues' / (run_id + '.json')
|
|
||||||
state = json.loads(checkpoint.read_bytes())
|
|
||||||
checkpoint.write_text(json.dumps(dict(state, manifest_digest=manifest['manifest_digest'])), encoding='utf-8')
|
|
||||||
folder.rename(folder.with_name('copied-evidence'))
|
|
||||||
result = incident(case)
|
|
||||||
assert result['attempts'] == 0
|
|
||||||
assert result['retry_error']['code'] == 'batch_manifest'
|
|
||||||
assert case['calls'] == ['OLD-OK', 'OLD-BAD']
|
|
||||||
|
|
||||||
|
|
||||||
def test_incident_dispatch_failure_exports_original_batch_revision(confirmed_incident_batch, monkeypatch):
|
|
||||||
from dx_productivity.dsh.execution_runs import _republish_incident_batch_summary
|
|
||||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
|
||||||
|
|
||||||
case, held = confirmed_incident_batch
|
|
||||||
held['value'] = False
|
|
||||||
service, task_id, run_id, root = (case[key] for key in ('service', 'task_id', 'run_id', 'root'))
|
|
||||||
journal = RunJournal(root)
|
|
||||||
checkpoint = root / 'task-queues' / (run_id + '.json')
|
|
||||||
folder = root / 'batch-runs' / run_id
|
|
||||||
path = folder / 'batch-receipt.json'
|
|
||||||
manifest = json.loads((folder / 'manifest.json').read_bytes())
|
|
||||||
state = json.loads(checkpoint.read_bytes())
|
|
||||||
checkpoint.write_text(json.dumps(dict(state, manifest_digest=manifest['manifest_digest'])), encoding='utf-8')
|
|
||||||
_republish_incident_batch_summary(service, root, run_id, journal.get(run_id)['result'])
|
|
||||||
previous = json.loads(path.read_bytes())
|
|
||||||
batch_id = '8' * 32
|
|
||||||
dispatched = []
|
|
||||||
|
|
||||||
def failed_dispatch(item, **controls):
|
|
||||||
controls['revalidate']()
|
|
||||||
dispatched.append(item)
|
|
||||||
service._last_supervisor_batch_id = batch_id
|
|
||||||
raise TaskCenterError('supervisor_interrupted', 'worker ended without a durable result')
|
|
||||||
|
|
||||||
monkeypatch.setattr(service, 'execute_quick_run_queue', failed_dispatch)
|
|
||||||
result = incident(case)
|
|
||||||
assert result['retry_error']['code'] == 'supervisor_interrupted'
|
|
||||||
assert dispatched == [task_id]
|
|
||||||
summary = json.loads(path.read_bytes())
|
|
||||||
assert summary['revision'] == previous['revision'] + 1
|
|
||||||
assert summary['stop_reason'] == 'supervisor_interrupted'
|
|
||||||
assert batch_id in summary['resource_batch_ids']
|
|
||||||
|
|
||||||
|
|
||||||
def test_uncertain_batch_sibling_blocks_direct_retry_intent(confirmed_incident_batch):
|
|
||||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
|
||||||
|
|
||||||
case, _ = confirmed_incident_batch
|
|
||||||
service, task_id, run_id, root = (case[key] for key in ('service', 'task_id', 'run_id', 'root'))
|
|
||||||
selected = service.reserve_problem_retry(task_id, source='dsh')
|
|
||||||
service.prepare_failed_quick_run(task_id, operation_keys=selected)
|
|
||||||
journal = RunJournal(root)
|
|
||||||
before = journal.get(run_id)
|
|
||||||
with pytest.raises(TaskCenterError) as caught:
|
|
||||||
journal.begin_retry(service, run_id, task_id, selected)
|
|
||||||
assert caught.value.code == 'quick_run_uncertain'
|
|
||||||
assert journal.get(run_id) == before
|
|
||||||
assert case['calls'] == ['OLD-OK', 'OLD-BAD']
|
|
||||||
|
|
||||||
|
|
||||||
def test_incident_rechecks_sibling_under_dispatch_lease(confirmed_incident_batch, monkeypatch):
|
|
||||||
from dx_productivity.trial_task_center.netlist_verification import NetlistVerification
|
|
||||||
|
|
||||||
case, held = confirmed_incident_batch
|
|
||||||
held['value'] = False
|
|
||||||
before_task = NetlistVerification.before_task
|
|
||||||
|
|
||||||
def expose_interruption(self, *args, **kwargs):
|
|
||||||
result = before_task(self, *args, **kwargs)
|
|
||||||
held['value'] = True
|
|
||||||
return result
|
|
||||||
|
|
||||||
monkeypatch.setattr(NetlistVerification, 'before_task', expose_interruption)
|
|
||||||
result = incident(case)
|
|
||||||
assert result['retry_error']['code'] == 'quick_run_uncertain'
|
|
||||||
assert case['calls'] == ['OLD-OK', 'OLD-BAD']
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize('damage', ['delete', 'tamper'])
|
@pytest.mark.parametrize('damage', ['delete', 'tamper'])
|
||||||
def test_rule_retry_rechecks_failure_proof_without_spending_or_dispatching(rule_run, damage):
|
def test_rule_retry_rechecks_failure_proof_without_spending_or_dispatching(rule_run, damage):
|
||||||
case = rule_run()
|
case = rule_run()
|
||||||
|
|||||||
@@ -1,385 +0,0 @@
|
|||||||
import json
|
|
||||||
from pathlib import Path
|
|
||||||
from threading import Event
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from dx_productivity.dsh import execution_runs
|
|
||||||
from dx_productivity.dsh.run_journal import RunJournal
|
|
||||||
from dx_productivity.trial_task_center import batch_resources
|
|
||||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
|
||||||
from dx_productivity.trial_task_center.logging_setup import configure_logging
|
|
||||||
from dx_productivity.trial_task_center.service import TaskCenterService
|
|
||||||
from dx_productivity.trial_task_center.store import TaskStore
|
|
||||||
from dx_productivity.trial_task_center.task_queue import TaskQueueEntry, TaskQueueResult
|
|
||||||
|
|
||||||
|
|
||||||
RUN_ID = '1' * 32
|
|
||||||
BATCH_ID = '2' * 32
|
|
||||||
TASK_ID = 'a' * 32
|
|
||||||
SKIPPED_ID = 'b' * 32
|
|
||||||
PLAN_HASHES = {TASK_ID: 'a' * 64}
|
|
||||||
|
|
||||||
|
|
||||||
def test_known_manifest_run_cannot_resume_through_legacy_path_when_manifest_is_missing(batch):
|
|
||||||
service, child, data, report, admission = batch
|
|
||||||
journal = RunJournal(data)
|
|
||||||
journal.begin(RUN_ID, [TASK_ID], PLAN_HASHES)
|
|
||||||
batch_resources.write_record(data / 'task-queues' / (RUN_ID + '.json'),
|
|
||||||
{'manifest_digest': admission['manifest_digest']})
|
|
||||||
with pytest.raises(TaskCenterError) as caught:
|
|
||||||
execution_runs.execute_confirmed_run(service, data, [TASK_ID], report, Event(), RUN_ID,
|
|
||||||
resume={'run_id': RUN_ID})
|
|
||||||
assert caught.value.code == 'batch_manifest'
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def batch(tmp_path, monkeypatch):
|
|
||||||
report = {'fingerprint': 'frozen', 'plan_hashes': PLAN_HASHES}
|
|
||||||
admission = {'candidate_task_ids': [SKIPPED_ID, TASK_ID],
|
|
||||||
'runnable_task_ids': [TASK_ID], 'plan_hashes': PLAN_HASHES,
|
|
||||||
'execution_report': report, 'manifest_digest': 'd' * 64, 'policy_version': 1,
|
|
||||||
'candidate_fingerprint': 'f' * 64, 'decisions': [
|
|
||||||
{'task_id': SKIPPED_ID, 'classification': 'skipped', 'message': 'no plan'},
|
|
||||||
{'task_id': TASK_ID, 'classification': 'executable'}]}
|
|
||||||
data = tmp_path / 'data'
|
|
||||||
store = TaskStore(tmp_path / 'tasks.db')
|
|
||||||
service = TaskCenterService(store, configure_logging(data))
|
|
||||||
child_db = tmp_path / 'child.db'
|
|
||||||
child = TaskStore(child_db)
|
|
||||||
service.for_project_task = lambda key: type('Child', (), {'_store': child})()
|
|
||||||
service.task_context = lambda key: type('Context', (), {
|
|
||||||
'task': type('Task', (), {'name': key}), 'progress': type('Progress', (), {
|
|
||||||
'saved_items': 1, 'failed_items': 0, 'no_match_items': 0, 'queue_complete': True}),
|
|
||||||
'interrupted': False})()
|
|
||||||
monkeypatch.setattr(execution_runs.tasks, 'fingerprint', lambda *_: 'frozen')
|
|
||||||
monkeypatch.setattr(execution_runs, 'validate_batch_admission', lambda *_: report)
|
|
||||||
try:
|
|
||||||
yield service, child, data, report, admission
|
|
||||||
finally:
|
|
||||||
child.close()
|
|
||||||
store.close()
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize('resource_state, outcome', [('released', 'completed'), ('isolated', 'paused')])
|
|
||||||
def test_bound_receipt_preserves_verified_result_and_checks_resource_state(batch, monkeypatch, resource_state, outcome):
|
|
||||||
service, child, data, report, admission = batch
|
|
||||||
directory = data / 'batch-runs' / RUN_ID
|
|
||||||
dispatches = []
|
|
||||||
|
|
||||||
def dispatch(current_service, scope, **kwargs):
|
|
||||||
assert json.loads((directory / 'manifest.json').read_bytes())['candidate_task_ids'] == [SKIPPED_ID, TASK_ID]
|
|
||||||
kwargs['revalidate']()
|
|
||||||
dispatches.append(scope)
|
|
||||||
assert RunJournal(data).get(RUN_ID)['task_ids'] == [TASK_ID]
|
|
||||||
with child.transaction():
|
|
||||||
child._connection.execute('INSERT INTO execution_rounds (task_id,round_id) VALUES (?,?)', (TASK_ID, 'round'))
|
|
||||||
child._connection.execute('INSERT INTO execution_operations VALUES (?,?,?,?,?,?,?,?)',
|
|
||||||
(TASK_ID, 'round', 'key', json.dumps({'target_scope': 'targets',
|
|
||||||
'project_path': 'board.prj', 'schematic_name': 'MAIN', 'sheet_number': '1',
|
|
||||||
'target_selectors': 'uid1\x1fR1'}), 'verified', 'a', 1, '{}'))
|
|
||||||
current_service._last_supervisor_batch_id = BATCH_ID
|
|
||||||
record = {'version': 1, 'session_id': BATCH_ID, 'kind': 'task_queue',
|
|
||||||
'generation': 1, 'desktop': 'dx-' + BATCH_ID, 'state': resource_state, 'processes': [],
|
|
||||||
'cad_pid': None, 'cad_guid': None, 'checkpoints': {}, 'retries': {}, 'timings': [],
|
|
||||||
'release_proof': {'generation': 1, 'desktop_not_acquired': True},
|
|
||||||
'cleanup': {'desktop_not_acquired': True, 'desktop_handle_closed': True,
|
|
||||||
'owned_cleanup_complete': True}}
|
|
||||||
batch_resources.write_record(data / 'batch-resources' / BATCH_ID / 'session.json', record)
|
|
||||||
from dx_productivity.trial_task_center.supervisor_protocol import VERSION
|
|
||||||
batch_resources.write_record(data / 'batch-resources' / BATCH_ID / 'supervisor.json',
|
|
||||||
{'version': VERSION, 'batch_id': BATCH_ID, 'state': 'finished', 'outcome': 'ok',
|
|
||||||
'operation': 'execute_task_queue', 'task_ids': [TASK_ID], 'attempt_id': '3' * 32,
|
|
||||||
'request_sha256': '0' * 64, 'parent_process': {'pid': 1, 'creation_time': 'test'}})
|
|
||||||
return TaskQueueResult(RUN_ID, (TaskQueueEntry(TASK_ID, 'completed'),), False,
|
|
||||||
netlist_verification={TASK_ID: {'status': 'verified', 'verified': True}})
|
|
||||||
|
|
||||||
monkeypatch.setattr(execution_runs, 'execute_task_queue', dispatch)
|
|
||||||
receipt = execution_runs.execute_confirmed_run(service, data, (TASK_ID,), report, Event(),
|
|
||||||
RUN_ID, admission=admission)
|
|
||||||
summary = json.loads((directory / 'batch-receipt.json').read_bytes())
|
|
||||||
assert dispatches == [(TASK_ID,)]
|
|
||||||
assert receipt['summary'] == summary
|
|
||||||
assert summary['manifest_digest'] == admission['manifest_digest']
|
|
||||||
assert summary['operation_counts']['saved'] == 1
|
|
||||||
assert summary['task_counts']['skipped'] == 1
|
|
||||||
assert summary['execution_status'] == 'completed'
|
|
||||||
assert summary['acceptance_status'] == 'verified'
|
|
||||||
assert summary['resource_state'] == resource_state
|
|
||||||
assert summary['status'] == RunJournal(data).get(RUN_ID)['result']['status'] == outcome
|
|
||||||
if resource_state == 'isolated':
|
|
||||||
session = data / 'batch-resources' / BATCH_ID / 'session.json'
|
|
||||||
record = json.loads(session.read_bytes())
|
|
||||||
batch_resources.write_record(session, dict(record, state='released'))
|
|
||||||
execution_runs.recover_batch_receipts(service, data)
|
|
||||||
reconciled = json.loads((directory / 'batch-receipt.json').read_bytes())
|
|
||||||
assert dispatches == [(TASK_ID,)]
|
|
||||||
assert reconciled['revision'] == summary['revision'] + 1
|
|
||||||
assert reconciled['operation_counts'] == summary['operation_counts']
|
|
||||||
assert reconciled['resource_state'] == 'released'
|
|
||||||
assert reconciled['status'] == 'completed'
|
|
||||||
|
|
||||||
|
|
||||||
def test_interrupted_receipt_recovery_after_export_failure_dispatches_once(batch, monkeypatch):
|
|
||||||
service, _, data, report, admission = batch
|
|
||||||
dispatches = []
|
|
||||||
directory = data / 'batch-runs' / RUN_ID
|
|
||||||
atomic_write = batch_resources.write_record
|
|
||||||
|
|
||||||
def dispatch(*args, **kwargs):
|
|
||||||
kwargs['revalidate']()
|
|
||||||
dispatches.append(True)
|
|
||||||
checkpoint = data / 'task-queues' / (RUN_ID + '.json')
|
|
||||||
atomic_write(checkpoint, {'task_ids': [TASK_ID], 'plan_hashes': PLAN_HASHES,
|
|
||||||
'entries': {TASK_ID: {'state': 'blocked', 'message': 'needs save verification'}}})
|
|
||||||
raise TaskCenterError('supervisor_interrupted', 'owner exited')
|
|
||||||
|
|
||||||
def write_failure(path, value):
|
|
||||||
if Path(path).name == 'batch-receipt.json':
|
|
||||||
raise OSError('fixture unavailable')
|
|
||||||
atomic_write(path, value)
|
|
||||||
|
|
||||||
monkeypatch.setattr(execution_runs, 'execute_task_queue', dispatch)
|
|
||||||
monkeypatch.setattr(batch_resources, 'write_record', write_failure)
|
|
||||||
with pytest.raises(TaskCenterError, match='owner exited'):
|
|
||||||
execution_runs.execute_confirmed_run(service, data, (TASK_ID,), report, Event(),
|
|
||||||
RUN_ID, admission=admission)
|
|
||||||
assert not (directory / 'batch-receipt.json').exists()
|
|
||||||
durable = RunJournal(data).batch_summary(RUN_ID)
|
|
||||||
assert durable['reporting_errors'][-1]['code'] == 'batch_receipt_export_unavailable'
|
|
||||||
monkeypatch.setattr(batch_resources, 'write_record', atomic_write)
|
|
||||||
execution_runs.recover_batch_receipts(service, data)
|
|
||||||
summary = json.loads((directory / 'batch-receipt.json').read_bytes())
|
|
||||||
assert dispatches == [True]
|
|
||||||
assert summary == RunJournal(data).batch_summary(RUN_ID)
|
|
||||||
assert summary['task_counts']['blocked'] == 1
|
|
||||||
assert summary['stop_reason'] == 'supervisor_interrupted'
|
|
||||||
|
|
||||||
|
|
||||||
def test_confirmed_scope_change_keeps_manifest_and_records_zero_dispatch(batch, monkeypatch):
|
|
||||||
service, _, data, report, admission = batch
|
|
||||||
directory = data / 'batch-runs' / RUN_ID
|
|
||||||
dispatches = []
|
|
||||||
|
|
||||||
def validate(current_service, frozen):
|
|
||||||
assert json.loads((directory / 'manifest.json').read_bytes())['manifest_digest'] == frozen['manifest_digest']
|
|
||||||
raise TaskCenterError('assistant_stale', 'scope changed')
|
|
||||||
|
|
||||||
def dispatch(*args, **kwargs):
|
|
||||||
kwargs['revalidate']()
|
|
||||||
dispatches.append(True)
|
|
||||||
|
|
||||||
monkeypatch.setattr(execution_runs, 'validate_batch_admission', validate)
|
|
||||||
monkeypatch.setattr(execution_runs, 'execute_task_queue', dispatch)
|
|
||||||
with pytest.raises(TaskCenterError, match='scope changed'):
|
|
||||||
execution_runs.execute_confirmed_run(service, data, (TASK_ID,), report, Event(),
|
|
||||||
RUN_ID, admission=admission)
|
|
||||||
summary = json.loads((directory / 'batch-receipt.json').read_bytes())
|
|
||||||
assert not dispatches
|
|
||||||
assert RunJournal(data).get(RUN_ID) is None
|
|
||||||
assert summary['status'] == 'rejected'
|
|
||||||
assert summary['dispatch_count'] == 0 and summary['queue_id'] is None
|
|
||||||
|
|
||||||
|
|
||||||
def test_restart_rebuilds_summary_after_sqlite_publish_error(batch, monkeypatch):
|
|
||||||
service, _, data, report, admission = batch
|
|
||||||
directory = data / 'batch-runs' / RUN_ID
|
|
||||||
dispatches = []
|
|
||||||
save_summary = RunJournal.save_batch_summary
|
|
||||||
|
|
||||||
def dispatch(*args, **kwargs):
|
|
||||||
kwargs['revalidate']()
|
|
||||||
dispatches.append(True)
|
|
||||||
checkpoint = data / 'task-queues' / (RUN_ID + '.json')
|
|
||||||
batch_resources.write_record(checkpoint, {'task_ids': [TASK_ID], 'plan_hashes': PLAN_HASHES,
|
|
||||||
'entries': {TASK_ID: {'state': 'failed', 'message': 'failed safely'}}})
|
|
||||||
return TaskQueueResult(RUN_ID, (TaskQueueEntry(TASK_ID, 'failed'),), False)
|
|
||||||
|
|
||||||
def fail_summary(*args, **kwargs):
|
|
||||||
raise OSError('fixture unavailable')
|
|
||||||
|
|
||||||
monkeypatch.setattr(RunJournal, 'save_batch_summary', fail_summary)
|
|
||||||
monkeypatch.setattr(execution_runs, 'execute_task_queue', dispatch)
|
|
||||||
receipt = execution_runs.execute_confirmed_run(service, data, (TASK_ID,), report, Event(),
|
|
||||||
RUN_ID, admission=admission)
|
|
||||||
assert receipt['reporting_errors'][-1]['code'] == 'batch_summary_unavailable'
|
|
||||||
assert RunJournal(data).get(RUN_ID)['result']['reporting_errors'] == receipt['reporting_errors']
|
|
||||||
assert not (directory / 'batch-receipt.json').exists()
|
|
||||||
monkeypatch.setattr(RunJournal, 'save_batch_summary', save_summary)
|
|
||||||
execution_runs.recover_batch_receipts(service, data)
|
|
||||||
summary = json.loads((directory / 'batch-receipt.json').read_bytes())
|
|
||||||
assert dispatches == [True]
|
|
||||||
assert summary['task_counts']['failed'] == 1 and summary['status'] == 'failed'
|
|
||||||
assert summary['reporting_errors'][-1]['code'] == 'batch_summary_unavailable'
|
|
||||||
|
|
||||||
|
|
||||||
def _durable_supervisor_result(data, result, *, stopping_reason=None, batch_id=BATCH_ID, resumed=False):
|
|
||||||
from hashlib import sha256
|
|
||||||
from dx_productivity.trial_task_center.supervisor_protocol import VERSION, encode
|
|
||||||
|
|
||||||
directory = data / 'batch-resources' / batch_id
|
|
||||||
attempt_id = '3' * 32
|
|
||||||
request_path = directory / 'request.json'
|
|
||||||
batch_resources.write_record(request_path, {'version': VERSION, 'batch_id': batch_id,
|
|
||||||
'attempt_id': attempt_id, 'root': str(data), 'operation': 'execute_task_queue',
|
|
||||||
'task_ids': [TASK_ID], 'arguments': encode({'task_ids': (TASK_ID,),
|
|
||||||
('queue_id' if resumed else 'checkpoint_id'): RUN_ID,
|
|
||||||
'expected_plan_hashes': PLAN_HASHES, 'manifest_digest': 'd' * 64})})
|
|
||||||
batch_resources.write_record(directory / 'supervisor.json',
|
|
||||||
{'version': VERSION, 'batch_id': batch_id, 'state': 'finished', 'outcome': 'ok',
|
|
||||||
'operation': 'execute_task_queue', 'task_ids': [TASK_ID], 'attempt_id': attempt_id,
|
|
||||||
'started_at': 2 if resumed else 1,
|
|
||||||
'stopping_reason': stopping_reason, 'business_idle_timeout_seconds': 150,
|
|
||||||
'request_sha256': sha256(request_path.read_bytes()).hexdigest(),
|
|
||||||
'parent_process': {'pid': 1, 'creation_time': 'test'}})
|
|
||||||
batch_resources.write_record(directory / 'result.json', {'version': VERSION, 'batch_id': batch_id,
|
|
||||||
'attempt_id': attempt_id, 'generation': 1, 'sequence': 1, 'type': 'result',
|
|
||||||
'payload': {'status': 'ok', 'business_succeeded': True, 'result': encode(result)}})
|
|
||||||
batch_resources.write_record(directory / 'session.json', {'version': 1, 'session_id': batch_id,
|
|
||||||
'kind': 'task_queue', 'generation': 1, 'desktop': 'dx-' + batch_id, 'state': 'released', 'processes': [],
|
|
||||||
'cad_pid': None, 'cad_guid': None, 'checkpoints': {}, 'retries': {}, 'timings': [],
|
|
||||||
'release_proof': {'generation': 1, 'desktop_not_acquired': True},
|
|
||||||
'cleanup': {'desktop_not_acquired': True, 'desktop_handle_closed': True, 'owned_cleanup_complete': True}})
|
|
||||||
|
|
||||||
|
|
||||||
def test_restart_recovers_business_and_netlist_before_first_journal_finish(batch, monkeypatch):
|
|
||||||
service, _, data, _, admission = batch
|
|
||||||
checkpoint = {'task_ids': [TASK_ID], 'plan_hashes': PLAN_HASHES, 'manifest_digest': 'd' * 64,
|
|
||||||
'entries': {TASK_ID: {'state': 'completed', 'message': 'saved'}}}
|
|
||||||
directory = data / 'batch-runs' / RUN_ID
|
|
||||||
batch_resources.write_record(directory / 'manifest.json', dict(admission, run_id=RUN_ID))
|
|
||||||
batch_resources.write_record(data / 'task-queues' / (RUN_ID + '.json'), checkpoint)
|
|
||||||
journal = RunJournal(data)
|
|
||||||
journal.begin(RUN_ID, [TASK_ID], PLAN_HASHES)
|
|
||||||
result = TaskQueueResult(RUN_ID, (TaskQueueEntry(TASK_ID, 'completed', 'saved'),), False,
|
|
||||||
netlist_verification={TASK_ID: {'status': 'verified', 'verified': True}})
|
|
||||||
_durable_supervisor_result(data, result)
|
|
||||||
monkeypatch.setattr(execution_runs, 'execute_task_queue',
|
|
||||||
lambda *args, **kwargs: pytest.fail('receipt recovery dispatched CAD'))
|
|
||||||
execution_runs.recover_batch_receipts(service, data)
|
|
||||||
summary = json.loads((directory / 'batch-receipt.json').read_bytes())
|
|
||||||
assert summary['status'] == 'completed'
|
|
||||||
assert summary['execution_status'] == 'completed'
|
|
||||||
assert summary['acceptance_status'] == 'verified'
|
|
||||||
assert journal.get(RUN_ID)['result']['netlist_verification'] == result.netlist_verification
|
|
||||||
|
|
||||||
|
|
||||||
def test_cleanup_only_stop_reason_resolves_without_replay(batch, monkeypatch):
|
|
||||||
service, _, data, report, admission = batch
|
|
||||||
directory = data / 'batch-runs' / RUN_ID
|
|
||||||
|
|
||||||
def dispatch(*args, **kwargs):
|
|
||||||
kwargs['revalidate']()
|
|
||||||
result = TaskQueueResult(RUN_ID, (TaskQueueEntry(TASK_ID, 'completed', 'saved'),), False,
|
|
||||||
netlist_verification={TASK_ID: {'status': 'verified', 'verified': True}})
|
|
||||||
_durable_supervisor_result(data, result)
|
|
||||||
session = data / 'batch-resources' / BATCH_ID / 'session.json'
|
|
||||||
batch_resources.write_record(session, dict(json.loads(session.read_bytes()), state='isolated'))
|
|
||||||
raise batch_resources.BatchResourceCleanupError('resources held', completed_result=result)
|
|
||||||
|
|
||||||
monkeypatch.setattr(execution_runs, 'execute_task_queue', dispatch)
|
|
||||||
with pytest.raises(batch_resources.BatchResourceCleanupError):
|
|
||||||
execution_runs.execute_confirmed_run(service, data, (TASK_ID,), report, Event(),
|
|
||||||
RUN_ID, admission=admission)
|
|
||||||
summary = json.loads((directory / 'batch-receipt.json').read_bytes())
|
|
||||||
assert summary['stop_reason'] == 'resource_pending'
|
|
||||||
assert summary['status'] == 'paused'
|
|
||||||
session = data / 'batch-resources' / BATCH_ID / 'session.json'
|
|
||||||
batch_resources.write_record(session, dict(json.loads(session.read_bytes()), state='released'))
|
|
||||||
execution_runs.recover_batch_receipts(service, data)
|
|
||||||
summary = json.loads((directory / 'batch-receipt.json').read_bytes())
|
|
||||||
assert summary['stop_reason'] is None and summary['status'] == 'completed'
|
|
||||||
|
|
||||||
|
|
||||||
def test_bound_incident_retry_refreshes_original_receipt(batch):
|
|
||||||
service, _, data, _, admission = batch
|
|
||||||
directory = data / 'batch-runs' / RUN_ID
|
|
||||||
batch_resources.write_record(directory / 'manifest.json', dict(admission, run_id=RUN_ID))
|
|
||||||
journal = RunJournal(data)
|
|
||||||
journal.begin(RUN_ID, [TASK_ID], PLAN_HASHES)
|
|
||||||
receipt = {'status': 'failed', 'execution_status': 'failed', 'queue_id': RUN_ID,
|
|
||||||
'entries': [{'task_id': TASK_ID, 'state': 'failed', 'message': 'retry failed safely'}]}
|
|
||||||
journal.finish(RUN_ID, receipt)
|
|
||||||
execution_runs._republish_incident_batch_summary(service, data, RUN_ID, receipt)
|
|
||||||
readback = json.loads((directory / 'batch-receipt.json').read_bytes())
|
|
||||||
assert readback['manifest_digest'] == 'd' * 64
|
|
||||||
assert readback['task_counts']['failed'] == readback['task_counts']['skipped'] == 1
|
|
||||||
|
|
||||||
|
|
||||||
def test_current_lookup_problem_codes_are_exported(batch):
|
|
||||||
service, child, data, _, admission = batch
|
|
||||||
directory = data / 'batch-runs' / RUN_ID
|
|
||||||
batch_resources.write_record(directory / 'manifest.json', dict(admission, run_id=RUN_ID))
|
|
||||||
journal = RunJournal(data)
|
|
||||||
journal.begin(RUN_ID, [TASK_ID], PLAN_HASHES)
|
|
||||||
with child.transaction():
|
|
||||||
child._connection.execute('INSERT INTO execution_rounds (task_id,round_id) VALUES (?,?)', (TASK_ID, 'r'))
|
|
||||||
for index, code in enumerate(('target_not_found', 'lookup_unavailable')):
|
|
||||||
key = str(index)
|
|
||||||
child._connection.execute('INSERT INTO execution_operations VALUES (?,?,?,?,?,?,?,?)',
|
|
||||||
(TASK_ID, 'r', key, '{"target_scope":"all"}', 'failed', 'a', 1, '{}'))
|
|
||||||
child._connection.execute('''INSERT INTO execution_problems
|
|
||||||
(task_id,round_id,problem_key,operation_key,classification,state,code,message,rule_version)
|
|
||||||
VALUES (?,?,?,?,?,?,?,?,?)''', (TASK_ID, 'r', key, key, 'action_required', 'open',
|
|
||||||
code, 'Native lookup report', 'test'))
|
|
||||||
journal.finish(RUN_ID, {'status': 'failed', 'entries': [{'task_id': TASK_ID, 'state': 'failed'}]})
|
|
||||||
execution_runs.recover_batch_receipts(service, data)
|
|
||||||
summary = json.loads((directory / 'batch-receipt.json').read_bytes())
|
|
||||||
assert summary['failure_code_counts'] == {'target_not_found': 1, 'lookup_unavailable': 1}
|
|
||||||
assert {item['code'] for item in summary['operation_failures']} == {'target_not_found', 'lookup_unavailable'}
|
|
||||||
assert all(item['message'] == 'Native lookup report' and item['round_id'] == 'r'
|
|
||||||
for item in summary['operation_failures'])
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize('reason', ['user_pause', 'inactivity'])
|
|
||||||
def test_restart_keeps_supervisor_stop_cause(batch, reason):
|
|
||||||
service, _, data, _, admission = batch
|
|
||||||
checkpoint = {'task_ids': [TASK_ID], 'plan_hashes': PLAN_HASHES, 'manifest_digest': 'd' * 64,
|
|
||||||
'entries': {TASK_ID: {'state': 'paused', 'message': 'paused'}}}
|
|
||||||
directory = data / 'batch-runs' / RUN_ID
|
|
||||||
batch_resources.write_record(directory / 'manifest.json', dict(admission, run_id=RUN_ID))
|
|
||||||
batch_resources.write_record(data / 'task-queues' / (RUN_ID + '.json'), checkpoint)
|
|
||||||
journal = RunJournal(data)
|
|
||||||
journal.begin(RUN_ID, [TASK_ID], PLAN_HASHES)
|
|
||||||
result = TaskQueueResult(RUN_ID, (TaskQueueEntry(TASK_ID, 'paused', 'paused'),), True)
|
|
||||||
_durable_supervisor_result(data, result, stopping_reason=reason)
|
|
||||||
execution_runs.recover_batch_receipts(service, data)
|
|
||||||
summary = json.loads((directory / 'batch-receipt.json').read_bytes())
|
|
||||||
assert summary['stop_reason'] == reason
|
|
||||||
assert journal.get(RUN_ID)['result']['user_pause_requested'] is (reason == 'user_pause')
|
|
||||||
assert summary['resource']['generations'][0]['business_idle_timeout_seconds'] == 150
|
|
||||||
|
|
||||||
|
|
||||||
def test_restart_recovers_new_supervisor_result_after_resumed_run(batch, monkeypatch):
|
|
||||||
service, _, data, _, admission = batch
|
|
||||||
directory = data / 'batch-runs' / RUN_ID
|
|
||||||
checkpoint_path = data / 'task-queues' / (RUN_ID + '.json')
|
|
||||||
checkpoint = {'task_ids': [TASK_ID], 'plan_hashes': PLAN_HASHES, 'manifest_digest': 'd' * 64,
|
|
||||||
'entries': {TASK_ID: {'state': 'paused', 'message': 'first attempt paused'}}}
|
|
||||||
batch_resources.write_record(directory / 'manifest.json', dict(admission, run_id=RUN_ID))
|
|
||||||
batch_resources.write_record(checkpoint_path, checkpoint)
|
|
||||||
journal = RunJournal(data)
|
|
||||||
journal.begin(RUN_ID, [TASK_ID], PLAN_HASHES)
|
|
||||||
_durable_supervisor_result(data, TaskQueueResult(RUN_ID,
|
|
||||||
(TaskQueueEntry(TASK_ID, 'paused', 'first attempt paused'),), True), stopping_reason='user_pause')
|
|
||||||
monkeypatch.setattr(execution_runs, 'execute_task_queue',
|
|
||||||
lambda *args, **kwargs: pytest.fail('receipt recovery dispatched CAD'))
|
|
||||||
execution_runs.recover_batch_receipts(service, data)
|
|
||||||
previous = journal.batch_summary(RUN_ID)
|
|
||||||
assert previous['status'] == 'paused'
|
|
||||||
assert journal.resume(RUN_ID)['result']['summary'] == previous
|
|
||||||
|
|
||||||
new_result = TaskQueueResult(RUN_ID, (TaskQueueEntry(TASK_ID, 'completed', 'resumed and saved'),), False,
|
|
||||||
netlist_verification={TASK_ID: {'status': 'verified', 'verified': True}})
|
|
||||||
_durable_supervisor_result(data, new_result, batch_id='4' * 32, resumed=True)
|
|
||||||
checkpoint.update(entries={TASK_ID: {'state': 'completed', 'message': 'resumed and saved'}},
|
|
||||||
netlist_verification=new_result.netlist_verification)
|
|
||||||
batch_resources.write_record(checkpoint_path, checkpoint)
|
|
||||||
execution_runs.recover_batch_receipts(service, data)
|
|
||||||
|
|
||||||
summary = journal.batch_summary(RUN_ID)
|
|
||||||
assert summary['revision'] == previous['revision'] + 1
|
|
||||||
assert summary['status'] == 'completed' and summary['acceptance_status'] == 'verified'
|
|
||||||
assert summary['stop_reason'] is None
|
|
||||||
assert summary == json.loads((directory / 'batch-receipt.json').read_bytes())
|
|
||||||
assert journal.get(RUN_ID)['result']['netlist_verification'] == new_result.netlist_verification
|
|
||||||
@@ -96,44 +96,27 @@ def test_inspect_accepts_frozen_workspace_checkpoint(project_service):
|
|||||||
assert result['remaining_task_ids'] == ids
|
assert result['remaining_task_ids'] == ids
|
||||||
|
|
||||||
|
|
||||||
def test_inspect_restores_a_determined_resource_pause_only_from_its_original_batch(project_service, monkeypatch):
|
def test_inspect_restores_a_legacy_resource_pause_only_from_its_original_batch(project_service, monkeypatch):
|
||||||
import hashlib
|
from dx_productivity.trial_task_center import task_queue
|
||||||
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
|
service, _, data, ids, hashes = project_service
|
||||||
journal = RunJournal(data)
|
journal = RunJournal(data)
|
||||||
token, batch_id, attempt = 'a' * 32, 'b' * 32, 'c' * 32
|
token, batch_id = 'a' * 32, 'b' * 32
|
||||||
journal.begin(token, ids, hashes)
|
journal.begin(token, ids, hashes)
|
||||||
evidence(service, ids[0])
|
checkpoint(data, token, ids, hashes, {ids[0]: 'blocked'})
|
||||||
checkpoint(data, token, ids, hashes, {ids[0]: 'completed'})
|
|
||||||
path = data / 'task-queues' / (token + '.json')
|
path = data / 'task-queues' / (token + '.json')
|
||||||
state = json.loads(path.read_bytes())
|
state = json.loads(path.read_bytes())
|
||||||
directory = data / 'batch-resources' / batch_id
|
path.write_text(json.dumps(dict(state, phase='primary')), encoding='utf-8')
|
||||||
identity = {'pid': 17, 'creation_time': 'worker'}
|
journal.finish(token, {'status': 'blocked', 'paused': True, 'user_pause_requested': False})
|
||||||
binding = {'version': 1, 'batch_id': batch_id, 'attempt_id': attempt}
|
archive = data / 'batch-resources' / batch_id / 'result.json'
|
||||||
request = dict(binding, operation='execute_task_queue', root=str(data),
|
archive.parent.mkdir(parents=True)
|
||||||
arguments=encode({'task_ids': tuple(ids), 'queue_id': None, 'checkpoint_id': token,
|
archive.touch()
|
||||||
'expected_plan_hashes': hashes, 'manifest_digest': 'e' * 64}))
|
monkeypatch.setattr(task_queue, 'resource_pause_admitted', lambda root, owner, tasks, plan:
|
||||||
batch_resources.write_record(directory / 'request.json', request)
|
TaskQueueResult(token, (), True, ids[0]) if owner == batch_id and tuple(ids) == tasks and hashes == plan else False)
|
||||||
request_digest = hashlib.sha256((directory / 'request.json').read_bytes()).hexdigest()
|
result = journal.inspect(service, token)
|
||||||
batch_resources.write_record(directory / 'supervisor.json', dict(binding,
|
assert result['resource_batch_id'] == batch_id
|
||||||
operation='execute_task_queue', task_ids=ids, state='finished', process=identity,
|
assert result['isolated_task_ids'] == ids[:1]
|
||||||
parent_process=identity, request_sha256=request_digest))
|
assert result['remaining_task_ids'] == ids[1:]
|
||||||
paused = TaskQueueResult(token, tuple(TaskQueueEntry(item, row['state'])
|
journal.finish(token, {'status': 'blocked', 'paused': True, 'user_pause_requested': True})
|
||||||
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
|
assert journal.inspect(service, token)['resource_batch_id'] is None
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -798,50 +798,6 @@ Require QP_App.UndoCount=0,"launch failure invoked undo"
|
|||||||
''', routines_transform=replace_shell)
|
''', 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):
|
def test_main_continues_after_zero_match_without_calling_native_helper(tmp_path):
|
||||||
run_vbs(tmp_path, 'preserve', r'''
|
run_vbs(tmp_path, 'preserve', r'''
|
||||||
QP_Fso.DeleteFile SnapshotPath
|
QP_Fso.DeleteFile SnapshotPath
|
||||||
|
|||||||
@@ -1,248 +0,0 @@
|
|||||||
"""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]
|
|
||||||
@@ -9,16 +9,11 @@ from dx_productivity.trial_task_center.stop_control import StopControl
|
|||||||
|
|
||||||
@pytest.mark.parametrize('batch', [False, True])
|
@pytest.mark.parametrize('batch', [False, True])
|
||||||
@pytest.mark.parametrize('change', ['worker', 'stop', 'closing', 'task', 'dirty', 'dialog'])
|
@pytest.mark.parametrize('change', ['worker', 'stop', 'closing', 'task', 'dirty', 'dialog'])
|
||||||
def test_confirmation_rechecks_admission_before_authorizing_or_replacing_controls(ui, monkeypatch, qtbot, batch, change):
|
def test_confirmation_rechecks_admission_before_authorizing_or_replacing_controls(ui, monkeypatch, batch, change):
|
||||||
window = ui.window
|
window = ui.window
|
||||||
ui.settle()
|
ui.settle()
|
||||||
submitted = []
|
submitted = []
|
||||||
original_run_async = window._run_async
|
monkeypatch.setattr(window, '_run_async', lambda *args, **kwargs: submitted.append(args))
|
||||||
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_task = window._task_id
|
||||||
original_authorization = set(window._dsh_authorized_tasks)
|
original_authorization = set(window._dsh_authorized_tasks)
|
||||||
original_dialog = window._dsh_operations.dialog
|
original_dialog = window._dsh_operations.dialog
|
||||||
@@ -27,9 +22,7 @@ def test_confirmation_rechecks_admission_before_authorizing_or_replacing_control
|
|||||||
live_worker = object()
|
live_worker = object()
|
||||||
live_run = {'active': True, 'run_id': 'already-running', 'task_id': 'other-owner'}
|
live_run = {'active': True, 'run_id': 'already-running', 'task_id': 'other-owner'}
|
||||||
|
|
||||||
confirmation_seen = []
|
|
||||||
def confirm(*_):
|
def confirm(*_):
|
||||||
confirmation_seen.append(True)
|
|
||||||
if change in {'worker', 'stop'}:
|
if change in {'worker', 'stop'}:
|
||||||
window._batch_stop = live_stop
|
window._batch_stop = live_stop
|
||||||
window._dsh_run_stop = live_stop
|
window._dsh_run_stop = live_stop
|
||||||
@@ -49,8 +42,6 @@ def test_confirmation_rechecks_admission_before_authorizing_or_replacing_control
|
|||||||
window._quick_run_confirmer = confirm
|
window._quick_run_confirmer = confirm
|
||||||
try:
|
try:
|
||||||
(window._execute_project_tasks if batch else window._prepare_quick_run)()
|
(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 not submitted, 'stale confirmation must not submit another execution'
|
||||||
assert window._dsh_authorized_tasks == original_authorization
|
assert window._dsh_authorized_tasks == original_authorization
|
||||||
assert '未启动' in window.run_panel.operator_band.text()
|
assert '未启动' in window.run_panel.operator_band.text()
|
||||||
@@ -68,24 +59,17 @@ def test_confirmation_rechecks_admission_before_authorizing_or_replacing_control
|
|||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize('batch', [False, True])
|
@pytest.mark.parametrize('batch', [False, True])
|
||||||
def test_idle_confirmation_still_starts_execution_while_read_query_is_busy(ui, monkeypatch, qtbot, batch):
|
def test_idle_confirmation_still_starts_execution_while_read_query_is_busy(ui, monkeypatch, batch):
|
||||||
window = ui.window
|
window = ui.window
|
||||||
ui.settle()
|
ui.settle()
|
||||||
submitted = []
|
submitted = []
|
||||||
original_run_async = window._run_async
|
monkeypatch.setattr(window, '_run_async', lambda *args, **kwargs: submitted.append(args))
|
||||||
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
|
original_query = window._feedback_query
|
||||||
window._quick_run_confirmer = lambda *_: True
|
window._quick_run_confirmer = lambda *_: True
|
||||||
# A background read is not the mutation/execution lane.
|
# A background read is not the mutation/execution lane.
|
||||||
window._feedback_query = SimpleNamespace(busy=True, invalidate=lambda: None)
|
window._feedback_query = SimpleNamespace(busy=True, invalidate=lambda: None)
|
||||||
try:
|
try:
|
||||||
(window._execute_project_tasks if batch else window._prepare_quick_run)()
|
(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 len(submitted) == 1
|
||||||
assert isinstance(window._batch_stop, StopControl)
|
assert isinstance(window._batch_stop, StopControl)
|
||||||
assert ui.tasks[0].task_id in window._dsh_authorized_tasks
|
assert ui.tasks[0].task_id in window._dsh_authorized_tasks
|
||||||
|
|||||||
@@ -20,7 +20,6 @@ def test_native_preflight_error_is_visible_and_does_not_start_execution(ui, monk
|
|||||||
window._prepare_quick_run()
|
window._prepare_quick_run()
|
||||||
else:
|
else:
|
||||||
window._execute_project_tasks()
|
window._execute_project_tasks()
|
||||||
ui.settle()
|
|
||||||
assert '受控预检异常' in window.run_panel.operator_band.text()
|
assert '受控预检异常' in window.run_panel.operator_band.text()
|
||||||
assert not ui.calls and not window._dsh_authorized_tasks
|
assert not ui.calls and not window._dsh_authorized_tasks
|
||||||
|
|
||||||
|
|||||||
@@ -76,7 +76,6 @@ def test_external_reference_preserves_completed_result_until_resource_only_clean
|
|||||||
assert json.loads(runtime.path.read_text())['state'] == 'isolated'
|
assert json.loads(runtime.path.read_text())['state'] == 'isolated'
|
||||||
log = runtime.path.with_name('resource-release.log').read_text(encoding='utf-8')
|
log = runtime.path.with_name('resource-release.log').read_text(encoding='utf-8')
|
||||||
assert 'isolated' in log
|
assert 'isolated' in log
|
||||||
with pytest.raises(BatchResourceCleanupError):
|
|
||||||
guard_pending_resources(tmp_path)
|
guard_pending_resources(tmp_path)
|
||||||
assert not list(Path(tmp_path).rglob('uncertain.flag'))
|
assert not list(Path(tmp_path).rglob('uncertain.flag'))
|
||||||
assert current_desktop_name() == before
|
assert current_desktop_name() == before
|
||||||
|
|||||||
@@ -1,22 +0,0 @@
|
|||||||
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
|
|
||||||
@@ -1,88 +0,0 @@
|
|||||||
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'] == []
|
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
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
|
|
||||||
@@ -1,85 +0,0 @@
|
|||||||
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()
|
|
||||||
@@ -1,148 +0,0 @@
|
|||||||
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')]
|
|
||||||
@@ -102,7 +102,7 @@ def test_mutex_release_error_preserves_the_durably_returned_lease(tmp_path):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
record = batch_resources.pending_resources(runtime.root)[0]
|
record = batch_resources.pending_resources(runtime.root)[0]
|
||||||
assert record['state'] == 'isolated' and record['blocking'] is True
|
assert record['state'] == 'isolated' and record['blocking'] is False
|
||||||
assert record['cleanup']['desktop_lease']['returned'] is True
|
assert record['cleanup']['desktop_lease']['returned'] is True
|
||||||
assert 'mutex release failed' in record['isolation_warning']
|
assert 'mutex release failed' in record['isolation_warning']
|
||||||
|
|
||||||
@@ -166,7 +166,7 @@ def test_resource_recheck_never_queries_a_reused_desktop_for_a_returned_lease(tm
|
|||||||
def forbidden(*args): pytest.fail('old batch queried the currently leased desktop')
|
def forbidden(*args): pytest.fail('old batch queried the currently leased desktop')
|
||||||
monkeypatch.setattr(isolated_desktop, '_Win32Api', forbidden)
|
monkeypatch.setattr(isolated_desktop, '_Win32Api', forbidden)
|
||||||
warnings = batch_resources.cleanup_pending_resources(runtime.root)
|
warnings = batch_resources.cleanup_pending_resources(runtime.root)
|
||||||
assert warnings and warnings[0]['blocking'] is True
|
assert warnings and warnings[0]['blocking'] is False
|
||||||
next_owner.release(desktop_disappeared=False)
|
next_owner.release(desktop_disappeared=False)
|
||||||
|
|
||||||
|
|
||||||
@@ -193,8 +193,8 @@ def test_transient_return_proof_read_failure_can_be_rechecked_without_permanent_
|
|||||||
monkeypatch.setattr(desktop_slot, 'returned_lease_intact', lambda *args: False)
|
monkeypatch.setattr(desktop_slot, 'returned_lease_intact', lambda *args: False)
|
||||||
assert batch_resources.cleanup_pending_resources(runtime.root)[0]['blocking'] is True
|
assert batch_resources.cleanup_pending_resources(runtime.root)[0]['blocking'] is True
|
||||||
monkeypatch.setattr(desktop_slot, 'returned_lease_intact', original)
|
monkeypatch.setattr(desktop_slot, 'returned_lease_intact', original)
|
||||||
assert batch_resources.cleanup_pending_resources(runtime.root)[0]['blocking'] is True
|
assert batch_resources.cleanup_pending_resources(runtime.root)[0]['blocking'] is False
|
||||||
assert batch_resources.blocking_resources(runtime.root)
|
assert not batch_resources.blocking_resources(runtime.root)
|
||||||
|
|
||||||
|
|
||||||
def test_native_job_creation_failure_is_certified_before_process_creation():
|
def test_native_job_creation_failure_is_certified_before_process_creation():
|
||||||
|
|||||||
@@ -361,7 +361,7 @@ def test_finished_supervisor_label_does_not_hide_a_live_original_process(tmp_pat
|
|||||||
'operation': 'execute_task_queue', 'state': 'finished', 'task_ids': ['A'],
|
'operation': 'execute_task_queue', 'state': 'finished', 'task_ids': ['A'],
|
||||||
'process': {'pid': 20, 'creation_time': 'worker'},
|
'process': {'pid': 20, 'creation_time': 'worker'},
|
||||||
'parent_process': {'pid': 10, 'creation_time': 'parent'}, 'request_sha256': 'f' * 64})
|
'parent_process': {'pid': 10, 'creation_time': 'parent'}, 'request_sha256': 'f' * 64})
|
||||||
monkeypatch.setattr(batch_resources, 'observe_process_identity', lambda identity: {'state': 'alive'})
|
monkeypatch.setattr(batch_resources, '_process_gone', lambda identity: False)
|
||||||
assert pending_supervisors(tmp_path)
|
assert pending_supervisors(tmp_path)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -24,13 +24,13 @@ class ReleasedRuntime:
|
|||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize('released',[False,True])
|
@pytest.mark.parametrize('released',[False,True])
|
||||||
def test_uncertain_project_holds_independent_tasks_regardless_of_writer_exit(tmp_path,released):
|
def test_uncertain_project_only_holds_independent_tasks_until_writers_exit(tmp_path,released):
|
||||||
service=Service(tmp_path,{'A':TaskCenterError('quick_run_uncertain','unknown saved result')})
|
service=Service(tmp_path,{'A':TaskCenterError('quick_run_uncertain','unknown saved result')})
|
||||||
runtime=ReleasedRuntime(tmp_path,released)
|
runtime=ReleasedRuntime(tmp_path,released)
|
||||||
result=execute_task_queue(service,('A','B'),stop_event=Event(),runtime=runtime)
|
result=execute_task_queue(service,('A','B'),stop_event=Event(),runtime=runtime)
|
||||||
assert result.entries[0].state=='blocked'
|
assert result.entries[0].state=='blocked'
|
||||||
assert result.paused
|
assert result.paused is (not released)
|
||||||
assert service.calls==[('start','A')]
|
assert service.calls==([('start','A'),('start','B'),('end','B')] if released else [('start','A')])
|
||||||
assert runtime.release_calls==['quick_run_uncertain']
|
assert runtime.release_calls==['quick_run_uncertain']
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -131,7 +131,7 @@ def test_closed_desktop_rechecks_only_observe_until_external_reference_disappear
|
|||||||
assert runtime.record['state'] == 'isolated'
|
assert runtime.record['state'] == 'isolated'
|
||||||
for _ in range(3):
|
for _ in range(3):
|
||||||
assert cleanup_pending_resources(tmp_path)
|
assert cleanup_pending_resources(tmp_path)
|
||||||
assert batch_resources.blocking_resources(tmp_path)
|
assert not batch_resources.blocking_resources(tmp_path)
|
||||||
assert calls.count('close') == 1
|
assert calls.count('close') == 1
|
||||||
api.present = False
|
api.present = False
|
||||||
assert cleanup_pending_resources(tmp_path) == ()
|
assert cleanup_pending_resources(tmp_path) == ()
|
||||||
|
|||||||
@@ -32,13 +32,13 @@ def runtime_with_residual(tmp_path, monkeypatch, *, confirmation=False):
|
|||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize('confirmation', [False, None])
|
@pytest.mark.parametrize('confirmation', [False, None])
|
||||||
def test_residual_desktop_blocks_fresh_batch_and_never_repeats_close(tmp_path, monkeypatch, confirmation):
|
def test_residual_desktop_is_warning_admits_fresh_batch_and_never_repeats_close(tmp_path, monkeypatch, confirmation):
|
||||||
runtime, calls = runtime_with_residual(tmp_path, monkeypatch, confirmation=confirmation)
|
runtime, calls = runtime_with_residual(tmp_path, monkeypatch, confirmation=confirmation)
|
||||||
runtime.close()
|
runtime.close()
|
||||||
assert runtime.record['state'] == 'isolated'
|
assert runtime.record['state'] == 'isolated'
|
||||||
assert runtime.record['blocking'] is True
|
assert runtime.record['blocking'] is False
|
||||||
assert runtime.record['release_results']['desktop_released'] is False
|
assert runtime.record['release_results']['desktop_released'] is False
|
||||||
assert batch_resources.blocking_resources(tmp_path)
|
assert batch_resources.blocking_resources(tmp_path) == ()
|
||||||
assert batch_resources.pending_resources(tmp_path)[0]['state'] == 'isolated'
|
assert batch_resources.pending_resources(tmp_path)[0]['state'] == 'isolated'
|
||||||
with pytest.raises(batch_resources.BatchResourceCleanupError):
|
with pytest.raises(batch_resources.BatchResourceCleanupError):
|
||||||
runtime._ensure_desktop()
|
runtime._ensure_desktop()
|
||||||
@@ -47,9 +47,8 @@ def test_residual_desktop_blocks_fresh_batch_and_never_repeats_close(tmp_path, m
|
|||||||
confirm_desktop_released=lambda name: (_ for _ in ()).throw(OSError('foreign reference'))))
|
confirm_desktop_released=lambda name: (_ for _ in ()).throw(OSError('foreign reference'))))
|
||||||
batch_resources.cleanup_pending_resources(tmp_path)
|
batch_resources.cleanup_pending_resources(tmp_path)
|
||||||
assert calls == ['close']
|
assert calls == ['close']
|
||||||
with pytest.raises(batch_resources.BatchResourceCleanupError):
|
with batch_runtime.BatchCadRuntime(tmp_path, 'next') as admitted:
|
||||||
with batch_runtime.BatchCadRuntime(tmp_path, 'next'):
|
assert admitted.generation == 0
|
||||||
pytest.fail('an isolated desktop admitted a fresh batch')
|
|
||||||
assert runtime.result == {'completed': True}
|
assert runtime.result == {'completed': True}
|
||||||
|
|
||||||
|
|
||||||
@@ -62,7 +61,7 @@ def test_isolation_proof_is_revalidated_after_restart_and_does_not_trust_label(t
|
|||||||
proof = runtime.record['isolation_proof']
|
proof = runtime.record['isolation_proof']
|
||||||
assert proof['processes'] == [identity]
|
assert proof['processes'] == [identity]
|
||||||
assert proof['session_id'] == runtime.session_id and proof['generation'] == 1
|
assert proof['session_id'] == runtime.session_id and proof['generation'] == 1
|
||||||
assert batch_resources.blocking_resources(tmp_path)
|
assert batch_resources.blocking_resources(tmp_path) == ()
|
||||||
monkeypatch.setattr(batch_resources, '_process_gone', lambda item: False)
|
monkeypatch.setattr(batch_resources, '_process_gone', lambda item: False)
|
||||||
assert batch_resources.blocking_resources(tmp_path)
|
assert batch_resources.blocking_resources(tmp_path)
|
||||||
monkeypatch.setattr(isolated_desktop, '_Win32Api', lambda: SimpleNamespace(confirm_desktop_released=lambda _: None))
|
monkeypatch.setattr(isolated_desktop, '_Win32Api', lambda: SimpleNamespace(confirm_desktop_released=lambda _: None))
|
||||||
@@ -109,7 +108,7 @@ def test_passive_disappearance_confirmation_updates_both_release_state_and_resul
|
|||||||
assert calls == ['close']
|
assert calls == ['close']
|
||||||
|
|
||||||
|
|
||||||
def test_supervisor_preserves_business_evidence_while_desktop_blocks_admission(tmp_path, monkeypatch):
|
def test_supervisor_preserves_success_and_business_failure_with_nonfatal_desktop_warning(tmp_path, monkeypatch):
|
||||||
from dx_productivity.trial_task_center.batch_supervisor import _finish_response
|
from dx_productivity.trial_task_center.batch_supervisor import _finish_response
|
||||||
from dx_productivity.trial_task_center.logging_setup import configure_logging
|
from dx_productivity.trial_task_center.logging_setup import configure_logging
|
||||||
from dx_productivity.trial_task_center.supervisor_protocol import encode, encode_error
|
from dx_productivity.trial_task_center.supervisor_protocol import encode, encode_error
|
||||||
@@ -121,29 +120,25 @@ def test_supervisor_preserves_business_evidence_while_desktop_blocks_admission(t
|
|||||||
journal = {'operation': 'probe', 'batch_id': runtime.session_id}
|
journal = {'operation': 'probe', 'batch_id': runtime.session_id}
|
||||||
result = {'verified': True}
|
result = {'verified': True}
|
||||||
response = {'business_succeeded': True, 'status': 'ok', 'result': encode(result)}
|
response = {'business_succeeded': True, 'status': 'ok', 'result': encode(result)}
|
||||||
with pytest.raises(TaskCenterError) as pending:
|
assert _finish_response(tmp_path, journal, response, configure_logging(tmp_path)) == result
|
||||||
_finish_response(tmp_path, journal, response, configure_logging(tmp_path))
|
assert journal['state'] == 'finished'
|
||||||
assert pending.value.code == 'batch_resources_pending'
|
|
||||||
assert pending.value.completed_result == result
|
|
||||||
assert journal['state'] == 'blocked'
|
|
||||||
assert journal['resource_recheck']['desktop_released'] is False
|
assert journal['resource_recheck']['desktop_released'] is False
|
||||||
response = {'business_succeeded': False, 'status': 'error',
|
response = {'business_succeeded': False, 'status': 'error',
|
||||||
'error': encode_error(TaskCenterError('replacement_uncertain', 'requires verification'))}
|
'error': encode_error(TaskCenterError('replacement_uncertain', 'requires verification'))}
|
||||||
with pytest.raises(TaskCenterError) as caught:
|
with pytest.raises(TaskCenterError) as caught:
|
||||||
_finish_response(tmp_path, journal, response, configure_logging(tmp_path))
|
_finish_response(tmp_path, journal, response, configure_logging(tmp_path))
|
||||||
assert caught.value.code == 'batch_resources_pending'
|
assert caught.value.code == 'replacement_uncertain'
|
||||||
assert caught.value.primary_error.code == 'replacement_uncertain'
|
|
||||||
assert caught.value.resources_released is False and caught.value.owned_writers_exited is True
|
assert caught.value.resources_released is False and caught.value.owned_writers_exited is True
|
||||||
|
|
||||||
|
|
||||||
def test_resource_status_displays_isolation_as_blocking(qtbot):
|
def test_resource_status_displays_isolation_warning_without_blocking(qtbot):
|
||||||
from dx_productivity.trial_task_center.ui.resource_status import ResourceStatus
|
from dx_productivity.trial_task_center.ui.resource_status import ResourceStatus
|
||||||
warning = {'state': 'isolated', 'blocking': False, 'desktop_released': False}
|
warning = {'state': 'isolated', 'blocking': False, 'desktop_released': False}
|
||||||
status = ResourceStatus(lambda: (warning,))
|
status = ResourceStatus(lambda: (warning,))
|
||||||
try:
|
try:
|
||||||
status.refresh()
|
status.refresh()
|
||||||
qtbot.waitUntil(lambda: not status.busy)
|
qtbot.waitUntil(lambda: not status.busy)
|
||||||
assert status.records == (warning,) and status.blocked
|
assert status.records == (warning,) and not status.blocked
|
||||||
status._received((warning, {'state': 'blocked'}))
|
status._received((warning, {'state': 'blocked'}))
|
||||||
assert status.blocked
|
assert status.blocked
|
||||||
finally:
|
finally:
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ def test_normal_supervised_queue_reuses_original_queue_after_resource_pause(tmp_
|
|||||||
ids = ('A', 'B', 'C')
|
ids = ('A', 'B', 'C')
|
||||||
token = 'a' * 32
|
token = 'a' * 32
|
||||||
hashes = dict.fromkeys(ids, 'f' * 64)
|
hashes = dict.fromkeys(ids, 'f' * 64)
|
||||||
result = TaskQueueResult(token, (TaskQueueEntry('A', 'completed'), TaskQueueEntry('B', 'completed'),
|
result = TaskQueueResult(token, (TaskQueueEntry('A', 'completed'), TaskQueueEntry('B', 'blocked'),
|
||||||
TaskQueueEntry('C', 'pending')), True, 'B')
|
TaskQueueEntry('C', 'pending')), True, 'B')
|
||||||
done = TaskQueueResult(token, (result.entries[0], result.entries[1], TaskQueueEntry('C', 'completed')), False)
|
done = TaskQueueResult(token, (result.entries[0], result.entries[1], TaskQueueEntry('C', 'completed')), False)
|
||||||
calls = []
|
calls = []
|
||||||
@@ -42,47 +42,18 @@ def test_normal_supervised_queue_reuses_original_queue_after_resource_pause(tmp_
|
|||||||
assert calls[-1]['expected_plan_hashes'] == hashes
|
assert calls[-1]['expected_plan_hashes'] == hashes
|
||||||
|
|
||||||
|
|
||||||
def test_automatic_resource_continuation_revalidates_before_later_dispatch(tmp_path, monkeypatch):
|
@pytest.mark.parametrize('reason', [None, 'unknown_writer', 'cancel', 'consumed', 'unknown_pause'])
|
||||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
|
||||||
|
|
||||||
ids = ('A', 'B')
|
|
||||||
queue_id = 'a' * 32
|
|
||||||
paused = TaskQueueResult(queue_id, (TaskQueueEntry('A', 'completed'), TaskQueueEntry('B', 'pending')), True, 'A')
|
|
||||||
dispatched, validations = [], []
|
|
||||||
|
|
||||||
def supervise(operation, arguments, **controls):
|
|
||||||
validate = controls.get('revalidate')
|
|
||||||
if validate is not None:
|
|
||||||
validate()
|
|
||||||
dispatched.append(arguments)
|
|
||||||
return paused
|
|
||||||
|
|
||||||
def continuation():
|
|
||||||
validations.append('continuation')
|
|
||||||
raise TaskCenterError('quick_run_uncertain', 'another member now needs verification')
|
|
||||||
|
|
||||||
service = SimpleNamespace(_supervised=True, _logging=SimpleNamespace(root=tmp_path),
|
|
||||||
_supervise=supervise, _last_supervisor_batch_id='b' * 32)
|
|
||||||
monkeypatch.setattr(task_queue, 'resource_pause_admitted', lambda *args, **kwargs: True)
|
|
||||||
with pytest.raises(TaskCenterError, match='quick_run_uncertain'):
|
|
||||||
task_queue.execute_task_queue(service, ids, stop_event=Event(), checkpoint_id=queue_id,
|
|
||||||
revalidate=lambda: validations.append('initial'), continuation_revalidate=continuation)
|
|
||||||
assert validations == ['initial', 'continuation']
|
|
||||||
assert len(dispatched) == 1 and dispatched[0]['checkpoint_id'] == queue_id
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize('reason', [None, 'unknown_writer', 'cancel', 'consumed', 'unknown_pause', 'uncertain'])
|
|
||||||
def test_original_receipt_must_prove_resource_pause_and_cannot_be_consumed_again(tmp_path, monkeypatch, reason):
|
def test_original_receipt_must_prove_resource_pause_and_cannot_be_consumed_again(tmp_path, monkeypatch, reason):
|
||||||
from dx_productivity.trial_task_center import batch_resources
|
from dx_productivity.trial_task_center import batch_resources
|
||||||
|
|
||||||
batch_id, attempt, queue = 'b' * 32, 'c' * 32, 'a' * 32
|
batch_id, attempt, queue = 'b' * 32, 'c' * 32, 'a' * 32
|
||||||
ids, hashes = ('A', 'B'), {'A': '01', 'B': '02'}
|
ids, hashes = ('A', 'B'), {'A': '01', 'B': '02'}
|
||||||
entries = (TaskQueueEntry('A', 'completed'), TaskQueueEntry('B', 'pending'))
|
entries = (TaskQueueEntry('A', 'blocked'), TaskQueueEntry('B', 'pending'))
|
||||||
result = TaskQueueResult(queue, entries, True, 'A')
|
result = TaskQueueResult(queue, entries, True, 'A')
|
||||||
folder = tmp_path / 'batch-resources' / batch_id
|
folder = tmp_path / 'batch-resources' / batch_id
|
||||||
request = {'batch_id': batch_id, 'attempt_id': attempt, 'operation': 'execute_task_queue', 'root': str(tmp_path),
|
request = {'batch_id': batch_id, 'attempt_id': attempt, 'operation': 'execute_task_queue', 'root': str(tmp_path),
|
||||||
'arguments': encode({'task_ids': ids, 'queue_id': None, 'checkpoint_id': queue,
|
'arguments': encode({'task_ids': ids, 'queue_id': None, 'checkpoint_id': queue,
|
||||||
'expected_plan_hashes': hashes, 'manifest_digest': 'm' * 64})}
|
'expected_plan_hashes': hashes})}
|
||||||
batch_resources.write_record(folder / 'request.json', request)
|
batch_resources.write_record(folder / 'request.json', request)
|
||||||
digest = hashlib.sha256((folder / 'request.json').read_bytes()).hexdigest()
|
digest = hashlib.sha256((folder / 'request.json').read_bytes()).hexdigest()
|
||||||
process = {'pid': 17, 'creation_time': 'worker'}
|
process = {'pid': 17, 'creation_time': 'worker'}
|
||||||
@@ -90,25 +61,18 @@ def test_original_receipt_must_prove_resource_pause_and_cannot_be_consumed_again
|
|||||||
'operation': 'execute_task_queue', 'task_ids': list(ids), 'parent_process': process,
|
'operation': 'execute_task_queue', 'task_ids': list(ids), 'parent_process': process,
|
||||||
'process': process, 'state': 'finished', 'request_sha256': digest})
|
'process': process, 'state': 'finished', 'request_sha256': digest})
|
||||||
payload = {'business_succeeded': True, 'status': 'ok', 'result': encode(result)}
|
payload = {'business_succeeded': True, 'status': 'ok', 'result': encode(result)}
|
||||||
|
if reason != 'unknown_pause':
|
||||||
payload['resource_warning'] = {'state': 'isolated', 'owned_writers_exited': True}
|
payload['resource_warning'] = {'state': 'isolated', 'owned_writers_exited': True}
|
||||||
batch_resources.write_record(folder / 'result.json', {'version': 1, 'batch_id': batch_id, 'attempt_id': attempt,
|
batch_resources.write_record(folder / 'result.json', {'version': 1, 'batch_id': batch_id, 'attempt_id': attempt,
|
||||||
'generation': 1, 'sequence': 1, 'type': 'result', 'payload': payload})
|
'generation': 1, 'sequence': 1, 'type': 'result', 'payload': payload})
|
||||||
state = {'version': 1, 'task_ids': list(ids), 'plan_hashes': hashes, 'phase': 'primary',
|
state = {'version': 1, 'task_ids': list(ids), 'plan_hashes': hashes, 'phase': 'primary',
|
||||||
'manifest_digest': 'm' * 64,
|
|
||||||
'entries': {entry.task_id: {'state': entry.state, 'message': entry.message} for entry in entries}}
|
'entries': {entry.task_id: {'state': entry.state, 'message': entry.message} for entry in entries}}
|
||||||
if reason != 'unknown_pause':
|
|
||||||
state['resource_pause'] = {'task_id': 'A', 'batch_id': batch_id, 'business_determined': True,
|
|
||||||
'manifest_digest': 'm' * 64, 'sources': {'A': ['a.prj'], 'B': ['b.prj']}}
|
|
||||||
if reason == 'consumed':
|
if reason == 'consumed':
|
||||||
state['consumed_resource_pauses'] = {batch_id: 'A'}
|
state['consumed_resource_pauses'] = {batch_id: 'A'}
|
||||||
if reason == 'cancel':
|
if reason == 'cancel':
|
||||||
(folder / 'cancel.json').write_text(json.dumps({'batch_id': batch_id}))
|
(folder / 'cancel.json').write_text(json.dumps({'batch_id': batch_id}))
|
||||||
if reason == 'uncertain':
|
|
||||||
from dx_productivity.trial_task_center.stop_control import protect_interruption
|
|
||||||
protect_interruption(tmp_path / 'tasks' / 'A' / 'quick-run', 'unknown result')
|
|
||||||
batch_resources.write_record(tmp_path / 'task-queues' / (queue + '.json'), state)
|
batch_resources.write_record(tmp_path / 'task-queues' / (queue + '.json'), state)
|
||||||
monkeypatch.setattr(batch_resources, '_process_gone', lambda _: reason != 'unknown_writer')
|
monkeypatch.setattr(batch_resources, '_process_gone', lambda _: reason != 'unknown_writer')
|
||||||
monkeypatch.setattr(batch_resources, 'observe_process_identity', lambda _: {'state': 'gone'})
|
|
||||||
assert task_queue.resource_pause_admitted(tmp_path, batch_id, ids, hashes) == (False if reason else result)
|
assert task_queue.resource_pause_admitted(tmp_path, batch_id, ids, hashes) == (False if reason else result)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -70,11 +70,11 @@ def test_changed_confirmed_plan_is_rejected_before_any_executor(tmp_path):
|
|||||||
assert not service.calls
|
assert not service.calls
|
||||||
|
|
||||||
|
|
||||||
def test_dispatched_error_with_no_no_write_proof_pauses_the_batch(tmp_path):
|
def test_dispatched_error_isolates_the_project_after_its_owned_resources_exit(tmp_path):
|
||||||
service = Service(tmp_path, {'A': TaskCenterError('quick_run_preflight', 'target absent')})
|
service = Service(tmp_path, {'A': TaskCenterError('quick_run_preflight', 'target absent')})
|
||||||
result = execute_task_queue(service, ('A', 'B'), stop_event=Event())
|
result = execute_task_queue(service, ('A', 'B'), stop_event=Event())
|
||||||
assert result.paused and result.entries[0].state == 'blocked'
|
assert not result.paused and result.entries[0].state == 'blocked'
|
||||||
assert service.calls == [('start', 'A')]
|
assert service.calls == [('start', 'A'), ('start', 'B'), ('end', 'B')]
|
||||||
|
|
||||||
|
|
||||||
def test_actual_read_phase_failure_allows_next_project(tmp_path):
|
def test_actual_read_phase_failure_allows_next_project(tmp_path):
|
||||||
@@ -93,12 +93,12 @@ def test_actual_read_phase_failure_allows_next_project(tmp_path):
|
|||||||
assert service.calls == [('start', 'B'), ('end', 'B')]
|
assert service.calls == [('start', 'B'), ('end', 'B')]
|
||||||
|
|
||||||
|
|
||||||
def test_uncertain_result_pauses_before_next_independent_task(tmp_path):
|
def test_uncertain_result_is_quarantined_without_replaying_before_next_independent_task(tmp_path):
|
||||||
service = Service(tmp_path, {'A': TaskCenterError('quick_run_uncertain', 'unknown')})
|
service = Service(tmp_path, {'A': TaskCenterError('quick_run_uncertain', 'unknown')})
|
||||||
result = execute_task_queue(service, ('A', 'B'), stop_event=Event())
|
result = execute_task_queue(service, ('A', 'B'), stop_event=Event())
|
||||||
assert result.paused
|
assert not result.paused
|
||||||
assert result.entries[0].state == 'blocked'
|
assert result.entries[0].state == 'blocked'
|
||||||
assert service.calls == [('start', 'A')]
|
assert service.calls == [('start', 'A'), ('start', 'B'), ('end', 'B')]
|
||||||
|
|
||||||
|
|
||||||
def test_pause_finishes_current_item_and_does_not_start_next_task(tmp_path):
|
def test_pause_finishes_current_item_and_does_not_start_next_task(tmp_path):
|
||||||
|
|||||||
@@ -40,7 +40,6 @@ def test_large_manual_batch_uses_full_lifecycle_confirmation(window, qtbot, tmp_
|
|||||||
return False
|
return False
|
||||||
window._quick_run_confirmer = confirm
|
window._quick_run_confirmer = confirm
|
||||||
window.task_list.queue_button.click()
|
window.task_list.queue_button.click()
|
||||||
qtbot.waitUntil(lambda: bool(confirmations), timeout=5000)
|
|
||||||
assert len(confirmations) == 1
|
assert len(confirmations) == 1
|
||||||
assert confirmations[0][0] == ('batch', 21, 21)
|
assert confirmations[0][0] == ('batch', 21, 21)
|
||||||
assert confirmations[0][1]['enabled_scope'] == 21
|
assert confirmations[0][1]['enabled_scope'] == 21
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
"""Keep legacy workspace checkpoints and enforce batch-wide uncertainty."""
|
"""Frozen parent queue survives one isolated project supervisor failure."""
|
||||||
import json
|
import json
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from threading import Event
|
from threading import Event
|
||||||
@@ -28,7 +28,7 @@ def service_for(tmp_path, monkeypatch, outcomes):
|
|||||||
for_project_task=lambda name: children[name], _supervise=supervise), calls
|
for_project_task=lambda name: children[name], _supervise=supervise), calls
|
||||||
|
|
||||||
|
|
||||||
def test_released_uncertain_A_pauses_before_B_and_retains_parent_order(tmp_path, monkeypatch):
|
def test_released_uncertain_A_isolated_from_B_and_parent_order_retained(tmp_path, monkeypatch):
|
||||||
from dx_productivity.trial_task_center.workspace_execution import execute_workspace_projects
|
from dx_productivity.trial_task_center.workspace_execution import execute_workspace_projects
|
||||||
failure = TaskCenterError('quick_run_uncertain', 'A write uncertain')
|
failure = TaskCenterError('quick_run_uncertain', 'A write uncertain')
|
||||||
failure.resources_released = True
|
failure.resources_released = True
|
||||||
@@ -36,9 +36,10 @@ def test_released_uncertain_A_pauses_before_B_and_retains_parent_order(tmp_path,
|
|||||||
stop = Event()
|
stop = Event()
|
||||||
result = execute_workspace_projects(service, ('A', 'B'), stop_event=stop,
|
result = execute_workspace_projects(service, ('A', 'B'), stop_event=stop,
|
||||||
expected_plan_hashes={'A': 'hash-A', 'B': 'hash-B'}, checkpoint_id='a' * 32)
|
expected_plan_hashes={'A': 'hash-A', 'B': 'hash-B'}, checkpoint_id='a' * 32)
|
||||||
assert [(entry.task_id, entry.state) for entry in result.entries] == [('A', 'blocked'), ('B', 'pending')]
|
assert [(entry.task_id, entry.state) for entry in result.entries] == [('A', 'blocked'), ('B', 'completed')]
|
||||||
assert result.queue_id == 'a' * 32 and result.paused
|
assert result.queue_id == 'a' * 32 and not result.paused
|
||||||
assert [call[1]['task_ids'] for call in calls] == [('A',)]
|
assert [call[1]['task_ids'] for call in calls] == [('A',), ('B',)]
|
||||||
|
assert calls[0][1]['checkpoint_id'] != calls[1][1]['checkpoint_id']
|
||||||
assert not stop.is_set()
|
assert not stop.is_set()
|
||||||
assert json.loads((tmp_path / 'workspace-queues' / (result.queue_id + '.json')).read_text())['task_ids'] == ['A', 'B']
|
assert json.loads((tmp_path / 'workspace-queues' / (result.queue_id + '.json')).read_text())['task_ids'] == ['A', 'B']
|
||||||
|
|
||||||
@@ -69,29 +70,6 @@ def test_missing_release_proof_prevents_B(tmp_path, monkeypatch):
|
|||||||
assert len(calls) == 1
|
assert len(calls) == 1
|
||||||
|
|
||||||
|
|
||||||
def test_legacy_workspace_retains_netlist_for_completed_child_with_pending_resources(tmp_path, monkeypatch):
|
|
||||||
from dx_productivity.trial_task_center.workspace_execution import execute_workspace_projects
|
|
||||||
|
|
||||||
service, calls = service_for(tmp_path, monkeypatch, {'A': 'completed', 'B': 'completed'})
|
|
||||||
supervise = service._supervise
|
|
||||||
report = {'status': 'verified', 'verified': True}
|
|
||||||
|
|
||||||
def pending(operation, arguments, **controls):
|
|
||||||
child = supervise(operation, arguments, **controls)
|
|
||||||
failure = TaskCenterError('batch_resources_pending', 'desktop still held')
|
|
||||||
failure.completed_result = TaskQueueResult(child.queue_id, child.entries, False,
|
|
||||||
netlist_verification={'A': report})
|
|
||||||
raise failure
|
|
||||||
|
|
||||||
service._supervise = pending
|
|
||||||
result = execute_workspace_projects(service, ('A', 'B'), stop_event=Event())
|
|
||||||
assert result.paused and len(calls) == 1
|
|
||||||
assert result.entries[0].state == 'completed'
|
|
||||||
assert result.netlist_verification == {'A': report}
|
|
||||||
path = tmp_path / 'workspace-queues' / (result.queue_id + '.json')
|
|
||||||
assert json.loads(path.read_text(encoding='utf-8'))['entries']['A']['netlist_verification'] == report
|
|
||||||
|
|
||||||
|
|
||||||
def test_resume_skips_terminal_and_blocked_tasks_without_replaying_A(tmp_path, monkeypatch):
|
def test_resume_skips_terminal_and_blocked_tasks_without_replaying_A(tmp_path, monkeypatch):
|
||||||
from dx_productivity.trial_task_center.workspace_execution import execute_workspace_projects
|
from dx_productivity.trial_task_center.workspace_execution import execute_workspace_projects
|
||||||
service, calls = service_for(tmp_path, monkeypatch, {'A': 'failed', 'B': 'completed'})
|
service, calls = service_for(tmp_path, monkeypatch, {'A': 'failed', 'B': 'completed'})
|
||||||
@@ -152,7 +130,7 @@ def test_all_primary_projects_precede_deferred_problem_pass(tmp_path, monkeypatc
|
|||||||
assert json.loads((tmp_path / 'workspace-queues' / (result.queue_id + '.json')).read_text())['phase'] == 'finished'
|
assert json.loads((tmp_path / 'workspace-queues' / (result.queue_id + '.json')).read_text())['phase'] == 'finished'
|
||||||
|
|
||||||
|
|
||||||
def test_resume_after_manual_resource_release_waits_for_reconciliation(tmp_path, monkeypatch):
|
def test_resume_after_manual_resource_release_skips_uncertain_A_and_runs_B(tmp_path, monkeypatch):
|
||||||
from dx_productivity.trial_task_center.workspace_execution import execute_workspace_projects
|
from dx_productivity.trial_task_center.workspace_execution import execute_workspace_projects
|
||||||
from dx_productivity.trial_task_center import batch_resources
|
from dx_productivity.trial_task_center import batch_resources
|
||||||
failure = TaskCenterError('quick_run_uncertain', 'A still owned')
|
failure = TaskCenterError('quick_run_uncertain', 'A still owned')
|
||||||
@@ -168,10 +146,6 @@ def test_resume_after_manual_resource_release_waits_for_reconciliation(tmp_path,
|
|||||||
batch_resources.write_record(tmp_path / 'batch-resources' / batch_id / 'supervisor.json', journal)
|
batch_resources.write_record(tmp_path / 'batch-resources' / batch_id / 'supervisor.json', journal)
|
||||||
monkeypatch.setattr(batch_resources, '_process_gone', lambda identity: True)
|
monkeypatch.setattr(batch_resources, '_process_gone', lambda identity: True)
|
||||||
resumed = execute_workspace_projects(service, ('A', 'B'), stop_event=Event(), queue_id=first.queue_id)
|
resumed = execute_workspace_projects(service, ('A', 'B'), stop_event=Event(), queue_id=first.queue_id)
|
||||||
assert resumed.paused and resumed.current_task_id == 'A'
|
|
||||||
assert [call[1]['task_ids'][0] for call in calls] == ['A']
|
|
||||||
(tmp_path / 'tasks' / 'A' / 'quick-run' / 'uncertain.flag').unlink()
|
|
||||||
resumed = execute_workspace_projects(service, ('A', 'B'), stop_event=Event(), queue_id=first.queue_id)
|
|
||||||
assert not resumed.paused
|
assert not resumed.paused
|
||||||
assert [call[1]['task_ids'][0] for call in calls] == ['A', 'B']
|
assert [call[1]['task_ids'][0] for call in calls] == ['A', 'B']
|
||||||
assert [entry.state for entry in resumed.entries] == ['blocked', 'completed']
|
assert [entry.state for entry in resumed.entries] == ['blocked', 'completed']
|
||||||
|
|||||||
Reference in new issue
Block a user