From 282252a5fb2a5470847ad8a97aeb1f2bc58fc616 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=98=BF=E7=99=BD=E5=8F=94?= <11794527+absfan@user.noreply.gitee.com> Date: Sat, 31 Oct 2026 20:24:04 +0800 Subject: [PATCH] fix(dsh): reconcile orphan schedules and preserve audit evidence --- docs/testing/2026-10-31-dsh-pr11-review129.md | 30 ++++++ docs/user/dsh-ai-supervision.md | 6 ++ integration/dsh/task-plugin/client.js | 3 + integration/dsh/task-plugin/lifecycle.mjs | 4 +- integration/dsh/task-plugin/model_results.mjs | 3 +- src/dx_productivity/dsh/execution_runs.py | 15 ++- src/dx_productivity/dsh/schedule_audit.py | 71 ++++++++++++++ src/dx_productivity/dsh/scheduling.py | 69 ++++++++++++++ .../trial_task_center/ui/dsh_operations.py | 38 ++++++-- tests/dsh/test_execution_recovery.py | 26 +++++ tests/dsh/test_schedule_audit.py | 86 +++++++++++++++++ tests/dsh/test_scheduling.py | 95 +++++++++++++++++++ tests/ui/test_dsh_operations.py | 61 +++++++++++- tools/accept_dsh_operations.py | 25 ++++- tools/verify_dsh_model_results.mjs | 4 + tools/verify_dsh_operations_ui.mjs | 69 ++++++++++++-- 16 files changed, 578 insertions(+), 27 deletions(-) create mode 100644 docs/testing/2026-10-31-dsh-pr11-review129.md create mode 100644 src/dx_productivity/dsh/schedule_audit.py create mode 100644 tests/dsh/test_schedule_audit.py diff --git a/docs/testing/2026-10-31-dsh-pr11-review129.md b/docs/testing/2026-10-31-dsh-pr11-review129.md new file mode 100644 index 0000000..890cc2f --- /dev/null +++ b/docs/testing/2026-10-31-dsh-pr11-review129.md @@ -0,0 +1,30 @@ +# PR #11 评论 #129 修复验证 + +基线:`4aaebcb`。本轮仅修改 PR #11,不合并 PR、不构建 EXE。 + +## 修复 + +- `claimed` 失联排期新增原生确认的“核对并收尾”入口。排期专属进程锁从领取前覆盖到最终回执,恢复原排期运行也取得同一把锁。对账再次检查活动队列、后台资源和运行绑定,活动执行不能被对账。已完成/失败的持久回执保持其结果,其余标记中断;不启动 CAD、不重新派发、不删除原运行。 +- 恢复执行的异常回执保留最后一份 `tasks`/`entries`,差异基线不会因一次软失败被清空。 +- 终态历史从持久任务回执逐字段汇总保存/失败/未命中。任一范围内任务缺少某字段,该字段合计保留 unknown,不假定为零,也不读取后来已变化的工程结果。 +- 近期排期审计以 5000 条为保留目标,到 6000 条后每次监管刷新最多无损归档 1000 条,避免逐事件产生碎片文件。JSONL 写入、fsync、原子替换和 SHA256 验证完成后,才在同一事务登记清单并移出近期表。导出失败不删除,数据库事务失败后文件可安全复用。归档完整性按元数据变化重新校验;丢失或损坏单独降级。界面和模型只展示归档摘要,原始事件保存在本地文件中。 + +## 验证 + +- DSH/UI、原队列、批次重试、任务 UI、操作生命周期、关闭归档、执行反馈及打包:346 passed。 +- 最终受影响模块(排期、审计归档、执行恢复、真实监管控制器):72 passed,与前项有覆盖重叠。 +- 独立复审补充 7 项轻量验证通过,未发现重要剩余问题。 +- 真子进程持锁时拒绝对账;`os._exit()` 硬退出后锁释放,重新打开 SQLite 可按确认流程收尾。覆盖运行尚未建立、运行仍未收尾、已完成、暂停、失败等状态,原运行记录保持不变。 +- 原生确认取消时不改变排期;确认后收尾,受控执行器调用为零。审计插入失败回滚,资源未释放拒绝对账。 +- 覆盖归档导出失败、删除事务失败后重试、归档内容精确重建、归档丢失/篡改及真实控制器区块降级;计数缺失保持未知。 +- 官方 runtime CLI、模型结果裁剪、dock 启动、Python 编译、修改 JS/MJS 语法与 diff 检查通过。 + +最后补充的批量归档策略 6 项通过;收尾后即时审计展示与取消路径另 2 项通过。归档目录与清单随数据目录保留,本轮未引入自动删除长期证据的策略。 + +## 实际点击验收 + +最终报告:build/dsh-pr11-review129/20261031-201906/report.json。两进程真实 Qt/CDP 验收通过:失联排期原生取消/确认、归档状态和审计卡片、自然语言执行、安全暂停、重启原队列续跑、终态历史合计、授权排期仅执行一次及已有工单只读 GET 均通过。归档完整性检查通过,1000 条旧事件已归档。3 次受控队列步骤唯一,源 fixture 哈希及损坏审计原字节不变,两个应用进程均正常退出。realCadStarted=false,remoteIssuesCreated=false。 + +前两次验收分别停于模型就可选基线提出澄清、排期点击遇到忙碌回执;均保留失败报告。验收脚本增加模拟用户自然语言回答及等待忙碌操作收尾后重新点击,不绕过原生确认或版本门禁。最终成功报告来自完整重新运行。 + +本轮 PR 增量及新文件的两份已知凭据逐字节扫描为 0 匹配;未输出凭据。未执行真实 CAD 写入、生产 broker 部署、EXE 构建或 PR 合并。 diff --git a/docs/user/dsh-ai-supervision.md b/docs/user/dsh-ai-supervision.md index 5cd0147..f54106a 100644 --- a/docs/user/dsh-ai-supervision.md +++ b/docs/user/dsh-ai-supervision.md @@ -69,6 +69,8 @@ Harness 使用任务中心数据目录下独立的 `dsh/harness-home` 保存会 最近一次执行回执独立保留,随后查看任务列表不会覆盖它。执行历史根据本地持久记录和任务证据判断可否恢复;重启只展示记录,不自动重放。点击 **核对并恢复原队列** 后仍须原生确认。计划变化、缺少或损坏检查点、未核验中断、失败项等会阻断恢复;待核验结果从任务中心原流程处理。 +已结束运行的保存、失败和未命中合计来自持久回执;任一任务缺少某项计数时,该项合计仍显示“未报告”,不会把未知当作零。恢复过程报错时保留上一份任务证据和队列基线,供下一次核对。 + 恢复执行后若在新回执写入前退出,原队列中新增的已核验进度可继续接续,不会因旧暂停回执的计数较小而重复执行或永久阻断。原先已收尾任务的证据变化、计数回退,以及完成检查点缺少匹配完成证据,仍会阻断。执行后核验只在队列完成且失败为零时报告就绪;未完成或有失败时明确显示待核验,实际保存与未命中数量分别保留。 原生任务中心的当前任务执行,以及不超过 20 个任务的原生批次,也写入这套运行记录。超过 20 个任务的原生分组继续使用原分组检查点,不加入 DSH 合并运行历史;不要把该分组当作可以从本页恢复的合并运行。 @@ -89,6 +91,10 @@ Harness 使用任务中心数据目录下独立的 `dsh/harness-home` 保存会 启动前重新检查预检、未保存编辑、冻结计划和资源门禁;忙碌、手动暂停任务、依赖未完成、计划变化或不确定结果都会阻断。排期领取持久且互斥,执行中断或重启后不自动重新领取并重放。需要继续时核对运行历史与原任务证据。 +应用退出后仍显示“已领取”的排期,可点击 **核对并收尾失联排期**。原生确认后检查执行占用与待释放资源,再按已有持久回执收尾;没有完成回执时标记中断。此操作不会执行工程,原运行记录继续保留供人工核验与恢复。仍有活动执行或资源未释放时拒绝收尾。 + +排期页显示近期审计与归档数量。近期事件以 5000 条为保留目标,累积到 6000 条后,每次刷新最多将 1000 条较早事件完整写入数据目录的 `dsh/schedule-audit/`,避免每条事件产生一个归档碎片;JSONL 文件名包含 SHA256,数据库保留归档清单。只有文件写入并校验成功后才移出近期表,不会静默丢弃历史事件。归档文件缺失、损坏或访问失败时单独显示降级,并保留其余监管功能;请备份清单和归档文件一起转移。 + ### 经验与工单 **经验**页按异常代码或诊断关键词检索本地事件,展示诊断/复盘、尝试次数、处理结果、后续建议和证据引用。优先呈现已验证经验,再比较异常代码精确匹配和记录新旧。只有独立持久化核验及证据证明队列完成、失败为零、无中断且无暂停,才显示“已验证”。模型声称修复、工单关闭或无证据建议保持未验证。 diff --git a/integration/dsh/task-plugin/client.js b/integration/dsh/task-plugin/client.js index 6565740..d76c522 100644 --- a/integration/dsh/task-plugin/client.js +++ b/integration/dsh/task-plugin/client.js @@ -154,12 +154,15 @@ window.__ModuleLoader__.load({id:'@dx/dsh-task',factory:require=>{ actions(button('dx-schedule-new','为当前任务设置排期',()=>perform({operation:'schedule_dialog',task_ids:scope}),pending||!scope.length), button('dx-schedules-refresh','刷新排期',()=>perform({operation:'refresh'}),pending)), empty('时间按本机时区显示。排期在工具打开期间检查,执行前仍需核对保存范围与实际预检。'), + operations.schedule_audit?.status==='ok'&&empty(`排期审计:近期 ${operations.schedule_audit.live_events} 条,已归档 ${operations.schedule_audit.archived_events} 条;旧记录完整保留在本地审计归档。`), + operations.schedule_audit?.status==='unavailable'&&empty('排期审计归档不可用,请保留现有记录并核对本地归档。'), ...(operations.schedules||[]).map(row=>card(row.schedule_id,row.title||'任务排期', detail('状态',status(row.status)),detail('优先级',priorities[row.priority]||display(row.priority)),detail('不早于',time(row.not_before)), detail('截止时间',time(row.due_at)),detail('任务',(row.task_ids||[]).join(' → ')),detail('依赖',(row.dependencies||[]).join('、')||'无'), detail('执行方式',row.auto_start?'已保存自动启动意图,依原生授权与预检执行':'等待手动确认'), blockerList(row.blockers),actions( button('dx-schedule-run-'+row.schedule_id,'核对并执行',()=>perform({operation:'run_schedule',schedule_id:row.schedule_id}),pending||row.ready!==true), + row.status==='claimed'&&button('dx-schedule-reconcile-'+row.schedule_id,'核对并收尾失联排期',()=>perform({operation:'reconcile_schedule',schedule_id:row.schedule_id}),pending), button('dx-schedule-cancel-'+row.schedule_id,'取消排期',()=>perform({operation:'cancel_schedule',schedule_id:row.schedule_id}),pending||row.status!=='pending')))), !operations.schedules?.length&&empty('暂无排期。'), ...(operations.schedule_events||[]).slice(0,10).map(row=>card('schedule-event-'+row.sequence, diff --git a/integration/dsh/task-plugin/lifecycle.mjs b/integration/dsh/task-plugin/lifecycle.mjs index 1b13e42..ae38d2f 100644 --- a/integration/dsh/task-plugin/lifecycle.mjs +++ b/integration/dsh/task-plugin/lifecycle.mjs @@ -44,13 +44,13 @@ export function registerLifecycle(ctx){ {name:'dx_task_execute',capability:'execute',parameters:{operation:{type:'string',required:true,enum:['start','pause','resume']},task_ids:{type:'array',items:{type:'string'},description:ids.description},run_id:{type:'string',description:'For resume only, use the real saved run ID from execution history. Original frozen scope/order and existing checkpoint are inspected, then natively confirmed.'}}, description:'Start or continue the existing serial execution queue for an explicit ordered list of real task IDs. Prechecks and native confirmation are required; actual execution can replace and save engineering files using existing backup, interruption and verification gates. Waits for real results including saved, failed and no-match counts. For pause, provide exactly the active run scope; requests safe stopping after the current item and returns pause_requested, not a claim that stopping has completed. No force-stop, no new CAD scripting or hidden retry. Interactive conversations only.'}, {name:'dx_task_operations',capability:'operations',parameters:{ - operation:{type:'string',required:true,enum:['refresh','history','health','decisions','impact','experience','tickets','refresh_ticket','schedule','schedule_dialog','cancel_schedule','run_schedule','resume']}, + operation:{type:'string',required:true,enum:['refresh','history','health','decisions','impact','experience','tickets','refresh_ticket','schedule','schedule_dialog','cancel_schedule','run_schedule','reconcile_schedule','resume']}, task_ids:{type:'array',items:{type:'string'},description:ids.description},run_id:{type:'string'},schedule_id:{type:'string'},incident_id:{type:'string'},issue_code:{type:'string'}, title:{type:'string'},priority:{type:'string',enum:['low','normal','high','urgent']}, not_before:{type:'string',description:'For schedule: earliest run time as ISO 8601 with explicit timezone offset, e.g. 2026-10-30T18:00:00+08:00. Ask when ambiguous; never guess a date.'}, due_at:{type:'string',description:'Optional deadline with timezone offset'},dependencies:{type:'array',items:{type:'string'},description:'Actual preceding task IDs that must complete without unresolved evidence'}, auto_start:{type:'boolean',description:'Future idle execution intent only. Native confirmation explicitly authorizes the frozen scope; never a bypass. Default false.'}}, - description:'Read execution history/recoverable runs, exact saved impact or unknown mapping counts, evidence-backed local experiences, and existing Git issue status/replies. Refresh one bound ticket by real incident ID; cannot write comments. Plan tasks with priority/time/dependencies and optional idle execution using a native confirmation. App must remain open; changed plans, pause, uncertainty and blockers prevent scheduled execution. Use only fields relevant to the selected operation. history/refresh return real saved run and schedule IDs. resume reconfirms an original frozen queue. Interactive conversations only.'}, + description:'Read execution history/recoverable runs, exact saved impact or unknown mapping counts, evidence-backed local experiences, and existing Git issue status/replies. Refresh one bound ticket by real incident ID; cannot write comments. Plan tasks with priority/time/dependencies and optional idle execution using a native confirmation. App must remain open; changed plans, pause, uncertainty and blockers prevent scheduled execution. reconcile_schedule requests native confirmation to close an orphan claimed schedule only when no execution owns it and resources are released; preserves the original run for recovery and never starts execution. Use only fields relevant to the selected operation. history/refresh return real saved run and schedule IDs. resume reconfirms an original frozen queue. Interactive conversations only.'}, ]; for(const {capability,...definition} of definitions){ ctx.tools.register(defineTool({...definition,output,execute:(spec,exec)=>request(capability,spec,exec)})); diff --git a/integration/dsh/task-plugin/model_results.mjs b/integration/dsh/task-plugin/model_results.mjs index 591cb77..4d7d219 100644 --- a/integration/dsh/task-plugin/model_results.mjs +++ b/integration/dsh/task-plugin/model_results.mjs @@ -28,6 +28,7 @@ export function compactResult(value){ if(result.tasks)result.tasks=result.tasks.map(t=>({...t,...t.note?{note:short(t.note,300)}:{}})); if(result.runs)result.runs=result.runs.slice(0,5).map(run); if(result.schedules)result.schedules=result.schedules.slice(0,10).map(schedule); + if(result.schedule_audit)result.schedule_audit=fields(result.schedule_audit,['status','live_events','archived_events','retained_limit']); if(result.schedule_events)result.schedule_events=result.schedule_events.slice(0,10).map(row=>({ ...fields(row,['sequence','schedule_id','at_utc','event','run_id']), payload:{...fields(row.payload,['automatic','authority','status']), @@ -47,7 +48,7 @@ export function modelSnapshot(value){ result.operations=compactResult({busy:ops.busy===true,live_run:ops.live_run,last_execution:ops.last_execution, runs:ops.runs||[],schedules:ops.schedules||[],experiences:ops.experiences||[],tickets:ops.tickets||[],health:ops.health, decision_audit:ops.decision_audit,decisions:ops.decisions||[], - section_errors:ops.section_errors||[],schedule_events:ops.schedule_events||[]}); + section_errors:ops.section_errors||[],schedule_events:ops.schedule_events||[],schedule_audit:ops.schedule_audit}); if(value.automation?.incident_id)result.automation=fields(value.automation,['incident_id','task_id','issue_code','status','attempts','verification']); if(value.lifecycle?.status)result.lifecycle=fields(value.lifecycle,['request_id','status','task_ids','run_id']); return result; diff --git a/src/dx_productivity/dsh/execution_runs.py b/src/dx_productivity/dsh/execution_runs.py index 261ef00..1be75bf 100644 --- a/src/dx_productivity/dsh/execution_runs.py +++ b/src/dx_productivity/dsh/execution_runs.py @@ -10,12 +10,23 @@ from ..trial_task_center.task_queue import execute_task_queue def execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, resume=None, schedule=None, automatic=False): + prior = RunJournal(root).get(run_id) if resume else None + schedule_id = schedule['schedule_id'] if schedule else (prior or {}).get('schedule_id') + if schedule_id: + with ScheduleStore(root).execution_lease(schedule_id): + return _execute_confirmed_run(service, root, task_ids, report, stop, run_id, + resume=resume, schedule=schedule, automatic=automatic) + return _execute_confirmed_run(service, root, task_ids, report, stop, run_id, resume=resume) + + +def _execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, resume=None, schedule=None, automatic=False): if tasks.fingerprint(service, task_ids) != report['fingerprint']: raise TaskCenterError('assistant_stale', '任务状态已变化,请重新预检后确认。') journal = RunJournal(root) schedules = ScheduleStore(root) initialized = False claimed = False + baseline = {} try: if schedule: current = next((r for r in schedules.evaluate(service) if r['schedule_id'] == schedule['schedule_id']), None) @@ -26,6 +37,7 @@ def execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, resu inspected = journal.inspect(service, resume['run_id']) if not inspected['resume_ready'] or inspected['plan_hashes'] != report['plan_hashes']: raise TaskCenterError('run_blocked', '原执行范围或证据已变化,请先核验。') + baseline = inspected.get('result') or {} journal.resume(run_id) else: journal.begin(run_id, task_ids, report['plan_hashes'], schedule_id=schedule['schedule_id'] if schedule else None) @@ -35,7 +47,8 @@ def execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, resu queue_id=run_id if resume and resume['queue_available'] else None, checkpoint_id=None if resume and resume['queue_available'] else run_id) except Exception as error: - failure = {'status': 'interrupted', 'run_id': run_id, 'queue_id': run_id, + failure = {**{key: baseline[key] for key in ('tasks', 'entries') if key in baseline}, + 'status': 'interrupted', 'run_id': run_id, 'queue_id': run_id, 'code': getattr(error, 'code', 'execution_interrupted'), 'message': '执行未完成,请按原队列证据核验后接续。'} if initialized: journal.finish(run_id, failure) diff --git a/src/dx_productivity/dsh/schedule_audit.py b/src/dx_productivity/dsh/schedule_audit.py new file mode 100644 index 0000000..d457ad7 --- /dev/null +++ b/src/dx_productivity/dsh/schedule_audit.py @@ -0,0 +1,71 @@ +"""Lossless rotation of schedule audit events out of the hot SQLite table.""" +from hashlib import sha256 +import json +import os +from uuid import uuid4 + + +def _write_archive(root, rows): + body = b''.join((json.dumps(row, ensure_ascii=False, sort_keys=True) + '\n').encode('utf8') for row in rows) + digest = sha256(body).hexdigest() + root.mkdir(parents=True, exist_ok=True) + name = f"{rows[0]['sequence']:012d}-{rows[-1]['sequence']:012d}-{digest}.jsonl" + path = root / name + if path.exists(): + if path.read_bytes() != body: + raise OSError('schedule_archive_conflict') + else: + temporary = root / (uuid4().hex + '.tmp') + try: + with temporary.open('xb') as stream: + stream.write(body) + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, path) + finally: + temporary.unlink(missing_ok=True) + if sha256(path.read_bytes()).hexdigest() != digest: + raise OSError('schedule_archive_verification') + return name, digest + + +def archive_events(store, *, keep=5000, batch=1000): + if type(keep) is not int or keep < 1 or type(batch) is not int or not 1 <= batch <= 1000: + raise ValueError('schedule_archive_limit') + with store._connect() as db: + db.execute('BEGIN IMMEDIATE') + cutoff = db.execute('SELECT sequence FROM schedule_events ORDER BY sequence DESC LIMIT 1 OFFSET ?', (keep - 1,)).fetchone() + rows = db.execute('SELECT * FROM schedule_events WHERE sequence < ? ORDER BY sequence LIMIT ?', + (cutoff['sequence'], batch)).fetchall() if cutoff else [] + if not rows: + db.execute('COMMIT') + return {'archived': 0} + values = [{**dict(row), 'payload': json.loads(row['payload'])} for row in rows] + name, digest = _write_archive(store.data_root / 'dsh' / 'schedule-audit', values) + # The archive is durable before deleting. If the DB transaction or + # process fails, retry verifies/reuses the same immutable file. + db.execute('INSERT INTO schedule_event_archives (file, first_sequence, last_sequence, event_count, sha256) VALUES (?, ?, ?, ?, ?)', + (name, rows[0]['sequence'], rows[-1]['sequence'], len(rows), digest)) + db.execute('DELETE FROM schedule_events WHERE sequence BETWEEN ? AND ?', (rows[0]['sequence'], rows[-1]['sequence'])) + db.execute('COMMIT') + return {'archived': len(rows), 'file': name, 'sha256': digest} + + +def verify_archives(root, records, cache): + current = {} + for row in records: + path = root / row['file'] + if path.name != row['file'] or path.is_symlink(): + raise OSError('schedule_archive_invalid') + stat = path.stat() + stamp = (stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns, stat.st_ino, row['sha256']) + if cache.get(row['file']) != stamp: + digest = sha256() + with path.open('rb') as stream: + for chunk in iter(lambda: stream.read(65536), b''): + digest.update(chunk) + if digest.hexdigest() != row['sha256']: + raise OSError('schedule_archive_corrupt') + current[row['file']] = stamp + cache.clear() + cache.update(current) diff --git a/src/dx_productivity/dsh/scheduling.py b/src/dx_productivity/dsh/scheduling.py index 6959ce5..d82d712 100644 --- a/src/dx_productivity/dsh/scheduling.py +++ b/src/dx_productivity/dsh/scheduling.py @@ -50,6 +50,7 @@ class ScheduleStore: self.data_root = Path(data_root) self.data_root.mkdir(parents=True, exist_ok=True) self.path = self.data_root / "dsh-state.sqlite3" + self._archive_stamps = {} with self._connect() as db: db.execute("""CREATE TABLE IF NOT EXISTS schedules ( schedule_id TEXT PRIMARY KEY, task_ids TEXT NOT NULL, plan_hashes TEXT NOT NULL, @@ -60,6 +61,9 @@ class ScheduleStore: db.execute("""CREATE TABLE IF NOT EXISTS schedule_events ( sequence INTEGER PRIMARY KEY AUTOINCREMENT, schedule_id TEXT NOT NULL, at_utc TEXT NOT NULL, event TEXT NOT NULL, run_id TEXT, payload TEXT NOT NULL)""") + db.execute("""CREATE TABLE IF NOT EXISTS schedule_event_archives ( + file TEXT PRIMARY KEY, first_sequence INTEGER NOT NULL, last_sequence INTEGER NOT NULL, + event_count INTEGER NOT NULL, sha256 TEXT NOT NULL)""") @contextmanager def _connect(self): @@ -177,6 +181,25 @@ class ScheduleStore: rows = db.execute('SELECT * FROM schedule_events ORDER BY sequence DESC LIMIT ?', (limit,)).fetchall() return [{**dict(row), 'payload': json.loads(row['payload'])} for row in rows] + def archive_events(self, *, keep=5000, batch=1000): + from .schedule_audit import archive_events + return archive_events(self, keep=keep, batch=batch) + + def audit_status(self, *, keep=5000): + from .schedule_audit import verify_archives + with self._connect() as db: + records = db.execute('SELECT file, sha256 FROM schedule_event_archives').fetchall() + count = db.execute('SELECT COUNT(*) FROM schedule_events').fetchone()[0] + verify_archives(self.data_root / 'dsh' / 'schedule-audit', records, self._archive_stamps) + # Bounded work per refresh. Old evidence is exported, never discarded. + batch = min(keep, 1000) + if count >= keep + batch: + self.archive_events(keep=keep, batch=batch) + with self._connect() as db: + live = db.execute('SELECT COUNT(*) FROM schedule_events').fetchone()[0] + archived = db.execute('SELECT COALESCE(SUM(event_count), 0) FROM schedule_event_archives').fetchone()[0] + return {'status': 'ok', 'live_events': live, 'archived_events': archived, 'retained_limit': keep + batch} + @staticmethod def _event(db, schedule_id, stamp, event, run_id, payload): from .evidence import scrub @@ -202,6 +225,52 @@ class ScheduleStore: db.execute("COMMIT") return self.get(schedule_id) + @contextmanager + def execution_lease(self, schedule_id): + """Hold from before claim until the final receipt, across processes.""" + if not isinstance(schedule_id, str) or not _ID.fullmatch(schedule_id): + raise TaskCenterError('schedule_missing', '排期编号无效。') + from ..trial_task_center.task_queue import _lock_file, _os_lock + with _lock_file(self.data_root / 'dsh' / 'schedule-leases' / schedule_id) as handle: + try: + _os_lock(handle, True) + except OSError as error: + raise TaskCenterError('schedule_busy', '排期仍有活动执行,不能对账收尾。') from error + try: + yield + finally: + _os_lock(handle, False) + + def reconcile_claim(self, service, schedule_id): + """Native-confirmed orphan reconciliation; never dispatch or reset a claim.""" + from ..trial_task_center.task_queue import assert_task_queue_idle, _queue_lease + with self.execution_lease(schedule_id): + assert_task_queue_idle(self.data_root) + with _queue_lease(self.data_root): + if service.pending_batch_resources(): + raise TaskCenterError('schedule_busy', '后台资源尚未释放,请先在任务中心核验和清理。') + with self._connect() as db: + db.execute('BEGIN IMMEDIATE') + row = self._row(db.execute('SELECT * FROM schedules WHERE schedule_id = ?', (schedule_id,)).fetchone()) + if not row or row['status'] != 'claimed': + raise TaskCenterError('schedule_status', '只有已领取的失联排期需要对账。') + run = None + if db.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='run_journal'").fetchone(): + run = db.execute('SELECT * FROM run_journal WHERE run_id = ?', (row['run_id'],)).fetchone() + if run and (run['schedule_id'] != schedule_id or json.loads(run['task_ids']) != row['task_ids'] + or json.loads(run['plan_hashes']) != row['plan_hashes']): + raise TaskCenterError('schedule_run_conflict', '运行记录与排期范围不一致,请保留证据人工核对。') + status = run['status'] if run and run['status'] in {'completed', 'failed'} else 'interrupted' + receipt = json.loads(run['result']) if run and run['result'] else None + payload = {'run_id': row['run_id'], 'reconciled': True, + 'reason': 'run_receipt' if run else 'claim_without_run', 'receipt': receipt} + stamp = _now().isoformat(timespec='seconds') + db.execute('UPDATE schedules SET status = ?, updated_utc = ?, finished_utc = ?, result = ? WHERE schedule_id = ?', + (status, stamp, stamp, json.dumps(payload, ensure_ascii=False), schedule_id)) + self._event(db, schedule_id, stamp, 'result', row['run_id'], {'status': status, **payload}) + db.execute('COMMIT') + return self.get(schedule_id) + def finish(self, schedule_id, status, **values): if status not in {"completed", "failed", "interrupted", "cancelled"}: raise TaskCenterError("schedule_status", "schedule finish status is invalid") diff --git a/src/dx_productivity/trial_task_center/ui/dsh_operations.py b/src/dx_productivity/trial_task_center/ui/dsh_operations.py index 046bce9..1fb8da7 100644 --- a/src/dx_productivity/trial_task_center/ui/dsh_operations.py +++ b/src/dx_productivity/trial_task_center/ui/dsh_operations.py @@ -75,7 +75,7 @@ class DshOperationsController(QObject): self.request_id = None self._observed_execution = None self.results = {} - self.cache = {'runs': [], 'schedules': [], 'schedule_events': [], 'section_errors': [], + self.cache = {'runs': [], 'schedules': [], 'schedule_events': [], 'schedule_audit': {}, 'section_errors': [], 'experiences': [], 'tickets': [], 'decisions': [], 'decision_audit': {'status': 'unknown'}, 'health': {'status': 'degraded', 'checks': []}, 'activity': {}} @@ -202,6 +202,12 @@ class DshOperationsController(QObject): # rehashing current CAD inputs on every timer tick. value = {**row, 'tasks': (row.get('result') or {}).get('tasks', []), 'resume_ready': False, 'remaining_task_ids': [], 'blockers': []} + by_id = {task['task_id']: task for task in value['tasks']} + value['counters'] = {} + for key in ('saved_items', 'failed_items', 'no_match_items'): + counts = [by_id.get(task_id, {}).get(key) for task_id in row['task_ids']] + value['counters'][key] = (sum(counts) if counts and all( + type(count) is int and count >= 0 for count in counts) else None) else: value = self.runs.inspect(service, row['run_id']) if not value.get('remaining_task_ids'): @@ -221,6 +227,7 @@ class DshOperationsController(QObject): 'runs': observe('runs', read_runs, []), 'schedules': observe('schedules', lambda: self.schedules.evaluate(service), []), 'schedule_events': observe('schedule_events', self.schedules.events, []), + 'schedule_audit': observe('schedule_audit', self.schedules.audit_status, {'status': 'unavailable'}), 'experiences': observe('experiences', lambda: self.experiences.refresh()[:20], []), 'tickets': observe('tickets', read_tickets, [])} decisions, audit = self._read_decisions() @@ -307,7 +314,7 @@ class DshOperationsController(QObject): allowed = { 'refresh': set(), 'history': set(), 'health': set(), 'decisions': set(), 'impact': {'task_ids'}, 'experience': {'issue_code'}, 'tickets': set(), 'refresh_ticket': {'incident_id'}, 'schedule_dialog': {'task_ids'}, 'cancel_schedule': {'schedule_id'}, - 'run_schedule': {'schedule_id'}, 'open_incident': {'incident_id'}, + 'run_schedule': {'schedule_id'}, 'reconcile_schedule': {'schedule_id'}, 'open_incident': {'incident_id'}, 'schedule': {'task_ids', 'priority', 'not_before', 'due_at', 'dependencies', 'auto_start', 'idle_only', 'title'}} if op not in allowed or set(spec) - ({'operation'} | allowed[op]): self._failed(key, ValueError('unknown operation fields')); return @@ -356,7 +363,7 @@ class DshOperationsController(QObject): self.window.service.get_task(dependency) return draft, report self._work(prepare, lambda result: self._schedule_ready(key, *result), request_id=key) - elif op in {'cancel_schedule', 'run_schedule'}: + elif op in {'cancel_schedule', 'run_schedule', 'reconcile_schedule'}: def loaded(): row = self.schedules.get(spec.get('schedule_id')) if row is None: @@ -395,17 +402,28 @@ class DshOperationsController(QObject): self.request_id = None QTimer.singleShot(0, lambda: self._dispatch(row, automatic=False, request_id=key)) return - self.dialog = DshLifecycleDialog('取消排期', (row['title'] or row['schedule_id']) + '\n只取消尚未领取的排期,不强制结束正在执行的任务。', self.window) + reconcile = op == 'reconcile_schedule' + self.dialog = DshLifecycleDialog('核对失联排期' if reconcile else '取消排期', + (row['title'] or row['schedule_id']) + ('\n运行编号:' + str(row.get('run_id') or '未建立') + + '\n仅在没有活动执行且后台资源已释放时,按持久回执收尾。未完成的运行保留供人工核验和恢复。不会启动 CAD 或自动重放。' + if reconcile else '\n只取消尚未领取的排期,不强制结束正在执行的任务。'), self.window) dialog = self.dialog def accept(): self.dialog = None; dialog.deleteLater() - self._state('saving', '正在取消已确认排期。') - def done(value): - self.cache['schedules'] = self.schedules.evaluate(self.window.service) - self._respond(key, status='schedule_cancelled', schedule=value) - QTimer.singleShot(0, lambda: self._work(lambda: self.schedules.cancel(row['schedule_id']), done, request_id=key)) + self._state('saving', '正在核对失联排期。' if reconcile else '正在取消已确认排期。') + def done(result): + value, rows, events = result + self.cache['schedules'] = rows + self.cache['schedule_events'] = events + self._respond(key, status='schedule_reconciled' if reconcile else 'schedule_cancelled', schedule=value, + message='排期已按持久回执收尾,原运行记录保留,未启动执行。' if reconcile else '排期已取消。') + def action(): + value = self.schedules.reconcile_claim(self.window.service, row['schedule_id']) if reconcile else ( + self.schedules.cancel(row['schedule_id'])) + return value, self.schedules.evaluate(self.window.service), self.schedules.events() + QTimer.singleShot(0, lambda: self._work(action, done, request_id=key)) def reject(): - self.dialog = None; dialog.deleteLater(); self._respond(key, status='cancelled', message='未取消排期。') + self.dialog = None; dialog.deleteLater(); self._respond(key, status='cancelled', message='未更改排期。') dialog.accepted.connect(accept); dialog.rejected.connect(reject); dialog.open() def cancel(self, value): diff --git a/tests/dsh/test_execution_recovery.py b/tests/dsh/test_execution_recovery.py index c100850..3a5d45a 100644 --- a/tests/dsh/test_execution_recovery.py +++ b/tests/dsh/test_execution_recovery.py @@ -9,6 +9,7 @@ from dx_productivity.dsh.execution_runs import execute_confirmed_run from dx_productivity.dsh.run_journal import RunJournal from dx_productivity.dsh.task_lifecycle import preflight from test_run_journal import project_service +from test_run_journal import checkpoint, evidence def test_second_resume_after_fatal_exit_preserves_verified_progress_and_runs_each_task_once(project_service, monkeypatch): @@ -51,3 +52,28 @@ def test_second_resume_after_fatal_exit_preserves_verified_progress_and_runs_eac assert last['status'] == 'completed' and last['queue_id'] == run_id assert calls == ids assert all(task['saved_items'] == 0 and task['no_match_items'] == 1 for task in last['tasks']) + + +def test_resume_soft_failure_retains_the_last_evidence_baseline(project_service, monkeypatch): + service, _, data, ids, hashes = project_service + journal = RunJournal(data) + run_id = 'e' * 32 + journal.begin(run_id, ids, hashes) + checkpoint(data, run_id, ids, hashes) + prior = {'status': 'paused', 'tasks': [{'task_id': ids[0], 'saved_items': 0, 'failed_items': 0, + 'no_match_items': 0, 'queue_complete': False, 'interrupted': False}], + 'entries': [{'task_id': key, 'state': 'paused' if key == ids[0] else 'pending'} for key in ids]} + journal.finish(run_id, prior) + resume = journal.inspect(service, run_id) + def unavailable(*args, **kwargs): + raise OSError('controlled queue failure before progress') + monkeypatch.setattr('dx_productivity.dsh.execution_runs.execute_task_queue', unavailable) + with pytest.raises(OSError): + execute_confirmed_run(service, data, ids, preflight(service, ids), Event(), run_id, resume=resume) + result = journal.get(run_id)['result'] + assert result['status'] == 'interrupted' + assert result['tasks'] == prior['tasks'] and result['entries'] == prior['entries'] + evidence(service, ids[0]) + inspected = journal.inspect(service, run_id) + assert inspected['diff']['evidence_baseline_available'] + assert 'evidence_changed' in inspected['blockers'] diff --git a/tests/dsh/test_schedule_audit.py b/tests/dsh/test_schedule_audit.py new file mode 100644 index 0000000..6565ad8 --- /dev/null +++ b/tests/dsh/test_schedule_audit.py @@ -0,0 +1,86 @@ +import hashlib +import json +import sqlite3 + +import pytest + +from dx_productivity.dsh.scheduling import ScheduleStore + + +def populate(root, count=6): + store = ScheduleStore(root) + with store._connect() as db: + for index in range(count): + store._event(db, 'a' * 32, '2026-10-31T12:00:00Z', 'result', 'b' * 32, + {'status': 'completed', 'index': index}) + return store + + +def test_archive_bounds_hot_events_without_losing_original_records(tmp_path): + store = populate(tmp_path) + before = store.events() + first = store.archive_events(keep=2, batch=2) + assert first['archived'] == 2 + assert len(store.events()) == 4 + store.archive_events(keep=2, batch=2) + summary = ScheduleStore(tmp_path).audit_status(keep=2) + assert summary['live_events'] == 2 and summary['archived_events'] == 4 + archived = [] + for path in sorted((tmp_path / 'dsh/schedule-audit').glob('*.jsonl')): + raw = path.read_bytes() + assert path.stem.endswith(hashlib.sha256(raw).hexdigest()) + archived.extend(json.loads(line) for line in raw.splitlines()) + assert sorted(archived + store.events(), key=lambda row: row['sequence']) == list(reversed(before)) + assert store.archive_events(keep=2)['archived'] == 0 + + +def test_failed_archive_export_never_deletes_audit_events(tmp_path, monkeypatch): + from dx_productivity.dsh import schedule_audit + store = populate(tmp_path) + before = store.events() + def unavailable(*args): + raise OSError('controlled export failure') + monkeypatch.setattr(schedule_audit, '_write_archive', unavailable) + with pytest.raises(OSError): + store.archive_events(keep=2) + assert store.events() == before + + +def test_database_failure_after_archive_is_safe_and_retryable(tmp_path): + store = populate(tmp_path) + before = store.events() + with sqlite3.connect(store.path) as db: + db.execute("CREATE TRIGGER reject_trim BEFORE DELETE ON schedule_events BEGIN SELECT RAISE(ABORT, 'controlled fault'); END") + with pytest.raises(sqlite3.IntegrityError): + store.archive_events(keep=2) + assert store.events() == before + files = list((tmp_path / 'dsh/schedule-audit').glob('*.jsonl')) + assert len(files) == 1 + raw = files[0].read_bytes() + with sqlite3.connect(store.path) as db: + db.execute('DROP TRIGGER reject_trim') + store.archive_events(keep=2) + assert files[0].read_bytes() == raw + assert store.audit_status(keep=2)['archived_events'] == 4 + + +@pytest.mark.parametrize('damage', ['missing', 'changed']) +def test_missing_or_changed_committed_archive_is_never_reported_healthy(tmp_path, damage): + store = populate(tmp_path) + store.audit_status(keep=2) + archive = next((tmp_path / 'dsh/schedule-audit').glob('*.jsonl')) + if damage == 'missing': + archive.unlink() + else: + archive.write_bytes(b'corrupted evidence\n') + with pytest.raises(OSError): + store.audit_status(keep=2) + + +def test_automatic_rotation_batches_overflow_instead_of_creating_one_file_per_event(tmp_path): + store = populate(tmp_path, count=3) + assert store.audit_status(keep=2)['archived_events'] == 0 + with store._connect() as db: + store._event(db, 'a' * 32, '2026-10-31T12:00:00Z', 'result', None, {'status': 'completed'}) + status = store.audit_status(keep=2) + assert status['live_events'] == 2 and status['archived_events'] == 2 diff --git a/tests/dsh/test_scheduling.py b/tests/dsh/test_scheduling.py index a19f2a7..f72846f 100644 --- a/tests/dsh/test_scheduling.py +++ b/tests/dsh/test_scheduling.py @@ -186,3 +186,98 @@ def test_cancel_is_durable_and_cannot_cancel_an_owned_claim(project_service): schedules.claim(claimed['schedule_id']) with pytest.raises(TaskCenterError): schedules.cancel(claimed['schedule_id']) + + +@pytest.mark.parametrize('run_state', [None, 'running', 'completed', 'paused', 'failed']) +def test_reconcile_orphan_claim_preserves_original_run_and_never_replays(project_service, run_state): + from dx_productivity.dsh.run_journal import RunJournal + service, _, data, ids, hashes = project_service + schedules = ScheduleStore(data) + row = schedules.save(spec(ids, auto_start=True), hashes) + run_id = 'c' * 32 + schedules.claim(row['schedule_id'], run_id=run_id, automatic=True) + journal = RunJournal(data) + if run_state: + journal.begin(run_id, ids, hashes, schedule_id=row['schedule_id']) + if run_state != 'running': + journal.finish(run_id, {'status': run_state, 'tasks': [], 'entries': []}) + before = journal.get(run_id) + reopened = ScheduleStore(data) + result = reopened.reconcile_claim(service, row['schedule_id']) + expected = run_state if run_state in {'completed', 'failed'} else 'interrupted' + assert result['status'] == expected and result['run_id'] == run_id + assert journal.get(run_id) == before + assert result['result']['reconciled'] is True + assert reopened.events()[0]['event'] == 'result' + assert reopened.events()[0]['payload']['reconciled'] is True + assert not reopened.evaluate(service, now=NOW)[0]['dispatchable'] + assert not list(data.rglob('command.tsv')) + + +def test_reconcile_refuses_active_owner_and_pending_resources(project_service, monkeypatch): + service, _, data, ids, hashes = project_service + schedules = ScheduleStore(data) + row = schedules.save(spec(ids), hashes) + schedules.claim(row['schedule_id'], run_id='d' * 32) + with schedules.execution_lease(row['schedule_id']): + with pytest.raises(TaskCenterError, match='schedule_busy'): + ScheduleStore(data).reconcile_claim(service, row['schedule_id']) + monkeypatch.setattr(service, 'pending_batch_resources', lambda: [object()]) + with pytest.raises(TaskCenterError, match='schedule_busy'): + schedules.reconcile_claim(service, row['schedule_id']) + assert schedules.get(row['schedule_id'])['status'] == 'claimed' + assert len(schedules.events()) == 1 + + +def test_reconcile_audit_failure_leaves_claim_unchanged(project_service): + import sqlite3 + service, _, data, ids, hashes = project_service + schedules = ScheduleStore(data) + row = schedules.save(spec(ids), hashes) + schedules.claim(row['schedule_id']) + with sqlite3.connect(schedules.path) as db: + db.execute("CREATE TRIGGER reject_result BEFORE INSERT ON schedule_events BEGIN SELECT RAISE(ABORT, 'controlled fault'); END") + with pytest.raises(sqlite3.IntegrityError): + schedules.reconcile_claim(service, row['schedule_id']) + assert schedules.get(row['schedule_id'])['status'] == 'claimed' + + +def test_hard_process_exit_releases_schedule_lease_for_native_reconciliation(project_service): + import subprocess + import sys + from pathlib import Path + service, _, data, ids, hashes = project_service + schedules = ScheduleStore(data) + row = schedules.save(spec(ids, auto_start=True), hashes) + child = subprocess.run([sys.executable, '-c', + "import os,sys; sys.path.insert(0, 'src'); from dx_productivity.dsh.scheduling import ScheduleStore; " + "s=ScheduleStore(sys.argv[1]); lease=s.execution_lease(sys.argv[2]); lease.__enter__(); " + "s.claim(sys.argv[2],run_id='e'*32,automatic=True); os._exit(19)", str(data), row['schedule_id']], + cwd=Path(__file__).resolve().parents[2], capture_output=True, timeout=20) + assert child.returncode == 19, child.stderr.decode('utf8', 'replace') + assert ScheduleStore(data).get(row['schedule_id'])['status'] == 'claimed' + result = ScheduleStore(data).reconcile_claim(service, row['schedule_id']) + assert result['status'] == 'interrupted' and result['run_id'] == 'e' * 32 + + +def test_active_claim_in_another_process_cannot_be_reconciled(project_service): + import subprocess + import sys + from pathlib import Path + service, _, data, ids, hashes = project_service + schedules = ScheduleStore(data) + row = schedules.save(spec(ids, auto_start=True), hashes) + child = subprocess.Popen([sys.executable, '-c', + "import sys; sys.path.insert(0,'src'); from dx_productivity.dsh.scheduling import ScheduleStore; " + "s=ScheduleStore(sys.argv[1]); lease=s.execution_lease(sys.argv[2]); lease.__enter__(); " + "s.claim(sys.argv[2],run_id='f'*32,automatic=True); print('ready',flush=True); " + "sys.stdin.buffer.read(1); lease.__exit__(None,None,None)", str(data), row['schedule_id']], + cwd=Path(__file__).resolve().parents[2], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + try: + assert child.stdout.readline().strip() == b'ready' + with pytest.raises(TaskCenterError, match='schedule_busy'): + schedules.reconcile_claim(service, row['schedule_id']) + assert schedules.get(row['schedule_id'])['status'] == 'claimed' + finally: + child.communicate(input=b'q', timeout=10) + assert child.returncode == 0 diff --git a/tests/ui/test_dsh_operations.py b/tests/ui/test_dsh_operations.py index 021ad9d..c5810f2 100644 --- a/tests/ui/test_dsh_operations.py +++ b/tests/ui/test_dsh_operations.py @@ -11,6 +11,62 @@ def setup_view(ui, monkeypatch): return ui.window._dsh_view +@pytest.mark.parametrize('missing', [False, True]) +def test_terminal_history_sums_persisted_counts_and_preserves_unknown(ui, monkeypatch, qtbot, missing): + from dx_productivity.dsh.task_lifecycle import preflight + view = setup_view(ui, monkeypatch) + ctl = ui.window._dsh_operations + ids = [task.task_id for task in ui.tasks] + ctl.runs.begin('e' * 32, ids, preflight(ui.service, ids)['plan_hashes']) + tasks = [{'task_id': ids[0], 'saved_items': 2, 'failed_items': 0, 'no_match_items': 1}, + {'task_id': ids[1], 'saved_items': None if missing else 3, 'failed_items': 1, 'no_match_items': 0}] + ctl.runs.finish('e' * 32, {'status': 'failed', 'tasks': tasks}) + ctl.refresh() + qtbot.waitUntil(lambda: ctl.worker is None, timeout=5000) + row = view.operations['runs'][0] + assert row['counters'] == {'saved_items': None if missing else 5, 'failed_items': 1, 'no_match_items': 1} + assert row['tasks'] == tasks + + +def test_orphan_schedule_reconciliation_waits_for_native_confirmation(ui, monkeypatch, qtbot): + from dx_productivity.dsh.task_lifecycle import preflight + from PySide6.QtWidgets import QDialogButtonBox + view = setup_view(ui, monkeypatch) + ctl = ui.window._dsh_operations + ids = [ui.tasks[0].task_id] + row = ctl.schedules.save({'task_ids': ids, 'not_before': '2026-10-30T12:00:00Z'}, preflight(ui.service, ids)['plan_hashes']) + ctl.schedules.claim(row['schedule_id'], run_id='9' * 32) + for key, accept in [('1', False), ('2', True)]: + ctl.request({'request_id': key * 32, 'spec': {'operation': 'reconcile_schedule', 'schedule_id': row['schedule_id']}}) + qtbot.waitUntil(lambda: ctl.dialog is not None, timeout=5000) + assert ctl.schedules.get(row['schedule_id'])['status'] == 'claimed' + button = QDialogButtonBox.StandardButton.Ok if accept else QDialogButtonBox.StandardButton.Cancel + qtbot.mouseClick(ctl.dialog.buttons.button(button), Qt.MouseButton.LeftButton) + qtbot.waitUntil(lambda: len(view.lifecycle_results) == int(key), timeout=5000) + qtbot.waitUntil(lambda: ctl.worker is None, timeout=5000) + assert ctl.schedules.get(row['schedule_id'])['status'] == ('interrupted' if accept else 'claimed') + assert view.lifecycle_results[-1]['status'] == 'schedule_reconciled' + assert view.operations['schedule_events'][0]['payload']['reconciled'] is True + assert not ui.calls + + +def test_missing_schedule_archive_degrades_its_section_without_hiding_history(ui, monkeypatch, qtbot): + view = setup_view(ui, monkeypatch) + ctl = ui.window._dsh_operations + with ctl.schedules._connect() as db: + for _ in range(4): + ctl.schedules._event(db, 'a' * 32, '2026-10-31T12:00:00Z', 'result', None, {'status': 'completed'}) + ctl.schedules.archive_events(keep=2) + next((ui.data / 'dsh/schedule-audit').glob('*.jsonl')).unlink() + ctl.refresh() + qtbot.waitUntil(lambda: ctl.worker is None, timeout=5000) + assert view.operations['schedule_audit']['status'] == 'unavailable' + assert view.operations['section_errors'] == [{'section': 'schedule_audit', 'code': 'section_unavailable'}] + assert view.operations['health']['status'] == 'degraded' + assert len(view.operations['schedule_events']) == 2 + assert isinstance(view.operations['runs'], list) + + def test_live_snapshot_reports_running_and_pause_request_without_claiming_paused(ui, monkeypatch): view = setup_view(ui, monkeypatch) window = ui.window @@ -199,13 +255,14 @@ def test_audit_read_error_does_not_hide_health_or_leak_error_text(ui, monkeypatc assert 'private-test-value' not in json.dumps(view.operations) -@pytest.mark.parametrize('section', ['experiences', 'schedule_events']) +@pytest.mark.parametrize('section', ['experiences', 'schedule_events', 'schedule_audit']) def test_independent_section_failure_keeps_schedules_and_health_visible(ui, monkeypatch, qtbot, section): view = setup_view(ui, monkeypatch) ctl = ui.window._dsh_operations def unavailable(*_args, **_kwargs): raise OSError('Authorization: Bearer private-test-value') - target, method = (ctl.experiences, 'refresh') if section == 'experiences' else (ctl.schedules, 'events') + target, method = (ctl.experiences, 'refresh') if section == 'experiences' else ( + ctl.schedules, 'events' if section == 'schedule_events' else 'audit_status') monkeypatch.setattr(target, method, unavailable) ctl.refresh() qtbot.waitUntil(lambda: ctl.worker is None, timeout=5000) diff --git a/tools/accept_dsh_operations.py b/tools/accept_dsh_operations.py index 3033059..cbbfb19 100644 --- a/tools/accept_dsh_operations.py +++ b/tools/accept_dsh_operations.py @@ -54,7 +54,21 @@ def seed(service, output, data): write(directory / 'snapshot.json', {'fixture': True, 'task_id': ids['Board-A']}) write(directory / 'verification.json', {'queue_complete': True, 'failed_items': 0, 'interrupted': False, 'paused': False, 'saved_items': 0, 'no_match_items': 1}) - manifest = {'tasks': ids, 'sourceHashes': hashes, 'data': str(data)} + from dx_productivity.dsh.scheduling import ScheduleStore + from dx_productivity.trial_task_center.task_queue import _plan_hash + schedules = ScheduleStore(data) + orphan = schedules.save({'task_ids': [ids['Board-C']], 'not_before': '2026-10-30T12:00:00Z'}, + {ids['Board-C']: _plan_hash(service.for_project_task(ids['Board-C']), ids['Board-C'])}) + schedules.claim(orphan['schedule_id'], run_id='f' * 32) + # Force one real bounded archival pass; no original audit event is deleted + # unless its lossless local JSONL has been durably written and verified. + with schedules._connect() as db: + db.execute('BEGIN IMMEDIATE') + for index in range(6000): + schedules._event(db, '0' * 32, '2026-10-30T12:00:00Z', 'result', None, + {'status': 'completed', 'fixture': True, 'index': index}) + db.execute('COMMIT') + manifest = {'tasks': ids, 'sourceHashes': hashes, 'data': str(data), 'orphanSchedule': orphan['schedule_id']} write(output / 'manifest.json', manifest) return manifest @@ -143,6 +157,9 @@ def phase(args): modal.setProperty('acceptanceClicked', True) text = modal.preview.toPlainText() cancel = False + if modal.windowTitle().endswith('核对失联排期'): + state['reconciliationDialogs'] = state.get('reconciliationDialogs', 0) + 1 + cancel = state['reconciliationDialogs'] == 1 if args.phase == 'initial' and modal.windowTitle().endswith('执行所选任务'): state['executionConfirmations'] = state.get('executionConfirmations', 0) + 1 # A safe pause is a user decision. Exercise cancellation @@ -269,10 +286,16 @@ def main(): if args.audit_fault: original = json.loads((output / 'audit-fault.json').read_text(encoding='utf8')) assert hashlib.sha256((data / 'dsh/decisions.jsonl').read_bytes()).hexdigest() == original['sha256'] + from dx_productivity.dsh.scheduling import ScheduleStore + schedules = ScheduleStore(data) + assert schedules.get(json.loads((output / 'manifest.json').read_text(encoding='utf8'))['orphanSchedule'])['status'] == 'interrupted' + archive_status = schedules.audit_status() + assert archive_status['archived_events'] > 0 write(output / 'report.json', {'status': 'passed', 'processes': 2, 'calls': calls, 'realCadStarted': False, 'remoteIssuesCreated': False, 'sourceFixtureHashesUnchanged': True, 'auditFault': args.audit_fault, 'auditFaultPreserved': True if args.audit_fault else None, 'cleanShutdowns': [value['cleanShutdown'] for value in phases], + 'orphanScheduleReconciled': True, 'scheduleAudit': archive_status, 'modelToolCalls': [json.loads(line) for line in audit.read_text(encoding='utf8').splitlines()] if audit.is_file() else [], 'data': str(data)}) print(json.dumps({'status': 'passed', 'output': str(output), 'controlledCalls': len(calls)})) diff --git a/tools/verify_dsh_model_results.mjs b/tools/verify_dsh_model_results.mjs index 4029358..189cf00 100644 --- a/tools/verify_dsh_model_results.mjs +++ b/tools/verify_dsh_model_results.mjs @@ -33,4 +33,8 @@ assert.equal(scheduleSnapshot.operations.schedules[0].requires_confirmation,fals assert.equal(scheduleSnapshot.operations.schedule_events.length,10); assert.equal(scheduleSnapshot.operations.schedule_events[0].payload.authority,'native_future_authorization'); assert.ok(!JSON.stringify(scheduleSnapshot).includes('frozen')); +const archiveSnapshot=modelSnapshot({operations:{schedule_audit:{status:'ok',live_events:5000,archived_events:3, + retained_limit:5000,files:['local-private-path']}}}); +assert.equal(archiveSnapshot.operations.schedule_audit.archived_events,3); +assert.equal(archiveSnapshot.operations.schedule_audit.files,undefined); console.log(JSON.stringify({status:'passed',committedIdsPreserved:true,impactRowsBounded:true,snapshotBounded:true})); diff --git a/tools/verify_dsh_operations_ui.mjs b/tools/verify_dsh_operations_ui.mjs index bf0cb33..b2e3463 100644 --- a/tools/verify_dsh_operations_ui.mjs +++ b/tools/verify_dsh_operations_ui.mjs @@ -26,6 +26,23 @@ const element=id=>`document.querySelector('[data-testid="${id}"]')`; async function click(id){await wait(()=>c.evaluate(`!!${element(id)}&&!${element(id)}.disabled`),id);await c.click(element(id));} async function tab(id){await click('dx-operations-tab-'+id);} async function idle(){await wait(()=>c.evaluate(`![...document.querySelectorAll('button[aria-label="停止生成"]')].some(e=>e.getBoundingClientRect().width>0)`),'generation idle');} +async function nativeScheduleStep(test,label){ + report.scheduleClicks??=[]; + for(let attempt=1;attempt<=3;attempt++){ + await wait(async()=>!(await context()).operations?.busy,'native operations settled'); + await click('dx-schedule-new'); + try{ + await wait(test,label,5000);report.scheduleClicks.push({label,attempt,accepted:true});return; + }catch(error){ + if(!error.message.startsWith('Timed out:'))throw error; + await wait(async()=>!(await context()).operations?.busy,'schedule request settled'); + if(await test()){report.scheduleClicks.push({label,attempt,accepted:true});return;} + const notice=await c.evaluate(`document.querySelector('[data-testid="dx-operations-notice"]')?.textContent||''`); + report.scheduleClicks.push({label,attempt,accepted:false,notice}); + } + } + throw Error('Native schedule clicks were not admitted: '+label); +} async function pauseLiveRun(){ const original=(await context()).operations.live_run; report.pauseClicks=[]; @@ -89,6 +106,20 @@ try{ report.checks.push('corrupt audit remains explicit while native health and independent operations refresh successfully'); } if(phase==='initial'){ + await tab('schedules');await click('dx-schedules-refresh'); + const orphanId=manifest.orphanSchedule; + await click('dx-schedule-reconcile-'+orphanId); + await wait(async()=>(await context()).operations?.activity?.status==='cancelled','orphan reconciliation native cancel'); + assert.equal((await context()).operations.schedules.find(row=>row.schedule_id===orphanId).status,'claimed'); + await click('dx-schedule-reconcile-'+orphanId); + await wait(async()=>(await context()).operations?.schedules?.find(row=>row.schedule_id===orphanId)?.status==='interrupted','orphan reconciliation native confirmation'); + await wait(async()=>(await context()).operations?.schedule_events?.some(row=>row.schedule_id===orphanId&&row.payload?.reconciled),'orphan reconciliation audit visible'); + await click('dx-schedules-refresh'); + await wait(async()=>((await context()).operations?.schedule_audit?.archived_events||0)>0,'lossless archive status'); + await wait(()=>c.evaluate(`document.body.innerText.includes('已归档')&&document.body.innerText.includes('旧记录完整保留')`),'archive status rendered'); + report.scheduleAudit=(await context()).operations.schedule_audit; + await c.screenshot(path.join(output,'orphan-reconciled-and-archive.png')); + report.checks.push('actual native cancel preserves claimed orphan; native confirm reconciles without execution; archive counts visible'); await send('只读检查当前 Board-A 任务的执行影响、已有执行历史和本地异常经验。说明匹配器件数量是否已知,暂时不要执行或修改任务。'); await wait(async()=>(await context()).operations?.impact?.task_ids?.includes(manifest.tasks['Board-A'])||(await context()).operations?.impact?.coverage==='mapping_only','real-model impact response');await idle(); await tab('impact');await click('dx-impact-refresh'); @@ -112,8 +143,21 @@ try{ await wait(()=>c.evaluate(`fetch('/dx/runtime').then(r=>r.json()).then(x=>x.settings.response_timeout_seconds===120&&x.settings.model_context_limit===12000)`),'usage settings persisted'); report.checks.push('actual numeric input and save configure response timeout and context limit'); await select('Board-A'); + const beforeExecute=(await context()).lifecycle?.request_id; await send('现在执行 Board-A 任务,只运行这一个工程,按原生确认的范围处理。结束后告诉我真实保存、失败和未命中数量。'); - await wait(async()=>(await context()).operations?.live_run?.active===true,'live controlled run'); + let clarified=false; + await wait(async()=>{ + const data=await context(); + if(data.operations?.live_run?.active===true)return true; + const generating=await c.evaluate(`[...document.querySelectorAll('button[aria-label="停止生成"]')].some(e=>e.getBoundingClientRect().width>0)`); + if(!clarified&&!generating&&data.lifecycle?.status==='preflight'&&data.lifecycle.request_id!==beforeExecute){ + clarified=true; + // Simulate a human answering the model's optional-baseline question. + // The actual task still has to pass native preflight/confirmation. + await send('继续立即执行 Board-A,仅此一个工程,并在原生窗口中确认。可选探测基线缺失请如实报告;按任务中心实际门禁处理,结束后只报告真实计数。'); + } + return false; + },'live controlled run after natural-language clarification',120000); assert.equal((await context()).operations.health.checks.find(row=>row.name==='execution')?.code,'execution_running'); await pauseLiveRun(); await wait(async()=>{const d=await context();return d.operations?.last_execution?.status==='paused'&&!d.operations?.live_run?.active;},'safe pause receipt'); @@ -140,20 +184,25 @@ try{ } await wait(async()=>(await context()).operations?.last_execution?.status==='completed','restarted original queue completed'); const result=(await context()).operations.last_execution;assert.equal(result.run_id,prior.run_id);assert.equal(result.queue_id,prior.queue_id);assert.equal(result.tasks[0].no_match_items,2); + await tab('running');await click('dx-history-refresh'); + await wait(async()=>(await context()).operations?.runs?.find(row=>row.run_id===prior.run_id)?.counters?.no_match_items===2,'terminal history persisted total'); + assert.equal((await context()).operations.runs.find(row=>row.run_id===prior.run_id).counters.saved_items,0); + report.checks.push('terminal history displays persisted totals instead of unknown'); report.checks.push('second actual application process resumed original frozen queue and skipped completed item'); - await select('Board-C');await tab('schedules');await click('dx-schedule-new'); - await wait(async()=>(await context()).operations?.activity?.status==='cancelled','native schedule cancellation'); - assert.equal((await context()).operations.schedules.length,0); - await click('dx-schedule-new');await wait(async()=>(await context()).operations?.schedules?.length===1,'natively authorized schedule saved'); - await wait(async()=>(await context()).operations?.schedules?.[0]?.status==='completed','automatic due schedule completed',70000); - const schedule=(await context()).operations.schedules[0];assert.equal(schedule.auto_start,true);report.schedule=schedule; + await select('Board-C');await tab('schedules'); + await nativeScheduleStep(async()=>(await context()).operations?.activity?.status==='cancelled','native schedule cancellation'); + assert.equal((await context()).operations.schedules.filter(row=>row.schedule_id!==manifest.orphanSchedule).length,0); + const ownSchedule=async()=>(await context()).operations?.schedules?.find(row=>row.schedule_id!==manifest.orphanSchedule); + await nativeScheduleStep(async()=>!!(await ownSchedule()),'natively authorized schedule saved'); + await wait(async()=>(await ownSchedule())?.status==='completed','automatic due schedule completed',70000); + const schedule=await ownSchedule();assert.equal(schedule.auto_start,true);report.schedule=schedule; await new Promise(r=>setTimeout(r,17000));await click('dx-schedules-refresh'); - await wait(async()=>(await context()).operations?.schedules?.[0]?.status==='completed','schedule remains terminal'); + await wait(async()=>(await ownSchedule())?.status==='completed','schedule remains terminal'); await wait(async()=>{const events=(await context()).operations?.schedule_events||[]; return events.some(row=>row.event==='dispatch')&&events.some(row=>row.event==='result');},'persisted schedule audit events'); const scheduleEvents=(await context()).operations.schedule_events; - assert.equal(scheduleEvents.find(row=>row.event==='dispatch').payload.authority,'native_future_authorization'); - assert.equal(scheduleEvents.find(row=>row.event==='result').payload.receipt.status,'completed'); + assert.equal(scheduleEvents.find(row=>row.event==='dispatch'&&row.schedule_id===schedule.schedule_id).payload.authority,'native_future_authorization'); + assert.equal(scheduleEvents.find(row=>row.event==='result'&&row.schedule_id===schedule.schedule_id).payload.receipt.status,'completed'); await wait(()=>c.evaluate(`document.body.innerText.includes('排期派发记录')&&document.body.innerText.includes('排期结果记录')`),'schedule audit cards rendered'); report.scheduleEvents=scheduleEvents; await c.screenshot(path.join(output,'schedule-audit-events.png'));