From c25db8ca25884c339b169facace4b0001c26434e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=98=BF=E7=99=BD=E5=8F=94?= <11794527+absfan@user.noreply.gitee.com> Date: Mon, 30 Nov 2026 10:45:12 +0800 Subject: [PATCH] fix: complete audit 657 recovery and batch regression contracts --- .../2026-11-30-pr47-audit657-remediation.md | 167 ++++++++++++++ .../2026-11-30-issue44-upgrade-notes.md | 28 +++ .../2026-11-30-pr47-audit657-acceptance.md | 48 ++++ src/dx_productivity/dsh/execution_runs.py | 23 +- .../trial_task_center/batch_admission.py | 41 ++-- .../trial_task_center/batch_resources.py | 37 ++- .../trial_task_center/batch_runtime.py | 6 +- .../trial_task_center/batch_summary.py | 42 +++- .../trial_task_center/batch_supervisor.py | 10 + .../trial_task_center/desktop_slot.py | 54 +++++ .../trial_task_center/isolated_desktop.py | 3 + .../trial_task_center/task_archive.py | 25 +- .../trial_task_center/task_queue.py | 45 +++- .../trial_task_center/ui/main_window.py | 29 ++- .../trial_task_center/ui/run_panel.py | 2 +- .../trial_task_center/ui/task_list.py | 3 + .../trial_task_center/worker_monitor.py | 21 +- tests/dsh/test_pr47_audit657_receipts.py | 201 ++++++++++++++++ tests/dsh/test_pr47_audit_receipts.py | 15 +- tests/ui/test_pr47_audit657_ui.py | 74 ++++++ tests/ui/test_trial_task_center_workflow.py | 6 +- tests/v1_1/test_bom_pending.py | 10 +- tests/v1_1/test_multi_project_regression.py | 6 +- tests/v1_1/test_nonblocking_acceptance.py | 20 +- tests/v1_1/test_pr47_audit657_archive.py | 51 ++++ tests/v1_1/test_pr47_audit657_resources.py | 217 ++++++++++++++++++ tests/v1_1/test_pr47_audit657_stall.py | 101 ++++++++ tests/v1_1/test_project_session_health.py | 15 +- tests/v1_1/test_target_cell_rules.py | 1 + tools/measure_task_queue.py | 13 +- 30 files changed, 1238 insertions(+), 76 deletions(-) create mode 100644 docs/superpowers/plans/2026-11-30-pr47-audit657-remediation.md create mode 100644 docs/testing/2026-11-30-issue44-upgrade-notes.md create mode 100644 docs/testing/2026-11-30-pr47-audit657-acceptance.md create mode 100644 tests/dsh/test_pr47_audit657_receipts.py create mode 100644 tests/ui/test_pr47_audit657_ui.py create mode 100644 tests/v1_1/test_pr47_audit657_archive.py create mode 100644 tests/v1_1/test_pr47_audit657_resources.py create mode 100644 tests/v1_1/test_pr47_audit657_stall.py diff --git a/docs/superpowers/plans/2026-11-30-pr47-audit657-remediation.md b/docs/superpowers/plans/2026-11-30-pr47-audit657-remediation.md new file mode 100644 index 0000000..403eae2 --- /dev/null +++ b/docs/superpowers/plans/2026-11-30-pr47-audit657-remediation.md @@ -0,0 +1,167 @@ +# PR #47 最新审计整改方案 + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [x]`) syntax for tracking. + +**Goal:** 同步残余测试契约,并补齐资源、历史任务和回执的安全恢复通道。 + +**Architecture:** 继续使用现有队列、DesktopSlot、RunJournal、归档和诊断接口。先修复测试与测量工具的旧契约,再修复证据恢复;不增加执行器,不通过删除保护记录解除阻断。 + +**Tech Stack:** Python、SQLite、PySide6/pytest-qt、Windows Desktop/Job/Mutex、pytest。 + +**Spec:** [Issue #44 已确认设计](../specs/2026-11-27-issue44-batch-remediation-design.md)。审计输入:[评论 657](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/pulls/47#issuecomment-657)、[评论 651](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/pulls/47#issuecomment-651)。 + +## Global Constraints + +- 方案形成时,分析基线与远端 PR HEAD 均为 `2a89d6fdd4196834efb7e95c4bfaf787daa09964`;当时只新增本地方案文件。用户随后授权修复,实施结果另记于 `docs/testing/2026-11-30-pr47-audit657-acceptance.md`。 +- 不可执行配置项在确认清单中说明原因,只执行已确认的合法子集。 +- isolated/unknown 阻断所有新写入,直到物理释放证明成立。 +- 写入结果不确定则暂停整批;释放资源不能代替原工程核验及重新确认。 +- 只验收增量实际功能和直接受影响的回归;不自行重跑默认全量、六卷、100 工程、冻结包或真实 Mentor 换料。 +- 保留 CI 中现有测试,不删除、跳过或放宽断言换取通过。不合并 PR,不关闭 #44。 + +## 核对结论 + +最新评论确认此前 P1-1~P1-6 整改成立,未发现新增 P0/P1。它报告当前默认套件为 14 failed / 2732 passed / 2 errors,其中相对基线新增 5 个失败用例和 1 个 teardown error。这些是审计执行结果,本次未重复该套件,也未宣称 CI 已绿。 + +| 审计项 | 源码核对与根因 | 建议 | +| --- | --- | --- | +| 5 个残余失败 | 两个 UI 用例在异步预检结束前断言;三个场景仍要求写入不确定后继续。BOM 用例还修改 `_tasks` 伪造执行范围,测量工具内部也有旧断言。 | 同步测试、夹具和工具;保留零后继派发、零重放和证据守恒。 | +| P2-1 pending 租约不可恢复 | `batch_resources.py:366` 在观察进程和桌面前直接拒绝。DesktopSlot 的废弃租约接管能力在 acquire 路径内,普通资源重查没有衔接。 | 独立恢复原租约归还证明;不领取新租约,不直接清 pending。 | +| P2-2 历史 completed 被 held | `_completed_acceptance_verified` 要求当前轮次和 DSH 验收关联,旧任务可能缺少这类证据。 | 保留保护,给出缺证据原因和定向安全归档入口;只有原始证据完整才允许建立历史关联。 | +| P2-3 重复工程全局阻断 | 工程身份在分类前登记,重复成员进入全局 blocker。 | 本轮保留:不能因另一别名 completed 而隐藏 held/不确定结果。改善清单说明,不自动任选一个可写别名。 | +| P2-4 缺失执行证据摘要固化 | `execution_runs.py` 同 revision 快捷路径只排除 `batch_snapshot_unstable`,`operation_evidence_missing` 或 round unknown 仍可能只刷新资源。 | 不完整业务证据也进入只读重建;内容未变时保持幂等。 | +| P2-5 未上报预算时回退 150 秒 | 外层只在活动 job 上报预算后采用较长预算。 | 在阻塞操作开始前绑定该操作的有限预算,区分启动和执行阶段。先验证实际未上报区间,不能整体禁用停滞保护。 | +| P2-6 本地零代异常收尾缺口 | 整批 `task_queue` 的 never_acquired 写在正常返回后;事件重试 `service` 已用 ExitStack 处理普通异常,两条路径不一致。 | 整批复用同样的关闭后收尾规则;硬退出、关闭异常仍 unknown。首次 revalidate 失败发生在写绑定之前,不能笼统归因于“revalidate 前异常”。 | +| P2-7 旧队列升级说明 | 属已确认的保护规则。 | 写明中断/隔离且证据不足的旧队列不能自动继续;仍保留有完整证据的确定性安全失败接续。 | +| P2-8 同 stage 计数重置 | ProgressWatch 的业务进展判断不以 total 变化或 done 回退为依据。 | 先核对生产端是否存在合法重复 pass;优先让新 pass 使用新的 current_job_id,不能把心跳或总数抖动无条件当进展。 | +| P2-9 三个 DSH 编码问题 | 评论说明基线也失败,未给本 PR 新回归证据。 | 单独记录环境/编码问题,不计入本轮新增缺陷修复。 | +| P2-10 导出包含工程绝对路径 | `_scrub_text` 会处理用户主目录和凭据,但保留其他工程路径;界面只写“脱敏诊断包”。 | 在导出界面说明仍含工程路径和标识;保留排障证据以及原凭据过滤。 | + +本次仅做了两个无 CAD、无文件修改的时钟反例:同 job/stage 的 total 从 10 变 20、done 仍为 1 时,last_business_progress 保持 1,在 t=151 请求停止;无预算时,外层心跳也不会延长 t=151 的业务停滞期限。这证明机制存在,不等同于已复现真实 CAD 长加载误停。 + +## Task 1:同步 5 个残余用例及测量工具 + +**Files:** `tests/v1_1/test_target_cell_rules.py`、`test_bom_pending.py`、`test_multi_project_regression.py`、`test_nonblocking_acceptance.py`、`test_project_session_health.py`;`tools/measure_task_queue.py`。CI 配置只核对,不修改测试清单。 + +**接口与结果:** 保留生产 `_execute_project_tasks()` 异步生命周期;测量工具 `run_scenario(..., behavior='uncertain_stop')` 输出暂停与真实调用数。 + +- [x] 两个 UI 用例等待确认实际出现且 `_workers` 清空,再核对取消确认后零执行;使用 qtbot 条件等待,不加 sleep。 + +```python +qtbot.waitUntil(lambda: len(confirmations) == 1 and not window._workers) +assert not errors and window._batch_stop is None +``` + +- [x] BOM 用例移除 `_tasks = (...)`,使用数据库中的真实批次;未启用计划的兄弟任务应显示 skipped,确认中保留两个目标和 R2 来源。 +- [x] 同时修测量工具内部与调用测试的 uncertain_stop 期望。当前三工程夹具首项即不确定,预期 1 次调用、0 次已核验模型变更,后两工程未启动。 + +```python +assert report['executed_steps'] == 1 +assert report['changed_components'] == 0 +assert report['result']['paused'] is True +assert [row['state'] for row in report['result']['entries']] == ['blocked', 'pending', 'pending'] +``` + +- [x] 100 UID 用例保留已有 93 verified 和 5 failed,C 的 1 个 UID 不确定后 D 不启动;因此当前夹具预期 99 次调用、1 条 uncertain,而非旧的 100 次调用和 2 条 uncertain。直接恢复原队列不得增加调用数,重开数据库后 93 条 verified 不丢失。 +- [x] 工程源改变用例预期 blocked/pending、只发生第一工程首个 UID 调用,恢复仍不得派发剩余 UID 或下一工程。 +- [x] 仅运行这 5 个受影响节点及必要的同文件正常相邻参数,记录 teardown 是否消失,提交测试/工具同步变更。不得改产品逻辑恢复旧放行。 + +## Task 2:补齐 pending 原租约恢复 + +**Files:** `desktop_slot.py`、`isolated_desktop.py`、`batch_runtime.py`、`batch_resources.py`;`tests/v1_1/test_desktop_slot.py`、`test_pr47_audit_resources.py`。 + +**拟议接口:** `desktop_slot.recover_abandoned_lease(binding: dict) -> dict`,返回与 `returned_lease_intact` 兼容的不可变归还回执。binding 含原 slot 路径、scope、name、lease_id、owner PID/creation_time,并由资源记录绑定 session_id/generation。它只恢复原租约,不调用 acquire 创建新租约。 + +- [x] 先加失主退出后仍被 pending 永久拒绝的反例,与失主 alive/unknown、Job 非空和租约被新 owner 替换的反例。 +- [x] 在取得租约后、允许任何 CAD/worker 派发前持久化原租约绑定;磁盘写入失败不得继续派发。slot 的 lease_id 与资源 generation 是不同身份,不能互相替代。 +- [x] 恢复时取得原命名 Mutex,校验当前登录上下文、slot 和绑定一致;所有原写进程身份明确 gone、所有命名 Job 为空,才能为原 lease 写归还回执。对完整且已存在的历史归还回执直接验证复用,重复执行不覆盖新租约。 +- [x] 新 owner 已取代原 lease 时,不改 slot、不打开或终止新 owner;只有独立的原归还回执可用于原代次。历史记录缺少可验证映射时保留阻断,显示缺失字段及导出指引,不指导删除证据。 +- [x] 归还证明成立后仍独立观察桌面:外部句柄存在则 isolated 并阻断新写入;物理消失且写进程证明完整才 released。lease 恢复本身不核验或重放业务。 + +```python +assert not blocking_resources(root) # 仅原租约可核对、Job 空、桌面物理消失的正例 +assert calls == [] # 恢复过程没有 CAD/换料派发 +``` + +- [x] 运行新反例、原租约幂等/新 owner 保护用例和一个真实 Windows 外部句柄生命周期用例,提交资源恢复变更。 + +## Task 3:给历史 completed 提供安全处置 + +**Files:** `batch_admission.py`、`task_archive.py`、`ui/main_window.py`;`tests/ui/test_pr47_audit_ui.py`、`tests/v1_1/test_task_archive.py`。 + +**拟议接口:** `_completed_acceptance_verified(service, context)` 保持严格布尔契约;另向 admission 决策提供缺失原因。`archive_completed_session(service, *, task_ids=None)` 可选择明确任务子集,默认值保持现有正常关闭行为,结果仍为 ArchiveReport。 + +- [x] 区分缺 DSH 关联、缺当前 round、已有验收失败三种原因,不能把它们都改为 already_completed。 +- [x] held 清单提供查看既有证据和定向安全归档操作;复用现有归档事务、资源阻断和中断保护,软归档保留数据库记录、日志和工程文件。 +- [x] 仅当原报告能同时证明工程、计划、原轮次及独立验收时建立带来源的历史关联;缺替换前基准时不得事后补造。无完整证据则解释限制,允许安全归档后由用户另行建立新的明确任务,不自动重放原换料。 +- [x] 验证归档只影响所选安全历史任务;恢复归档记录后保护仍有效,不确定任务和未释放资源不能归档绕过保护。 + +```python +assert report.archived_ids == (safe_legacy_id,) +assert uncertain_id in report.retained_ids +assert cad_calls == [] +``` + +- [x] 只验证历史证据关联/缺失/失败、定向归档与原归档正常相邻路径,提交历史任务处置变更。 + +## Task 4:重读不完整回执并统一零代收尾 + +**Files:** `dsh/execution_runs.py`、`batch_summary.py`、`task_queue.py`;`tests/dsh/test_pr47_audit_receipts.py`。参考现有 `service.py` 本地重试 ExitStack 行为。 + +- [x] 加两组反例:同 revision 的 operation_evidence_missing 在数据源恢复后仍不重建;本地整批绑定已经写入、generation=0 时遇到普通前置异常,正常关闭后却没有 never_acquired 证明。 +- [x] 同 revision 快捷路径同时排除业务证据缺失和 round unknown,重建只读源;数据仍缺时继续暂停,不推测成功。按源摘要和内容决定是否发布新版本,连续读取同样缺失不反复涨 revision。 +- [x] 保留原 verified、耗时、验收和归属证据;资源恢复与业务证据恢复互不替代,恢复不派发 CAD。 +- [x] 整批采用关闭后收尾规则:绑定已写、runtime 正常退出且 generation=0 才能写 never_acquired;普通业务前置异常可触发收尾,BaseException/硬退出和资源清理失败不得解除 unknown。 + +```python +assert repaired['operation_evidence_missing'] == [] +assert repaired['revision'] == previous['revision'] + 1 +assert second_read['revision'] == repaired['revision'] +assert cad_calls == [] +``` + +- [x] 运行上述新边界,以及已有本地重试普通异常/硬退出和绑定范围变化的直接相邻用例,提交回执恢复变更。 + +## Task 5:核实并修正超时预算和重复阶段进展 + +**Files:** `batch_supervisor.py`、`batch_worker.py`、`worker_monitor.py`,及定位到的实际进度生产端;`tests/v1_1/test_pr47_audit_resources.py`、`tests/v1_1/test_issue44_stall_policy.py`、`tests/trial_task_center/test_worker_monitor.py`。 + +- [x] 先记录启动、加载、保存期间首次活动 job/预算上报的时点,定位无预算的实际区间;保留当前纯时钟机制反例,不能将它写成真实 Mentor 误停结论。 +- [x] 活动阻塞操作开始前传递并验证其有限预算,拒绝 bool、负数、NaN、无穷;外层使用与内层同源的操作预算。缺预算阶段有明确启动边界和有限时限,不靠心跳无限延长,也不把所有阶段统一加大常量。 +- [x] 对同 stage 合法重复 pass 优先复用现有 current_job_id 边界;生产端重置 done 时提供新子作业身份。仅 total 变化、重复帧或序号增长不视作已完成工作。 +- [x] 用模拟时钟覆盖:长预算内不误停、真停滞一次请求停止、无预算启动超时、重复心跳不续命、新 pass 进展有效;先证明真实生产端缺口再改协议,不为假设加新配置面板。 + +```python +assert requests == [] # 已绑定长预算且仍在预算内 +assert requests == ['inactivity'] # 真停滞到期,只请求一次合作停止 +``` + +- [x] 只验收发生变化的预算/进度路径与原合作停止相邻场景,提交明确成立的修正;未证实生产缺口则保留分析和反例,不改状态机。 + +## Task 6:升级说明、重复任务说明和诊断导出提示 + +**Files:** 新增 `docs/testing/2026-11-30-issue44-upgrade-notes.md`;修改 `ui/main_window.py`、`diagnostics_bundle.py`;测试 `tests/ui/test_pr47_audit_ui.py`、`tests/v1_1/test_diagnostics_bundle.py`、`tests/v1_1/test_issue44_batch_bundle.py`。 + +- [x] 说明升级后中断/isolated 且证据不足的旧队列须先核验、重新确认;列出资源释放与业务核验两个步骤,不能概括为所有旧队列都无法继续。 +- [x] 重复工程保持当前阻断规则,清单指出冲突任务和工程身份;只有用户明确重新选定无歧义范围且不存在同批未核验写入,才重新预检。 +- [x] 导出入口写明“已过滤凭据和用户信息,仍含工程路径、任务标识及执行日志”,不虚称全面匿名;保留既有脱敏和允许列表。提示融入现有导出交互,不新增泛化审批流程。 +- [x] 验证可见提示及实际 ZIP 仍过滤凭据、保留必要工程关联。基线编码问题独立记录,不作为本 PR 新增修复计数。 + +## 验收与交付顺序 + +1. Task 1 先解除已知的测试契约不一致,保留 CI 原测试入口。 +2. Task 2、3、4 解决有具体代码证据的恢复缺口,分别增量验收,避免交叉误计。 +3. Task 5 先证实生产触发路径,再决定是否改预算和进度协议;Task 6 与对应功能一起更新说明。 +4. 每项只跑新增反例和直接受影响的正常相邻用例;本次分析不重复审计已经做过的默认全量。最终逐项记录命令、实际 pass/fail 和未验证范围,静态检查修改文件与 git diff --check。 +5. 定向通过只证明相应增量功能;实际 CI 状态需看后续运行结果,不能由本地窄组替代。没有真实现场核验依据,不声明卷四达标,不关闭 #44。 + +## 本方案自审 + +10 项 P2 均有处置:1/2/4/6 有恢复改动,5/8 先证实触发路径,3 保持严格重复保护,7/10 改说明,9 归既有环境问题。五项失败覆盖到测试、夹具和测量工具,没有修改产品安全契约。方案形成时仅新增本文件;后续实施以验收记录为准。 + +## 实施裁决 + +- 旧 pending 缺精确原租约映射时,不靠同名桌面补造证据;新原租约回执必须覆盖所有资源 writer 根,才能补足历史树关闭证明。它不替代桌面物理消失核验。 +- 不自动导入缺来源的历史网表报告。现有严格的计划/轮次/报告关联保留,为缺证据的安全已完成任务提供定向归档替代路径,归档不等于验收通过。 +- 重复阶段在真实 VBS 调用路径成立;采用监控快照 business_sequence 传递已证明进展,保留现有 job/VBS 协议和默认超时,避免为每次重复读取重建执行作业。 +- 复审新增的跨轮次借证据风险纳入 Task 4:回执恢复必须引用原运行绑定的 round_id;未知或冲突身份不能从当前新轮次补造。 diff --git a/docs/testing/2026-11-30-issue44-upgrade-notes.md b/docs/testing/2026-11-30-issue44-upgrade-notes.md new file mode 100644 index 0000000..03c5502 --- /dev/null +++ b/docs/testing/2026-11-30-issue44-upgrade-notes.md @@ -0,0 +1,28 @@ +# Issue #44 升级与恢复说明 + +本次升级保留“写入结果待核验则暂停整批”的保护。不能通过隔离任务、归档任务或清理资源自动跳过未知写入,也不会自动重放原换料。 + +## 旧队列与资源恢复 + +- 中断、隔离且证据不足的旧队列,需要先核验原工程,再重新确认继续。有完整证明的确定性安全失败仍按已有规则接续,不能概括为所有旧队列都禁止恢复。 +- “重试释放资源”只处理资源证据。原租约失主已退出、Job 为空且身份可精确关联时,可恢复该租约的归还证明;同名桌面已经由新 owner 租用时不会操作新 owner。 +- 租约归还与桌面物理释放分别核验。桌面仍被外部句柄持有时保持隔离,并阻断新 CAD 写入。释放成功也不代表原换料结果核验通过。 +- 历史记录缺少可验证的原租约绑定、原进程身份或代次关联时,继续保护并显示具体缺证据原因。请导出诊断保留现场,不删除 session/slot 文件解除保护。 + +## 历史已完成任务 + +旧版本的 completed 状态不能替代当前计划、当前轮次的独立验收。批次清单会区分缺执行轮次、缺匹配运行记录和已有验收未通过,显示查看执行日志与导出诊断的路径。 + +不再参与当前批次的安全历史任务,可在“任务管理 → 归档当前已完成任务”中单独归档。它移至回收站,保留原计划、工程、日志、SQL 执行记录和验收证据;可以恢复。归档不会把未知或失败的验收改成通过,也不会自动建立新一轮换料。 + +存在 prepared、pending_save、uncertain 或未完成作业、中断保护、活动工程和归属未释放资源的任务不会被此入口归档。恢复历史任务后仍使用相同的验收和止写规则。 + +同一工程的重复任务仍会阻断批次。清单指出冲突任务和工程;先核对原任务及其待核验结果,再明确选择无歧义的范围重新预检,不自动任选一个别名执行。 + +## 诊断导出 + +导出会按现有规则过滤凭据、用户名等信息,仍保留工程路径、任务标识、执行日志和资源关联,便于排查现场问题。诊断包不包含原工程文件、中心库、BOM 或完整任务数据库。分享前应了解其中仍有工程相关信息。 + +## 验证范围 + +本轮按增量功能及直接受影响的回归验证。默认全量套件、真实 Mentor 换料、六卷评分、100 工程和冻结包没有重复验收。现场 ETHERNET_1G 原工程与配对报告仍缺,不据此关闭 #44 或声明卷四达标。 diff --git a/docs/testing/2026-11-30-pr47-audit657-acceptance.md b/docs/testing/2026-11-30-pr47-audit657-acceptance.md new file mode 100644 index 0000000..527ed5d --- /dev/null +++ b/docs/testing/2026-11-30-pr47-audit657-acceptance.md @@ -0,0 +1,48 @@ +# PR #47 审计 657:增量修复与验收 + +日期:2026-11-30。修复基线:`2a89d6fdd4196834efb7e95c4bfaf787daa09964`。输入:[评论 657](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/pulls/47#issuecomment-657)、[整改方案](../superpowers/plans/2026-11-30-pr47-audit657-remediation.md)。 + +## 修改结果 + +- 五个残余失败的测试契约及测量工具同步:异步预检按实际完成等待,不再修改 UI 缓存伪造范围;不确定写入暂停整批,后续工程未启动。100 UID 场景保留 93 verified、5 failed,出现一条 uncertain 后停止,D 不派发,调用总数为 99。 +- 原 pending 租约可凭精确 lease/session/generation 绑定恢复不可变归还回执。原 owner 明确退出、命名 Job 为空、原回执覆盖全部 writer 根才可证明进程树关闭;不领取新租约,不操作后来的 owner,不伪造 owned_cleanup_complete。外部桌面句柄仍存在时保持 isolated,句柄关闭并核验消失后才 released。 +- 历史 completed 缺证据时给出缺轮次、缺匹配运行记录、验收未通过等具体原因。“任务管理 → 归档当前已完成任务”只软归档明确选中的安全完成任务;重新检查 SQL pending/prepared/pending_save/uncertain、中断、活动工程和资源归属,保留原计划与证据。 +- 不完整回执会重新读取原业务证据,内容不变不空转增加 revision。整批零代普通异常在正常关闭后补未获取资源证明;BaseException、清理失败和未写入绑定的路径仍保护。 +- 复审发现并关闭跨轮借证据风险:原回执、原持久摘要和原队列检查点一致的轮次身份才可使用;首次发布也不例外。新队列实际执行时记录 round_ids;身份缺失或冲突保持 unknown。历史 SQL 只按原 round 查询,旧验收不能认证后来同计划的新轮;准入也拒绝轮次未知或作业证据缺失的已完成结果。 +- 修复实际重复语义读取阶段被外层最高值忽略的问题:worker 快照提供单调业务序号,真实阶段边界和进展才递增;计数回退、total 抖动、重复快照和心跳不续期。创建进程前先发布有效预算,拒绝非法预算,保留默认超时和原有 120 秒 bootstrap 限期。 +- 补充[升级说明](2026-11-30-issue44-upgrade-notes.md)和导出提示:诊断仍含工程路径与任务标识。导出过滤与 ZIP 格式未改,不重复运行上轮已验收的导出全组。 + +## 定向验证证据 + +以下集合存在交集,不累加为总测试数。除新增反例先复现失败、修复后验证,以及新变更直接影响的相邻场景外,没有重复宽范围验收。 + +| 范围 | 最终证据 | +| --- | --- | +| 原五项失败、测试夹具、测量工具 | 五函数共 10 个不同节点最终通过;含两个 UI 正常参数及 success/failure_continue/pause_resume 正常邻接。真实数据库批次、兄弟任务 skipped、原队列恢复零重放与 SQL/源文件守恒均保留。 | +| 原租约与树关闭证明 | 新反例先 RED;新资源组 10 passed,资源/slot 邻接组 10 passed,实际正常发布/现存活租约 2 passed,最后多 worker/精确绑定/真实 Windows 外部句柄窄组 6 passed。集合有交集。 | +| 归档、历史验收原因及 UI | 归档及原准入/归档邻接组 18 passed;一个测试夹具实际缺 round 而非缺 DSH DB,拆为两种实际缺证据分支后 2 passed。新增“不完整证据不能认证”两反例先 RED,修后连同当前轮次有效验收正例 3 passed。 | +| 回执缺证据、零代及跨轮归属 | 最终 `tests/dsh/test_pr47_audit657_receipts.py`:12 passed。包含原 r1/新 r2、无身份、身份冲突、首次发布缺绑定/缺检查点、幂等重建及正常异常/硬退出/清理失败。 | +| 实际 UI 非监督完成与原回执相邻回归 | 最终 3 passed,14.36 秒。真实两任务顺序、调用数、no-match 及 completed 断言保留。第一次 UI 用例在 5 秒通用 settle 窗口超时,实际日志已经生成 completed;仅该用例增加明确的“预期调用已发生且后台 worker 结束”条件等待,上限 10 秒,不修改产品超时或通用夹具。 | +| 进展与预算 | 新反例先 RED,worker/外层看门狗与原生进度邻接组 14 passed;runtime 实际 JSON 转发单例 1 passed,覆盖 15 个不同节点。 | +| 独立限定复审 | 原租约桥接、归档、异步生命周期、预算及最终轮次绑定复核通过;复审发现的跨轮风险已经关闭,无遗留可确认问题。复审只读,没有另跑宽测试。 | +| 静态检查 | 27 个修改或新增 Python 文件 AST 可解析,修改的 Markdown 空白/代码块检查及 git diff --check 通过。 | + +最后回执及实际 UI 两次命令: + +```powershell +$env:PYTHONPATH = (Resolve-Path src).Path +$env:PYTHONUTF8 = '1' +$env:QT_QPA_PLATFORM = 'offscreen' +$py = 'F:/Sync Tool Skyworth/Work Maps/dxdesigner-part-replacement/.venv/Scripts/python.exe' +& $py -X utf8 -m pytest tests/dsh/test_pr47_audit657_receipts.py tests/ui/test_trial_task_center_workflow.py::test_native_batch_records_complete_order_and_actual_results -q --tb=short +# 12 passed,1 个 UI 条件等待超时;业务日志已完成。 +& $py -X utf8 -m pytest tests/ui/test_trial_task_center_workflow.py::test_native_batch_records_complete_order_and_actual_results tests/dsh/test_pr47_audit_receipts.py::test_recovery_retries_a_previously_unstable_snapshot_at_the_same_revision 'tests/dsh/test_pr47_audit_receipts.py::test_local_manifest_run_completes_from_its_actual_runtime_release[False]' -q --tb=short +# 收紧完成条件、给予该功能用例合理等待窗口后,3 passed。 +``` + +## 支持边界 + +- 缺少精确原租约映射的旧 pending 记录仍保留保护及缺证据诊断,不凭同名桌面收养资源。没有原轮次身份的旧回执也不按当前 SQL 补造归属。 +- 没有原始可证明匹配的历史报告时,不自动导入或补造验收;提供安全归档替代路径,归档不表示验收通过。 +- 没有重跑默认全量,也没有删除/跳过 CI 原有测试。五个已知残余失败的定向通过不能代替整条 CI 的实际运行结果。 +- 未执行真实 Mentor 换料、六卷评分、100 工程或冻结包复测。原 ETHERNET_1G 工程及配对报告仍缺,本 PR 不关闭 #44,不声明卷四达标。 diff --git a/src/dx_productivity/dsh/execution_runs.py b/src/dx_productivity/dsh/execution_runs.py index 33dc9b0..11c04c4 100644 --- a/src/dx_productivity/dsh/execution_runs.py +++ b/src/dx_productivity/dsh/execution_runs.py @@ -370,10 +370,12 @@ def _finish_batch_summary(service, root, journal, manifest, receipt, elapsed): has_run = False try: has_run = journal.get(run_id) is not None + previous_summary = journal.batch_summary(run_id) batch_ids = _receipt_resource_batches(root, manifest, _bound_supervisors(root, manifest), - journal.batch_summary(run_id)) + previous_summary) summary = collect_batch_summary(service, root, manifest, receipt, - batch_ids=batch_ids, elapsed_seconds=elapsed, no_dispatch=not has_run) + batch_ids=batch_ids, elapsed_seconds=elapsed, no_dispatch=not has_run, + prior_summary=previous_summary) if not has_run: summary.update(queue_id=None, dispatch_count=0) summary = _publish_batch_summary(root, journal, summary, receipt, has_run=has_run) @@ -483,8 +485,11 @@ def _recover_batch_receipts(service, root, paths): 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'] + summary_linked = (not running and durable + and receipt.get('summary', {}).get('revision') == durable['revision']) + if (summary_linked and not durable.get('operation_evidence_missing') + and not any(row.get('state') == 'unknown' + for row in durable['source_versions']['rounds'].values()) and not any(row.get('code') == 'batch_snapshot_unstable' for row in durable['reporting_errors'])): refreshed = refresh_batch_resources(root, manifest, durable) @@ -511,7 +516,15 @@ def _recover_batch_receipts(service, root, paths): elapsed = receipt.get('elapsed_seconds', (durable or {}).get('elapsed_seconds', 0)) batch_ids = _receipt_resource_batches(root, manifest, main_batches, durable) summary = collect_batch_summary(service, root, manifest, receipt, elapsed_seconds=elapsed, - batch_ids=batch_ids) + batch_ids=batch_ids, prior_summary=durable) + if summary_linked and summary == {key: value for key, value in durable.items() if key != 'revision'}: + try: + if json.loads(output.read_bytes()) == durable: + continue + except (OSError, ValueError): + pass + batch_resources.write_record(output, durable) + continue _publish_batch_summary(root, journal, summary, receipt, has_run=True) except (OSError, ValueError, KeyError, TypeError, RuntimeError) as error: service._logging.logger.warning('batch_receipt_recovery_unavailable run_id=%s error=%s', diff --git a/src/dx_productivity/trial_task_center/batch_admission.py b/src/dx_productivity/trial_task_center/batch_admission.py index 546a1c4..4dfa1f6 100644 --- a/src/dx_productivity/trial_task_center/batch_admission.py +++ b/src/dx_productivity/trial_task_center/batch_admission.py @@ -14,31 +14,43 @@ POLICY_VERSION = 'issue44-strict-v1' def _completed_acceptance_verified(service, context): + return _completed_acceptance_problem(service, context) is None + + +def _completed_acceptance_problem(service, context): if not context.progress.saved_items: - return True # A certified no-match result requires no saved-netlist acceptance. + return None # A certified no-match result requires no saved-netlist acceptance. from ..dsh.run_journal import RunJournal from .task_queue import _plan_hash task_id = context.task.task_id root = service.layout_settings_path.parent if not (root / 'dsh-state.sqlite3').is_file(): - return False + return 'acceptance_history_missing', '历史结果缺少可关联的运行验收记录。' child = service.for_project_task(task_id) current_hash = _plan_hash(child, task_id) with child._store._lock: current = child._store._connection.execute( 'SELECT round_id FROM execution_rounds WHERE task_id=?', (task_id,)).fetchone() if current is None or not current[0]: - return False + return 'acceptance_round_missing', '已保存结果缺少当前执行轮次,不能沿用历史验收。' for run in RunJournal(root).list_runs(limit=1000): if task_id not in run['task_ids'] or run['plan_hashes'].get(task_id) != current_hash: continue result = run['result'] or {} - known_round = result.get('summary', {}).get('source_versions', {}).get('rounds', {}).get(task_id, {}).get('round_id') - if known_round != current[0]: - return False + summary = result.get('summary') or {} + round_source = summary.get('source_versions', {}).get('rounds', {}).get(task_id, {}) + if (round_source.get('state') == 'unknown' + or task_id in summary.get('operation_evidence_missing', ())): + return 'acceptance_evidence_unavailable', '原运行的轮次或作业证据尚未完整核对,不能认证当前结果。' + if round_source.get('round_id') != current[0]: + return 'acceptance_round_mismatch', '现有验收不属于当前执行轮次。' report = (result.get('netlist_verification') or {}).get(task_id) or {} - return run['status'] != 'running' and report.get('status') == 'verified' and report.get('verified') is True - return False + if run['status'] != 'running' and report.get('status') == 'verified' and report.get('verified') is True: + return None + if report and report.get('status') not in {'unavailable', 'not_required'}: + return 'acceptance_failed', '当前轮次的独立网表验收未通过。' + return 'acceptance_report_missing', '当前轮次缺少完整的独立网表验收。' + return 'acceptance_history_missing', '历史结果缺少与当前计划匹配的运行验收记录。' def resolve_batch_task_ids(tasks, group_id, *, selected_ids=None): @@ -70,7 +82,7 @@ def build_batch_admission(service, task_ids, *, scope_kind): if ids != tuple(task_ids): raise TaskCenterError('batch_scope', '本批成员或顺序已变化,请重新确认。') from .batch_resources import resource_blockers - blockers, decisions, fingerprints, paths, runnable = [], [], [], set(), [] + blockers, decisions, fingerprints, paths, runnable = [], [], [], {}, [] try: if resource_blockers(service.pending_batch_resources()): blockers.append('后台资源尚未确认物理释放,请先重试释放资源。') @@ -96,17 +108,20 @@ def build_batch_admission(service, task_ids, *, scope_kind): path_key = str(context.project.path.resolve(strict=False)).casefold() if path_key in paths: blockers.append('本批重复包含同一个工程,请核对任务绑定。') - row.update(reason_code='project_duplicate', message='工程在本次范围重复。') + row.update(reason_code='project_duplicate', + message=f'与任务“{paths[path_key]}”重复绑定工程:{context.project.path};请核对原任务及待核验结果。') continue - paths.add(path_key) + paths[path_key] = task.name if context.interrupted or task.status is TaskStatus.BLOCKED: row.update(classification='held', reason_code='quick_run_uncertain', message='写入结果待核验,本批暂停。') continue if (task.status is TaskStatus.COMPLETED and context.progress.queue_complete and not context.progress.failed_items): - if not _completed_acceptance_verified(service, context): + problem = _completed_acceptance_problem(service, context) + if problem is not None: row.update(classification='held', reason_code='acceptance_unverified', - message='已保存结果的当前轮次验收未通过或证据不可核验,请先核对。') + acceptance_reason=problem[0], message=problem[1] + + '请查看执行日志或导出诊断;可在“任务管理”中归档当前已完成任务,原结果和证据保留。') blockers.append(f'{task.name}:{row["message"]}') continue row.update(classification='already_completed', reason_code='already_completed', diff --git a/src/dx_productivity/trial_task_center/batch_resources.py b/src/dx_productivity/trial_task_center/batch_resources.py index e759957..64e7c3b 100644 --- a/src/dx_productivity/trial_task_center/batch_resources.py +++ b/src/dx_productivity/trial_task_center/batch_resources.py @@ -164,6 +164,27 @@ def writer_identities(record): return identities +def _lease_writer_trees_closed(record): + """A bound immutable lease return certifies every covered named Job empty.""" + try: + from .desktop_slot import returned_lease_intact + binding = record['desktop_lease_binding'] + receipt = record['cleanup']['desktop_lease'] + if (binding['session_id'] != record['session_id'] or binding['generation'] != record['generation'] + or binding['name'] != record['desktop'] or binding['lease_id'] != receipt['lease_id'] + or binding['scope'] != receipt['scope'] + or not returned_lease_intact(receipt, record['desktop'])): + return False + returned = json.loads(internal_path(receipt['path']).read_bytes()) + if returned['owner'] != binding['owner'] or returned['context'] != binding['context']: + return False + roots = [launch['process'] for launch in returned['launches'] if launch.get('process')] + identities = writer_identities(record) + return bool(identities) and all(identity in roots for identity in identities) + except (OSError, ValueError, KeyError, TypeError, AttributeError): + return False + + def isolation_proof(record): """Certify handle closure and exact writer exit, never a desktop disappearance.""" cleanup = record.get('cleanup') or {} @@ -174,7 +195,7 @@ def isolation_proof(record): if not returned_lease_intact(cleanup['desktop_lease'], record['desktop']): raise ValueError('Managed desktop return proof changed') if (cleanup.get('desktop_handle_closed') is not True - or cleanup.get('owned_cleanup_complete') is not True): + or not (cleanup.get('owned_cleanup_complete') is True or _lease_writer_trees_closed(record))): raise ValueError('Owned resource cleanup is not proven') identities = writer_identities(record) if not all(_process_gone(item) for item in identities): @@ -284,6 +305,8 @@ def _historical_writer_trees_closed(record, path): cleanup = record.get('cleanup') or {} if cleanup.get('owned_cleanup_complete') is True: return True + if _lease_writer_trees_closed(record): + return True if not record.get('processes'): return record.get('cad_pid') is None and record.get('cad_start_requested') is not True if not record.get('cad_process') or record['processes'] != [record['cad_process']]: @@ -363,8 +386,6 @@ def cleanup_pending_resources(root, *, logging_context=None, retry_failed=False) if not record.get('session_id'): continue # Corrupt evidence cannot authorize resource actions. log('started') - if (record.get('cleanup') or {}).get('desktop_lease_pending') is True: - raise ValueError('Managed desktop lease return is not proven') identities = writer_identities(record) cad_identity = record.get('cad_process') if record.get('cad_pid') is not None: @@ -377,6 +398,16 @@ def cleanup_pending_resources(root, *, logging_context=None, retry_failed=False) if not all(_process_gone(item) for item in identities): log('failed', '记录中的进程仍未确认退出') continue + if (record.get('cleanup') or {}).get('desktop_lease_pending') is True: + binding = record.get('desktop_lease_binding') or {} + if (binding.get('session_id') != record['session_id'] + or binding.get('generation') != record['generation'] + or binding.get('name') != record['desktop']): + raise ValueError('缺少本会话和代次的原桌面租约绑定,请保留记录并导出诊断') + from .desktop_slot import recover_abandoned_lease + receipt = recover_abandoned_lease(binding) + record['cleanup'] = dict(record['cleanup'], desktop_lease=receipt, desktop_lease_pending=False) + write_record(path, {key: value for key, value in record.items() if key != 'record_path'}) if not _historical_writer_trees_closed(record, path): log('failed', '缺少历史写入进程树退出证明') continue diff --git a/src/dx_productivity/trial_task_center/batch_runtime.py b/src/dx_productivity/trial_task_center/batch_runtime.py index 59a2364..c0dedb7 100644 --- a/src/dx_productivity/trial_task_center/batch_runtime.py +++ b/src/dx_productivity/trial_task_center/batch_runtime.py @@ -224,6 +224,7 @@ class BatchCadRuntime: blocking=True, isolation_proof=None, stopping_reason='', wait_reason='', primary_error=None, cad_process=None, cad_token=None, cad_shutdown=None, cad_start_requested=False, cleanup=None, + desktop_lease_binding=None, release_rechecks=[], release_state={'mentor': 'not_started', 'desktop': 'pending'}) self.generation = generation @@ -231,6 +232,9 @@ class BatchCadRuntime: LIVE_RESOURCES[str(self.path)] = self started = time.monotonic() try: + if isinstance(self.desktop, PrivateDesktop): + self.desktop.on_lease_acquired = lambda binding: self._save( + desktop_lease_binding=dict(binding, session_id=self.session_id, generation=generation)) self.desktop.__enter__() except Exception: if getattr(self.desktop, '_slot', None) is not None and not self.desktop._slot_acquired: @@ -360,7 +364,7 @@ class BatchCadRuntime: value = json.loads(path.read_text(encoding='utf-8')) if not isinstance(value, dict): return None - return {key: value.get(key) for key in ('job_id', 'stage', 'done', 'total', 'safe_stop', + return {key: value.get(key) for key in ('job_id', 'token', 'business_sequence', 'stage', 'done', 'total', 'safe_stop', 'stop_requested', 'stopping_reason', 'idle_timeout_seconds', 'failure_completion_grace_seconds')} except (OSError, ValueError, TypeError): return None diff --git a/src/dx_productivity/trial_task_center/batch_summary.py b/src/dx_productivity/trial_task_center/batch_summary.py index 2139fef..0feb122 100644 --- a/src/dx_productivity/trial_task_center/batch_summary.py +++ b/src/dx_productivity/trial_task_center/batch_summary.py @@ -137,18 +137,23 @@ def _digest(value): return sha256(json.dumps(value, ensure_ascii=False, sort_keys=True).encode('utf-8')).hexdigest() -def _operation_sources(service, task_ids): +def _operation_sources(service, task_ids, round_ids=None): rows, versions, missing = [], {}, [] for task_id in task_ids: + round_id = round_ids.get(task_id) if round_ids is not None else None try: + if round_ids is not None and not round_id: + raise LookupError('original execution round is not bound') store = service.for_project_task(task_id)._store with store._lock: - round_row = store._connection.execute( + current = store._connection.execute( 'SELECT * FROM execution_rounds WHERE task_id=?', (task_id,)).fetchone() - if not round_row: + if round_ids is None and not current: versions[task_id] = {'round_id': None} continue - round_id = round_row['round_id'] + round_id = round_id or current['round_id'] + is_current = current is not None and current['round_id'] == round_id + round_row = dict(current) if is_current else {'round_id': round_id} raw_rows = [dict(row) for row in store._connection.execute('''SELECT o.*, p.classification, p.auto_retries, p.state AS problem_state, p.code, p.message FROM execution_operations o LEFT JOIN execution_problems p @@ -156,6 +161,8 @@ def _operation_sources(service, task_ids): WHERE o.task_id=? AND o.round_id=? ORDER BY o.operation_key''', (task_id, round_id))] commits = [dict(row) for row in store._connection.execute('''SELECT * FROM execution_project_commits WHERE task_id=? AND round_id=? ORDER BY session_token''', (task_id, round_id))] + if not is_current and not raw_rows and not commits: + raise LookupError('original round evidence is unavailable') task_rows = [] for row in raw_rows: command = json.loads(row['command_json']) @@ -165,7 +172,7 @@ def _operation_sources(service, task_ids): target_keys = () else: target_keys = None - can_retry = (row['state'] == 'failed' and row['classification'] == 'retryable' and row['problem_state'] == 'open' + can_retry = (is_current and row['state'] == 'failed' and row['classification'] == 'retryable' and row['problem_state'] == 'open' and not row['auto_retries'] and command.get('execution_unit') == 'component' and not any(commit['state'] in {'verified', 'pending_save'} for commit in commits)) if can_retry: @@ -176,7 +183,7 @@ def _operation_sources(service, task_ids): 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'} + versions[task_id] = {'state': 'unknown', **({'round_id': round_id} if round_id else {})} missing.append(task_id) return rows, versions, missing @@ -346,7 +353,23 @@ def _resource_source(root, batch_ids, *, manifest, no_dispatch): 'supervisor_outcomes': supervisor_outcomes} -def collect_batch_summary(service, root, manifest, receipt, *, batch_ids, elapsed_seconds, no_dispatch=False): +def _original_rounds(task_ids, checkpoint, receipt, prior_summary): + histories = [summary.get('source_versions', {}).get('rounds', {}) + for summary in (receipt.get('summary') or {}, prior_summary or {})] + bound, conflicts = {}, set() + for task_id in task_ids: + records = [previous.get(task_id, {}) for previous in histories] + candidates = {value for value in [checkpoint.get('round_ids', {}).get(task_id), + *(old.get('round_id') for old in records)] + if isinstance(value, str) and value} + if any(old.get('round_conflict') for old in records) or len(candidates) > 1: + conflicts.add(task_id) + bound[task_id] = next(iter(candidates)) if len(candidates) == 1 and task_id not in conflicts else None + return bound, conflicts + + +def collect_batch_summary(service, root, manifest, receipt, *, batch_ids, elapsed_seconds, no_dispatch=False, + prior_summary=None): """Read versioned sources twice and retry once when writes overlap the read.""" from .netlist_verification import verification_summary @@ -354,8 +377,11 @@ def collect_batch_summary(service, root, manifest, receipt, *, batch_ids, elapse 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) + bound, conflicts = _original_rounds(task_ids, checkpoint, receipt, prior_summary) + rows, rounds, missing = _operation_sources(service, task_ids, bound) + for task_id in conflicts: + rounds[task_id]['round_conflict'] = True resource = _resource_source(root, batch_ids, manifest=manifest, no_dispatch=no_dispatch) return rows, missing, checkpoint, resource, path, error, { 'rounds': rounds, 'checkpoint_digest': checkpoint_digest, 'resource_digest': _digest(resource)} diff --git a/src/dx_productivity/trial_task_center/batch_supervisor.py b/src/dx_productivity/trial_task_center/batch_supervisor.py index f3ebbc3..d4b3988 100644 --- a/src/dx_productivity/trial_task_center/batch_supervisor.py +++ b/src/dx_productivity/trial_task_center/batch_supervisor.py @@ -34,6 +34,7 @@ class BusinessProgressWatch: self.idle_timeout = idle_timeout self.signatures = {} self.stage_progress = {} + self.business_sequences = {} self.worker_stop_requested = False self.stop_requested = False @@ -48,6 +49,15 @@ class BusinessProgressWatch: if (progress.get('job_id') and type(timeout) in (int, float) and 0 < timeout < math.inf): self.idle_timeout = max(self.fallback_idle_timeout, timeout) + token, business_sequence = progress.get('token'), progress.get('business_sequence') + if (isinstance(token, str) and len(token) == 32 + and all(character in '0123456789abcdef' for character in token) + and isinstance(progress.get('job_id'), str) and progress['job_id'] + and type(business_sequence) is int and business_sequence > 0): + binding = (token, progress['job_id']) + if business_sequence > self.business_sequences.get(binding, 0): + self.business_sequences[binding] = business_sequence + self.last_progress = now payload = {key: payload.get(key) for key in ('phase', 'queue', 'active_project')} payload['business_progress'] = {key: progress.get(key) for key in ('job_id', 'stage')} stage = json.dumps(payload, ensure_ascii=True, sort_keys=True, default=str) diff --git a/src/dx_productivity/trial_task_center/desktop_slot.py b/src/dx_productivity/trial_task_center/desktop_slot.py index c317341..3eef6ad 100644 --- a/src/dx_productivity/trial_task_center/desktop_slot.py +++ b/src/dx_productivity/trial_task_center/desktop_slot.py @@ -143,6 +143,54 @@ def observe_current_desktop_name(name): return managed_desktop_disappeared({'scope': slot.scope, 'name': slot.name}) +def recover_abandoned_lease(binding, *, root=None, context=None, backend=None): + """Return only an exactly bound orphan lease, without acquiring a new one.""" + slot = DesktopSlot(root=root, context=context, backend=backend) + try: + if (binding.get('version') != 1 or binding.get('context') != slot.context + or binding.get('scope') != slot.scope or binding.get('name') != slot.name + or canonical_path(binding['path']) != slot.path + or not re.fullmatch('[0-9a-f]{32}', binding.get('lease_id', ''))): + _fail('原桌面租约归属不完整,请导出诊断;保留资源保护。') + return_path = slot.path.parent / 'leases' / (binding['lease_id'] + '.json') + + def receipt(record, raw): + if (record.get('context') != slot.context or record.get('owner') != binding['owner'] + or record.get('lease_id') != binding['lease_id']): + _fail('原桌面租约身份已变化,保留资源保护。') + value = dict(returned=True, name=slot.name, scope=slot.scope, lease_id=binding['lease_id'], + desktop_disappeared=record.get('desktop_disappeared'), path=str(return_path), + sha256=hashlib.sha256(raw).hexdigest()) + if not returned_lease_intact(value, slot.name): + _fail('原桌面租约归还记录不完整,保留资源保护。') + return value + + if internal_path(return_path).exists(): + raw = internal_path(return_path).read_bytes() + return receipt(json.loads(raw), raw) + mutex = slot.backend.lock('Local\\DxPartReplace-Desktop-' + slot.scope) + try: + original = json.loads(internal_path(slot.path).read_bytes()) + if (original.get('lease_id') != binding['lease_id'] + or original.get('owner') != binding['owner']): + _fail('原桌面已由其他租约接替,未操作新的持有者。') + slot._validate(original) + if not slot.backend.process_gone(original['owner']): + _fail('原租约持有者尚未确认退出,保留资源保护。') + returned = dict(original, state='idle', writers_exited=True, + desktop_disappeared=not slot.backend.desktop_exists(slot.name), recovered=True) + write_record(return_path, returned) + write_record(slot.path, returned) + return receipt(returned, internal_path(return_path).read_bytes()) + finally: + slot.backend.unlock(mutex) + except TaskCenterError: + raise + except (OSError, ValueError, KeyError, TypeError, AttributeError) as error: + raise TaskCenterError('desktop_slot_busy', + '无法核对原桌面租约,请保留记录并导出诊断;未解除资源保护。') from error + + class DesktopSlot: def __init__(self, *, root=None, context=None, backend=None): self.context = _context() if context is None else context @@ -164,6 +212,12 @@ class DesktopSlot: write_record(self.path, record) self.record = record + def binding(self): + if self.handle is None or self.receipt is not None: + _fail('桌面租约尚未领取或已经归还。') + return dict(version=1, path=str(self.path), context=dict(self.context), scope=self.scope, + name=self.name, lease_id=self.lease_id, owner=dict(self.record['owner'])) + def _validate(self, record): if (record.get('version') != 1 or record.get('context') != self.context or record.get('name') != self.name or record.get('scope') != self.scope diff --git a/src/dx_productivity/trial_task_center/isolated_desktop.py b/src/dx_productivity/trial_task_center/isolated_desktop.py index 63aa7b7..ca1bf30 100644 --- a/src/dx_productivity/trial_task_center/isolated_desktop.py +++ b/src/dx_productivity/trial_task_center/isolated_desktop.py @@ -605,6 +605,7 @@ class PrivateDesktop: self.cleanup_record = None self._desktop_handle_history = [] self._process_history = [] + self.on_lease_acquired = None def __enter__(self) -> "PrivateDesktop": if not self.enabled: @@ -613,6 +614,8 @@ class PrivateDesktop: self._slot.acquire() self._slot_acquired = True try: + if self._slot is not None and self.on_lease_acquired is not None: + self.on_lease_acquired(self._slot.binding()) self._create() if self._slot is not None and hasattr(self._api, 'validate_desktop_owner'): self._api.validate_desktop_owner(self._handle, self._slot.context['sid']) diff --git a/src/dx_productivity/trial_task_center/task_archive.py b/src/dx_productivity/trial_task_center/task_archive.py index 85cf2d0..d91c65f 100644 --- a/src/dx_productivity/trial_task_center/task_archive.py +++ b/src/dx_productivity/trial_task_center/task_archive.py @@ -1,4 +1,4 @@ -"""Recoverable task-list archival performed only during an opted-in normal close.""" +"""Recoverable archival for normal close and explicit completed-task selection.""" from dataclasses import dataclass from .models import ProjectStatus, TaskStatus @@ -15,14 +15,16 @@ class ArchiveReport: return tuple(task_id for task_id, _ in self.retained) -def archive_completed_session(service): +def archive_completed_session(service, *, task_ids=None): """Soft-delete safe tasks atomically; preserve recovery tasks and all files.""" return service._idle_quick_run_operation('archive_completed_session', None, - lambda: _archive(service)) + lambda: _archive(service, task_ids)) -def _archive(service): +def _archive(service, requested_ids=None): store = service._store + from .errors import TaskCenterError + from .execution_problems import ExecutionProblems from .batch_resources import resource_blockers pending = resource_blockers(service.pending_batch_resources()) owned = set() @@ -36,12 +38,25 @@ def _archive(service): owned.update(task_ids) retained, safe = [], [] with store.transaction(): - for task in store.list_tasks(): + tasks = tuple(store.list_tasks()) + if requested_ids is not None: + selected = tuple(requested_ids) + if (not selected or len(set(selected)) != len(selected) + or not set(selected).issubset(task.task_id for task in tasks)): + raise TaskCenterError('archive_scope', '归档范围已变化,请重新选择已完成任务。') + tasks = tuple(task for task in tasks if task.task_id in selected) + for task in tasks: reason = None + child = service._project_task_service(task.task_id) + problems = ExecutionProblems(child._store).overview(task.task_id) if unknown or task.task_id in owned: reason = '后台资源尚未确认释放;重新打开后使用“重新清理资源”。' + elif requested_ids is not None and task.status is not TaskStatus.COMPLETED: + reason = '当前任务已不处于已完成状态,未归档。' elif task.status in {TaskStatus.RUNNING, TaskStatus.BLOCKED}: reason = '任务仍在执行状态;重新打开后暂停或核验恢复。' + elif problems['uncertain'] or problems['held']: + reason = '仍有未执行或待核验作业,请先核验恢复。' elif any(project.status in {ProjectStatus.CAPTURING_BEFORE, ProjectStatus.AWAITING_OPERATOR, ProjectStatus.CAPTURING_AFTER, ProjectStatus.VERIFYING} for project in store.list_projects(task.task_id)): diff --git a/src/dx_productivity/trial_task_center/task_queue.py b/src/dx_productivity/trial_task_center/task_queue.py index 3fa64a9..fe0111b 100644 --- a/src/dx_productivity/trial_task_center/task_queue.py +++ b/src/dx_productivity/trial_task_center/task_queue.py @@ -1,6 +1,6 @@ """Durable serial scheduling of single-project tasks, above the existing runner.""" -from contextlib import contextmanager +from contextlib import ExitStack, contextmanager from dataclasses import asdict, dataclass, is_dataclass import hashlib import inspect @@ -328,17 +328,32 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event, controls = {'revalidate': continuation_revalidate} if continuation_revalidate is not None else {} arguments = dict(arguments, queue_id=result.queue_id, checkpoint_id=None, resource_batch_id=batch_id) if runtime is None: - from .batch_runtime import BatchCadRuntime + from .batch_runtime import BatchCadRuntime, BatchResourceCleanupError from .batch_resources import write_record token = queue_id or checkpoint_id binding = binding_path = None + binding_written = False def bind_local_session(): + nonlocal binding_written if revalidate is not None: revalidate() write_record(binding_path, binding) + binding_written = True - with BatchCadRuntime(service._logging.root, 'task_queue', stop_event) as owned_runtime: + def finish_local_binding(error_type, _error, _traceback): + orderly = error_type is None or ( + issubclass(error_type, Exception) and not issubclass(error_type, BatchResourceCleanupError)) + if orderly and binding_written and owned_runtime.generation == 0: + try: + write_record(binding_path, dict(binding, never_acquired=True)) + except OSError as error: + service._logging.logger.error('local_resource_release_proof_unavailable queue_id=%s error=%s', + token, type(error).__name__) + + with ExitStack() as ownership: + ownership.push(finish_local_binding) + owned_runtime = ownership.enter_context(BatchCadRuntime(service._logging.root, 'task_queue', stop_event)) if manifest_digest is not None: if (not isinstance(token, str) or len(token) != 32 or any(char not in '0123456789abcdef' for char in token)): @@ -354,12 +369,6 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event, revalidate=bind_local_session if binding else revalidate, manifest_digest=manifest_digest) owned_runtime.result = result - if binding and owned_runtime.generation == 0: - try: - write_record(binding_path, dict(binding, never_acquired=True)) - except OSError as error: - service._logging.logger.error('local_resource_release_proof_unavailable queue_id=%s error=%s', - token, type(error).__name__) return result ids = tuple(task_ids) if not ids or len(set(ids)) != len(ids): @@ -421,6 +430,21 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event, _save(path, state) paused = False current = None + + def bind_task_round(task_id): + if manifest_digest is None: + return + child = children[task_id] + with child._store._lock: + row = child._store._connection.execute( + 'SELECT round_id FROM execution_rounds WHERE task_id=?', (task_id,)).fetchone() + if row is not None: + known = state.setdefault('round_ids', {}).get(task_id) + if known is not None and known != row[0]: + raise TaskCenterError('task_queue_state', '原队列执行轮次已变化,不能沿用原验收。') + state['round_ids'][task_id] = row[0] + _save(path, state) + from .stop_control import ProjectStopControl parent_control = getattr(runtime, 'stop_event', None) isolated_tasks = state.setdefault('isolated_tasks', {}) @@ -509,6 +533,7 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event, if hasattr(child, '_quick_run_preparer'): child._quick_run_preparer.reconcile_terminal_receipts(task_id) progress = child.quick_run_progress(task_id) + bind_task_round(task_id) if progress.queue_complete: checks.before_task(child, task_id, existing_only=True) entry = {'state': 'failed' if getattr(progress, 'failed_items', 0) else 'completed', @@ -528,6 +553,7 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event, execution_dispatched = True result = execute(task_id, expected_item=expected, stop_event=project_control, **runtime_options) + bind_task_round(task_id) if child.has_interrupted_quick_run(task_id) or ( result.last_result is not None and result.last_result.state == 'batch_saved_unverified' ): @@ -616,6 +642,7 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event, checks.before_task(children[task_id], task_id) from .problem_pass import run_problem_pass def capture_retry(task_id, result): + bind_task_round(task_id) if not result.paused and not children[task_id].has_interrupted_quick_run(task_id): checks.after_task(task_id, execution_state='failed' if result.progress.failed_items else 'completed', refresh=True, execution_summary={key: getattr(result.progress, key, None) diff --git a/src/dx_productivity/trial_task_center/ui/main_window.py b/src/dx_productivity/trial_task_center/ui/main_window.py index e43b73c..77eacca 100644 --- a/src/dx_productivity/trial_task_center/ui/main_window.py +++ b/src/dx_productivity/trial_task_center/ui/main_window.py @@ -148,6 +148,7 @@ class TrialTaskCenterWindow(MaterialMainWindow): self.task_list.new_button.clicked.connect(self._new_task) self.task_list.edit_button.clicked.connect(self._edit_task) self.task_list.delete_button.clicked.connect(self._delete_task) + self.task_list.archive_button.clicked.connect(self._archive_completed_task) self.task_list.restore_button.clicked.connect(self._restore_task) self.task_list.up_button.clicked.connect(lambda: self._move_project_task(-1)) self.task_list.down_button.clicked.connect(lambda: self._move_project_task(1)) @@ -575,6 +576,8 @@ class TrialTaskCenterWindow(MaterialMainWindow): dirty=self.plan_panel.table.dirty or self.plan_panel.table.has_pending_editor()) group_unsaved = self._group_has_unsaved_plans() if state.editable or state.new_round else False context = self._context + self.task_list.archive_button.setEnabled(bool(context and context.task.status is TaskStatus.COMPLETED + and not busy and not resources_pending and self._batch_stop is None)) save_pending = bool(context and state.editable and (self.plan_panel.table.dirty or self.plan_panel.table.has_pending_editor() or self.plan_panel._active_bom_batch())) self.run_panel.quick_run_button.setText('保存计划以执行' if save_pending else state.execute_text) @@ -733,6 +736,30 @@ class TrialTaskCenterWindow(MaterialMainWindow): self._metadata_changed(None) self._run_async(operation, done, self.task_list.delete_button) + def _archive_completed_task(self): + if not self._context or self._workers: + return + task_id = self._context.task.task_id + if QMessageBox.question(self, '归档当前已完成任务', + '归档后移至回收站,可恢复。工程、计划和原执行证据均保留;归档不会将缺失验收变为验收通过。', + QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, + QMessageBox.StandardButton.No) != QMessageBox.StandardButton.Yes: + return + from ..task_archive import archive_completed_session + + def done(report): + if task_id in report.archived_ids: + self.plan_panel.forget_task(task_id) + self._task_id = None + self._context = None + self._metadata_changed(None) + self._set_operator_message('已归档,原执行结果和证据保留。' if report.archived_ids else + '未归档:' + ';'.join(reason for _, reason in report.retained), + 'success' if report.archived_ids else 'warning') + + self._run_async(lambda: archive_completed_session(self.service, task_ids=(task_id,)), + done, self.task_list.archive_button) + def _restore_task(self): if self._task_id: task_id = self._task_id @@ -1246,7 +1273,7 @@ class TrialTaskCenterWindow(MaterialMainWindow): def _export_diagnostics(self): from pathlib import Path name = 'DxPartReplace-诊断-' + time.strftime('%Y%m%d-%H%M%S') + '.zip' - value, _ = QFileDialog.getSaveFileName(self, '导出脱敏诊断包', name, 'ZIP 文件 (*.zip)') + value, _ = QFileDialog.getSaveFileName(self, '导出诊断包(过滤凭据,仍含工程路径和任务标识)', name, 'ZIP 文件 (*.zip)') if not value or self._diagnostic_worker is not None: return # A read-only support export remains available while CAD is waiting. diff --git a/src/dx_productivity/trial_task_center/ui/run_panel.py b/src/dx_productivity/trial_task_center/ui/run_panel.py index afcd9d8..e08c3d5 100644 --- a/src/dx_productivity/trial_task_center/ui/run_panel.py +++ b/src/dx_productivity/trial_task_center/ui/run_panel.py @@ -36,7 +36,7 @@ class RunPanel(QWidget): self.cleanup_resources_button = QPushButton('重新清理资源', objectName='cleanupBatchResources') self.cleanup_resources_button.setToolTip('只释放本程序拥有的后台资源,不执行工程替换。') self.diagnostics_button = QPushButton('导出诊断包', objectName='exportDiagnosticBundle') - self.diagnostics_button.setToolTip('导出脱敏日志与资源记录,不包含工程、中心库、BOM 或任务数据库。') + self.diagnostics_button.setToolTip('导出时过滤凭据和用户名,仍含工程路径、任务标识及执行日志;不包含工程文件、中心库、BOM 或任务数据库。') self.new_round_button = QPushButton('开始新一轮', objectName='startNewRoundButton') self.history_button = QPushButton('查看轮次证据', objectName='roundHistoryButton') self.copy_value_check = QCheckBox('Value 策略:替换后将 Part Label 写入 Value(逐行自定义优先)', objectName='copyPartNumberToValue') diff --git a/src/dx_productivity/trial_task_center/ui/task_list.py b/src/dx_productivity/trial_task_center/ui/task_list.py index d873cee..0f30997 100644 --- a/src/dx_productivity/trial_task_center/ui/task_list.py +++ b/src/dx_productivity/trial_task_center/ui/task_list.py @@ -102,6 +102,8 @@ class TaskList(QWidget): self.clear_selection_button = QPushButton('清空选择', objectName='clearTaskSelection') self.edit_button = QPushButton("编辑", objectName="editTaskButton") self.delete_button = QPushButton("删除", objectName="deleteTaskButton") + self.archive_button = QPushButton('归档当前已完成任务', objectName='archiveCompletedTask') + self.archive_button.setToolTip('保留原计划、工程和执行证据,移至回收站;待核验作业和未释放资源仍会阻止归档。') self.restore_button = QPushButton("恢复", objectName="restoreTaskButton") self.queue_button = QPushButton("顺序执行本批任务", objectName="executeProjectTasks") self.queue_button.setToolTip('按保存的执行顺序执行本批全部任务,不受搜索和显示排序影响。') @@ -118,6 +120,7 @@ class TaskList(QWidget): for button in (self.edit_button,self.restore_button,self.up_button,self.down_button): self.manage_menu.add_button(button) self.manage_menu.addSeparator() + self.manage_menu.add_button(self.archive_button) self.manage_menu.add_button(self.delete_button) self.manage_button=QToolButton(objectName='taskManageMenu') self.manage_button.setText('任务管理') diff --git a/src/dx_productivity/trial_task_center/worker_monitor.py b/src/dx_productivity/trial_task_center/worker_monitor.py index 161fe5b..319748d 100644 --- a/src/dx_productivity/trial_task_center/worker_monitor.py +++ b/src/dx_productivity/trial_task_center/worker_monitor.py @@ -4,6 +4,7 @@ from __future__ import annotations import ctypes import json +import math import os from pathlib import Path import queue @@ -118,8 +119,8 @@ def cleanup_retained_workers(root, *, force=False): class ProgressWatch: def __init__(self, token: str, job_id: str, idle_timeout: float, started: float) -> None: - if idle_timeout <= 0: - raise ValueError('Idle timeout must be positive') + if type(idle_timeout) not in (int, float) or not 0 < idle_timeout < math.inf: + raise ValueError('Idle timeout must be finite and positive') self.token = token self.job_id = job_id self.current_job_id = job_id @@ -127,7 +128,10 @@ class ProgressWatch: self.last_progress = started self.last_business_progress = started self.sequence = 0 + self.business_sequence = 0 + self.business_done = 0 self.native_sequence = 0 + self.native_business_done = 0 self.native_progress_frames = 0 self.stop_requested = False self.stopping_reason = '' @@ -156,7 +160,10 @@ class ProgressWatch: return False except (ValueError, UnicodeError): return False - if ((current_job, fields[4]) != (self.current_job_id, self.stage) or done > self.done): + boundary = (current_job, fields[4]) != (self.current_job_id, self.stage) + if boundary or done > self.business_done: + self.business_sequence += 1 + self.business_done = done self.last_business_progress = now self.waiting_for_safe_completion = False if current_job != self.current_job_id: @@ -170,6 +177,7 @@ class ProgressWatch: self.stage_started = now self.sequence = sequence self.native_sequence = 0 + self.native_business_done = done self.last_progress = now self.stage, self.done, self.total, self.safe_stop = fields[4], done, total, bool(safe) self.unsafe_seen = self.unsafe_seen or not bool(safe) @@ -199,7 +207,9 @@ class ProgressWatch: self.native_sequence = sequence self.native_progress_frames += 1 self.last_progress = now - if done > self.done: + if done > self.native_business_done: + self.business_sequence += 1 + self.native_business_done = done self.last_business_progress = now self.waiting_for_safe_completion = False self.done, self.total = done, total @@ -229,6 +239,7 @@ class ProgressWatch: stages = dict(self.stage_seconds) stages[self.stage] = stages.get(self.stage, 0.0) + max(0.0, now - self.stage_started) return {name: getattr(self, name) for name in ('token', 'sequence', 'stage', 'done', 'total', 'safe_stop', 'stop_requested', 'waiting_for_safe_completion')} | { + 'business_sequence': self.business_sequence, 'job_id': self.current_job_id, 'native_progress_frames': self.native_progress_frames, 'business_idle_seconds': max(0.0, now - self.last_business_progress), @@ -450,6 +461,7 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor stop_warning = '' try: + _publish_progress(progress_path, watch.snapshot()) if process_factory is None: process = subprocess.Popen((*command, token), stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=subprocess.CREATE_NO_WINDOW) @@ -462,7 +474,6 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor thread = threading.Thread(target=read_stream, args=(stream, channel), daemon=True) thread.start() threads.append(thread) - _publish_progress(progress_path, watch.snapshot()) _atomic_text(ready, token) while process.poll() is None: if cooperative_abort and owner_loss_path is not None and Path(owner_loss_path).is_file(): diff --git a/tests/dsh/test_pr47_audit657_receipts.py b/tests/dsh/test_pr47_audit657_receipts.py new file mode 100644 index 0000000..bc1df61 --- /dev/null +++ b/tests/dsh/test_pr47_audit657_receipts.py @@ -0,0 +1,201 @@ +"""Recovery of incomplete evidence does not repeat engineering work.""" +import json +from threading import Event + +import pytest + +from dx_productivity.dsh import execution_runs +from dx_productivity.dsh.run_journal import RunJournal +from dx_productivity.trial_task_center import batch_resources, batch_summary, task_queue +from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime, BatchResourceCleanupError +from dx_productivity.trial_task_center.errors import TaskCenterError +from test_issue44_batch_receipt import BATCH_ID, RUN_ID, TASK_ID, batch +from test_pr47_audit_receipts import _start, _supervised_complete +from test_run_journal import project_service + + +def _verified_batch(case): + service, child, root, _, admission = case + with child.transaction(): + child._connection.execute('INSERT INTO execution_rounds(task_id,round_id) VALUES (?,?)', + (TASK_ID, 'round')) + command = {'target_scope': 'targets', 'project_path': 'board.prj', + 'schematic_name': 'MAIN', 'sheet_number': '1', 'target_selectors': 'uid1\x1fR1'} + child._connection.execute('INSERT INTO execution_operations VALUES (?,?,?,?,?,?,?,?)', + (TASK_ID, 'round', 'key', json.dumps(command), 'verified', 'attempt', 1, '{}')) + journal = _start(root, admission) + journal.finish(RUN_ID, dict(_supervised_complete(root), elapsed_seconds=28.125)) + checkpoint = root / 'task-queues' / (RUN_ID + '.json') + batch_resources.write_record(checkpoint, + dict(json.loads(checkpoint.read_bytes()), round_ids={TASK_ID: 'round'})) + return service, root, journal + + +def test_same_revision_rebuilds_missing_evidence_without_version_churn(batch, monkeypatch): + service, root, journal = _verified_batch(batch) + read_sources = batch_summary._operation_sources + unavailable = True + + def evidence(*args): + if unavailable: + return [], {TASK_ID: {'state': 'unknown'}}, [TASK_ID] + return read_sources(*args) + + monkeypatch.setattr(batch_summary, '_operation_sources', evidence) + monkeypatch.setattr(execution_runs, 'execute_task_queue', lambda *_args, **_kwargs: + pytest.fail('receipt recovery dispatched engineering work')) + execution_runs.recover_batch_receipts(service, root) + first = journal.batch_summary(RUN_ID) + assert first['operation_evidence_missing'] == [TASK_ID] + assert first['status'] == 'paused' and first['resource_state'] == 'released' + execution_runs.recover_batch_receipts(service, root) + assert journal.batch_summary(RUN_ID) == first + exported = root / 'batch-runs' / RUN_ID / 'batch-receipt.json' + exported.write_text('{incomplete export', encoding='utf-8') + execution_runs.recover_batch_receipts(service, root) + assert journal.batch_summary(RUN_ID) == first + assert json.loads(exported.read_bytes()) == first + + unavailable = False + execution_runs.recover_batch_receipts(service, root) + recovered = journal.batch_summary(RUN_ID) + assert recovered['revision'] == first['revision'] + 1 + assert recovered['operation_evidence_missing'] == [] + assert recovered['operation_counts']['verified'] == 1 + assert recovered['status'] == recovered['execution_status'] == 'completed' + assert recovered['acceptance'] == first['acceptance'] + assert recovered['elapsed_seconds'] == first['elapsed_seconds'] == 28.125 + assert recovered['resource_batch_ids'] == first['resource_batch_ids'] == [BATCH_ID] + assert recovered['netlist_verification'] == first['netlist_verification'] + execution_runs.recover_batch_receipts(service, root) + assert journal.batch_summary(RUN_ID) == recovered + assert json.loads((root / 'batch-runs' / RUN_ID / 'batch-receipt.json').read_bytes()) == recovered + + +def test_same_revision_rechecks_unknown_round_even_without_missing_field(batch, monkeypatch): + service, root, journal = _verified_batch(batch) + execution_runs.recover_batch_receipts(service, root) + previous = journal.batch_summary(RUN_ID) + previous.update(status='paused', source_versions={**previous['source_versions'], + 'rounds': {TASK_ID: {'state': 'unknown'}}}) + journal.save_batch_summary(RUN_ID, previous, journal.get(RUN_ID)['result'], revision=previous['revision']) + monkeypatch.setattr(execution_runs, 'execute_task_queue', lambda *_args, **_kwargs: + pytest.fail('unknown-round recovery dispatched engineering work')) + execution_runs.recover_batch_receipts(service, root) + repaired = journal.batch_summary(RUN_ID) + assert repaired['status'] == 'completed' + assert repaired['source_versions']['rounds'][TASK_ID]['round_id'] == 'round' + assert repaired['operation_counts']['verified'] == 1 + assert repaired['revision'] == previous['revision'] + 1 + + +@pytest.mark.parametrize('bound', [True, False]) +def test_first_publication_never_lends_a_new_round_to_an_old_report(batch, bound): + service, root, journal = _verified_batch(batch) + with batch[1].transaction(): + batch[1]._connection.execute('UPDATE execution_rounds SET round_id=? WHERE task_id=?', + ('round-2', TASK_ID)) + if not bound: + checkpoint = root / 'task-queues' / (RUN_ID + '.json') + state = json.loads(checkpoint.read_bytes()) + state.pop('round_ids') + batch_resources.write_record(checkpoint, state) + manifest = json.loads((root / 'batch-runs' / RUN_ID / 'manifest.json').read_bytes()) + execution_runs._finish_batch_summary(service, root, journal, manifest, journal.get(RUN_ID)['result'], 28.125) + summary = journal.batch_summary(RUN_ID) + version = summary['source_versions']['rounds'][TASK_ID] + if bound: + assert version['round_id'] == 'round' + assert summary['operation_counts']['verified'] == 1 + else: + assert version['state'] == 'unknown' and 'round_id' not in version + assert summary['status'] == 'paused' and summary['operation_evidence_missing'] == [TASK_ID] + + +@pytest.mark.parametrize('binding', ['checkpoint', 'summary', 'missing', 'conflict']) +def test_recovery_never_lends_a_new_round_to_an_old_netlist_report(batch, monkeypatch, binding): + service, root, journal = _verified_batch(batch) + if binding == 'summary': + execution_runs.recover_batch_receipts(service, root) + previous = journal.batch_summary(RUN_ID) + previous.update(status='paused', operation_evidence_missing=[TASK_ID]) + journal.save_batch_summary(RUN_ID, previous, journal.get(RUN_ID)['result'], revision=previous['revision']) + else: + with monkeypatch.context() as unavailable: + unavailable.setattr(batch_summary, '_operation_sources', + lambda *_args: ([], {TASK_ID: {'state': 'unknown'}}, [TASK_ID])) + execution_runs.recover_batch_receipts(service, root) + first = journal.batch_summary(RUN_ID) + checkpoint = root / 'task-queues' / (RUN_ID + '.json') + state = json.loads(checkpoint.read_bytes()) + if binding in {'missing', 'summary'}: + state.pop('round_ids') + elif binding == 'conflict': + previous = journal.batch_summary(RUN_ID) + previous['source_versions']['rounds'][TASK_ID] = {'round_id': 'foreign-round'} + journal.save_batch_summary(RUN_ID, previous, journal.get(RUN_ID)['result'], revision=previous['revision']) + batch_resources.write_record(checkpoint, state) + child = batch[1] + with child.transaction(): + child._connection.execute('UPDATE execution_rounds SET round_id=? WHERE task_id=?', ('round-2', TASK_ID)) + command = json.loads(child._connection.execute( + 'SELECT command_json FROM execution_operations WHERE task_id=?', (TASK_ID,)).fetchone()[0]) + for i in range(2): + child._connection.execute('INSERT INTO execution_operations VALUES (?,?,?,?,?,?,?,?)', + (TASK_ID, 'round-2', 'new-key-' + str(i), json.dumps(command), 'verified', 'new-attempt', 1, '{}')) + execution_runs.recover_batch_receipts(service, root) + repaired = journal.batch_summary(RUN_ID) + version = repaired['source_versions']['rounds'][TASK_ID] + assert version.get('round_id') != 'round-2' + assert repaired['netlist_verification'] == first['netlist_verification'] + if binding in {'checkpoint', 'summary'}: + assert version['round_id'] == 'round' + assert repaired['operation_counts']['verified'] == 1 + else: + assert version['state'] == 'unknown' and repaired['status'] == 'paused' + assert repaired['operation_evidence_missing'] == [TASK_ID] + execution_runs.recover_batch_receipts(service, root) + assert journal.batch_summary(RUN_ID)['source_versions']['rounds'][TASK_ID] == version + + +class FatalExit(BaseException): + pass + + +@pytest.mark.parametrize('failure', ['ordinary', 'fatal', 'cleanup', 'revalidation']) +def test_local_queue_zero_generation_finalizes_only_after_orderly_close(project_service, monkeypatch, failure): + service, _, root, ids, hashes = project_service + task_id = ids[0] + child = service.for_project_task(task_id) + validations = [] + + def revalidate(): + validations.append(True) + if failure == 'revalidation': + raise TaskCenterError('preflight_changed', 'scope changed before binding') + + def fail_before_any_cad(*args): + if failure == 'fatal': + raise FatalExit('simulated hard boundary interruption') + raise TaskCenterError('preflight_changed', 'scope changed after binding') + + monkeypatch.setattr(child, 'get_task', fail_before_any_cad) + if failure == 'cleanup': + def cannot_close(*args): + raise OSError('cleanup was not confirmed') + monkeypatch.setattr(BatchCadRuntime, 'close', cannot_close) + expected_error = FatalExit if failure == 'fatal' else ( + BatchResourceCleanupError if failure == 'cleanup' else TaskCenterError) + with pytest.raises(expected_error): + task_queue.execute_task_queue(service, (task_id,), stop_event=Event(), checkpoint_id=RUN_ID, + expected_plan_hashes={task_id: hashes[task_id]}, manifest_digest='d' * 64, revalidate=revalidate) + links = list((root / 'batch-runs' / RUN_ID).glob('local-resource-*.json')) + assert bool(validations) + assert not list((root / 'batch-resources').glob('*/session.json')) + if failure == 'revalidation': + assert links == [] + else: + assert len(links) == 1 + binding = json.loads(links[0].read_bytes()) + assert binding['never_acquired'] is (failure == 'ordinary') + assert binding['task_ids'] == [task_id] diff --git a/tests/dsh/test_pr47_audit_receipts.py b/tests/dsh/test_pr47_audit_receipts.py index 3869f32..ba7ff68 100644 --- a/tests/dsh/test_pr47_audit_receipts.py +++ b/tests/dsh/test_pr47_audit_receipts.py @@ -83,6 +83,11 @@ def test_local_manifest_run_completes_from_its_actual_runtime_release(project_se assert result['execution_status'] == 'completed' assert result['status'] == 'completed' and result['summary']['resource_state'] == 'released' assert result['summary']['resource']['evidence'] + checkpoint = json.loads((root / 'task-queues' / (RUN_ID + '.json')).read_bytes()) + with child._store._lock: + actual_round = child._store._connection.execute( + 'SELECT round_id FROM execution_rounds WHERE task_id=?', (task_id,)).fetchone()[0] + assert checkpoint['round_ids'][task_id] == actual_round assert result['tasks'][0]['no_match_items'] == 1 assert bool(result['summary']['resource']['generations']) is owns_desktop journal = RunJournal(root) @@ -112,16 +117,20 @@ def test_incident_publication_preserves_the_recorded_elapsed_time(batch, already def test_recovery_retries_a_previously_unstable_snapshot_at_the_same_revision(batch, monkeypatch): - service, _, data, _, admission = batch + service, child, data, _, admission = batch journal = _start(data, admission) receipt = _supervised_complete(data) + with child.transaction(): + child._connection.execute('INSERT INTO execution_rounds(task_id,round_id) VALUES (?,?)', (TASK_ID, 'round')) + checkpoint = data / 'task-queues' / (RUN_ID + '.json') + _update_json(checkpoint, round_ids={TASK_ID: 'round'}) journal.finish(RUN_ID, receipt) original = batch_summary._operation_sources generations = iter(range(3)) def changing(*args): - rows, _, missing = original(*args) - return rows, {TASK_ID: {'round_id': str(next(generations))}}, missing + rows, versions, missing = original(*args) + return rows, {TASK_ID: {**versions[TASK_ID], 'digest': str(next(generations))}}, missing with monkeypatch.context() as unstable: unstable.setattr(batch_summary, '_operation_sources', changing) diff --git a/tests/ui/test_pr47_audit657_ui.py b/tests/ui/test_pr47_audit657_ui.py new file mode 100644 index 0000000..e21e577 --- /dev/null +++ b/tests/ui/test_pr47_audit657_ui.py @@ -0,0 +1,74 @@ +from dataclasses import replace + +import pytest +from PySide6.QtWidgets import QMessageBox + +from dx_productivity.trial_task_center.batch_admission import build_batch_admission +from dx_productivity.trial_task_center.models import TaskStatus + + +def completed_context(ui, monkeypatch): + task_id = ui.tasks[0].task_id + ui.store.set_task_status(task_id, TaskStatus.RUNNING) + ui.store.set_task_status(task_id, TaskStatus.COMPLETED) + original = ui.service.task_context + context = original(task_id) + context = replace(context, has_evidence=True, progress=replace(context.progress, + queue_complete=True, saved_items=1, completed_items=1, total_items=1, next_project_path=None)) + monkeypatch.setattr(ui.service, 'task_context', + lambda key, **kw: context if key == task_id else original(key, **kw)) + return task_id, context + + +@pytest.mark.parametrize('missing', ['round', 'history']) +def test_legacy_completed_explains_missing_evidence_without_claiming_acceptance(ui, monkeypatch, missing): + task_id, _ = completed_context(ui, monkeypatch) + if missing == 'history': + with ui.store.transaction(): + ui.store._connection.execute('INSERT INTO execution_rounds(task_id,round_id) VALUES (?,?)', (task_id, 'r')) + admission = build_batch_admission(ui.service, tuple(t.task_id for t in ui.tasks), scope_kind='batch') + row = admission['decisions'][0] + assert row['classification'] == 'held' and not admission['ready'] + assert row['acceptance_reason'] == f'acceptance_{missing}_missing' + assert '归档' in row['message'] and '日志' in row['message'] + assert not ui.calls + + +def test_legacy_completed_archive_action_preserves_original_evidence(ui, qtbot, monkeypatch): + task_id, context = completed_context(ui, monkeypatch) + ui.window._context = context + ui.window._update_gates() + assert ui.window.task_list.archive_button.isEnabled() + monkeypatch.setattr(QMessageBox, 'question', lambda *a, **kw: QMessageBox.StandardButton.Yes) + ui.window.task_list.archive_button.click() + qtbot.waitUntil(lambda: ui.service.get_task(task_id).status is TaskStatus.DELETED, timeout=5000) + ui.settle() + assert ui.service.get_task(ui.tasks[1].task_id).status is not TaskStatus.DELETED + assert not ui.calls + + +def test_diagnostics_export_discloses_retained_project_paths(ui): + assert '工程路径' in ui.window.run_panel.diagnostics_button.toolTip() + assert '凭据' in ui.window.run_panel.diagnostics_button.toolTip() + + +@pytest.mark.parametrize('missing', ['round_state', 'operations']) +def test_incomplete_round_evidence_cannot_certify_a_completed_task(ui, monkeypatch, missing): + from dx_productivity.dsh.run_journal import RunJournal + from dx_productivity.trial_task_center.task_queue import _plan_hash + task_id, _ = completed_context(ui, monkeypatch) + with ui.store.transaction(): + ui.store._connection.execute('INSERT INTO execution_rounds(task_id,round_id) VALUES (?,?)', (task_id, 'r')) + source = {'round_id': 'r'} + if missing == 'round_state': + source['state'] = 'unknown' + summary = {'source_versions': {'rounds': {task_id: source}}, + 'operation_evidence_missing': [task_id] if missing == 'operations' else []} + journal = RunJournal(ui.data) + journal.begin('f' * 32, [task_id], {task_id: _plan_hash(ui.service.for_project_task(task_id), task_id)}) + journal.finish('f' * 32, {'status': 'completed', 'summary': summary, + 'netlist_verification': {task_id: {'status': 'verified', 'verified': True}}}) + result = build_batch_admission(ui.service, tuple(t.task_id for t in ui.tasks), scope_kind='batch') + assert not result['ready'] + assert result['decisions'][0]['acceptance_reason'] == 'acceptance_evidence_unavailable' + assert not ui.calls diff --git a/tests/ui/test_trial_task_center_workflow.py b/tests/ui/test_trial_task_center_workflow.py index 000a15d..19a814e 100644 --- a/tests/ui/test_trial_task_center_workflow.py +++ b/tests/ui/test_trial_task_center_workflow.py @@ -77,11 +77,13 @@ def test_mapping_enable_uses_model_and_persists_without_row_widgets(ui): assert not w.run_panel.quick_run_button.isEnabled() -def test_native_batch_records_complete_order_and_actual_results(ui): +def test_native_batch_records_complete_order_and_actual_results(ui, qtbot): from dx_productivity.dsh.run_journal import RunJournal window=ui.window window._quick_run_confirmer=lambda *args:True - window._execute_project_tasks();ui.settle() + window._execute_project_tasks() + qtbot.waitUntil(lambda: len(ui.calls) == len(ui.tasks) and not window._workers, timeout=10000) + ui.settle() rows=RunJournal(ui.data).list_runs() assert len(ui.calls)==2 and len(rows)==1 assert rows[0]['task_ids']==[task.task_id for task in ui.tasks] diff --git a/tests/v1_1/test_bom_pending.py b/tests/v1_1/test_bom_pending.py index 96e822a..5864d70 100644 --- a/tests/v1_1/test_bom_pending.py +++ b/tests/v1_1/test_bom_pending.py @@ -389,11 +389,15 @@ def test_confirmation_counts_imported_and_retained_targets(batch, tmp_path, qtbo window._prepare_quick_run() else: qtbot.waitUntil(window.task_list.queue_button.isEnabled) - # This confirmation concerns the imported task and its retained R2; - # the untouched sibling has no enabled plan to execute. - window._tasks = (service.get_task(task_id),) + # The real group includes an untouched sibling with no enabled plan. window._execute_project_tasks() + qtbot.waitUntil(lambda: len(captured) == 1 and not window._workers) assert captured[0][0] == scope and captured[0][2] == 2 + if scope == 'batch': + admission = window._batch_confirmation_admission + assert admission['candidate_task_ids'] == [task.task_id for task in tasks] + assert admission['runnable_task_ids'] == [task_id] and captured[0][1] == 1 + assert admission['decisions'][1]['classification'] == 'skipped' assert not calls and not window._workers from PySide6.QtWidgets import QMessageBox text = [] diff --git a/tests/v1_1/test_multi_project_regression.py b/tests/v1_1/test_multi_project_regression.py index ecba132..a764fe0 100644 --- a/tests/v1_1/test_multi_project_regression.py +++ b/tests/v1_1/test_multi_project_regression.py @@ -10,7 +10,7 @@ import pytest @pytest.mark.parametrize('behavior, steps, changed, states', [ ('success', 24, 24, ['completed', 'completed', 'completed']), ('failure_continue', 24, 23, ['failed', 'completed', 'completed']), - ('uncertain_stop', 17, 16, ['blocked', 'completed', 'completed']), + ('uncertain_stop', 1, 0, ['blocked', 'pending', 'pending']), ('pause_resume', 24, 24, ['completed', 'completed', 'completed']), ]) def test_multiple_projects_preserve_task_order_scope_results_and_measurements(tmp_path, behavior, steps, changed, states): @@ -24,14 +24,14 @@ def test_multiple_projects_preserve_task_order_scope_results_and_measurements(tm assert report['executed_steps'] == steps assert report['changed_components'] == changed assert report['unselected_components_preserved'] == 12 - assert report['result']['paused'] is False + assert report['result']['paused'] is (behavior == 'uncertain_stop') assert [entry['state'] for entry in report['result']['entries']] == states calls = report['calls'] assert len(calls) == steps assert all(len(call['refdes']) == 1 for call in calls) assert len({(call['project'], call['sheet'], call['refdes'][0]) for call in calls}) == steps assert sum(call['state'] == 'saved_ok' for call in calls) == changed - assert [call['project'] for call in calls] == (['board-000'] + ['board-001'] * 8 + ['board-002'] * 8 if behavior == 'uncertain_stop' else + assert [call['project'] for call in calls] == (['board-000'] if behavior == 'uncertain_stop' else ['board-000'] * 8 + ['board-001'] * 8 + ['board-002'] * 8) assert calls[0]['state'] == {'failure_continue': 'batch_failed', 'uncertain_stop': 'batch_saved_unverified'}.get(behavior, 'saved_ok') with sqlite3.connect(output / 'tasks.db') as connection: diff --git a/tests/v1_1/test_nonblocking_acceptance.py b/tests/v1_1/test_nonblocking_acceptance.py index 269369d..d12aeee 100644 --- a/tests/v1_1/test_nonblocking_acceptance.py +++ b/tests/v1_1/test_nonblocking_acceptance.py @@ -66,15 +66,21 @@ def test_hundred_uid_batch_keeps_93_verified_items_and_isolates_unknown_writes(t ids = tuple(task.task_id for task in tasks) try: result = execute_task_queue(gui, ids, stop_event=Event()) - assert not result.paused - assert [entry.state for entry in result.entries] == ['failed', 'completed', 'blocked', 'blocked'] - assert len(calls) == 100 and set(Counter(calls).values()) == {1} - assert (tasks[3].task_id, 'u1') in calls + assert result.paused and result.current_task_id == tasks[2].task_id + assert [entry.state for entry in result.entries] == ['failed', 'completed', 'blocked', 'pending'] + assert len(calls) == 99 and set(Counter(calls).values()) == {1} + assert (tasks[3].task_id, 'u1') not in calls records = dict(store._connection.execute('SELECT state,count(*) FROM execution_operations GROUP BY state')) - assert records == {'verified': 93, 'failed': 5, 'uncertain': 2} + assert records == {'verified': 93, 'failed': 5, 'uncertain': 1} resumed = execute_task_queue(gui, ids, stop_event=Event(), queue_id=result.queue_id) - assert not resumed.paused and resumed.entries[2].state == 'blocked' - assert len(calls) == 100 + assert resumed.paused and resumed.queue_id == result.queue_id + assert resumed.current_task_id == tasks[2].task_id + assert [(entry.task_id, entry.state) for entry in resumed.entries] == [ + (entry.task_id, entry.state) for entry in result.entries] + assert dict(store._connection.execute( + 'SELECT state,count(*) FROM execution_operations GROUP BY state')) == records + assert engine.has_interrupted_quick_run(tasks[2].task_id) + assert len(calls) == 99 finally: store.close() reopened = TaskStore(database) diff --git a/tests/v1_1/test_pr47_audit657_archive.py b/tests/v1_1/test_pr47_audit657_archive.py new file mode 100644 index 0000000..14f39bd --- /dev/null +++ b/tests/v1_1/test_pr47_audit657_archive.py @@ -0,0 +1,51 @@ +import pytest + +from test_task_archive import service +from dx_productivity.trial_task_center.errors import TaskCenterError +from dx_productivity.trial_task_center.models import TaskStatus +from dx_productivity.trial_task_center.task_archive import archive_completed_session + + +def complete(service, name): + task = service.create_task(name) + service._store.set_task_status(task.task_id, TaskStatus.RUNNING) + service._store.set_task_status(task.task_id, TaskStatus.COMPLETED) + return task.task_id + + +def test_selected_archive_preserves_other_completed_tasks_and_evidence(service): + chosen, other = complete(service, 'old'), complete(service, 'other') + evidence = service._logging.root / 'old-report.json' + evidence.write_text('original acceptance evidence') + report = archive_completed_session(service, task_ids=(chosen,)) + assert report.archived_ids == (chosen,) + assert [t.task_id for t in service.tasks()] == [other] + assert evidence.read_text() == 'original acceptance evidence' + assert service.restore_task(chosen).status is TaskStatus.COMPLETED + + +@pytest.mark.parametrize('state', ['prepared', 'pending_save', 'uncertain']) +def test_selected_archive_retains_unresolved_sql_evidence(service, state): + task_id = complete(service, 'protected') + with service._store.transaction(): + service._store._connection.execute( + 'INSERT INTO execution_rounds(task_id,round_id) VALUES (?,?)', (task_id, 'r')) + service._store._connection.execute('INSERT INTO execution_operations VALUES (?,?,?,?,?,?,?,?)', + (task_id, 'r', 'op', '{}', state, 'attempt', 1, '{}')) + report = archive_completed_session(service, task_ids=(task_id,)) + assert report.retained_ids == (task_id,) and not report.archived_ids + assert service.get_task(task_id).status is TaskStatus.COMPLETED + + +def test_selected_archive_rejects_invalid_scope_atomically(service): + chosen = complete(service, 'old') + with pytest.raises(TaskCenterError, match='归档范围'): + archive_completed_session(service, task_ids=(chosen, 'missing')) + assert service.get_task(chosen).status is TaskStatus.COMPLETED + + +def test_selected_archive_does_not_archive_a_newly_running_task(service): + task = service.create_task('now running') + service._store.set_task_status(task.task_id, TaskStatus.RUNNING) + report = archive_completed_session(service, task_ids=(task.task_id,)) + assert report.retained_ids == (task.task_id,) and not report.archived_ids diff --git a/tests/v1_1/test_pr47_audit657_resources.py b/tests/v1_1/test_pr47_audit657_resources.py new file mode 100644 index 0000000..be51f57 --- /dev/null +++ b/tests/v1_1/test_pr47_audit657_resources.py @@ -0,0 +1,217 @@ +import json +import os +from pathlib import Path +import subprocess +import sys +from types import SimpleNamespace + +import pytest + +from test_desktop_slot import Backend, CONTEXT, slot +from test_managed_desktop import Api +from dx_productivity.trial_task_center import batch_resources, desktop_slot +from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime +from dx_productivity.trial_task_center.errors import TaskCenterError +from dx_productivity.trial_task_center.isolated_desktop import PrivateDesktop + + +def binding(owner): + return dict(version=1, path=str(owner.path), context=CONTEXT, scope=owner.scope, + name=owner.name, lease_id=owner.lease_id, owner=owner.record['owner']) + + +def recover(value, tmp_path, backend): + return desktop_slot.recover_abandoned_lease(value, root=tmp_path, context=CONTEXT, backend=backend) + + +def test_abandoned_return_is_idempotent_and_does_not_rewrite_a_new_lease(tmp_path): + backend = Backend() + first = slot(tmp_path, backend).acquire() + original = binding(first) + job = first.prepare_launch(atomic_job=True) + first.launched(job, {'pid': 200, 'creation_time': 'worker-200'}) + backend.locked = False # The original owner exited without returning its lease. + backend.exists = True + receipt = recover(original, tmp_path, backend) + assert desktop_slot.returned_lease_intact(receipt, first.name) + assert receipt['lease_id'] == first.lease_id and receipt['desktop_disappeared'] is False + assert json.loads(first.path.read_bytes())['state'] == 'idle' + second = slot(tmp_path, backend).acquire() + before = second.path.read_bytes() + assert recover(original, tmp_path, backend) == receipt + assert second.path.read_bytes() == before and backend.locked + second.release(desktop_disappeared=False) + + +@pytest.mark.parametrize('damage', ['alive', 'unknown', 'job', 'replaced', 'changed_owner', 'wrong_context']) +def test_recovery_cannot_steal_live_unknown_or_replaced_ownership(tmp_path, damage): + backend = Backend() + first = slot(tmp_path, backend).acquire() + original = binding(first) + job = first.prepare_launch(atomic_job=True) + backend.locked = False + if damage == 'alive': + backend.alive.add(100) + elif damage == 'unknown': + backend.process_gone = lambda identity: False + elif damage == 'job': + backend.jobs.add(job) + elif damage == 'replaced': + second = slot(tmp_path, backend).acquire() + second.release(desktop_disappeared=True) + elif damage == 'changed_owner': + original['owner'] = {'pid': 100, 'creation_time': 'other-generation'} + else: + original['context'] = dict(CONTEXT, logon='other-logon') + before = first.path.read_bytes() + with pytest.raises(TaskCenterError): + recover(original, tmp_path, backend) + assert first.path.read_bytes() == before and not first.return_path.exists() + assert not backend.locked + + +@pytest.mark.parametrize('damage', ['', 'missing', 'generation', 'trees', 'unbound_trees']) +def test_pending_cleanup_requires_exact_binding_and_physical_disappearance(tmp_path, monkeypatch, damage): + backend = Backend() + owner = slot(tmp_path / 'slots', backend).acquire() + original = binding(owner) + writers = [{'pid': 200, 'creation_time': 'worker-200'}, {'pid': 201, 'creation_time': 'worker-201'}] + if damage in {'trees', 'unbound_trees'}: + for identity in writers[:2 if damage == 'trees' else 1]: + owner.launched(owner.prepare_launch(atomic_job=True), identity) + backend.locked = False + backend.exists = True + session = 'a' * 32 + directory = tmp_path / 'data' / 'batch-resources' / session + record = dict(version=1, session_id=session, generation=1, kind='task_queue', state='blocked', + desktop=owner.name, processes=[], cad_pid=None, cad_guid=None, checkpoints={}, retries={}, timings=[], + desktop_lease_binding=dict(original, session_id=session, generation=1), + cleanup=dict(desktop_lease_pending=True, desktop_handle_closed=True, owned_cleanup_complete=True, errors=[])) + if damage == 'missing': + record.pop('desktop_lease_binding') + elif damage == 'generation': + record['desktop_lease_binding']['generation'] = 2 + elif damage in {'trees', 'unbound_trees'}: + record['processes'] = writers + record['cleanup']['owned_cleanup_complete'] = False + batch_resources.write_record(directory / 'session.json', record) + real_recover = desktop_slot.recover_abandoned_lease + monkeypatch.setattr(desktop_slot, 'recover_abandoned_lease', lambda value: real_recover( + value, root=tmp_path / 'slots', context=CONTEXT, backend=backend)) + monkeypatch.setattr(desktop_slot, 'managed_desktop_disappeared', lambda receipt: not backend.exists) + monkeypatch.setattr(batch_resources, 'RESOURCE_RELEASE_BACKOFF_SECONDS', ()) + monkeypatch.setattr(batch_resources, 'observe_process_identity', lambda identity: {'state': 'gone'}) + pending, = batch_resources.cleanup_pending_resources(tmp_path / 'data') + if damage in {'missing', 'generation'}: + assert pending['state'] == 'blocked' and pending['cleanup']['desktop_lease_pending'] is True + assert not owner.return_path.exists() + return + if damage == 'unbound_trees': + assert pending['state'] == 'blocked' and pending['cleanup']['desktop_lease_pending'] is False + assert pending['cleanup']['owned_cleanup_complete'] is False + return + assert pending['state'] == 'isolated' + assert pending['cleanup']['desktop_lease_pending'] is False + assert pending['cleanup']['desktop_lease']['lease_id'] == owner.lease_id + with pytest.raises(batch_resources.BatchResourceCleanupError): + batch_resources.guard_pending_resources(tmp_path / 'data') + backend.exists = False + assert batch_resources.cleanup_pending_resources(tmp_path / 'data') == () + assert json.loads((directory / 'session.json').read_bytes())['state'] == 'released' + + +@pytest.mark.parametrize('writable', [True, False]) +def test_runtime_binds_the_lease_before_creating_a_desktop(tmp_path, monkeypatch, writable): + backend = Backend() + api = Api(backend) + root = tmp_path / 'data' + owner = slot(tmp_path / 'slots', backend) + created = [] + + def create(name): + persisted = json.loads(runtime.path.read_bytes())['desktop_lease_binding'] + assert persisted == dict(binding(owner), session_id=runtime.session_id, generation=1) + created.append(name) + return SimpleNamespace(CloseDesktop=lambda: setattr(backend, 'exists', False)) + + api.create_desktop = create + runtime = BatchCadRuntime(root, 'task_queue', desktop_factory=lambda name, **options: + PrivateDesktop(name, **options, api=api, slot=owner)) + atomic_write = batch_resources.write_record + + def write(path, value): + if not writable and value.get('desktop_lease_binding'): + raise OSError('lease binding unavailable') + return atomic_write(path, value) + + from dx_productivity.trial_task_center import batch_runtime + monkeypatch.setattr(batch_runtime, 'write_record', write) + try: + if writable: + runtime._ensure_desktop() + assert len(created) == 1 + else: + with pytest.raises(OSError, match='lease binding unavailable'): + runtime._ensure_desktop() + assert not created and not api.launches + finally: + monkeypatch.setattr(batch_runtime, 'write_record', atomic_write) + if runtime.desktop is not None: + runtime.close() + + +@pytest.mark.skipif(os.name != 'nt', reason='Windows abandoned desktop ownership') +def test_real_orphaned_lease_stays_isolated_until_the_external_handle_closes(tmp_path, monkeypatch): + import win32service + + root, slots = tmp_path / 'data', tmp_path / 'slots' + source = ''' +import os,sys +from pathlib import Path +from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime +from dx_productivity.trial_task_center.desktop_slot import DesktopSlot +from dx_productivity.trial_task_center.isolated_desktop import PrivateDesktop +root,slots=map(Path,sys.argv[1:]) +runtime=BatchCadRuntime(root,'task_queue',desktop_factory=lambda name,**options: + PrivateDesktop(name,**options,slot=DesktopSlot(root=slots))) +desktop=runtime._ensure_desktop() +print(desktop.name,flush=True) +sys.stdin.readline() +desktop._handle.CloseDesktop() +desktop._handle=None +runtime._save(state='blocked',cleanup=dict(desktop_lease_pending=True, + desktop_handle_closed=True,owned_cleanup_complete=True,errors=[])) +os._exit(0) +''' + process = subprocess.Popen((sys.executable, '-u', '-c', source, str(root), str(slots)), + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + creationflags=subprocess.CREATE_NO_WINDOW) + external = None + actual_recover = desktop_slot.recover_abandoned_lease + monkeypatch.setattr(desktop_slot, 'recover_abandoned_lease', + lambda value: actual_recover(value, root=slots)) + monkeypatch.setattr(batch_resources, 'RESOURCE_RELEASE_BACKOFF_SECONDS', ()) + try: + name = process.stdout.readline().decode().strip() + assert name.startswith('dx-'), process.stderr.read().decode(errors='replace') + external = win32service.OpenDesktop(name, 0, False, 0x10000000) + process.stdin.write(b'owner may exit\n') + process.stdin.flush() + assert process.wait(timeout=15) == 0 + pending, = batch_resources.cleanup_pending_resources(root) + assert pending['state'] == 'isolated' and pending['cleanup']['desktop_lease_pending'] is False + with pytest.raises(batch_resources.BatchResourceCleanupError): + batch_resources.guard_pending_resources(root) + external.CloseDesktop() + external = None + assert batch_resources.cleanup_pending_resources(root) == () + record, = (root / 'batch-resources').glob('*/session.json') + assert json.loads(record.read_bytes())['state'] == 'released' + finally: + if external is not None: + external.CloseDesktop() + if process.poll() is None: + process.kill() + process.wait(timeout=15) + for stream in (process.stdin, process.stdout, process.stderr): + stream.close() diff --git a/tests/v1_1/test_pr47_audit657_stall.py b/tests/v1_1/test_pr47_audit657_stall.py new file mode 100644 index 0000000..345932c --- /dev/null +++ b/tests/v1_1/test_pr47_audit657_stall.py @@ -0,0 +1,101 @@ +import json +import os + +import pytest + +from dx_productivity.trial_task_center import worker_monitor +from dx_productivity.trial_task_center.batch_supervisor import BusinessProgressWatch + + +@pytest.mark.parametrize('budget', [True, float('nan'), float('inf'), -float('inf'), 0, -1]) +def test_worker_watch_requires_a_finite_positive_numeric_budget(budget): + with pytest.raises(ValueError): + worker_monitor.ProgressWatch('t', 'j', budget, 0) + + +@pytest.mark.skipif(os.name != 'nt', reason='Windows Job monitoring') +def test_initial_worker_budget_is_published_before_process_creation(tmp_path): + path = tmp_path / 'worker-progress.json' + path.write_text(json.dumps({'job_id': 'old-job', 'idle_timeout_seconds': 150})) + + def create_process(command, **options): + state = json.loads(path.read_text()) + assert state['job_id'] == 'job' + assert state['idle_timeout_seconds'] == 240 + assert state['sequence'] == 0 and state['stage'] == 'starting' + raise RuntimeError('controlled failure before any process starts') + + command = ('controlled-worker.exe', '-u', 'worker.py', str(tmp_path), 'controlled-worker.exe', '', 'job') + with pytest.raises(RuntimeError, match='controlled failure'): + worker_monitor.run_monitored_process(command, 240, process_factory=create_process) + + +def frame(sequence, stage, done, total=5): + return f'DX_PROGRESS\t{"a" * 32}\tjob\t{sequence}\t{stage}\t{done}\t{total}\t1\n'.encode() + + +def publish(watch, outer, now): + state = watch.snapshot(now=now) + outer.observe('state', {'business_progress': state}, now) + return state + + +def test_repeated_semantic_capture_pass_keeps_outer_watch_in_step_with_worker(): + watch = worker_monitor.ProgressWatch('a' * 32, 'job', 150, 0) + outer = BusinessProgressWatch(0) + # The VBS captures semantic state before/after replacement and at checkpoints. + steps = ((1, 'capture_semantic_state', 1), (2, 'snapshot_attributes', 1), + (50, 'capture_semantic_state', 2), (100, 'snapshot_attributes', 1), + (150, 'capture_semantic_state', 1), (200, 'snapshot_attributes', 1), + (250, 'capture_semantic_state', 2)) + for sequence, (now, stage, done) in enumerate(steps, 1): + assert watch.accept(frame(sequence, stage, done), now) + publish(watch, outer, now) + assert watch.action(now) is None + assert not outer.request_cooperative_stop(now, lambda _: pytest.fail('valid pass stopped')) + requests = [] + assert outer.request_cooperative_stop(400, requests.append) + assert not outer.request_cooperative_stop(550, requests.append) + assert requests == ['inactivity'] + + +def test_same_stage_regression_total_changes_and_heartbeats_do_not_create_progress(): + watch = worker_monitor.ProgressWatch('a' * 32, 'job', 150, 0) + outer = BusinessProgressWatch(0) + snapshots = [] + for sequence, (now, done, total) in enumerate(((1, 4, 5), (100, 3, 20), (149, 4, 30)), 1): + assert watch.accept(frame(sequence, 'save', done, total), now) + snapshots.append(publish(watch, outer, now)) + outer.observe('heartbeat', {}, now) + assert [row['business_sequence'] for row in snapshots] == [1, 1, 1] + assert watch.last_business_progress == 1 + assert watch.action(151) == 'request_stop' + requests = [] + assert outer.request_cooperative_stop(151, requests.append) + assert requests == ['inactivity'] + + +def test_repeated_snapshot_cannot_keep_the_outer_watch_alive(): + watch = worker_monitor.ProgressWatch('a' * 32, 'job', 240, 0) + outer = BusinessProgressWatch(0) + assert watch.accept(frame(1, 'open_project', 0), 1) + state = publish(watch, outer, 1) + outer.observe('state', {'business_progress': state}, 150) + assert not outer.stalled(200) + assert outer.stalled(241) + + +def test_runtime_forwards_the_monitor_identity_and_business_sequence(tmp_path): + from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime + + watch = worker_monitor.ProgressWatch('a' * 32, 'job', 240, 0) + assert watch.accept(frame(1, 'open_project', 0), 1) + (tmp_path / 'worker-progress.json').write_text(json.dumps(watch.snapshot(now=1))) + runtime = BatchCadRuntime(tmp_path, 'task_queue') + runtime._active_evidence = tmp_path + state = runtime.business_progress() + assert state['token'] == 'a' * 32 and state['business_sequence'] == 1 + outer = BusinessProgressWatch(0) + outer.observe('state', {'business_progress': state}, 1) + assert not outer.stalled(200) + assert outer.stalled(241) diff --git a/tests/v1_1/test_project_session_health.py b/tests/v1_1/test_project_session_health.py index 43a3715..21bfd3c 100644 --- a/tests/v1_1/test_project_session_health.py +++ b/tests/v1_1/test_project_session_health.py @@ -52,11 +52,18 @@ def test_changed_project_after_controlled_failure_blocks_remaining_uid(component outcomes['after_call'] = lambda count: project.write_text('unexpected source mutation') if count == 1 else None ids = tuple(task.task_id for task in tasks) result = execute_task_queue(service, ids, stop_event=Event()) - assert not result.paused and [entry.state for entry in result.entries] == ['blocked', 'completed'] - assert calls == [(task_id, ('R1',)), (ids[1], ('R1',)), (ids[1], ('R2',))] + assert result.paused and result.current_task_id == task_id + assert [entry.state for entry in result.entries] == ['blocked', 'pending'] + assert calls == [(task_id, ('R1',))] assert service.has_interrupted_quick_run(task_id) - execute_task_queue(service, ids, stop_event=Event(), queue_id=result.queue_id) - assert len(calls) == 3 + changed_source = project.read_bytes() + resumed = execute_task_queue(service, ids, stop_event=Event(), queue_id=result.queue_id) + assert resumed.paused and resumed.queue_id == result.queue_id and resumed.current_task_id == task_id + assert [(entry.task_id, entry.state) for entry in resumed.entries] == [ + (entry.task_id, entry.state) for entry in result.entries] + assert service.has_interrupted_quick_run(task_id) + assert project.read_bytes() == changed_source + assert calls == [(task_id, ('R1',))] def test_tampered_failure_health_denies_resume(component_case): diff --git a/tests/v1_1/test_target_cell_rules.py b/tests/v1_1/test_target_cell_rules.py index 5c03920..ae30209 100644 --- a/tests/v1_1/test_target_cell_rules.py +++ b/tests/v1_1/test_target_cell_rules.py @@ -221,6 +221,7 @@ def test_gui_optional_cell_reaches_confirmation_without_starting_execution(windo window.run_panel.quick_run_button.setEnabled(True) window.task_list.queue_button.setEnabled(True) (window._execute_project_tasks if batch_run else window._prepare_quick_run)() + qtbot.waitUntil(lambda: len(confirmations) == 1 and not window._workers) assert not errors assert len(confirmations) == 1 assert not window._workers and window._batch_stop is None diff --git a/tools/measure_task_queue.py b/tools/measure_task_queue.py index e99e739..0bd2fba 100644 --- a/tools/measure_task_queue.py +++ b/tools/measure_task_queue.py @@ -143,11 +143,18 @@ def run_scenario(output: Path, *, projects=3, sheets=2, rules=2, behavior='succe stop.clear() result = measured('queue_resume_wall', lambda: execute_task_queue(service, ids, stop_event=stop, queue_id=result.queue_id, runtime=simulated_runtime)) expected_steps = projects * sheets * rules * 2 - expected_calls = 1 + (projects - 1) * sheets * rules * 2 if behavior == 'uncertain_stop' else expected_steps + expected_calls = 1 if behavior == 'uncertain_stop' else expected_steps assert len(calls) == expected_calls if behavior == 'uncertain_stop': - assert not result.paused and result.entries[0].state == 'blocked' - assert all(entry.state == 'completed' for entry in result.entries[1:]) + assert result.paused and result.entries[0].state == 'blocked' + assert all(entry.state == 'pending' for entry in result.entries[1:]) + held = execute_task_queue(service, ids, stop_event=stop, queue_id=result.queue_id, + runtime=simulated_runtime) + assert held.paused and held.queue_id == result.queue_id + assert held.current_task_id == ids[0] + assert [(entry.task_id, entry.state) for entry in held.entries] == [ + (entry.task_id, entry.state) for entry in result.entries] + assert len(calls) == expected_calls else: assert not result.paused assert [entry.state for entry in result.entries] == ['failed' if behavior == 'failure_continue' and i == 0 else 'completed' for i in range(projects)]