diff --git a/docs/reviews/2026-11-27-pr47-audit-649.md b/docs/reviews/2026-11-27-pr47-audit-649.md new file mode 100644 index 0000000..d5fd0aa --- /dev/null +++ b/docs/reviews/2026-11-27-pr47-audit-649.md @@ -0,0 +1,63 @@ +# PR #47 审计 649:核对与整改 + +日期:2026-11-27。审计来源:[评论 649](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/pulls/47#issuecomment-649)。审计基线 `f80127e`,被审计提交 `392ae365`。本次在原 PR 分支上整改,不合并、不关闭 #44。 + +## P1 逐项结论 + +| 项 | 核对结论 | 整改 | +| --- | --- | --- | +| 1 非监督批次恒 paused | 成立 | 由实际拥有本地 BatchCadRuntime 的队列记录运行身份;只有上下文退出且租约、桌面、写进程证明完整才发布释放。没有 supervisor 不再等同未知,也不直接视作成功。实际 UI 完成态用例通过。 | +| 2 资源分支遮住异常 shutdown | 成立,按 P0 处理 | 先确定应用退出结论,再处理资源待释放;`application_shutdown_failed` 持久化并贯穿资源重查、自动续跑和回执恢复。资源消失不能把异常退出升级成完成。 | +| 3 安全失败被改 uncertain | 成立 | 从绑定的最终监督结果恢复确定性业务失败。有效 error 不是“没有最终结果”;缺失或损坏结果仍保护,不删除原 uncertain 证据。 | +| 4 UI 缓存/DB 范围不同 | 成立 | 在后台从新数据库快照解析初始批次;显式所选以所选任务所属批次为准,详情焦点不充当选集。确认后仍严格核对冻结范围,不能扩大。 | +| 5 dirty 提示破坏未启动契约 | 成立 | 候选编辑未保存时明确显示“未启动执行”,保留原控制和授权,零派发。 | +| 6 legacy isolated/interrupted 放行 | 与已确认业务规则冲突 | 保留“写入未知整批暂停,即使资源释放仍需核验并重新确认”。旧用例现在断言待核验分支不准入、零 CAD;同一用例的确定性安全失败分支继续验证正常接续,未删保护断言换绿。 | +| 7 默认套件新增失败 | 审计所报统计作为输入保留 | 定向复现已点名的受影响功能并分类;真实回归修代码,旧隔离/未知续跑断言改为更严格策略。未重跑全量,不能据此宣称默认套件零失败或把原环境问题计作本轮修复。 | + +## P2 摘选逐项处理 + +| 审计指出的现象 | 处理 | +| --- | --- | +| already_completed 未核对当前验收 | 已保存任务需要匹配当前计划和当前轮次的独立网表核验;失败、缺失或不能关联的验收进入 held,不能当作已验收成功。无保存的 no-match 不强求保存网表。 | +| 重复工程登记受完成状态影响 | 在完成/配置等分类之前登记规范化工程身份,不因首项已完成而漏掉重复;重复任务不派发。 | +| 所选范围取焦点 group_id | 改从显式选集的数据库任务解析批次;跨批显式选择仍拒绝。 | +| 启动/清理回执恢复覆盖提示 | 回执修复不占用前台操作提示,资源重启指引和原始错误保留。另复现并修复后台回执读取抢占“确认强制结束”的竞争,读通道结束后按原确认执行一次。 | +| 重试 republish 耗时归零 | 沿用持久化的批次耗时;既有回执没有摘要时也保留已有 elapsed_seconds。 | +| 同 revision 固化瞬时快照不稳定 | 不复用带 batch_snapshot_unstable 的暂时摘要,重新读取生产证据后发布新版本;不重复执行业务。 | +| 代次 state 直接采用自报 released | 当前及历史代次都验证释放证明、租约和资源观察,不凭字符串发布成功。 | +| 重建遗漏已关联 quick-run 资源 | 监督重试在创建工作进程之前绑定请求摘要;本地重试在取得 CAD 资源之前绑定实际运行会话。重建核对原 scope、身份和释放证明,诊断 ZIP 包含被引用的归属记录。 | +| pending_save 不进入问题计数 | 纳入问题项、待核验数量和任务内重试阻断;界面显示“保存待核验”,不提供重试勾选。 | +| 已打开句柄后 WinError 87 被当 gone | 在被审计提交中已经返回 unknown;保留实现并新增此边界的回归。只有 OpenProcess 未找到原 PID 或已证实身份复用等原证明能判 gone。 | +| desktop_lease_pending 可发布 released | 持续阻断直到取得该代租约归还及物理消失证明;历史证明不足不能自行补造归还。 | +| 外层 150 秒与 worker 预算不同 | 外层采用现有活动 worker 报告的更长预算,短预算仍由原 worker 看门狗负责;不新增配置页面或第二套独立计时器。 | + +审计评论称 13 项 P2,但公开正文使用“摘选”,可直接定位的是上表内容;本记录不声称已处理未给出位置和触发条件的其他项。 + +## 本地增量验证 + +只运行新增缺陷及直接受影响的用例;首次反例先红,修改后验证相同边界,不重复全量验收。以下集合有交集,不累加为去重总数。 + +- 监督/资源定向 45 项通过,含真实 Windows 子进程崩溃、Job 收尾、活动 worker 超时、未归还租约和异常退出禁止自动续跑。 +- 回执/运行时/导出定向 40 项通过,含本地真实 PrivateDesktop、generation-zero 从未取得桌面、回执恢复和实际 ZIP 内容;事件重试专项另有 33 项通过。 +- 五个旧策略测试文件的 19 个受影响场景通过:损坏交接/缺少证明不重放,后续工程不派发;显式模拟验证后只处理剩余工程。 +- UI 缓存、显式批次、pending_save、dirty、重启提示与实际非监督批次完成态 6 项通过。 +- 自动诊断 stop/force 交接、导入预检和启动资源重查 11 项通过。旧同步测试替身现在正确完成新增异步预检生命周期;局部批次测试使用显式所选入口,不伪造数据库范围。 +- 重复工程和已完成任务验收两个实际缺陷已复现并修复;当前轮次通过/失败的双向用例通过。 +- 后台回执读取与强制结束确认的竞争已复现,修改后竞争用例与 6 种已有完成/确认顺序共 7 项通过。 + +## 独立复审补充 + +复审进一步指出四个证据缺口,继续按原保护规则整改: + +- 旧监督记录即使标记 completed,也检查实际 CAD shutdown;强制结束记录不能用于接续。 +- 资源暂停的实际续跑必须有匹配会话和结果代次的完整物理释放证明,不能将缺失的 session.json 当作释放。 +- 已保存任务缺少当前 round_id 时保持 held,不能用同计划历史验收替代当前轮次。 +- 事件重试在启动监督进程之前持久化原运行归属,关联写入失败时零启动。本地重试沿用 local-resource 记录绑定自己的实际运行会话;原批已释放、重试桌面仍被外部句柄持有时保持 isolated。 + +前三项新增反例已先复现失败,修改后含对应正常路径共 13 项通过;运行日志接续正例补齐物理证明后 1 项通过。 + +重试启动和本地归属最终窄组 5 项通过:监督启动前中断、关联写盘失败零启动、本地首份业务回执失败、明确前置拒绝的零代关闭、原批释放而重试桌面仍被真实 Windows 外部句柄持有。两个相邻的既有事件重试回归此前也通过。最终命令使用 `-k 'local_retry or incident_supervisor_launch'`,显式附带的两个既有事件节点被该过滤条件排除,因此最终 5 项不重复计入它们;两次命令合计覆盖 7 个不同节点。 + +最终独立只读复审核对了以上四个缺口的实际入口和对应回归;本次限定范围内未发现剩余 P0/P1。27 个修改或新增 Python 文件 AST 可解析;Markdown 代码块成对,差异检查无空白错误。 + +原 ETHERNET_1G 工程和配对 scope/effective 报告仍缺,不放宽其身份一致性校验;本轮没有真实 Mentor 换料、六卷评分、100 工程或冻结包复测。本地重试零代运行遇到明确前置错误且正常关闭后记录未获取资源;进程硬退出、关闭异常或释放证明不足时保留 unknown,不认作成功。 diff --git a/docs/testing/2026-11-27-issue44-incremental-acceptance.md b/docs/testing/2026-11-27-issue44-incremental-acceptance.md index 39df3aa..61f88c5 100644 --- a/docs/testing/2026-11-27-issue44-incremental-acceptance.md +++ b/docs/testing/2026-11-27-issue44-incremental-acceptance.md @@ -61,3 +61,5 @@ - 新一轮和完整恢复工作台的既有功能没有因本轮重复重写。其跨 #43/#46 的现场缺陷仍需原现场证据;本轮仅处理共同的整批准入、写入保护、入口反馈与回执。 本地分支保留,可继续定位剩余现场问题。没有推送、合并、发布或向远端工单发送消息。 + +后续已按要求提交 PR #47。评论 649 引发的增量整改、策略分歧和定向验证另记于 [PR 审计整改记录](../reviews/2026-11-27-pr47-audit-649.md);以上为首次验收当时的记录。 diff --git a/src/dx_productivity/dsh/execution_runs.py b/src/dx_productivity/dsh/execution_runs.py index 562532c..33dc9b0 100644 --- a/src/dx_productivity/dsh/execution_runs.py +++ b/src/dx_productivity/dsh/execution_runs.py @@ -15,14 +15,18 @@ from .scheduling import ScheduleStore from .cad_verification import CadVerificationAdapter from ..trial_task_center import batch_resources from ..trial_task_center.batch_admission import validate_batch_admission -from ..trial_task_center.batch_summary import _checkpoint_source, collect_batch_summary, refresh_batch_resources +from ..trial_task_center.batch_summary import ( + _checkpoint_source, _incident_resource_binding, _incident_resource_path, _queue_request_matches, + _supervisor_request, collect_batch_summary, refresh_batch_resources, +) from ..trial_task_center.errors import TaskCenterError -from ..trial_task_center.path_access import canonical_path, internal_path +from ..trial_task_center.path_access import internal_path from ..trial_task_center.task_queue import execute_task_queue def _failure_evidence(service, journal, run_id, baseline): - evidence = {key: baseline[key] for key in ('tasks', 'entries', 'retry', 'netlist_verification') if key in baseline} + evidence = {key: baseline[key] + for key in ('tasks', 'entries', 'retry', 'netlist_verification', 'elapsed_seconds') if key in baseline} if not baseline: return evidence try: @@ -78,7 +82,6 @@ def execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, resu return _execute_with_schedule(service, root, task_ids, report, stop, run_id, resume=resume, schedule=schedule, automatic=automatic) start = monotonic() - original_supervisor = getattr(service, '_last_supervisor_batch_id', None) journal = RunJournal(root) previous_run = journal.get(run_id) if resume else None try: @@ -101,9 +104,9 @@ def execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, resu receipt = {**receipt, 'entries': entries, 'paused': completed.paused, 'queue_id': completed.queue_id, 'execution_status': _business_status(entries, completed.paused), 'netlist_verification': completed.netlist_verification} - _finish_batch_summary(service, root, journal, manifest, receipt, start, original_supervisor) + _finish_batch_summary(service, root, journal, manifest, receipt, round(monotonic() - start, 3)) raise - return _finish_batch_summary(service, root, journal, manifest, receipt, start, original_supervisor) + return _finish_batch_summary(service, root, journal, manifest, receipt, round(monotonic() - start, 3)) def _execute_with_schedule(service, root, task_ids, report, stop, run_id, *, resume=None, schedule=None, @@ -222,6 +225,8 @@ def _finish_execution_run(service, root, task_ids, stop, run_id, result, *, base 'user_pause_requested': bool(stop.is_set()), 'awaiting_user_resume': bool(result.paused and stop.is_set()), 'entries': entries, 'tasks': [], 'reporting_errors': [], 'message': '请按每项实际计数判断;未命中不表示已替换保存。'} + if 'elapsed_seconds' in baseline: + receipt['elapsed_seconds'] = baseline['elapsed_seconds'] batch_id = getattr(service, '_last_supervisor_batch_id', None) if result.paused and not stop.is_set() and batch_id: from ..trial_task_center.task_queue import resource_pause_admitted @@ -289,33 +294,29 @@ def _business_status(entries, paused): def _bound_supervisors(root, manifest): - from ..trial_task_center.supervisor_protocol import VERSION, decode, valid_journal - records = [] for path in internal_path(root / 'batch-resources').glob('*/request.json'): try: - raw = path.read_bytes() - request = json.loads(raw) - journal = json.loads(path.with_name('supervisor.json').read_bytes()) batch_id = path.parent.name - if (not valid_journal(journal, batch_id) or sha256(raw).hexdigest() != journal['request_sha256'] - or request['version'] != VERSION or canonical_path(request['root']) != canonical_path(root) - or request['batch_id'] != batch_id or request['attempt_id'] != journal['attempt_id'] - or request['operation'] != journal['operation'] or journal['operation'] != 'execute_task_queue' - or request['task_ids'] != journal['task_ids'] - or journal['task_ids'] != manifest['runnable_task_ids']): - continue - arguments = decode(request['arguments']) - if ((arguments.get('queue_id') or arguments.get('checkpoint_id')) == manifest['run_id'] - and list(arguments.get('task_ids', ())) == manifest['runnable_task_ids'] - and arguments.get('expected_plan_hashes') == manifest['plan_hashes'] - and arguments.get('manifest_digest') == manifest['manifest_digest']): + journal, arguments = _supervisor_request(root, batch_id) + if _queue_request_matches(manifest, journal, arguments): records.append((journal.get('started_at') or 0, batch_id)) - except (OSError, ValueError, TypeError, KeyError): + except (OSError, ValueError, TypeError, KeyError, AttributeError): continue return [batch_id for _, batch_id in sorted(records)] +def _receipt_resource_batches(root, manifest, main_batches, previous): + directory = internal_path(root / 'batch-runs' / manifest['run_id']) + linked = [path.stem.removeprefix('incident-resource-') + for path in sorted(directory.glob('incident-resource-*.json'))] + local = [path.stem.removeprefix('local-resource-') + for path in sorted(directory.glob('local-resource-*.json'))] + return list(dict.fromkeys(batch_id for batch_id in + [*main_batches, *(previous or {}).get('resource_batch_ids', ()), *linked, *local] + if isinstance(batch_id, str) and re.fullmatch('[0-9a-f]{32}', batch_id))) + + def _recover_supervised_business(root, manifest, batch_ids): from ..trial_task_center.supervisor_protocol import MessageGate, VERSION from ..trial_task_center.supervisor_result import validated_outcome @@ -329,6 +330,8 @@ def _recover_supervised_business(root, manifest, batch_ids): directory = internal_path(root / 'batch-resources' / batch_id) try: supervisor = json.loads((directory / 'supervisor.json').read_bytes()) + if supervisor.get('business_uncertain') is True: + return {} attempt_id = supervisor['attempt_id'] try: envelope = json.loads((directory / 'result.json').read_bytes()) @@ -360,21 +363,15 @@ def _recover_supervised_business(root, manifest, batch_ids): return {} -def _finish_batch_summary(service, root, journal, manifest, receipt, start, original_supervisor=None, - *, incident_batch_ids=()): +def _finish_batch_summary(service, root, journal, manifest, receipt, elapsed): run_id = manifest['run_id'] - elapsed = round(monotonic() - start, 3) log = service._logging.logger receipt = {**receipt, 'elapsed_seconds': elapsed} has_run = False try: has_run = journal.get(run_id) is not None - batch_ids = list(dict.fromkeys([*_bound_supervisors(root, manifest), *incident_batch_ids])) - current = getattr(service, '_last_supervisor_batch_id', None) - if isinstance(current, str) and current != original_supervisor and re.fullmatch('[0-9a-f]{32}', current): - has_request = internal_path(root / 'batch-resources' / current / 'request.json').is_file() - if not has_request and current not in batch_ids: - batch_ids.append(current) + batch_ids = _receipt_resource_batches(root, manifest, _bound_supervisors(root, manifest), + journal.batch_summary(run_id)) summary = collect_batch_summary(service, root, manifest, receipt, batch_ids=batch_ids, elapsed_seconds=elapsed, no_dispatch=not has_run) if not has_run: @@ -397,7 +394,33 @@ def _finish_batch_summary(service, root, journal, manifest, receipt, start, orig 'acceptance': summary['acceptance'], 'reporting_errors': summary['reporting_errors'], 'summary': summary} -def _republish_incident_batch_summary(service, root, run_id, receipt, *, batch_id=None): +def _record_incident_resource_link(root, run_id, batch_id, task_id, expected_item, *, local=False, + manifest_digest=None): + path = internal_path(root / 'batch-runs' / run_id / 'manifest.json') + try: + manifest = json.loads(path.read_bytes()) + if (manifest['run_id'] != run_id or task_id not in manifest['runnable_task_ids'] + or (manifest_digest is not None and manifest['manifest_digest'] != manifest_digest)): + raise ValueError('incident resource run identity changed') + if local: + from ..trial_task_center.task_queue import _local_resource_path + path = root / _local_resource_path(run_id, batch_id) + binding = {'version': 1, 'session_id': batch_id, 'queue_id': run_id, 'kind': 'quick_run_queue', + 'manifest_digest': manifest['manifest_digest'], 'task_ids': manifest['runnable_task_ids'], + 'plan_hashes': manifest['plan_hashes'], 'task_id': task_id, 'never_acquired': False} + batch_resources.write_record(path, binding) + return lambda: batch_resources.write_record(path, dict(binding, never_acquired=True)) + supervisor, arguments = _supervisor_request(root, batch_id) + binding = _incident_resource_binding(manifest, supervisor, arguments) + if binding['task_id'] != task_id or arguments.get('expected_item') != expected_item: + raise ValueError('incident resource request selection changed') + batch_resources.write_record(root / _incident_resource_path(manifest, batch_id), binding) + except (OSError, ValueError, TypeError, KeyError, AttributeError) as error: + raise TaskCenterError('incident_resource_link_unavailable', + '无法记录本次重试与原批次的资源关联,未启动后台执行。') from error + + +def _republish_incident_batch_summary(service, root, run_id, receipt): """Update the original batch revision after an admitted incident retry.""" root = Path(root) path = internal_path(root / 'batch-runs' / run_id / 'manifest.json') @@ -410,16 +433,14 @@ def _republish_incident_batch_summary(service, root, run_id, receipt, *, batch_i or manifest['plan_hashes'] != run['plan_hashes']): raise TaskCenterError('run_scope', '原批次回执身份变化,无法更新。') previous = journal.batch_summary(run_id) or {} - batch_ids = list(previous.get('resource_batch_ids', ())) - if isinstance(batch_id, str) and re.fullmatch('[0-9a-f]{32}', batch_id): - batch_ids.append(batch_id) - return _finish_batch_summary(service, root, journal, manifest, receipt, monotonic(), - getattr(service, '_last_supervisor_batch_id', None), - incident_batch_ids=batch_ids) + elapsed = previous.get('elapsed_seconds', + receipt.get('elapsed_seconds', (run['result'] or {}).get('elapsed_seconds', 0))) + return _finish_batch_summary(service, root, journal, manifest, receipt, elapsed) def _publish_batch_summary(root, journal, summary, receipt, *, has_run): run_id = summary['run_id'] + receipt = dict(receipt, elapsed_seconds=summary['elapsed_seconds']) summary = (journal.save_batch_summary(run_id, summary, receipt) if has_run else dict(summary, revision=1)) try: batch_resources.write_record(root / 'batch-runs' / run_id / 'batch-receipt.json', summary) @@ -463,7 +484,9 @@ def _recover_batch_receipts(service, root, paths): durable = journal.batch_summary(run_id) running = run['status'] == 'running' if (not running and durable - and receipt.get('summary', {}).get('revision') == durable['revision']): + and receipt.get('summary', {}).get('revision') == durable['revision'] + and not any(row.get('code') == 'batch_snapshot_unstable' + for row in durable['reporting_errors'])): refreshed = refresh_batch_resources(root, manifest, durable) if refreshed is not durable: _publish_batch_summary(root, journal, refreshed, receipt, has_run=True) @@ -475,17 +498,18 @@ def _recover_batch_receipts(service, root, paths): pass batch_resources.write_record(output, durable) continue - batch_ids = _bound_supervisors(root, manifest) + main_batches = _bound_supervisors(root, manifest) if running or not receipt: previous_ids = set((durable or {}).get('resource_batch_ids', ())) if running else set() - current_ids = [batch_id for batch_id in batch_ids if batch_id not in previous_ids] + current_ids = [batch_id for batch_id in main_batches if batch_id not in previous_ids] recovered = _recover_supervised_business(root, manifest, current_ids) if recovered: receipt = recovered elif running: receipt.update(status='interrupted', execution_status='interrupted', code='execution_interrupted') receipt.setdefault('status', 'interrupted') - elapsed = receipt.get('elapsed_seconds') or 0 + 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) _publish_batch_summary(root, journal, summary, receipt, has_run=True) @@ -572,8 +596,6 @@ def _execute_incident_retry(service, root, task_id, run_id, *, expected_item, st raise TaskCenterError('run_scope', '原队列检查点身份或范围已变化;不执行重试。') retry_run = journal.begin_retry(service, run_id, task_id, operation_keys) baseline = (retry_run.get('result') or {}) if original else {} - before_batch = None - retry_dispatched = False try: if original: checkpoint['entries'][task_id].update(state='running', message='仅执行已预约的原失败项重试。') @@ -582,10 +604,15 @@ def _execute_incident_retry(service, root, task_id, run_id, *, expected_item, st with NetlistVerification(root, token, stop_event) as checks: # Never capture a partially replaced project as a new "before". checks.before_task(child, task_id, existing_only=True) - before_batch = getattr(service, '_last_supervisor_batch_id', None) - retry_dispatched = True + controls = {} + if revalidate is not None: + def bind_request(batch_id, *, local=False): + return _record_incident_resource_link(root, run_id, batch_id, task_id, expected_item, + local=local, manifest_digest=checkpoint.get('manifest_digest')) + + controls.update(revalidate=revalidate, before_launch=bind_request) outcome = service.execute_quick_run_queue(task_id, expected_item=expected_item, stop_event=stop_event, - **({'revalidate': revalidate} if revalidate is not None else {})) + **controls) current = service.task_context(task_id) p = current.progress complete = p.queue_complete and not p.failed_items and not current.interrupted and not outcome.paused @@ -643,9 +670,7 @@ def _execute_incident_retry(service, root, task_id, run_id, *, expected_item, st receipt = _finish_execution_run(service, root, original['task_ids'], stop_event, run_id, result, baseline=baseline, resource_report_pending=revalidate is not None) if revalidate is not None: - batch_id = getattr(service, '_last_supervisor_batch_id', None) - receipt = _republish_incident_batch_summary(service, root, run_id, receipt, - batch_id=batch_id if batch_id != before_batch else None) + receipt = _republish_incident_batch_summary(service, root, run_id, receipt) verification.update(run_receipt_updated=True, run_status=receipt['status']) return outcome, current, verification except Exception as error: @@ -665,10 +690,8 @@ def _execute_incident_retry(service, root, task_id, run_id, *, expected_item, st 'error': type(readback_error).__name__}] journal.finish(run_id, failure) if revalidate is not None: - batch_id = getattr(service, '_last_supervisor_batch_id', None) try: - _republish_incident_batch_summary(service, root, run_id, failure, - batch_id=batch_id if retry_dispatched and batch_id != before_batch else None) + _republish_incident_batch_summary(service, root, run_id, failure) except Exception as reporting_error: service._logging.logger.error('incident_batch_receipt_unavailable run_id=%s error=%s', run_id, type(reporting_error).__name__) diff --git a/src/dx_productivity/trial_task_center/batch_admission.py b/src/dx_productivity/trial_task_center/batch_admission.py index c73d130..546a1c4 100644 --- a/src/dx_productivity/trial_task_center/batch_admission.py +++ b/src/dx_productivity/trial_task_center/batch_admission.py @@ -13,6 +13,34 @@ _digest = task_lifecycle._digest POLICY_VERSION = 'issue44-strict-v1' +def _completed_acceptance_verified(service, context): + if not context.progress.saved_items: + return True # 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 + 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 + 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 + 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 + + def resolve_batch_task_ids(tasks, group_id, *, selected_ids=None): records = {task.task_id: task for task in tasks} members = sorted((task for task in records.values() if task.group_id == group_id @@ -61,25 +89,32 @@ def build_batch_admission(service, task_ids, *, scope_kind): decisions.append(row) try: context = service.task_context(task_id) + task = context.task fingerprints.append(asdict(context)) row['project'] = str(context.project.path) if context.project else '' + if context.project is not None: + path_key = str(context.project.path.resolve(strict=False)).casefold() + if path_key in paths: + blockers.append('本批重复包含同一个工程,请核对任务绑定。') + row.update(reason_code='project_duplicate', message='工程在本次范围重复。') + continue + paths.add(path_key) 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): + row.update(classification='held', reason_code='acceptance_unverified', + message='已保存结果的当前轮次验收未通过或证据不可核验,请先核对。') + blockers.append(f'{task.name}:{row["message"]}') + continue row.update(classification='already_completed', reason_code='already_completed', message='本轮已有完整执行结果,不重复派发。') continue if context.project is None or not context.project.path.is_file(): row.update(reason_code='project_missing', message='工程文件不存在或不可访问。') continue - path_key = str(context.project.path.resolve()).casefold() - if path_key in paths: - blockers.append('本批重复包含同一个工程,请核对任务绑定。') - row.update(reason_code='project_duplicate', message='工程在本次范围重复。') - continue - paths.add(path_key) report = task_lifecycle.preflight(service, [task_id]) item = report['tasks'][0] count = item['enabled_rules'] diff --git a/src/dx_productivity/trial_task_center/batch_resources.py b/src/dx_productivity/trial_task_center/batch_resources.py index c765448..e759957 100644 --- a/src/dx_productivity/trial_task_center/batch_resources.py +++ b/src/dx_productivity/trial_task_center/batch_resources.py @@ -199,6 +199,8 @@ def _released_evidence(record): """A state label alone must never reopen the physical resource gate.""" proof = record.get('release_proof', {}) cleanup = record.get('cleanup') or {} + if cleanup.get('desktop_lease_pending') is True: + return False if (proof.get('generation') == record['generation'] and proof.get('desktop_not_acquired') is True and cleanup.get('desktop_not_acquired') is True and cleanup.get('desktop_handle_closed') is True and cleanup.get('owned_cleanup_complete') is True and not cleanup.get('errors') @@ -217,6 +219,7 @@ def _released_evidence(record): last = releases[-1] cleanup = last.get('cleanup') or {} return (last.get('generation') == record['generation'] and last.get('desktop') == record['desktop'] + and cleanup.get('desktop_lease_pending') is not True and cleanup.get('desktop_handle_closed') is True and not cleanup.get('errors') and (cleanup.get('desktop_confirmation') or {}).get('released') is True) @@ -360,6 +363,8 @@ 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: diff --git a/src/dx_productivity/trial_task_center/batch_summary.py b/src/dx_productivity/trial_task_center/batch_summary.py index 6b96070..2139fef 100644 --- a/src/dx_productivity/trial_task_center/batch_summary.py +++ b/src/dx_productivity/trial_task_center/batch_summary.py @@ -3,11 +3,12 @@ from collections import Counter from hashlib import sha256 import json from pathlib import Path +import re import sqlite3 from . import batch_resources from .execution_journal import ExecutionJournal, _targets -from .path_access import internal_path +from .path_access import canonical_path, internal_path _TASK_STATES = ('completed', 'failed', 'blocked', 'skipped', 'already_completed', @@ -198,13 +199,54 @@ def _checkpoint_source(root, manifest): return {}, None, None, 'checkpoint_unavailable' -def _resource_source(root, batch_ids, *, scope, no_dispatch): - from .batch_supervisor import pending_supervisors - from .supervisor_protocol import valid_journal +def _supervisor_request(root, batch_id): + from .supervisor_protocol import VERSION, decode, valid_journal + + if not isinstance(batch_id, str) or not re.fullmatch('[0-9a-f]{32}', batch_id): + raise ValueError('invalid supervisor identifier') + directory = internal_path(root / 'batch-resources' / batch_id) + raw = (directory / 'request.json').read_bytes() + request = json.loads(raw) + supervisor = json.loads((directory / 'supervisor.json').read_bytes()) + if (not valid_journal(supervisor, batch_id) or sha256(raw).hexdigest() != supervisor['request_sha256'] + or request['version'] != VERSION or canonical_path(request['root']) != canonical_path(root) + or request['batch_id'] != batch_id or request['attempt_id'] != supervisor['attempt_id'] + or request['operation'] != supervisor['operation'] or request['task_ids'] != supervisor['task_ids']): + raise ValueError('supervisor request identity changed') + return supervisor, decode(request['arguments']) + + +def _queue_request_matches(manifest, supervisor, arguments): + scope = manifest['runnable_task_ids'] + return (supervisor['operation'] == 'execute_task_queue' and supervisor['task_ids'] == scope + and (arguments.get('queue_id') or arguments.get('checkpoint_id')) == manifest['run_id'] + and list(arguments.get('task_ids', ())) == scope + and arguments.get('expected_plan_hashes') == manifest['plan_hashes'] + and arguments.get('manifest_digest') == manifest['manifest_digest']) + + +def _incident_resource_path(manifest, batch_id): + return Path('batch-runs') / manifest['run_id'] / f'incident-resource-{batch_id}.json' + + +def _incident_resource_binding(manifest, supervisor, arguments): + task_id = arguments.get('task_id') + if (supervisor['operation'] != 'execute_quick_run_queue' or supervisor['task_ids'] != [task_id] + or task_id not in manifest['runnable_task_ids']): + raise ValueError('incident resource request scope changed') + return {'manifest_digest': manifest['manifest_digest'], 'task_id': task_id, + 'request_sha256': supervisor['request_sha256']} + + +def _resource_source(root, batch_ids, *, manifest, no_dispatch): + from .batch_supervisor import _abnormal_shutdown, pending_supervisors + from .task_queue import _local_resource_path references, generations, states = [], [], [] + supervisor_outcomes = {} try: related = batch_resources.pending_resources(root) + supervisors = pending_supervisors(root) if not batch_ids: states.extend('unknown' if record.get('error') else 'isolated' if record.get('state') == 'isolated' else 'pending' for record in related) @@ -215,18 +257,45 @@ def _resource_source(root, batch_ids, *, scope, no_dispatch): if internal_path(root / path).is_file(): references.append(path.as_posix()) record_path = internal_path(root / directory / 'session.json') - supervisor_path = internal_path(root / directory / 'supervisor.json') try: + local_kind = None + local_path = _local_resource_path(manifest['run_id'], batch_id) + if internal_path(root / local_path).is_file(): + references.append(local_path.as_posix()) + local = json.loads(internal_path(root / local_path).read_bytes()) + expected = {'version': 1, 'session_id': batch_id, 'queue_id': manifest['run_id'], + 'manifest_digest': manifest['manifest_digest'], + 'task_ids': manifest['runnable_task_ids'], 'plan_hashes': manifest['plan_hashes']} + if any(local.get(key) != value for key, value in expected.items()): + raise ValueError('local runtime scope changed') + local_kind = local.get('kind', 'task_queue') + if (local_kind not in {'task_queue', 'quick_run_queue'} + or local_kind == 'quick_run_queue' and local.get('task_id') not in manifest['runnable_task_ids']): + raise ValueError('local runtime task scope changed') + if local.get('never_acquired') is True and not record_path.is_file(): + states.append('released' if not related and not supervisors else 'unknown') + continue + supervisor = {} + else: + supervisor, arguments = _supervisor_request(root, batch_id) + if supervisor['operation'] == 'execute_quick_run_queue': + binding = _incident_resource_binding(manifest, supervisor, arguments) + binding_path = _incident_resource_path(manifest, batch_id) + if internal_path(root / binding_path).is_file(): + references.append(binding_path.as_posix()) + if json.loads(internal_path(root / binding_path).read_bytes()) != binding: + raise ValueError('incident resource binding changed') + # Previously published receipt IDs predate the dedicated binding file. + elif not _queue_request_matches(manifest, supervisor, arguments): + raise ValueError('resource request scope changed') + supervisor_outcomes[batch_id] = supervisor.get('outcome') record = json.loads(record_path.read_bytes()) - supervisor = json.loads(supervisor_path.read_bytes()) if (not batch_resources._valid_record(record, record_path) - or not valid_journal(supervisor, batch_id)): - raise ValueError('resource record scope changed') - tasks = supervisor['task_ids'] - if not ((supervisor['operation'] == 'execute_task_queue' and tasks == scope) - or (supervisor['operation'] == 'execute_quick_run_queue' - and len(tasks) == 1 and tasks[0] in scope)): + or local_kind and record['kind'] != local_kind + or local_kind == 'quick_run_queue' and record.get('log_task_ids') != [local['task_id']]): raise ValueError('resource record scope changed') + if _abnormal_shutdown(record_path.parent): + supervisor_outcomes[batch_id] = 'application_shutdown_failed' matching = [item for item in related if item.get('session_id') == batch_id or f'/{batch_id}/' in item.get('record_path', '').replace('\\', '/')] states.extend('unknown' if item.get('error') else @@ -235,18 +304,28 @@ def _resource_source(root, batch_ids, *, scope, no_dispatch): name = Path(item['record_path']).name if name.startswith('isolated-generation-'): references.append((directory / name).as_posix()) - generations.extend({'session_id': batch_id, 'generation': release['generation'], - 'state': 'released', 'reason': release.get('reason')} - for release in record.get('generation_releases', ()) - if release['generation'] != record['generation']) + for release in record.get('generation_releases', ()): + generation = release['generation'] + if generation == record['generation']: + continue + historical = {**record, **release, 'release_proof': {}, 'processes': [], + 'generation_releases': [release]} + released = (batch_resources._valid_record(historical, record_path) + and batch_resources._released_evidence(historical) + and not any(item.get('generation') == generation for item in matching)) + states.append('released' if released else 'unknown') + generations.append({'session_id': batch_id, 'generation': generation, + 'state': 'released' if released else 'unknown', 'reason': release.get('reason')}) declared = record['state'] + proven = (declared == 'released' and batch_resources._released_evidence(record) + and not any(item.get('generation') == record['generation'] for item in matching)) + generation_state = 'unknown' if declared == 'released' and not proven else declared + if generation_state == 'unknown': + states.append('unknown') if not matching: - if declared == 'released' and batch_resources._released_evidence(record): - states.append('released') - else: - states.append('unknown') + states.append('released' if proven else 'unknown') generations.append({'session_id': batch_id, 'generation': record['generation'], - 'state': declared, 'supervisor_status': supervisor.get('outcome'), + 'state': generation_state, 'supervisor_status': supervisor_outcomes[batch_id], 'stopping_reason': supervisor.get('stopping_reason') or record.get('stopping_reason'), 'stop_requested_at': supervisor.get('stop_requested_at'), 'business_idle_timeout_seconds': supervisor.get('business_idle_timeout_seconds'), @@ -256,14 +335,15 @@ def _resource_source(root, batch_ids, *, scope, no_dispatch): 'supervisor_digest': _digest(supervisor)}) except (OSError, ValueError, TypeError, KeyError, AttributeError): states.append('unknown') - for item in pending_supervisors(root): + for item in supervisors: if not batch_ids or item.get('batch_id') in batch_ids: states.append('unknown' if item.get('error') else 'pending') except (OSError, ValueError, TypeError, KeyError, RuntimeError): states.append('unknown') state = next((state for state in ('unknown', 'isolated', 'pending') if state in states), 'released' if states or no_dispatch else 'unknown') - return {'state': state, 'generations': generations, 'evidence': references} + return {'state': state, 'generations': generations, 'evidence': references, + 'supervisor_outcomes': supervisor_outcomes} def collect_batch_summary(service, root, manifest, receipt, *, batch_ids, elapsed_seconds, no_dispatch=False): @@ -276,7 +356,7 @@ def collect_batch_summary(service, root, manifest, receipt, *, batch_ids, elapse def sources(): rows, rounds, missing = _operation_sources(service, task_ids) checkpoint, checkpoint_digest, path, error = _checkpoint_source(root, manifest) - resource = _resource_source(root, batch_ids, scope=manifest['runnable_task_ids'], no_dispatch=no_dispatch) + 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)} @@ -299,10 +379,16 @@ def collect_batch_summary(service, root, manifest, receipt, *, batch_ids, elapse summary = summarize_batch(manifest, {'entries': entries, 'paused': receipt.get('paused'), 'acceptance': acceptance, 'execution_status': execution_status, 'snapshot_unstable': unstable, 'operation_evidence_missing': missing}, rows, resource, elapsed_seconds=elapsed_seconds) - reporting_errors = list(receipt.get('reporting_errors', ())) + reporting_errors = [row for row in receipt.get('reporting_errors', ()) + if row.get('code') != 'batch_snapshot_unstable'] if error or unstable: reporting_errors.append({'code': 'batch_snapshot_unstable' if unstable else error}) stop_reason = receipt.get('code') or receipt.get('stop_reason') + if (stop_reason == 'application_shutdown_failed' + or 'application_shutdown_failed' in resource['supervisor_outcomes'].values()): + stop_reason = 'application_shutdown_failed' + if summary['execution_status'] == 'completed': + summary['status'] = 'failed' if stop_reason == 'batch_resources_pending' and summary['execution_status'] in {'completed', 'failed'}: stop_reason = 'resource_pending' if summary['resource_state'] != 'released' else None if not stop_reason and receipt.get('user_pause_requested'): @@ -328,13 +414,18 @@ def collect_batch_summary(service, root, manifest, receipt, *, batch_ids, elapse def refresh_batch_resources(root, manifest, summary): """Reconcile resource closure while keeping the durable business snapshot.""" batch_ids = summary['resource_batch_ids'] - if summary['resource_state'] == 'released' or not batch_ids: + if not batch_ids or (summary['resource_state'] == 'released' and 'supervisor_outcomes' in summary['resource']): return summary - resource = _resource_source(root, batch_ids, scope=manifest['runnable_task_ids'], no_dispatch=False) - if resource['state'] != 'released': + resource = _resource_source(root, batch_ids, manifest=manifest, no_dispatch=False) + shutdown_failed = 'application_shutdown_failed' in resource['supervisor_outcomes'].values() + if resource['state'] != 'released' and not shutdown_failed: return summary status = summary['status'] stop_reason = summary['stop_reason'] + if shutdown_failed: + stop_reason = 'application_shutdown_failed' + if summary['execution_status'] == 'completed': + status = 'failed' source_unavailable = (any(row.get('state') == 'unknown' for row in summary['source_versions']['rounds'].values()) or any(row.get('code') == 'batch_snapshot_unstable' for row in summary['reporting_errors'])) if (summary['execution_status'] == 'completed' and summary['acceptance_status'] in {'verified', 'not_required'} @@ -342,6 +433,9 @@ def refresh_batch_resources(root, manifest, summary): status = 'completed' if stop_reason == 'resource_pending': stop_reason = None - return {**summary, 'status': status, 'stop_reason': stop_reason, 'resource_state': 'released', 'resource': resource, + if resource == summary['resource'] and status == summary['status'] and stop_reason == summary['stop_reason']: + return summary + return {**summary, 'status': status, 'stop_reason': stop_reason, 'resource_state': resource['state'], + 'resource': resource, 'source_versions': {**summary['source_versions'], 'resource_digest': _digest(resource)}, 'evidence': {**summary['evidence'], 'resource_records': resource['evidence']}} diff --git a/src/dx_productivity/trial_task_center/batch_supervisor.py b/src/dx_productivity/trial_task_center/batch_supervisor.py index 225b353..f3ebbc3 100644 --- a/src/dx_productivity/trial_task_center/batch_supervisor.py +++ b/src/dx_productivity/trial_task_center/batch_supervisor.py @@ -4,6 +4,7 @@ from __future__ import annotations from contextlib import contextmanager import json import hashlib +import math import os from pathlib import Path import queue @@ -29,6 +30,7 @@ class BusinessProgressWatch: """Control-channel liveness cannot certify forward business progress.""" def __init__(self, started, idle_timeout=150): self.last_progress = started + self.fallback_idle_timeout = idle_timeout self.idle_timeout = idle_timeout self.signatures = {} self.stage_progress = {} @@ -41,6 +43,11 @@ class BusinessProgressWatch: if kind == 'state': progress = payload.get('business_progress') or {} self.worker_stop_requested = bool(progress.get('stop_requested') or payload.get('stopping_reason')) + timeout = progress.get('idle_timeout_seconds') + self.idle_timeout = self.fallback_idle_timeout + if (progress.get('job_id') and type(timeout) in (int, float) + and 0 < timeout < math.inf): + self.idle_timeout = max(self.fallback_idle_timeout, timeout) 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) @@ -328,6 +335,7 @@ def reconcile_supervisors(root): """Recheck orphan ownership only; this never launches or replays a job.""" from .batch_resources import _process_gone, blocking_resources, write_record from .read_recovery import process_tree_exited + from .supervisor_result import validated_outcome physical = blocking_resources(root) for record in pending_supervisors(root): owner = (_LIVE_SUPERVISORS.get(canonical_path(record['record_path'])) @@ -339,12 +347,21 @@ def reconcile_supervisors(root): or (record.get('process_observation') or {}).get('state') == 'unknown' or (identity and not _process_gone(identity))): continue - if record.get('outcome') not in {'interrupted', 'completed_resources_pending'}: - _mark_interrupted(root, record, 'Supervisor ended without a reconciled final result') - if any(item.get('session_id') == record['batch_id'] or not item.get('session_id') for item in physical): - continue path = Path(record.pop('record_path')) - outcome = 'completed' if record.get('outcome') == 'completed_resources_pending' else 'interrupted' + related = _related_resources(physical, record['batch_id']) + if record.get('outcome') != 'interrupted': + try: + response, _ = _read_final_response(path.parent, record) + validated_outcome(record['operation'], response) + except (OSError, ValueError, KeyError, TypeError, AttributeError): + _mark_interrupted(root, record, 'Supervisor ended without a reconciled final result') + else: + _record_response_outcome(record, response, path.parent, related) + if related: + write_record(path, record) + if related: + continue + outcome = 'completed' if record['outcome'] == 'ok' else record['outcome'] if outcome == 'interrupted': from .task_queue import reconcile_interrupted_queue reconcile_interrupted_queue(root, record) @@ -369,65 +386,101 @@ def _environment(): return environment -def _finish_response(root, journal, response, context): +def _read_final_response(directory, journal, gate=None): + saved_only = False + try: + response = json.loads(internal_path(directory / 'result.json').read_bytes()) + except FileNotFoundError: + response = json.loads(internal_path(directory / 'business-result.json').read_bytes()) + if response['payload'].get('business_succeeded') is not True: + raise ValueError('Untrusted saved business result') + response = dict(response, type='result', sequence=(gate.sequence if gate else 0) + 1) + saved_only = True + minimum_sequence = max(1, gate.sequence) if gate else 1 + minimum_generation = gate.generation if gate else 1 + if (response.get('version') != VERSION or response.get('batch_id') != journal['batch_id'] + or response.get('attempt_id') != journal['attempt_id'] or response.get('type') != 'result' + or type(response.get('sequence')) is not int or response['sequence'] < minimum_sequence + or type(response.get('generation')) is not int or response['generation'] < minimum_generation): + raise ValueError('stale or invalid final supervisor result') + return response['payload'], saved_only + + +def _related_resources(pending, batch_id): + return tuple(item for item in pending if item.get('session_id') == batch_id or not item.get('session_id')) + + +def _abnormal_shutdown(directory): + resource_path = internal_path(directory / 'session.json') + try: + resource = json.loads(resource_path.read_bytes()) + except FileNotFoundError: + return False + shutdown = resource.get('cad_shutdown') if isinstance(resource, dict) else None + if shutdown is None and isinstance(resource, dict): + return False + if (not isinstance(shutdown, dict) + or not isinstance(shutdown.get('cleanup_errors', ()), (list, tuple)) + or any(not isinstance(item, dict) for item in shutdown.get('cleanup_errors', ()))): + raise ValueError('invalid shutdown record shape') + return (shutdown.get('orderly_shutdown') is False or bool(shutdown.get('forced_termination')) + or bool(shutdown.get('diagnostic_errors')) + or any(item.get('stage') != 'desktop_release' for item in shutdown.get('cleanup_errors', ()))) + + +def _record_response_outcome(journal, response, directory, related, *, ownership_pending=False): + from .batch_resources import _isolation_evidence + + isolated = tuple(item for item in related if item.get('state') == 'isolated' and _isolation_evidence(item)) + pending = bool(related) or ownership_pending + writers_exited = not ownership_pending and len(related) == len(isolated) + try: + abnormal_shutdown = _abnormal_shutdown(directory) + except (OSError, ValueError, TypeError) as failure: + journal['shutdown_record_error'] = str(failure) + abnormal_shutdown = True + journal['state'] = 'blocked' if pending or journal.get('shutdown_record_error') else 'finished' + if abnormal_shutdown or journal.get('outcome') == 'application_shutdown_failed': + journal['outcome'] = 'application_shutdown_failed' + elif response['business_succeeded']: + journal['outcome'] = 'completed_resources_pending' if pending else 'ok' + else: + journal['outcome'] = 'error' + journal['resource_recheck'] = {'pending': pending, 'warnings': list(isolated), + 'desktop_released': not pending, 'owned_writers_exited': writers_exited, 'checked_at': time.time()} + return isolated + + +def _finish_response(root, journal, response, context, *, transport_error=None, ownership_pending=False): """A supervisor exit may release its last USER reference. Never repeat work.""" - from .batch_resources import cleanup_pending_resources, _isolation_evidence, write_record + from .batch_resources import cleanup_pending_resources, pending_resources, write_record from .supervisor_result import validated_outcome, resource_pending_error, application_shutdown_error result, error, primary = validated_outcome(journal['operation'], response) - pending = cleanup_pending_resources(root, logging_context=context) - related = tuple(item for item in pending if item.get('session_id') == journal['batch_id'] or not item.get('session_id')) - isolated = tuple(item for item in related if item.get('state') == 'isolated' and _isolation_evidence(item)) - writers_exited = len(related) == len(isolated) - journal['state'] = 'blocked' if related else 'finished' - journal['outcome'] = ('completed_resources_pending' if related and response.get('business_succeeded') - else response.get('status', 'interrupted')) - journal['resource_recheck'] = {'pending': bool(related), 'warnings': list(isolated), - 'desktop_released': not related, 'owned_writers_exited': writers_exited, 'checked_at': time.time()} - write_record(Path(root) / 'batch-resources' / journal['batch_id'] / 'supervisor.json', journal) - if related: - failure = resource_pending_error(journal['operation'], result, error, primary or error) - failure.resources_released = False - failure.owned_writers_exited = writers_exited + if transport_error is None: + pending = cleanup_pending_resources(root, logging_context=context) + related = _related_resources(pending, journal['batch_id']) + else: + related = pending_resources(root) + journal['error'] = str(transport_error) + path = Path(root) / 'batch-resources' / journal['batch_id'] / 'supervisor.json' + isolated = _record_response_outcome(journal, response, path.parent, related, ownership_pending=ownership_pending) + write_record(path, journal) + recheck = journal['resource_recheck'] + if journal['outcome'] == 'application_shutdown_failed': + failure = application_shutdown_error(result, transport_error or error, primary) + elif recheck['pending'] or transport_error is not None: + failure = resource_pending_error(journal['operation'], result, transport_error or error, primary or error) + else: + failure = None + if failure is not None: + failure.resources_released = recheck['desktop_released'] + failure.owned_writers_exited = recheck['owned_writers_exited'] failure.resource_warnings = isolated raise failure for failure in (error, primary): if failure is not None: failure.resources_released = True failure.owned_writers_exited = True - resource_path = internal_path(Path(root) / 'batch-resources' / journal['batch_id'] / 'session.json') - def preserve_shutdown_failure(detail): - try: - write_record(Path(root) / 'batch-resources' / journal['batch_id'] / 'supervisor.json', journal) - except OSError as record_error: - context.logger.error('supervisor_shutdown_record_failed batch_id=%s error=%s', - journal['batch_id'], record_error) - journal['shutdown_record_error'] = str(record_error) - def shutdown_failure(): - failure = application_shutdown_error(result, error, primary) - failure.resources_released = True - failure.owned_writers_exited = True - return failure - try: - resource = json.loads(resource_path.read_text(encoding='utf-8')) - except FileNotFoundError: - resource = {} - except (OSError, ValueError, TypeError) as failure: - journal.update(state='blocked', shutdown_record_error=str(failure)) - preserve_shutdown_failure(failure) - raise shutdown_failure() from failure - shutdown = resource.get('cad_shutdown') if isinstance(resource, dict) else None - if shutdown is None and isinstance(resource, dict): - shutdown = {} - if (not isinstance(shutdown, dict) - or not isinstance(shutdown.get('cleanup_errors', ()), (list, tuple)) - or any(not isinstance(item, dict) for item in shutdown.get('cleanup_errors', ()))): - journal.update(state='blocked', shutdown_record_error='invalid shutdown record shape') - preserve_shutdown_failure('invalid shutdown record shape') - raise shutdown_failure() - if (shutdown.get('orderly_shutdown') is False or shutdown.get('forced_termination') - or shutdown.get('diagnostic_errors') - or any(item.get('stage') != 'desktop_release' for item in shutdown.get('cleanup_errors', ()))): - raise shutdown_failure() if response.get('business_succeeded'): if response.get('error'): context.logger.info('supervisor_resource_recovery_passed batch_id=%s business_replayed=false', journal['batch_id']) @@ -442,7 +495,7 @@ def _finish_response(root, journal, response, context): def run_supervised(service, operation, arguments, *, stop_event=None, on_progress=None, on_phase=None, - revalidate=None): + revalidate=None, before_launch=None): from .batch_resources import write_record, process_identity from .isolated_desktop import _Win32Api from .stop_control import StopControl @@ -493,7 +546,18 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres 'operation': operation, 'arguments': encode(arguments), 'task_ids': journal['task_ids'], 'interactive_stop': isinstance(stop_event, StopControl)}) journal['request_sha256'] = hashlib.sha256(internal_path(request).read_bytes()).hexdigest() - write_record(directory / 'supervisor.json', journal) + journal_path = directory / 'supervisor.json' + write_record(journal_path, journal) + if before_launch is not None: + try: + before_launch(batch_id) + except Exception as error: + journal.update(state='finished', outcome='prelaunch_rejected', error=str(error)) + try: + write_record(journal_path, journal) + except OSError: + service._logging.logger.exception('supervisor_prelaunch_rejection_unavailable batch_id=%s', batch_id) + raise from .supervisor_evidence import LifecycleEvidence lifecycle = LifecycleEvidence(directory) lifecycle.try_append('supervisor_starting', operation=operation) @@ -710,22 +774,11 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres raise resource_pending_error(operation, None, ownership_cleanup_error, failure) raise failure try: - try: - response = json.loads(internal_path(directory / 'result.json').read_text(encoding='utf-8')) - except FileNotFoundError: - saved = json.loads(internal_path(directory / 'business-result.json').read_text(encoding='utf-8')) - if (saved.get('version') != VERSION or saved.get('batch_id') != batch_id - or saved.get('attempt_id') != attempt_id or not saved['payload'].get('business_succeeded')): - raise ValueError('Untrusted saved business result') - response = dict(saved, type='result', sequence=gate.sequence + 1) + response, saved_only = _read_final_response(directory, journal, gate) + if saved_only: service._logging.logger.warning('supervisor_final_missing_saved_result_retained batch_id=%s', batch_id) - if (response.get('version') != VERSION or response.get('batch_id') != batch_id - or response.get('attempt_id') != attempt_id or response.get('type') != 'result' - or type(response.get('sequence')) is not int or response['sequence'] < gate.sequence - or type(response.get('generation')) is not int or response['generation'] < gate.generation): - raise ValueError('stale or invalid final supervisor result') - from .supervisor_result import validated_outcome, resource_pending_error - decoded_result, decoded_error, decoded_primary = validated_outcome(operation, response['payload']) + from .supervisor_result import validated_outcome + validated_outcome(operation, response) except (OSError, ValueError, KeyError, TypeError, AttributeError) as error: from .supervisor_evidence import MissingSupervisorResult, InvalidSupervisorResult failure_type = MissingSupervisorResult if isinstance(error, FileNotFoundError) else InvalidSupervisorResult @@ -759,20 +812,9 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres failure.owned_writers_exited = (not resource_blockers(outstanding) and ownership_cleanup_error is None and (process is None or process_tree_exited(process))) raise failure from (transport_error or error) + ownership_pending = False if transport_error is not None: - if response['payload']['business_succeeded']: - journal.update(state='blocked', outcome='completed_resources_pending', error=str(transport_error)) - write_record(directory / 'supervisor.json', journal) - else: - _mark_interrupted(root, journal, transport_error) - failure = resource_pending_error(operation, decoded_result, transport_error, decoded_primary) - from .batch_resources import pending_resources, resource_blockers from .read_recovery import process_tree_exited - pending = pending_resources(root) - failure.resources_released = (ownership_cleanup_error is None and not pending - and process is not None and process_tree_exited(process)) - failure.owned_writers_exited = (ownership_cleanup_error is None and not resource_blockers(pending) - and process is not None and process_tree_exited(process)) - failure.resource_warnings = tuple(row for row in pending if row not in resource_blockers(pending)) - raise failure - return _finish_response(root, journal, response['payload'], service._logging) + ownership_pending = ownership_cleanup_error is not None or process is None or not process_tree_exited(process) + return _finish_response(root, journal, response, service._logging, + transport_error=transport_error, ownership_pending=ownership_pending) diff --git a/src/dx_productivity/trial_task_center/diagnostics_bundle.py b/src/dx_productivity/trial_task_center/diagnostics_bundle.py index 12aaa76..40f582c 100644 --- a/src/dx_productivity/trial_task_center/diagnostics_bundle.py +++ b/src/dx_productivity/trial_task_center/diagnostics_bundle.py @@ -58,7 +58,8 @@ def _scrub_json(value): def _allowed(parts): if parts[0] == 'batch-runs': return (len(parts) == 3 and bool(re.fullmatch(r'[0-9a-f]{32}', parts[1])) - and parts[2] in {'manifest.json', 'batch-receipt.json'}) + and (parts[2] in {'manifest.json', 'batch-receipt.json'} + or bool(re.fullmatch(r'(?:local|incident)-resource-[0-9a-f]{32}\.json', parts[2])))) if parts[0] == 'execution-proof' or (len(parts) > 3 and parts[0] == 'tasks' and parts[2] == 'execution-proof'): return (parts[-1] == 'completion.json' or bool(re.fullmatch(r'project-(?:commit|pause)-[a-f0-9]{32}\.tsv', parts[-1])) diff --git a/src/dx_productivity/trial_task_center/execution_problems.py b/src/dx_productivity/trial_task_center/execution_problems.py index c9bb638..627c314 100644 --- a/src/dx_productivity/trial_task_center/execution_problems.py +++ b/src/dx_productivity/trial_task_center/execution_problems.py @@ -121,11 +121,11 @@ class ExecutionProblems: ON p.task_id=o.task_id AND p.round_id=o.round_id AND p.operation_key=o.operation_key WHERE o.task_id=? AND o.round_id=? ORDER BY o.rowid''', (task_id, current[0])).fetchall() if current else () - blocked = any(row['state'] in {'pending', 'prepared', 'uncertain'} for row in rows) + blocked = any(row['state'] in {'pending', 'prepared', 'pending_save', 'uncertain'} for row in rows) items = [] for row in rows: if row['state'] == 'superseded' or (not row['problem_key'] and row['state'] not in - {'pending', 'prepared', 'uncertain', 'failed'}): + {'pending', 'prepared', 'pending_save', 'uncertain', 'failed'}): continue command = json.loads(row['command_json']) targets = [selector.split('\x1f') for selector in @@ -143,7 +143,7 @@ class ExecutionProblems: return dict(round_id=current[0] if current else None, items=tuple(items), failed=sum(item['state'] == 'failed' for item in items), held=sum(item['state'] == 'pending' for item in items), - uncertain=sum(item['state'] in {'prepared', 'uncertain'} for item in items), + uncertain=sum(item['state'] in {'prepared', 'pending_save', 'uncertain'} for item in items), resolved=sum(item['problem_state'] == 'resolved' for item in items)) def validate_selection(self, task_id, keys, round_id, generations): diff --git a/src/dx_productivity/trial_task_center/service.py b/src/dx_productivity/trial_task_center/service.py index 270d150..352b57c 100644 --- a/src/dx_productivity/trial_task_center/service.py +++ b/src/dx_productivity/trial_task_center/service.py @@ -882,21 +882,44 @@ class TaskCenterService: reuse_project_session: bool = True, runtime=None, revalidate=None, + before_launch=None, ): if runtime is None and self._supervised: return self._supervise('execute_quick_run_queue', {'task_id': task_id, 'expected_item': expected_item, 'continue_after_backup_failure': continue_after_backup_failure, 'reuse_project_session': reuse_project_session}, stop_event=stop_event, - **({'revalidate': revalidate} if revalidate is not None else {})) + **({'revalidate': revalidate} if revalidate is not None else {}), + **({'before_launch': before_launch} if before_launch is not None else {})) if runtime is None: - from .batch_runtime import BatchCadRuntime - with BatchCadRuntime(self._logging.root, 'quick_run_queue', stop_event) as owned_runtime: + from .batch_runtime import BatchCadRuntime, BatchResourceCleanupError + mark_never_acquired = None + + def finish_local_binding(error_type, _error, _traceback): + orderly = error_type is None or ( + issubclass(error_type, Exception) and not issubclass(error_type, BatchResourceCleanupError)) + if orderly and mark_never_acquired is not None and owned_runtime.generation == 0: + try: + mark_never_acquired() + except OSError: + self._logging.logger.exception('local_incident_release_proof_unavailable task_id=%s', task_id) + + with ExitStack() as ownership: + ownership.push(finish_local_binding) + owned_runtime = ownership.enter_context(BatchCadRuntime(self._logging.root, 'quick_run_queue', stop_event)) owned_runtime.bind_logs(self._logging, (task_id,)) + + def bind_local_session(): + nonlocal mark_never_acquired + if revalidate is not None: + revalidate() + mark_never_acquired = before_launch(owned_runtime.session_id, local=True) + result = self.execute_quick_run_queue(task_id, expected_item=expected_item, stop_event=stop_event, continue_after_backup_failure=continue_after_backup_failure, - reuse_project_session=reuse_project_session, runtime=owned_runtime, revalidate=revalidate) + reuse_project_session=reuse_project_session, runtime=owned_runtime, + revalidate=bind_local_session if before_launch is not None else revalidate) owned_runtime.result = result - return result + return result delegated = self._project_task_service(task_id) if delegated is not self: return delegated.execute_quick_run_queue(task_id, expected_item=expected_item, diff --git a/src/dx_productivity/trial_task_center/task_queue.py b/src/dx_productivity/trial_task_center/task_queue.py index cb13844..3fa64a9 100644 --- a/src/dx_productivity/trial_task_center/task_queue.py +++ b/src/dx_productivity/trial_task_center/task_queue.py @@ -197,8 +197,8 @@ def reconcile_interrupted_queue(root, journal): def resource_pause_admitted(root, batch_id, task_ids, plan_hashes, result=None, *, require_released=True): """Bind a completed supervisor's resource pause to the frozen queue.""" - from .batch_resources import _process_gone, blocking_resources - from .batch_supervisor import pending_supervisors + from .batch_resources import _process_gone, _released_evidence, _valid_record, blocking_resources + from .batch_supervisor import _abnormal_shutdown, pending_supervisors from .path_access import canonical_path, internal_path from .supervisor_protocol import MessageGate, decode, valid_journal @@ -213,10 +213,13 @@ def resource_pause_admitted(root, batch_id, task_ids, plan_hashes, result=None, journal = json.loads((directory / 'supervisor.json').read_bytes()) if (not valid_journal(journal, batch_id) or journal['state'] not in {'blocked', 'finished'} or journal['operation'] != 'execute_task_queue' or journal['task_ids'] != list(task_ids) + or journal.get('outcome') == 'application_shutdown_failed' or not journal['process'] or journal.get('business_uncertain') or 'stop_requested_at' in journal or journal.get('stopping_reason') or journal.get('stop_mode') in {'safe', 'forced'} or (directory / 'cancel.json').exists()): return False + if _abnormal_shutdown(directory): + return False raw_request = (directory / 'request.json').read_bytes() request = json.loads(raw_request) arguments = decode(request['arguments']) @@ -249,6 +252,12 @@ def resource_pause_admitted(root, batch_id, task_ids, plan_hashes, result=None, return False if batch_id in state.get('consumed_resource_pauses', {}): return False + if require_released: + session_path = directory / 'session.json' + session = json.loads(session_path.read_bytes()) + if (not _valid_record(session, session_path) or session['state'] != 'released' + or session['generation'] != message['generation'] or not _released_evidence(session)): + return False pause = state.get('resource_pause') or {} intended = ((pause.get('task_id'), pause.get('batch_id')) == (current, batch_id) and pause.get('business_determined') is True @@ -270,6 +279,10 @@ def resource_pause_admitted(root, batch_id, task_ids, plan_hashes, result=None, return False +def _local_resource_path(queue_id, session_id): + return Path('batch-runs') / queue_id / f'local-resource-{session_id}.json' + + def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event, queue_id: str | None = None, runtime=None, expected_plan_hashes=None, checkpoint_id=None, defer_problem_pass=False, resource_batch_id=None, revalidate=None, @@ -316,14 +329,38 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event, 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_resources import write_record + token = queue_id or checkpoint_id + binding = binding_path = None + + def bind_local_session(): + if revalidate is not None: + revalidate() + write_record(binding_path, binding) + with BatchCadRuntime(service._logging.root, 'task_queue', stop_event) as owned_runtime: + if manifest_digest is not None: + if (not isinstance(token, str) or len(token) != 32 + or any(char not in '0123456789abcdef' for char in token)): + raise TaskCenterError('task_queue_state', '冻结任务队列编号无效。') + binding_path = service._logging.root / _local_resource_path(token, owned_runtime.session_id) + binding = {'version': 1, 'session_id': owned_runtime.session_id, 'queue_id': token, + 'manifest_digest': manifest_digest, 'task_ids': list(task_ids), + 'plan_hashes': expected_plan_hashes, 'never_acquired': False} result = execute_task_queue(service, task_ids, stop_event=stop_event, queue_id=queue_id, runtime=owned_runtime, expected_plan_hashes=expected_plan_hashes, checkpoint_id=checkpoint_id, defer_problem_pass=defer_problem_pass, - resource_batch_id=resource_batch_id, revalidate=revalidate, + resource_batch_id=resource_batch_id, + revalidate=bind_local_session if binding else revalidate, manifest_digest=manifest_digest) owned_runtime.result = result - return 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): raise TaskCenterError('task_queue_selection', '请选择不同的单工程任务。') 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 bf9e2f0..e43b73c 100644 --- a/src/dx_productivity/trial_task_center/ui/main_window.py +++ b/src/dx_productivity/trial_task_center/ui/main_window.py @@ -912,20 +912,21 @@ class TrialTaskCenterWindow(MaterialMainWindow): if not button.isEnabled() or self._context is None: return owner_task_id = self._context.task.task_id - group = self._context.task.group_id from ..batch_admission import build_batch_admission, resolve_batch_task_ids - try: - candidates = resolve_batch_task_ids(self._tasks, group, - selected_ids=self.task_list.selected_task_ids() if selected else None) - except TaskCenterError as error: - self._show_error(error, owner_task_id=owner_task_id) - return - token, ids = self._project_queues.get(group, (None, candidates)) - if token and selected and tuple(ids) != candidates: - self._set_operator_message('本批有原队列待接续,请按原确认范围继续,或先核验并结束原批次。', 'warning') - return + selection = self.task_list.selected_task_ids() if selected else None + queues = dict(self._project_queues) prepared = [] def inspect(): + records = tuple(self.service.tasks()) + anchor = selection[0] if selection else owner_task_id + owner = next((task for task in records if task.task_id == anchor), None) + if owner is None: + raise TaskCenterError('batch_scope', '候选任务已变化,请重新选择并确认。') + group = owner.group_id + candidates = resolve_batch_task_ids(records, group, selected_ids=selection) + token, ids = queues.get(group, (None, candidates)) + if token and selected and tuple(ids) != candidates: + raise TaskCenterError('batch_scope', '本批有原队列待接续,请按原确认范围继续,或先核验并结束原批次。') if token: from ...dsh.run_journal import resume_preflight inspected = self._dsh_operations.runs.inspect(self.service, token) @@ -939,14 +940,14 @@ class TrialTaskCenterWindow(MaterialMainWindow): admission = build_batch_admission(self.service, candidates, scope_kind='selected' if selected else 'batch') report = admission['execution_report'] - return admission, report + return admission, report, group, candidates, token, ids def collected(value): if value is not None: prepared.append(value) def confirm(): if not prepared or self._closed or self._close_pending or self._task_id != owner_task_id: return - admission, report = prepared[0] + admission, report, group, candidates, token, ids = prepared[0] if admission is not None and not admission['ready'] and not token: from ..batch_admission import write_preflight_receipt path = write_preflight_receipt(self.service.layout_settings_path.parent, admission, 'rejected') @@ -977,7 +978,7 @@ class TrialTaskCenterWindow(MaterialMainWindow): write_preflight_receipt(self.service.layout_settings_path.parent, admission, 'rejected', reason=reason) return if self.plan_panel.has_unsaved_plan(candidates): - self._set_operator_message('候选任务有未保存编辑,请保存后重新确认。', 'warning') + self._set_operator_message('未启动执行:候选任务有未保存编辑,请保存后重新确认。', 'warning') return if not self._confirmed_execution_allowed(owner_task_id, active, button): return @@ -1172,18 +1173,23 @@ class TrialTaskCenterWindow(MaterialMainWindow): force_started = False def start_force_if_ready(): nonlocal force_started - if force_confirmed and cleanup_finished and not force_started and not self._close_pending: + if force_confirmed and cleanup_finished and not force_started and not self._close_pending and not self._workers: force_started = True self._run_async(lambda: self.service.force_pending_owned_resources(confirmed=True), - forced, self.run_panel.cleanup_resources_button) + forced, self.run_panel.cleanup_resources_button, on_finished=repair_reports) + def after_report(): + start_force_if_ready() + self._resume_resource_queue() + def repair_reports(): + from ...dsh.execution_runs import recover_batch_receipts + self._run_async(lambda: recover_batch_receipts(self.service, self.service.layout_settings_path.parent), + lambda _: None, operation_area='batch_receipts', on_finished=after_report) def after_cleanup(): nonlocal cleanup_finished cleanup_finished = True start_force_if_ready() if not force_started and not self._workers: - from ...dsh.execution_runs import recover_batch_receipts - self._run_async(lambda: recover_batch_receipts(self.service, self.service.layout_settings_path.parent), - lambda _: None, operation_area='batch_receipts', on_finished=self._resume_resource_queue) + repair_reports() def forced(remaining): from ..batch_resources import resource_blockers self._resource_status.refresh() @@ -1607,8 +1613,10 @@ class TrialTaskCenterWindow(MaterialMainWindow): owner = expected_task_id or self._active_quick_run_task_id label = button.text() if button is not None else '操作' self._dsh_blockers.watch(worker, label, owner or expected_task_id or self._task_id, operation_area) - self.operation_state = OperationState.start(label, owner, operation_area) - self._set_operator_message(self.operation_state.message) + receipt_recovery = operation_area == 'batch_receipts' + if not receipt_recovery: + self.operation_state = OperationState.start(label, owner, operation_area) + self._set_operator_message(self.operation_state.message) self.plan_panel._summary() operation_error = None def valid(): @@ -1617,13 +1625,17 @@ class TrialTaskCenterWindow(MaterialMainWindow): nonlocal operation_error if valid(): try: - self.operation_state = self.operation_state.finish() - self._set_operator_message(self.operation_state.message) - if self.operation_state.phase is OperationPhase.CANCELLED: - return + if not receipt_recovery: + self.operation_state = self.operation_state.finish() + self._set_operator_message(self.operation_state.message) + if self.operation_state.phase is OperationPhase.CANCELLED: + return callback(result) except Exception as error: operation_error = error + if receipt_recovery: + self.service._logging.logger.warning('batch_receipt_recovery_unavailable error=%s', type(error).__name__) + return self._close_pending = False if execution: # A result renderer is part of the worker lifecycle. @@ -1638,6 +1650,9 @@ class TrialTaskCenterWindow(MaterialMainWindow): operation_error = error if not isValid(self) or self._closed: return + if receipt_recovery: + self.service._logging.logger.warning('batch_receipt_recovery_unavailable error=%s', type(error).__name__) + return self.operation_state = self.operation_state.finish(error) if self._close_saving or not (isinstance(error, TaskCenterError) and error.code == 'operation_cancelled'): self._close_pending = False diff --git a/src/dx_productivity/trial_task_center/ui/problem_items.py b/src/dx_productivity/trial_task_center/ui/problem_items.py index 41ae8ca..37fc393 100644 --- a/src/dx_productivity/trial_task_center/ui/problem_items.py +++ b/src/dx_productivity/trial_task_center/ui/problem_items.py @@ -24,11 +24,11 @@ class ProblemItemsDialog(QDialog): self.table.setHorizontalHeaderLabels(headers) self.table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers) self.table.setAlternatingRowColors(True) - states = {'failed': '失败', 'pending': '尚未执行', 'prepared': '待核验', 'uncertain': '待核验', + states = {'failed': '失败', 'pending': '尚未执行', 'prepared': '待核验', 'pending_save': '保存待核验', 'uncertain': '待核验', 'verified': '已解决', 'restored': '已解决', 'no_match': '已解决'} for index, row in enumerate(overview['items']): can_retry = allow_retry and row['can_retry'] - action = ('可勾选手动重试' if can_retry else '先核验并恢复' if row['state'] in {'prepared', 'uncertain'} + action = ('可勾选手动重试' if can_retry else '先核验并恢复' if row['state'] in {'prepared', 'pending_save', 'uncertain'} else '继续原队列/工程级重试' if row['state'] in {'pending', 'failed'} else '无需操作') values = ('', states.get(row['state'], row['state']), row['project_path'], f"{row['schematic_name']} / {row['sheet_number']}", row['refdes'], row['uid'], diff --git a/tests/dsh/test_incident_rule_retry.py b/tests/dsh/test_incident_rule_retry.py index 7fa22d8..42e1d17 100644 --- a/tests/dsh/test_incident_rule_retry.py +++ b/tests/dsh/test_incident_rule_retry.py @@ -188,8 +188,11 @@ def test_missing_confirmed_manifest_cannot_fall_back_to_legacy_retry(confirmed_i def test_incident_dispatch_failure_exports_original_batch_revision(confirmed_incident_batch, monkeypatch): + from hashlib import sha256 from dx_productivity.dsh.execution_runs import _republish_incident_batch_summary + from dx_productivity.trial_task_center.batch_resources import write_record from dx_productivity.trial_task_center.errors import TaskCenterError + from dx_productivity.trial_task_center.supervisor_protocol import VERSION, encode case, held = confirmed_incident_batch held['value'] = False @@ -208,8 +211,17 @@ def test_incident_dispatch_failure_exports_original_batch_revision(confirmed_inc def failed_dispatch(item, **controls): controls['revalidate']() + directory = root / 'batch-resources' / batch_id + request = directory / 'request.json' + header = {'version': VERSION, 'batch_id': batch_id, 'attempt_id': '5' * 32, + 'operation': 'execute_quick_run_queue', 'task_ids': [item]} + write_record(request, dict(header, root=str(root), + arguments=encode({'task_id': item, 'expected_item': controls['expected_item']}))) + write_record(directory / 'supervisor.json', dict(header, state='starting', + request_sha256=sha256(request.read_bytes()).hexdigest(), + parent_process={'pid': 1, 'creation_time': 'test'})) + controls['before_launch'](batch_id) dispatched.append(item) - service._last_supervisor_batch_id = batch_id raise TaskCenterError('supervisor_interrupted', 'worker ended without a durable result') monkeypatch.setattr(service, 'execute_quick_run_queue', failed_dispatch) diff --git a/tests/dsh/test_issue44_batch_receipt.py b/tests/dsh/test_issue44_batch_receipt.py index 073bdf7..6239d68 100644 --- a/tests/dsh/test_issue44_batch_receipt.py +++ b/tests/dsh/test_issue44_batch_receipt.py @@ -78,21 +78,13 @@ def test_bound_receipt_preserves_verified_result_and_checks_resource_state(batch (TASK_ID, 'round', 'key', json.dumps({'target_scope': 'targets', 'project_path': 'board.prj', 'schematic_name': 'MAIN', 'sheet_number': '1', 'target_selectors': 'uid1\x1fR1'}), 'verified', 'a', 1, '{}')) - current_service._last_supervisor_batch_id = BATCH_ID - record = {'version': 1, 'session_id': BATCH_ID, 'kind': 'task_queue', - 'generation': 1, 'desktop': 'dx-' + BATCH_ID, 'state': resource_state, 'processes': [], - 'cad_pid': None, 'cad_guid': None, 'checkpoints': {}, 'retries': {}, 'timings': [], - 'release_proof': {'generation': 1, 'desktop_not_acquired': True}, - 'cleanup': {'desktop_not_acquired': True, 'desktop_handle_closed': True, - 'owned_cleanup_complete': True}} - batch_resources.write_record(data / 'batch-resources' / BATCH_ID / 'session.json', record) - from dx_productivity.trial_task_center.supervisor_protocol import VERSION - batch_resources.write_record(data / 'batch-resources' / BATCH_ID / 'supervisor.json', - {'version': VERSION, 'batch_id': BATCH_ID, 'state': 'finished', 'outcome': 'ok', - 'operation': 'execute_task_queue', 'task_ids': [TASK_ID], 'attempt_id': '3' * 32, - 'request_sha256': '0' * 64, 'parent_process': {'pid': 1, 'creation_time': 'test'}}) - return TaskQueueResult(RUN_ID, (TaskQueueEntry(TASK_ID, 'completed'),), False, + result = TaskQueueResult(RUN_ID, (TaskQueueEntry(TASK_ID, 'completed'),), False, netlist_verification={TASK_ID: {'status': 'verified', 'verified': True}}) + _durable_supervisor_result(data, result) + path = data / 'batch-resources' / BATCH_ID / 'session.json' + record = json.loads(path.read_bytes()) + batch_resources.write_record(path, dict(record, state=resource_state)) + return result monkeypatch.setattr(execution_runs, 'execute_task_queue', dispatch) receipt = execution_runs.execute_confirmed_run(service, data, (TASK_ID,), report, Event(), diff --git a/tests/dsh/test_pr47_audit_receipts.py b/tests/dsh/test_pr47_audit_receipts.py new file mode 100644 index 0000000..3869f32 --- /dev/null +++ b/tests/dsh/test_pr47_audit_receipts.py @@ -0,0 +1,387 @@ +import hashlib +import json +from pathlib import Path +import os +import subprocess +from threading import Event +import zipfile + +import pytest + +from dx_productivity.dsh import execution_runs +from dx_productivity.dsh.run_journal import RunJournal +from dx_productivity.trial_task_center import batch_resources, batch_summary +from dx_productivity.trial_task_center.batch_admission import build_batch_admission +from dx_productivity.trial_task_center.diagnostics_bundle import export_diagnostic_bundle +from dx_productivity.trial_task_center.supervisor_protocol import VERSION, encode +from dx_productivity.trial_task_center.task_queue import TaskQueueEntry, TaskQueueResult +from test_incident_rule_retry import confirmed_incident_batch, incident, rule_run +from test_issue44_batch_receipt import ( + BATCH_ID, PLAN_HASHES, RUN_ID, TASK_ID, _durable_supervisor_result, batch, +) +from test_run_journal import project_service + + +def _complete(): + return {'status': 'completed', 'execution_status': 'completed', 'queue_id': RUN_ID, + 'entries': [{'task_id': TASK_ID, 'state': 'completed', 'message': 'done'}], + 'netlist_verification': {TASK_ID: {'status': 'verified', 'verified': True}}} + + +def _start(data, admission): + batch_resources.write_record(data / 'batch-runs' / RUN_ID / 'manifest.json', + dict(admission, run_id=RUN_ID)) + journal = RunJournal(data) + journal.begin(RUN_ID, [TASK_ID], PLAN_HASHES) + return journal + + +def _supervised_complete(data): + receipt = _complete() + _durable_supervisor_result(data, TaskQueueResult(RUN_ID, (TaskQueueEntry(TASK_ID, 'completed', 'done'),), + False, netlist_verification=receipt['netlist_verification'])) + batch_resources.write_record(data / 'task-queues' / (RUN_ID + '.json'), + {'task_ids': [TASK_ID], 'plan_hashes': PLAN_HASHES, 'manifest_digest': 'd' * 64, + 'entries': {TASK_ID: {'state': 'completed', 'message': 'done'}}}) + return receipt + + +def _update_json(path, **changes): + batch_resources.write_record(path, dict(json.loads(path.read_bytes()), **changes)) + + +@pytest.mark.parametrize('owns_desktop', [False, pytest.param(True, + marks=pytest.mark.skipif(os.name != 'nt', reason='Windows desktop lifetime'))]) +def test_local_manifest_run_completes_from_its_actual_runtime_release(project_service, monkeypatch, owns_desktop): + service, _, root, ids, _ = project_service + task_id = ids[0] + child = service.for_project_task(task_id) + calls = [] + + def worker(command, timeout): + job = command[-1] + calls.append(job) + with (Path(command[3]) / 'status.tsv').open('a', encoding='utf-8') as stream: + stream.write(f'{job}\tno_match\tbatch_closed\tNo matching components\n') + return subprocess.CompletedProcess(command, 0, '', '') + + monkeypatch.setattr(child._quick_run_preparer, '_process_runner', worker) + monkeypatch.setattr(child._quick_run_preparer, '_cscript_resolver', lambda: Path('cscript.exe')) + if owns_desktop: + execute = child.execute_quick_run_queue + + def execute_on_desktop(task_id, *, runtime, **kwargs): + runtime._ensure_desktop() + return execute(task_id, runtime=runtime, **kwargs) + + monkeypatch.setattr(child, 'execute_quick_run_queue', execute_on_desktop) + admission = build_batch_admission(service, [task_id], scope_kind='selected') + report = admission['execution_report'] + result = execution_runs.execute_confirmed_run(service, root, [task_id], report, Event(), + RUN_ID, admission=admission) + assert len(calls) == 1 + assert result['execution_status'] == 'completed' + assert result['status'] == 'completed' and result['summary']['resource_state'] == 'released' + assert result['summary']['resource']['evidence'] + assert result['tasks'][0]['no_match_items'] == 1 + assert bool(result['summary']['resource']['generations']) is owns_desktop + journal = RunJournal(root) + assert journal.get(RUN_ID)['status'] == 'completed' + if not owns_desktop: + proof = result['summary']['resource']['evidence'][0] + with zipfile.ZipFile(export_diagnostic_bundle(root, root.parent / 'receipt-support.zip')) as bundle: + assert json.loads(bundle.read(proof))['never_acquired'] is True + (root / proof).unlink() + journal.finish(RUN_ID, {key: value for key, value in result.items() if key != 'summary'}) + execution_runs.recover_batch_receipts(service, root) + rebuilt = journal.batch_summary(RUN_ID) + assert rebuilt['resource_state'] == 'unknown' and rebuilt['status'] == 'paused' + + +@pytest.mark.parametrize('already_summarized', [False, True]) +def test_incident_publication_preserves_the_recorded_elapsed_time(batch, already_summarized): + service, _, data, _, admission = batch + journal = _start(data, admission) + receipt = _supervised_complete(data) + journal.finish(RUN_ID, dict(receipt, elapsed_seconds=28.125)) + if already_summarized: + execution_runs.recover_batch_receipts(service, data) + result = execution_runs._republish_incident_batch_summary(service, data, RUN_ID, receipt) + assert result['elapsed_seconds'] == result['summary']['elapsed_seconds'] == 28.125 + assert journal.get(RUN_ID)['result']['elapsed_seconds'] == 28.125 + + +def test_recovery_retries_a_previously_unstable_snapshot_at_the_same_revision(batch, monkeypatch): + service, _, data, _, admission = batch + journal = _start(data, admission) + receipt = _supervised_complete(data) + 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 + + with monkeypatch.context() as unstable: + unstable.setattr(batch_summary, '_operation_sources', changing) + execution_runs.recover_batch_receipts(service, data) + first = journal.batch_summary(RUN_ID) + assert first['status'] == 'paused' + assert {'code': 'batch_snapshot_unstable'} in first['reporting_errors'] + execution_runs.recover_batch_receipts(service, data) + recovered = journal.batch_summary(RUN_ID) + assert recovered['status'] == 'completed' + assert recovered['revision'] == first['revision'] + 1 + assert {'code': 'batch_snapshot_unstable'} not in recovered['reporting_errors'] + + +def test_generation_cannot_publish_released_without_physical_proof(batch): + service, _, data, _, admission = batch + journal = _start(data, admission) + receipt = _supervised_complete(data) + session = data / 'batch-resources' / BATCH_ID / 'session.json' + _update_json(session, release_proof={}, cleanup={}, generation_releases=[ + {'generation': 1, 'desktop': 'dx-' + BATCH_ID, 'reason': 'unverified'}], generation=2) + journal.finish(RUN_ID, receipt) + execution_runs.recover_batch_receipts(service, data) + summary = journal.batch_summary(RUN_ID) + assert summary['status'] == 'paused' + assert {row['generation']: row['state'] for row in summary['resource']['generations']} == { + 1: 'unknown', 2: 'unknown'} + + +def _quick_retry(data, retry_id, *, task_id=TASK_ID, expected_item=('p', 's', 'old', 'new')): + _durable_supervisor_result(data, None, batch_id=retry_id) + directory = data / 'batch-resources' / retry_id + request = directory / 'request.json' + _update_json(request, operation='execute_quick_run_queue', task_ids=[task_id], + arguments=encode({'task_id': task_id, 'expected_item': expected_item})) + _update_json(directory / 'supervisor.json', operation='execute_quick_run_queue', task_ids=[task_id], + request_sha256=hashlib.sha256(request.read_bytes()).hexdigest()) + _update_json(directory / 'session.json', kind='quick_run_queue') + return request + + +@pytest.mark.parametrize('damaged_request', ['', 'request', 'request_and_digest']) +def test_full_recovery_preserves_and_rechecks_the_bound_quick_run(batch, damaged_request): + service, _, data, _, admission = batch + journal = _start(data, admission) + receipt = _supervised_complete(data) + retry_id = '5' * 32 + retry_request = _quick_retry(data, retry_id) + journal.finish(RUN_ID, receipt) + execution_runs._record_incident_resource_link(data, RUN_ID, retry_id, TASK_ID, ('p', 's', 'old', 'new')) + execution_runs._republish_incident_batch_summary(service, data, RUN_ID, receipt) + assert retry_id in journal.batch_summary(RUN_ID)['resource_batch_ids'] + if damaged_request: + _update_json(retry_request, arguments=encode({'task_id': TASK_ID, 'expected_item': ('other',)})) + if damaged_request == 'request_and_digest': + _update_json(retry_request.with_name('supervisor.json'), + request_sha256=hashlib.sha256(retry_request.read_bytes()).hexdigest()) + journal.finish(RUN_ID, receipt) # No matching receipt revision, so startup rebuilds all sources. + execution_runs.recover_batch_receipts(service, data) + summary = journal.batch_summary(RUN_ID) + assert retry_id in summary['resource_batch_ids'] + assert summary['resource_state'] == ('unknown' if damaged_request else 'released') + if not damaged_request: + assert any(row['session_id'] == retry_id for row in summary['resource']['generations']) + proof = f'batch-runs/{RUN_ID}/incident-resource-{retry_id}.json' + with zipfile.ZipFile(export_diagnostic_bundle(data, data.parent / 'retry-support.zip')) as bundle: + assert json.loads(bundle.read(proof))['task_id'] == TASK_ID + + +def test_receipt_rebuild_preserves_supervisor_shutdown_failure_after_release(batch): + service, _, data, _, admission = batch + journal = _start(data, admission) + _supervised_complete(data) + supervisor = data / 'batch-resources' / BATCH_ID / 'supervisor.json' + _update_json(supervisor, outcome='application_shutdown_failed') + execution_runs.recover_batch_receipts(service, data) + summary = journal.batch_summary(RUN_ID) + assert summary['execution_status'] == 'completed' and summary['resource_state'] == 'released' + assert summary['status'] == 'failed' and summary['stop_reason'] == 'application_shutdown_failed' + + +def test_recovery_rejects_success_when_the_supervisor_marked_the_business_uncertain(batch): + service, _, data, _, admission = batch + journal = _start(data, admission) + _supervised_complete(data) + supervisor = data / 'batch-resources' / BATCH_ID / 'supervisor.json' + _update_json(supervisor, outcome='interrupted', business_uncertain=True) + execution_runs.recover_batch_receipts(service, data) + summary = journal.batch_summary(RUN_ID) + assert summary['status'] == 'interrupted' + + +def test_shutdown_diagnostics_also_protect_old_supervisor_receipts(batch): + service, _, data, _, admission = batch + journal = _start(data, admission) + _supervised_complete(data) + session = data / 'batch-resources' / BATCH_ID / 'session.json' + _update_json(session, cad_shutdown={'orderly_shutdown': False, 'forced_termination': True}) + execution_runs.recover_batch_receipts(service, data) + summary = journal.batch_summary(RUN_ID) + assert summary['execution_status'] == 'completed' and summary['resource_state'] == 'released' + assert summary['status'] == 'failed' and summary['stop_reason'] == 'application_shutdown_failed' + + +def test_local_retry_keeps_its_runtime_after_first_business_receipt_fails(confirmed_incident_batch, monkeypatch): + case, held = confirmed_incident_batch + held['value'] = False + service, task_id, run_id, root = (case[key] for key in ('service', 'task_id', 'run_id', 'root')) + manifest = json.loads((root / 'batch-runs' / run_id / 'manifest.json').read_bytes()) + checkpoint = root / 'task-queues' / (run_id + '.json') + _update_json(checkpoint, manifest_digest=manifest['manifest_digest']) + class FatalExit(BaseException): + pass + + def fail_first_receipt(*args): + raise FatalExit('first business receipt write failed') + + with monkeypatch.context() as damaged: + damaged.setattr(RunJournal, 'finish', fail_first_receipt) + with pytest.raises(FatalExit): + incident(case) + execution_runs.recover_batch_receipts(service, root) + summary = RunJournal(root).batch_summary(run_id) + assert summary['status'] == 'interrupted' + retry_id, = summary['resource_batch_ids'] + evidence = root / summary['resource']['evidence'][0] + binding = json.loads(evidence.read_bytes()) + assert binding['task_id'] == task_id and binding['session_id'] == retry_id + assert binding['kind'] == 'quick_run_queue' and binding['never_acquired'] is True + assert summary['resource_state'] == 'released' + assert case['calls'] == ['OLD-OK', 'OLD-BAD', 'OLD-BAD'] + + +def test_local_retry_records_no_acquisition_after_an_explicit_precondition_error( + confirmed_incident_batch, monkeypatch): + case, held = confirmed_incident_batch + held['value'] = False + service, task_id, run_id, root = (case[key] for key in ('service', 'task_id', 'run_id', 'root')) + folder = root / 'batch-runs' / run_id + manifest = json.loads((folder / 'manifest.json').read_bytes()) + _update_json(root / 'task-queues' / (run_id + '.json'), manifest_digest=manifest['manifest_digest']) + store = service.for_project_task(task_id)._store + original = store.has_active_project + monkeypatch.setattr(store, 'has_active_project', + lambda: any(folder.glob('local-resource-*.json')) or original()) + result = incident(case) + assert result['retry_error']['code'] == 'active_project_exists' + path, = folder.glob('local-resource-*.json') + assert json.loads(path.read_bytes())['never_acquired'] is True + assert RunJournal(root).batch_summary(run_id)['resource_state'] == 'released' + assert case['calls'] == ['OLD-OK', 'OLD-BAD'] + + +@pytest.mark.skipif(os.name != 'nt', reason='Windows desktop lifetime') +def test_local_retry_isolation_cannot_borrow_the_original_batch_release( + confirmed_incident_batch, monkeypatch): + import sys + from dx_productivity.trial_task_center import batch as native_batch + from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime + from dx_productivity.trial_task_center.isolated_desktop import _Win32Api, build_startup_info + from dx_productivity.trial_task_center.task_queue import _local_resource_path + + case, held = confirmed_incident_batch + held['value'] = False + service, task_id, run_id, root = (case[key] for key in ('service', 'task_id', 'run_id', 'root')) + manifest = json.loads((root / 'batch-runs' / run_id / 'manifest.json').read_bytes()) + _update_json(root / 'task-queues' / (run_id + '.json'), manifest_digest=manifest['manifest_digest']) + with BatchCadRuntime(root, 'task_queue') as main: + main.bind_logs(service._logging, (task_id,)) + main._ensure_desktop() + batch_resources.write_record(root / _local_resource_path(run_id, main.session_id), + {'version': 1, 'session_id': main.session_id, 'queue_id': run_id, + 'manifest_digest': manifest['manifest_digest'], 'task_ids': [task_id], + 'plan_hashes': manifest['plan_hashes'], 'never_acquired': False}) + assert main.record['state'] == 'released' + execute_batch = native_batch.execute_batch + external = None + + def execute_on_retained_desktop(*args, runtime, **kwargs): + nonlocal external + desktop = runtime._ensure_desktop() + external = _Win32Api().create_process((sys.executable, '-u', '-c', + 'import sys,time,win32service; ' + 'desktop=win32service.OpenDesktop(sys.argv[1],0,False,0x10000000); ' + 'desktop.SetThreadDesktop(); print("ready",flush=True); time.sleep(30)', desktop.name), + build_startup_info(desktop.name).lpDesktop, None, None, + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + assert external.stdout.readline() == b'ready\r\n' + return execute_batch(*args, runtime=runtime, **kwargs) + + monkeypatch.setattr(native_batch, 'execute_batch', execute_on_retained_desktop) + try: + incident(case) + summary = RunJournal(root).batch_summary(run_id) + assert summary['execution_status'] == 'completed' + assert summary['status'] == 'paused' and summary['resource_state'] == 'isolated' + assert {row['state'] for row in summary['resource']['generations']} == {'released', 'isolated'} + assert external.poll() is None + assert case['calls'] == ['OLD-OK', 'OLD-BAD', 'OLD-BAD'] + finally: + if external is not None: + external.close() + assert batch_resources.cleanup_pending_resources(root) == () + + +@pytest.mark.skipif(os.name != 'nt', reason='Windows supervisor launch') +@pytest.mark.parametrize('link_writable', [True, False]) +def test_incident_supervisor_launch_requires_its_durable_request_link( + confirmed_incident_batch, monkeypatch, link_writable): + from dx_productivity.trial_task_center import batch_supervisor + from dx_productivity.trial_task_center.isolated_desktop import _Win32Api + + case, held = confirmed_incident_batch + held['value'] = False + service, task_id, run_id, root = (case[key] for key in ('service', 'task_id', 'run_id', 'root')) + folder = root / 'batch-runs' / run_id + manifest = json.loads((folder / 'manifest.json').read_bytes()) + _update_json(root / 'task-queues' / (run_id + '.json'), manifest_digest=manifest['manifest_digest']) + execute = service.execute_quick_run_queue + atomic_write = batch_resources.write_record + launches = [] + + class FatalExit(BaseException): + pass + + def supervised_retry(*args, **kwargs): + with monkeypatch.context() as mode: + mode.setattr(service, '_supervised', True) + return execute(*args, **kwargs) + + def write_record(path, value): + if not link_writable and Path(path).name.startswith('incident-resource-'): + raise OSError('fixture cannot write incident link') + return atomic_write(path, value) + + def interrupt_at_create_process(*args, **kwargs): + assert link_writable, 'worker launch must wait for durable incident binding' + batch_id = service._last_supervisor_batch_id + directory = root / 'batch-resources' / batch_id + raw = (directory / 'request.json').read_bytes() + supervisor = json.loads((directory / 'supervisor.json').read_bytes()) + link = json.loads((folder / f'incident-resource-{batch_id}.json').read_bytes()) + assert link == {'manifest_digest': manifest['manifest_digest'], 'task_id': task_id, + 'request_sha256': hashlib.sha256(raw).hexdigest()} + assert supervisor['state'] == 'starting' and supervisor['process'] is None + launches.append(batch_id) + raise FatalExit('interrupted at native launch boundary') + + monkeypatch.setattr(service, 'execute_quick_run_queue', supervised_retry) + monkeypatch.setattr(batch_resources, 'write_record', write_record) + monkeypatch.setattr(_Win32Api, 'create_process', interrupt_at_create_process) + if link_writable: + with pytest.raises(FatalExit): + incident(case) + execution_runs.recover_batch_receipts(service, root) + summary = RunJournal(root).batch_summary(run_id) + assert len(launches) == 1 and summary['resource_batch_ids'] == launches + assert summary['status'] == 'interrupted' and summary['resource_state'] == 'unknown' + else: + result = incident(case) + assert result['retry_error']['code'] == 'incident_resource_link_unavailable' + assert not launches and not batch_supervisor.pending_supervisors(root) + assert case['calls'] == ['OLD-OK', 'OLD-BAD'] diff --git a/tests/dsh/test_run_journal.py b/tests/dsh/test_run_journal.py index 424d7c1..bd5bb4c 100644 --- a/tests/dsh/test_run_journal.py +++ b/tests/dsh/test_run_journal.py @@ -120,6 +120,10 @@ def test_inspect_restores_a_determined_resource_pause_only_from_its_original_bat batch_resources.write_record(directory / 'supervisor.json', dict(binding, operation='execute_task_queue', task_ids=ids, state='finished', process=identity, parent_process=identity, request_sha256=request_digest)) + batch_resources.write_record(directory / 'session.json', dict(version=1, session_id=batch_id, + kind='task_queue', generation=1, desktop='dx-' + batch_id, state='released', processes=[], + cad_pid=None, cad_guid=None, checkpoints={}, retries={}, timings=[], release_proof={ + 'generation': 1, 'desktop_released': True, 'processes_exited': True})) paused = TaskQueueResult(token, tuple(TaskQueueEntry(item, row['state']) for item, row in state['entries'].items()), True, ids[0]) batch_resources.write_record(directory / 'result.json', dict(binding, generation=1, sequence=1, type='result', @@ -166,7 +170,7 @@ def test_shared_safe_primary_failure_can_hold_remaining_commands_on_resume(proje @pytest.mark.parametrize('isolated', [True, False]) -def test_released_isolated_project_does_not_block_resume_of_other_projects(project_service, isolated): +def test_released_projects_require_a_verified_result_to_resume_other_projects(project_service, isolated): from dx_productivity.dsh.run_journal import resume_preflight service, _, data, ids, hashes = project_service journal = RunJournal(data) @@ -181,13 +185,21 @@ def test_released_isolated_project_does_not_block_resume_of_other_projects(proje path.write_text(json.dumps({'version': 1, 'task_ids': ids, 'plan_hashes': hashes, 'phase': 'primary' if isolated else 'problems', 'entries': entries})) result = journal.inspect(service, 'd' * 32) - assert result['queue_available'] and result['resume_ready'], result['blockers'] + assert result['queue_available'] assert result['remaining_task_ids'] == (ids[1:] if isolated else ids) assert result['isolated_task_ids'] == ([ids[0]] if isolated else []) - assert result['tasks'][0]['interrupted'] == isolated + assert result['tasks'][0]['interrupted'] is isolated + if isolated: + assert not result['resume_ready'] and 'interrupted' in result['blockers'] + assert not result['cad_execution_started'] + with pytest.raises(TaskCenterError) as caught: + resume_preflight(service, result) + assert caught.value.code == 'run_blocked' + return + assert result['resume_ready'], result['blockers'] report = resume_preflight(service, result) assert report['ready'] - assert report['tasks'][0]['isolated'] == isolated + assert report['tasks'][0]['isolated'] is False def test_unpaused_blocked_project_is_not_a_completed_run(project_service): diff --git a/tests/ui/test_import_execution.py b/tests/ui/test_import_execution.py index 8791102..2d60552 100644 --- a/tests/ui/test_import_execution.py +++ b/tests/ui/test_import_execution.py @@ -33,7 +33,8 @@ def test_manual_confirmation_obeys_fresh_preflight_blockers(ui, batch): confirmations = [] window._quick_run_confirmer = lambda *args: confirmations.append(args) or False (window.task_list.queue_button if batch else window.run_panel.quick_run_button).click() - assert confirmations == [] + ui.settle() + assert confirmations == ([('batch', 1, 1)] if batch else []) assert not ui.calls and not window._workers diff --git a/tests/ui/test_pr10_review_edges.py b/tests/ui/test_pr10_review_edges.py index 058451c..e7bf260 100644 --- a/tests/ui/test_pr10_review_edges.py +++ b/tests/ui/test_pr10_review_edges.py @@ -63,7 +63,12 @@ def test_last_failed_item_keeps_stop_intent_in_automatic_diagnosis(ui,qtbot,monk monkeypatch.setattr(ui.service.for_project_task(task.task_id)._quick_run_preparer,'_process_runner',executor) monkeypatch.setattr(QMessageBox,'question',lambda *args:QMessageBox.StandardButton.Yes) def dispatch(operation,callback,*args,**kwargs): - result=operation();outcomes.append(result);callback(result) + result=operation() + if kwargs.get('operation_area') == 'batch_preflight': + callback(result) + kwargs['on_finished']() + return + outcomes.append(result);callback(result) monkeypatch.setattr(window,'_run_async',dispatch) monkeypatch.setattr(window,'_open_dsh',lambda:None) automation=dsh_automation.DshAutomation(window) @@ -86,7 +91,7 @@ def test_last_failed_item_keeps_stop_intent_in_automatic_diagnosis(ui,qtbot,monk qtbot.waitUntil(finished,timeout=10000) monkeypatch.setattr(dsh_automation,'GitIssuePublisher',lambda *args:lambda *args:{'status':'unavailable'}) if scope=='single':window._prepare_quick_run() - else:window._execute_project_tasks() + else:window._execute_project_tasks(selected=True) assert len(outcomes)==1 # A stopped primary pass retains its deferred failures for explicit resume. # Its diagnosis must also retain the original stop/force request. @@ -111,7 +116,7 @@ def test_last_failed_item_keeps_stop_intent_in_automatic_diagnosis(ui,qtbot,monk window._tasks=(ui.service.get_task(task.task_id),) window._update_gates() if scope=='single':window._prepare_quick_run() - else:window._execute_project_tasks() + else:window._execute_project_tasks(selected=True) wait_for_diagnosis(original_run) ui.settle() # Explicit reauthorization performs the one shared replay. Its second diff --git a/tests/ui/test_pr47_audit_ui.py b/tests/ui/test_pr47_audit_ui.py new file mode 100644 index 0000000..dc4fca4 --- /dev/null +++ b/tests/ui/test_pr47_audit_ui.py @@ -0,0 +1,108 @@ +"""Regressions from PR #47 audit 649 at the actual service/UI boundaries.""" +import json +from dataclasses import replace +import pytest + +from PySide6.QtCore import QSignalBlocker, Qt + + +def test_batch_preview_reads_full_group_from_db_when_navigation_cache_is_stale(ui, qtbot): + ui.window._tasks = (ui.tasks[0],) + seen = [] + ui.window._quick_run_confirmer = lambda *_: seen.append(ui.window._batch_confirmation_admission) or False + ui.window._execute_project_tasks() + qtbot.waitUntil(lambda: bool(seen), timeout=5000) + ui.settle() + assert seen[0]['candidate_task_ids'] == [task.task_id for task in ui.tasks] + assert not ui.calls + + +def test_selected_scope_uses_selected_group_instead_of_detail_focus(ui, qtbot, tmp_path): + project = tmp_path / 'other-group' / 'board.prj' + project.parent.mkdir() + project.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n') + selected, = ui.service.create_project_tasks(project.parent) + ui.service.add_rule(selected.task_id, 'OLD', 'NEW') + ui.window._tasks = ui.service.tasks() + ui.window.task_list.populate(ui.window._tasks, selected_task_id=ui.tasks[0].task_id) + with QSignalBlocker(ui.window.task_list.list): + ui.window.task_list.list.clearSelection() + for row in range(ui.window.task_list.list.count()): + item = ui.window.task_list.list.item(row) + item.setSelected(item.data(Qt.ItemDataRole.UserRole) == selected.task_id) + ui.window._update_gates() + seen = [] + ui.window._quick_run_confirmer = lambda *_: seen.append(ui.window._batch_confirmation_admission) or False + ui.window._execute_project_tasks(selected=True) + qtbot.waitUntil(lambda: bool(seen), timeout=5000) + ui.settle() + assert seen[0]['candidate_task_ids'] == [selected.task_id] + assert seen[0]['group_id'] == selected.group_id + assert not ui.calls + + +def test_problem_overview_includes_pending_save_and_blocks_failed_retries(ui): + from dx_productivity.trial_task_center.execution_problems import ExecutionProblems + task_id = ui.tasks[0].task_id + with ui.store.transaction(): + ui.store._connection.execute('INSERT INTO execution_rounds(task_id,round_id) VALUES (?,?)', (task_id, 'r')) + for key, state in (('saved-pending', 'pending_save'), ('failed', 'failed')): + command = json.dumps({'project_path': str(ui.service.projects(task_id)[0].path), + 'target_selectors': 'uid\x1fR1', 'schematic_name': 'MAIN', 'sheet_number': '1'}) + ui.store._connection.execute('INSERT INTO execution_operations VALUES (?,?,?,?,?,?,?,?)', + (task_id, 'r', key, command, state, 'attempt', 1, '{}')) + overview = ExecutionProblems(ui.store).overview(task_id) + assert overview['uncertain'] == 1 + assert {row['state'] for row in overview['items']} == {'pending_save', 'failed'} + assert all(not row['can_retry'] for row in overview['items']) + + +@pytest.mark.parametrize('verified,has_round', [(False, True), (True, True), (True, False)]) +def test_completed_tasks_require_current_round_acceptance(ui, monkeypatch, verified, has_round): + from dx_productivity.dsh.run_journal import RunJournal + from dx_productivity.trial_task_center.batch_admission import build_batch_admission + from dx_productivity.trial_task_center.models import TaskStatus + from dx_productivity.trial_task_center.task_queue import _plan_hash + task_id = ui.tasks[0].task_id + ui.store.set_task_status(task_id, TaskStatus.RUNNING) + ui.store.set_task_status(task_id, TaskStatus.COMPLETED) + original = ui.service.task_context + context = original(task_id) + completed = replace(context, has_evidence=True, progress=replace(context.progress, + queue_complete=True, saved_items=1, completed_items=1, total_items=1, next_project_path=None)) + monkeypatch.setattr(ui.service, 'task_context', lambda key, **kw: completed if key == task_id else original(key, **kw)) + if has_round: + with ui.store.transaction(): + ui.store._connection.execute('INSERT INTO execution_rounds(task_id,round_id) VALUES (?,?)', (task_id, 'r')) + journal = RunJournal(ui.data) + journal.begin('f' * 32, [task_id], {task_id: _plan_hash(ui.service.for_project_task(task_id), task_id)}) + journal.finish('f' * 32, {'status': 'completed' if verified else 'failed', + 'acceptance': {'status': 'verified' if verified else 'different'}, + 'summary': {'source_versions': {'rounds': {task_id: {'round_id': 'r'}}}}, + 'netlist_verification': {task_id: {'status': 'verified' if verified else 'different', 'verified': verified}}}) + admission = build_batch_admission(ui.service, tuple(t.task_id for t in ui.tasks), scope_kind='batch') + accepted = verified and has_round + assert admission['ready'] is accepted + assert admission['decisions'][0]['classification'] == ('already_completed' if accepted else 'held') + if not accepted: + assert '验收' in admission['decisions'][0]['message'] + + +def test_duplicate_project_is_rejected_even_when_first_task_is_completed(ui, monkeypatch): + from dx_productivity.trial_task_center.batch_admission import build_batch_admission + from dx_productivity.trial_task_center.models import TaskStatus + first, second = ui.tasks + project = ui.service.projects(first.task_id)[0] + with ui.store.transaction(): + ui.store._connection.execute('UPDATE projects SET path=? WHERE task_id=?', (str(project.path), second.task_id)) + ui.store.set_task_status(first.task_id, TaskStatus.RUNNING) + ui.store.set_task_status(first.task_id, TaskStatus.COMPLETED) + original = ui.service.task_context + context = original(first.task_id) + completed = replace(context, has_evidence=True, progress=replace(context.progress, + queue_complete=True, no_match_items=1, completed_items=1, total_items=1, next_project_path=None)) + monkeypatch.setattr(ui.service, 'task_context', lambda key, **kw: completed if key == first.task_id else original(key, **kw)) + admission = build_batch_admission(ui.service, (first.task_id, second.task_id), scope_kind='batch') + assert not admission['ready'] + assert admission['decisions'][1]['reason_code'] == 'project_duplicate' + assert not ui.calls diff --git a/tests/v1_1/test_failed_native_recovery_guard.py b/tests/v1_1/test_failed_native_recovery_guard.py index f03df33..c4d0927 100644 --- a/tests/v1_1/test_failed_native_recovery_guard.py +++ b/tests/v1_1/test_failed_native_recovery_guard.py @@ -1,4 +1,5 @@ import json +import subprocess from pathlib import Path import pytest @@ -116,28 +117,55 @@ def test_manual_failure_cannot_be_completed_by_native_progress(failed_native): service.quick_run_progress(task_id) -def test_uncertain_batch_failed_isolated_before_next_project_in_task_queue(failed_native, tmp_path, monkeypatch): +def test_native_uncertainty_holds_batch_until_verified_resume(failed_native, tmp_path, monkeypatch): from threading import Event + from test_project_isolation_queue import ReleasedRuntime from dx_productivity.trial_task_center.task_queue import execute_task_queue - service, store, task_id, _, _ = failed_native + + service, store, task_id, handoff, report = failed_native other = store.create_task('independent next project') - path = tmp_path / 'next.prj' - path.touch() + path = tmp_path / 'follower' / 'next.prj' + path.parent.mkdir() + path.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n') project = store.sync_projects(other.task_id, tmp_path, (path,))[0] store.set_project_selected(project.project_id, True) + service.add_rule(other.task_id, 'OLD', 'NEW') store.bind_project_task(other.task_id, project.project_id, 'batch', 1) - from test_project_isolation_queue import ReleasedRuntime - from dx_productivity.trial_task_center.quick_run_protocol import QuickRunProgress + calls = [] - child = service.for_project_task(other.task_id) - monkeypatch.setattr(child, 'quick_run_progress', lambda _: calls.append(other.task_id) or QuickRunProgress( - 0, 0, None, None, None, (path,), True)) - monkeypatch.setattr(child, 'has_interrupted_quick_run', lambda _: False) - child._quick_run_preparer.reconcile_terminal_receipts = lambda _: None - original_child = service.for_project_task - monkeypatch.setattr(service, 'for_project_task', lambda identifier: child if identifier == other.task_id else original_child(identifier)) - result = execute_task_queue(service, (task_id, other.task_id), stop_event=Event(), runtime=ReleasedRuntime(service._logging.root)) - assert not result.paused - assert [entry.state for entry in result.entries] == ['blocked', 'completed'] - assert calls == [other.task_id] - assert not (service.for_project_task(other.task_id)._quick_run_preparer.data_root / 'quick-run').exists() + + def worker(command, timeout): + root, job = Path(command[3]), command[-1] + calls.append(root) + with (root / 'status.tsv').open('a', encoding='utf-8') as stream: + stream.write(f'{job}\tawaiting_native_replace\t\tcaptured\n' + f'{job}\tsaved_ok\tbatch_closed\tverified\n') + return subprocess.CompletedProcess(command, 0, '', '') + + original = service.for_project_task(task_id)._quick_run_preparer + follower = service.for_project_task(other.task_id)._quick_run_preparer + monkeypatch.setattr(original, '_cscript_resolver', lambda: pytest.fail('original operation replayed')) + monkeypatch.setattr(follower, '_process_runner', worker) + monkeypatch.setattr(follower, '_cscript_resolver', lambda: Path('controlled-cscript')) + monkeypatch.setattr(follower, '_sheet_discoverer', lambda _: (('MAIN', '1'),)) + runtime = ReleasedRuntime(service._logging.root) + ids = (task_id, other.task_id) + evidence = {file: file.read_bytes() for file in (handoff.command_path, handoff.status_path, report)} + first = execute_task_queue(service, ids, stop_event=Event(), runtime=runtime) + assert first.paused and first.current_task_id == task_id + assert [entry.state for entry in first.entries] == ['blocked', 'pending'] + assert execute_task_queue(service, ids, stop_event=Event(), runtime=runtime, queue_id=first.queue_id) == first + assert calls == [] and not (follower.data_root / 'quick-run').exists() + assert all(file.read_bytes() == contents for file, contents in evidence.items()) + + job = handoff.command_path.read_text(encoding='utf-8').splitlines()[1].split('\t')[1] + with handoff.status_path.open('a', encoding='utf-8') as stream: + stream.write(f'{job}\trestored_ok\trecovery_verified\tsaved and verified\n') + service.quick_run_progress(task_id) + assert not service.has_interrupted_quick_run(task_id) + + resumed = execute_task_queue(service, ids, stop_event=Event(), runtime=runtime, queue_id=first.queue_id) + assert not resumed.paused + assert [entry.state for entry in resumed.entries] == ['completed', 'completed'] + assert execute_task_queue(service, ids, stop_event=Event(), runtime=runtime, queue_id=first.queue_id).entries == resumed.entries + assert calls == [follower.data_root / 'quick-run'] diff --git a/tests/v1_1/test_lifecycle_integration_fix.py b/tests/v1_1/test_lifecycle_integration_fix.py index efe9d37..33369c6 100644 --- a/tests/v1_1/test_lifecycle_integration_fix.py +++ b/tests/v1_1/test_lifecycle_integration_fix.py @@ -22,8 +22,11 @@ def test_project_force_observes_user_force_without_leaking_failure_to_parent(tmp @pytest.mark.parametrize('residual', [False, True]) -def test_failed_project_retires_proven_exit_despite_shutdown_error(tmp_path, residual): +def test_failed_project_requires_physical_release_despite_proven_writer_exit(tmp_path, monkeypatch, residual): + import json from test_batch_runtime import Desktop + from dx_productivity.trial_task_center import desktop_slot, isolated_desktop + class OwnedDesktop(Desktop): def close(self): self.cleanup_record = {'desktop_handle_closed': True, 'owned_cleanup_complete': True, @@ -34,12 +37,33 @@ def test_failed_project_retires_proven_exit_despite_shutdown_error(tmp_path, res def cad_exit(*args): raise OSError('shutdown diagnostics failed after exit') runtime.cad = SimpleNamespace(cad=SimpleNamespace(poll=lambda: 0), record={}, __exit__=cad_exit) original = RuntimeError('original failed project') - assert runtime.release_failed_project(original, tmp_path / 'failed') - assert batch_resources.blocking_resources(tmp_path) == () - assert runtime.record['state'] == ('isolated' if residual else 'released') - assert runtime.record['release_results']['desktop_released'] is (not residual) - assert runtime.desktop is None and 'shutdown diagnostics failed' in original.shutdown_warning - assert (tmp_path / 'failed' / 'uncertain.flag').exists() + evidence = tmp_path / 'failed' + if residual: + with pytest.raises(batch_resources.BatchResourceCleanupError, match='shutdown diagnostics failed'): + runtime.release_failed_project(original, evidence) + pending, = batch_resources.blocking_resources(tmp_path) + assert pending['state'] == 'isolated' + assert pending['release_results']['desktop_released'] is False + with pytest.raises(batch_resources.BatchResourceCleanupError): + batch_resources.guard_pending_resources(tmp_path) + original_protection = (evidence / 'uncertain.flag').read_bytes() + assert not (evidence / 'project-resource-release.json').exists() + + monkeypatch.setattr(desktop_slot, 'observe_current_desktop_name', lambda _: None) + monkeypatch.setattr(isolated_desktop, '_Win32Api', + lambda: SimpleNamespace(confirm_desktop_released=lambda _: None)) + assert batch_resources.cleanup_pending_resources(tmp_path) == () + released = json.loads(runtime.path.read_bytes()) + assert released['state'] == 'released' + assert released['release_proof']['desktop_released'] is True + assert (evidence / 'uncertain.flag').read_bytes() == original_protection + else: + assert runtime.release_failed_project(original, evidence) + assert runtime.record['state'] == 'released' + assert runtime.record['release_results']['desktop_released'] is True + assert runtime.desktop is None and 'shutdown diagnostics failed' in original.shutdown_warning + assert (evidence / 'uncertain.flag').exists() + batch_resources.guard_pending_resources(tmp_path) def test_runtime_cleanup_events_record_real_boundaries_and_preserve_error(tmp_path): @@ -56,7 +80,8 @@ def test_runtime_cleanup_events_record_real_boundaries_and_preserve_error(tmp_pa ('mentor_exit', 'enter'), ('mentor_exit', 'error'), ('desktop_release', 'enter'), ('desktop_release', 'return')] -def test_workspace_accepts_writer_exit_warning_and_blocks_shared_source_follower(tmp_path, monkeypatch): +@pytest.mark.parametrize('shared_source', [False, True]) +def test_workspace_holds_follower_after_writer_exit_without_verified_result(tmp_path, monkeypatch, shared_source): from test_workspace_execution import service_for from dx_productivity.trial_task_center.workspace_execution import execute_workspace_projects from dx_productivity.trial_task_center.errors import TaskCenterError @@ -64,16 +89,22 @@ def test_workspace_accepts_writer_exit_warning_and_blocks_shared_source_follower failure.resources_released = False failure.owned_writers_exited = True service, calls = service_for(tmp_path, monkeypatch, {'A': failure, 'B': 'completed'}) - result = execute_workspace_projects(service, ('A', 'B'), stop_event=StopControl()) - assert not result.paused and result.entries[1].state == 'completed' - calls.clear() for name in ('A', 'B'): path = tmp_path / name / 'board.prj' - path.parent.mkdir(exist_ok=True) - path.write_text('KEY iCDBDir "../shared"\n') - result = execute_workspace_projects(service, ('A', 'B'), stop_event=StopControl()) - assert not result.paused and [row.state for row in result.entries] == ['blocked', 'blocked'] - assert [call[1]['task_ids'][0] for call in calls] == ['A'] + path.parent.mkdir() + source = '../shared' if shared_source else 'database' + path.write_text(f'KEY iCDBDir "{source}"\n') + ids = ('A', 'B') + result = execute_workspace_projects(service, ids, stop_event=StopControl()) + assert result.paused and result.current_task_id == 'A' + assert [entry.state for entry in result.entries] == ['blocked', 'pending'] + protection = tmp_path / 'tasks' / 'A' / 'quick-run' / 'uncertain.flag' + original = protection.read_bytes() + resumed = execute_workspace_projects(service, ids, stop_event=StopControl(), queue_id=result.queue_id) + assert resumed.paused and resumed.current_task_id == 'A' + assert [entry.state for entry in resumed.entries] == ['blocked', 'pending'] + assert [call[1]['task_ids'] for call in calls] == [('A',)] + assert protection.read_bytes() == original def test_blocked_progress_read_does_not_promote_or_throw(failed_native): diff --git a/tests/v1_1/test_managed_desktop.py b/tests/v1_1/test_managed_desktop.py index 9baf58c..649c92b 100644 --- a/tests/v1_1/test_managed_desktop.py +++ b/tests/v1_1/test_managed_desktop.py @@ -113,7 +113,7 @@ def test_mutex_release_error_preserves_the_durably_returned_lease(tmp_path): def test_failed_lease_return_stays_blocking_until_the_slot_can_be_returned(tmp_path, monkeypatch): - from dx_productivity.trial_task_center import batch_resources + from dx_productivity.trial_task_center import batch_resources, desktop_slot from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime backend = Backend() @@ -135,6 +135,15 @@ def test_failed_lease_return_stays_blocking_until_the_slot_can_be_returned(tmp_p monkeypatch.undo() batch_resources.cleanup_pending_resources(runtime.root, retry_failed=True) assert not backend.locked + pending, = batch_resources.blocking_resources(runtime.root) + assert pending['state'] == 'isolated' + assert pending['cleanup']['desktop_lease']['returned'] is True + assert backend.desktop_exists(pending['desktop']) + + monkeypatch.setattr(desktop_slot, 'managed_desktop_disappeared', + lambda receipt: not backend.desktop_exists(receipt['name'])) + backend.exists = False + assert batch_resources.cleanup_pending_resources(runtime.root) == () assert batch_resources.blocking_resources(runtime.root) == () diff --git a/tests/v1_1/test_nonblocking_items.py b/tests/v1_1/test_nonblocking_items.py index 8cd2f9e..3a782c5 100644 --- a/tests/v1_1/test_nonblocking_items.py +++ b/tests/v1_1/test_nonblocking_items.py @@ -84,17 +84,19 @@ def test_safe_component_failure_continues_independent_component_and_project(comp assert store._connection.execute("SELECT count(*) FROM execution_operations WHERE state='verified'").fetchone()[0] == 3 -def test_uncertain_component_never_runs_same_project_remainder(component_case): +def test_uncertain_component_holds_same_and_later_projects(component_case): service, _, tasks, calls, outcomes = component_case - task_id = tasks[0].task_id - outcomes[(task_id, ('R1',))] = 'batch_saved_unverified' ids = tuple(task.task_id for task in tasks) + task_id = ids[0] + outcomes[(task_id, ('R1',))] = 'batch_saved_unverified' 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 service.has_interrupted_quick_run(task_id) - execute_task_queue(service, ids, stop_event=Event(), queue_id=result.queue_id) - assert len(calls) == 3 + resumed = execute_task_queue(service, ids, stop_event=Event(), queue_id=result.queue_id) + assert resumed.paused and resumed.current_task_id == task_id + assert [entry.state for entry in resumed.entries] == ['blocked', 'pending'] + assert calls == [(task_id, ('R1',))] def test_problem_retry_budget_survives_rebinding_and_is_shared(component_case): diff --git a/tests/v1_1/test_pr47_audit_resources.py b/tests/v1_1/test_pr47_audit_resources.py new file mode 100644 index 0000000..c5f8bbe --- /dev/null +++ b/tests/v1_1/test_pr47_audit_resources.py @@ -0,0 +1,155 @@ +import json + +import pytest + +from dx_productivity.trial_task_center import batch_resources, batch_supervisor +from dx_productivity.trial_task_center.errors import TaskCenterError +from dx_productivity.trial_task_center.logging_setup import configure_logging +from dx_productivity.trial_task_center.supervisor_protocol import encode, encode_error + + +@pytest.fixture +def resource_session(tmp_path, monkeypatch): + batch_id = 'a' * 32 + directory = tmp_path / 'batch-resources' / batch_id + identity = {'pid': 123, 'creation_time': 'original'} + journal = dict(version=1, batch_id=batch_id, attempt_id='b' * 32, state='running', + operation='execute_task_queue', task_ids=['task'], process=identity, + parent_process=identity, request_sha256='c' * 64) + record = dict(version=1, session_id=batch_id, kind='execution', generation=1, + desktop='dx-' + 'd' * 32, state='blocked', processes=[], + cad_pid=None, cad_guid=None, checkpoints={}, retries={}, timings=[], + cleanup={'desktop_handle_closed': True, 'owned_cleanup_complete': True}) + monkeypatch.setattr(batch_resources, 'observe_process_identity', lambda identity: {'state': 'gone'}) + monkeypatch.setattr(batch_resources, 'RESOURCE_RELEASE_BACKOFF_SECONDS', ()) + from dx_productivity.trial_task_center import desktop_slot + observation = {'gone': False} + monkeypatch.setattr(desktop_slot, 'observe_current_desktop_name', lambda name: observation['gone']) + batch_resources.write_record(directory / 'supervisor.json', journal) + batch_resources.write_record(directory / 'session.json', record) + return directory, journal, record, observation + + +def _write_result(directory, journal, payload): + batch_resources.write_record(directory / 'result.json', dict( + version=1, batch_id=journal['batch_id'], attempt_id=journal['attempt_id'], + type='result', sequence=1, generation=1, payload=payload)) + + +def _successful_result(): + from dx_productivity.trial_task_center.task_queue import TaskQueueEntry, TaskQueueResult + + result = TaskQueueResult('e' * 32, (TaskQueueEntry('task', 'completed'),), False) + return {'status': 'ok', 'business_succeeded': True, 'result': encode(result)} + + +@pytest.mark.parametrize('shutdown', [{'forced_termination': True}, {'orderly_shutdown': False}]) +def test_abnormal_shutdown_survives_isolation_and_later_release(tmp_path, resource_session, shutdown): + directory, journal, record, observation = resource_session + record['cad_shutdown'] = shutdown + batch_resources.write_record(directory / 'session.json', record) + payload = _successful_result() + _write_result(directory, journal, payload) + with pytest.raises(TaskCenterError) as caught: + batch_supervisor._finish_response(tmp_path, journal, payload, configure_logging(tmp_path)) + assert caught.value.code == 'application_shutdown_failed' + assert caught.value.completed_result.entries[0].state == 'completed' + assert caught.value.resources_released is False + assert caught.value.owned_writers_exited is True + with pytest.raises(batch_resources.BatchResourceCleanupError): + batch_resources.guard_pending_resources(tmp_path) + assert batch_supervisor.reconcile_supervisors(tmp_path)[0]['outcome'] == 'application_shutdown_failed' + + observation['gone'] = True + assert not batch_resources.cleanup_pending_resources(tmp_path) + assert not batch_supervisor.reconcile_supervisors(tmp_path) + finished = json.loads((directory / 'supervisor.json').read_bytes()) + assert finished['state'] == 'finished' + assert finished['outcome'] == 'application_shutdown_failed' + assert finished['resource_recheck']['desktop_released'] is True + + +@pytest.mark.parametrize('legacy', [False, True]) +def test_confirmed_business_failure_does_not_create_uncertainty(tmp_path, resource_session, legacy): + directory, journal, _, observation = resource_session + error = encode_error(TaskCenterError('lookup_unavailable', 'timeout before changing the project')) + payload = {'status': 'error', 'business_succeeded': False, 'operation_error': error, 'error': error} + _write_result(directory, journal, payload) + if legacy: + batch_resources.cleanup_pending_resources(tmp_path) + batch_resources.write_record(directory / 'supervisor.json', dict(journal, state='blocked', outcome='error')) + else: + with pytest.raises(TaskCenterError) as caught: + batch_supervisor._finish_response(tmp_path, journal, payload, configure_logging(tmp_path)) + assert caught.value.code == 'batch_resources_pending' + assert caught.value.primary_error.code == 'lookup_unavailable' + pending, = batch_supervisor.reconcile_supervisors(tmp_path) + assert pending['outcome'] == 'error' + assert not pending.get('business_uncertain') + assert not tuple(tmp_path.rglob('uncertain.flag')) + + observation['gone'] = True + assert not batch_resources.cleanup_pending_resources(tmp_path) + assert not batch_supervisor.reconcile_supervisors(tmp_path) + finished = json.loads((directory / 'supervisor.json').read_bytes()) + assert (finished['state'], finished['outcome']) == ('finished', 'error') + assert not finished.get('business_uncertain') + + +@pytest.mark.parametrize('content', [None, '{bad']) +def test_missing_or_corrupt_result_remains_uncertain_after_release(tmp_path, resource_session, content): + directory, journal, _, observation = resource_session + if content is not None: + (directory / 'result.json').write_text(content, encoding='utf-8') + batch_resources.write_record(directory / 'supervisor.json', dict( + journal, state='blocked', outcome='completed_resources_pending')) + observation['gone'] = True + assert not batch_resources.cleanup_pending_resources(tmp_path) + assert not batch_supervisor.reconcile_supervisors(tmp_path) + finished = json.loads((directory / 'supervisor.json').read_bytes()) + assert finished['outcome'] == 'interrupted' + assert finished['business_uncertain'] is True + assert tuple(tmp_path.rglob('uncertain.flag')) + + +@pytest.mark.parametrize('state', ['blocked', 'released']) +def test_pending_managed_lease_cannot_be_released_by_desktop_absence(tmp_path, resource_session, state): + directory, _, record, observation = resource_session + record.update(state=state, release_proof={'generation': 1, 'desktop_released': True, 'processes_exited': True}) + record['cleanup']['desktop_lease_pending'] = True + batch_resources.write_record(directory / 'session.json', record) + observation['gone'] = True + assert batch_resources.cleanup_pending_resources(tmp_path) + assert json.loads((directory / 'session.json').read_bytes())['state'] == 'blocked' + with pytest.raises(batch_resources.BatchResourceCleanupError): + batch_resources.guard_pending_resources(tmp_path) + + +def test_invalid_parameter_after_open_keeps_process_identity_unknown(monkeypatch): + from types import SimpleNamespace + + import pywintypes + import win32api + import win32process + + closed = [] + monkeypatch.setattr(win32api, 'OpenProcess', lambda *args: SimpleNamespace(Close=lambda: closed.append(True))) + + def read_times(handle): + raise pywintypes.error(87, 'GetProcessTimes', 'injected') + + monkeypatch.setattr(win32process, 'GetProcessTimes', read_times) + result = batch_resources.observe_process_identity({'pid': 123, 'creation_time': 'original'}) + assert (result['state'], result['error_code']) == ('unknown', 87) + assert closed == [True] + + +def test_parent_stall_watch_respects_a_longer_active_worker_budget(): + watch = batch_supervisor.BusinessProgressWatch(0) + requests = [] + watch.observe('state', {'business_progress': {'job_id': 'worker', 'stage': 'save', + 'idle_timeout_seconds': 220}}, 1) + assert not watch.request_cooperative_stop(151, requests.append) + assert not watch.request_cooperative_stop(220, requests.append) + assert watch.request_cooperative_stop(221, requests.append) + assert requests == ['inactivity'] diff --git a/tests/v1_1/test_resource_queue_resume.py b/tests/v1_1/test_resource_queue_resume.py index 98eb21b..b0deea1 100644 --- a/tests/v1_1/test_resource_queue_resume.py +++ b/tests/v1_1/test_resource_queue_resume.py @@ -71,7 +71,9 @@ def test_automatic_resource_continuation_revalidates_before_later_dispatch(tmp_p assert len(dispatched) == 1 and dispatched[0]['checkpoint_id'] == queue_id -@pytest.mark.parametrize('reason', [None, 'unknown_writer', 'cancel', 'consumed', 'unknown_pause', 'uncertain']) +@pytest.mark.parametrize('reason', [None, 'unknown_writer', 'cancel', 'consumed', 'unknown_pause', 'uncertain', + 'shutdown_failed', 'legacy_shutdown_failed', 'session_missing', + 'release_unproven']) def test_original_receipt_must_prove_resource_pause_and_cannot_be_consumed_again(tmp_path, monkeypatch, reason): from dx_productivity.trial_task_center import batch_resources @@ -86,9 +88,24 @@ def test_original_receipt_must_prove_resource_pause_and_cannot_be_consumed_again batch_resources.write_record(folder / 'request.json', request) digest = hashlib.sha256((folder / 'request.json').read_bytes()).hexdigest() process = {'pid': 17, 'creation_time': 'worker'} - batch_resources.write_record(folder / 'supervisor.json', {'version': 1, 'batch_id': batch_id, 'attempt_id': attempt, + journal = {'version': 1, 'batch_id': batch_id, 'attempt_id': attempt, 'operation': 'execute_task_queue', 'task_ids': list(ids), 'parent_process': process, - 'process': process, 'state': 'finished', 'request_sha256': digest}) + 'process': process, 'state': 'finished', 'request_sha256': digest} + if reason == 'shutdown_failed': + journal['outcome'] = 'application_shutdown_failed' + batch_resources.write_record(folder / 'supervisor.json', journal) + if reason != 'session_missing': + session = dict(version=1, session_id=batch_id, kind='task_queue', generation=1, + desktop='dx-' + batch_id, state='released', processes=[], cad_pid=None, cad_guid=None, + checkpoints={}, retries={}, timings=[], release_proof={ + 'generation': 1, 'desktop_released': True, 'processes_exited': True}) + if reason == 'legacy_shutdown_failed': + journal['outcome'] = 'completed' + batch_resources.write_record(folder / 'supervisor.json', journal) + session['cad_shutdown'] = {'orderly_shutdown': False, 'forced_termination': True} + if reason == 'release_unproven': + session['release_proof'] = {} + batch_resources.write_record(folder / 'session.json', session) payload = {'business_succeeded': True, 'status': 'ok', 'result': encode(result)} payload['resource_warning'] = {'state': 'isolated', 'owned_writers_exited': True} batch_resources.write_record(folder / 'result.json', {'version': 1, 'batch_id': batch_id, 'attempt_id': attempt, diff --git a/tests/v1_1/test_resource_reconciliation_ui.py b/tests/v1_1/test_resource_reconciliation_ui.py index 54786eb..43d8c01 100644 --- a/tests/v1_1/test_resource_reconciliation_ui.py +++ b/tests/v1_1/test_resource_reconciliation_ui.py @@ -18,7 +18,9 @@ def test_startup_rechecks_isolation_without_using_the_manual_button(window, qtbo window._resource_status.records = pending window._resource_status.known = True window._update_gates() - assert not window.run_panel.cleanup_resources_button.isEnabled() + assert window.run_panel.cleanup_resources_button.isEnabled() + assert not window.run_panel.quick_run_button.isEnabled() + assert not window.task_list.queue_button.isEnabled() window._startup_resource_recheck() qtbot.waitUntil(lambda: len(modes) == 1 and not window._workers) assert modes == [True] @@ -91,3 +93,34 @@ def test_lost_handles_show_restart_hint_without_unusable_force_prompt(window, qt qtbot.waitUntil(lambda: not window._workers) assert questions == [] assert hint in window.run_panel.operator_band.text() + + +def test_force_confirmation_waits_for_background_receipt_lane(window, qtbot, monkeypatch): + qtbot.waitUntil(lambda: not window._workers and not window._resource_status.busy) + pending = ({'state': 'blocked', 'kind': 'retained_worker', 'force_available': True},) + monkeypatch.setattr(window.service, 'pending_batch_resources', lambda: pending) + monkeypatch.setattr(window.service, 'cleanup_batch_resources', lambda: pending) + report_started, release_report = Event(), Event() + def recover(*_): + report_started.set() + assert release_report.wait(5) + monkeypatch.setattr('dx_productivity.dsh.execution_runs.recover_batch_receipts', recover) + calls = [] + monkeypatch.setattr(window.service, 'force_pending_owned_resources', + lambda *, confirmed: calls.append(confirmed) or ()) + def confirm(*_): + qtbot.waitUntil(report_started.is_set, timeout=5000) + QTimer.singleShot(0, release_report.set) + return QMessageBox.StandardButton.Yes + monkeypatch.setattr(QMessageBox, 'question', confirm) + window._resource_status.records = pending + window._resource_status.known = True + window._update_gates() + try: + window.run_panel.cleanup_resources_button.click() + qtbot.waitUntil(report_started.is_set, timeout=5000) + qtbot.waitUntil(lambda: not window._workers, timeout=5000) + assert calls == [True], 'A receipt read must not swallow an explicit force confirmation' + finally: + release_report.set() + qtbot.waitUntil(lambda: not window._workers, timeout=5000) diff --git a/tests/v1_1/test_resume_evidence.py b/tests/v1_1/test_resume_evidence.py index d872611..291fabc 100644 --- a/tests/v1_1/test_resume_evidence.py +++ b/tests/v1_1/test_resume_evidence.py @@ -53,8 +53,11 @@ def test_restart_with_incomplete_handoff_never_replays_worker(resume_case,damage context=restarted.task_context(task.task_id) assert context.interrupted assert context.has_evidence - outcome=execute_task_queue(restarted,(task.task_id,),stop_event=Event()) - assert not outcome.paused and outcome.entries[0].state=='blocked' + damaged = path.read_bytes() if path.exists() else None + outcome=execute_task_queue(restarted,(task.task_id,),stop_event=Event(),queue_id=result.queue_id) + assert outcome.paused and outcome.current_task_id == task.task_id + assert outcome.entries[0].state == 'blocked' + assert (path.read_bytes() if path.exists() else None) == damaged assert len(calls)==2 @@ -83,14 +86,21 @@ def test_receipts_block_rollback_to_an_empty_status_even_without_sidecars(resume (root/'current-command.tsv').unlink(missing_ok=True) restarted=reopen() assert restarted.task_context(task.task_id).interrupted - result=execute_task_queue(restarted,(task.task_id,),stop_event=Event()) - assert not result.paused and result.entries[0].state=='blocked' and len(calls)==2 + resumed=execute_task_queue(restarted,(task.task_id,),stop_event=Event(),queue_id=result.queue_id) + assert resumed.paused and resumed.current_task_id == task.task_id + assert resumed.entries[0].state == 'blocked' and len(calls) == 2 + assert (root/'status.tsv').read_text(encoding='utf8') == 'job_id\tstate\tcode\tmessage\n' + assert not (root/'current-command.tsv').exists() def test_missing_entire_handoff_cannot_erase_database_receipts(resume_case): service,task,result,root,calls,reopen=resume_case - root.rename(root.with_name('preserved-probe-handoff')) + original = root.rename(root.with_name('preserved-probe-handoff')) + verified_status = (original/'status.tsv').read_bytes() restarted=reopen() assert restarted.task_context(task.task_id).interrupted - result=execute_task_queue(restarted,(task.task_id,),stop_event=Event()) - assert not result.paused and result.entries[0].state=='blocked' and len(calls)==2 + resumed=execute_task_queue(restarted,(task.task_id,),stop_event=Event(),queue_id=result.queue_id) + assert resumed.paused and resumed.current_task_id == task.task_id + assert resumed.entries[0].state == 'blocked' and len(calls) == 2 + assert not root.exists() + assert (original/'status.tsv').read_bytes() == verified_status diff --git a/tests/v1_1/test_safe_timeout_problems.py b/tests/v1_1/test_safe_timeout_problems.py index 1bce29a..e626ab9 100644 --- a/tests/v1_1/test_safe_timeout_problems.py +++ b/tests/v1_1/test_safe_timeout_problems.py @@ -67,10 +67,13 @@ def test_safe_timeout_runs_independent_uid_then_one_problem_retry(component_case @pytest.mark.parametrize('unsafe', ['unconfirmed', 'changed_status', 'changed_source', 'changed_command', 'wrong_stage', 'cancelled']) def test_timeout_without_complete_proof_stays_uncertain(component_case, unsafe): service, _, tasks, calls, _ = component_case - task_id = tasks[0].task_id + ids = tuple(task.task_id for task in tasks) + task_id = ids[0] preparer = service.for_project_task(task_id)._quick_run_preparer stop = Event() + attempts = [] def worker(command, timeout): + attempts.append(command[-1]) error = confirmed_timeout() if unsafe == 'unconfirmed': error.prewrite_cleanup_confirmed = False @@ -88,10 +91,16 @@ def test_timeout_without_complete_proof_stays_uncertain(component_case, unsafe): stop.set() raise error preparer._process_runner = worker - result = execute_task_queue(service, (task_id,), stop_event=stop) - assert result.paused is (unsafe == 'cancelled') - assert result.entries[0].state == 'blocked' - assert calls == [] + result = execute_task_queue(service, ids, stop_event=stop) + assert result.paused and result.current_task_id == task_id + assert [entry.state for entry in result.entries] == ['blocked', 'pending'] + protection = preparer.data_root / 'quick-run' / 'uncertain.flag' + evidence = protection.read_bytes() + resumed = execute_task_queue(service, ids, stop_event=Event(), queue_id=result.queue_id) + assert resumed.paused and resumed.current_task_id == task_id + assert [entry.state for entry in resumed.entries] == ['blocked', 'pending'] + assert protection.read_bytes() == evidence + assert len(attempts) == 1 and calls == [] assert service.reserve_problem_retry(task_id) == () assert preparer.has_interrupted(task_id) assert not any(issue['classification'] == 'retryable' for issue in service.execution_problems(task_id))