test: close packaged stop recovery and real saved handoff workflows

This commit is contained in:
阿白叔 committed 2026-11-18 18:00:22 +08:00
1 parent d9bfc57900
commit b038951cc4
8 files changed
+359 -15

No files matched your search

@@ -147,8 +147,8 @@ input_record = {
- [x] C07:实际包单项重校验,新attempt及generation递增,旧结果/报告不被覆盖。
- [x] C08受控回归:反脚、命名警告、必查未知、停止/资源未知、版本竞争和单项失败后继续的服务/Qt反例。
- [x] C08实际包补充:原生导出失败项先运行,后续正常项仍完成;混合批次的报告、重启和重校验均通过,见[本轮闭环验收](../../testing/2026-11-18-verification-closed-loop.md)。
- [ ] C08实际包停止与资源未知:需要各自独立的受控现场,正常路径不替代。
- [ ] 真实已保存换料回执触发的自动交接实际包闭环;合同/幂等测试已通过,不能冒用独立输入证明。
- [x] C08实际包停止与资源未知:已有各自独立现场,见[剩余闭环执行记录](2026-11-18-verification-remaining-closure.md);三工程停止/继续和自有实例异常退出后资源未知保护分别通过。
- [x] 真实已保存换料回执触发的自动交接实际包闭环:新临时副本真实换料1项,自动交接后校验、报告、重启和重校验通过,校验期间换料增量0;见同一执行记录。
- [ ] 连续默认全量稳定全绿;前轮既有时序波动仍交由原修复任务处理,不改旧断言。
单次只读验收入口为 `tools/verify_independent_verification.py --expect-verdict ...`,明确只覆盖 C01~C05;实际包入口为 `tools/accept_verification_closed_loop.py`,覆盖独立输入 C01~C07,并可用 `--fault-batch` 增加原生失败隔离反例。未测项在JSON里保留not_run。测试失败或标准不符均非零退出;已有换料历史采用执行前基线,不能要求历史总数为0。
@@ -0,0 +1,14 @@
# 剩余四项闭环执行计划
用户确认顺序实施并允许在工具新建的临时副本中执行真实换料。使用 `codex/independent-verification` 工作区,不修改另一修复工作区,不合并/推送/发布。
- [x] 实际包停止、重启不重跑、继续未派发项、明确重校验已停止项。三工程现场:`D:/dx-vfy-stop-three-20261118/acceptance.json`,两项未派发均保持待校验,继续和重校验的报告绑定通过。
- [x] 本工具自有实例异常退出,按PID和创建时间证明后才中断;重启保留资源未知,不派发后续原生导出,仍能新建校验。现场:`D:/dx-vfy-owner-exit-20261118/acceptance.json`。不为闭环伪造退出证明,不终止其他进程。
- [x] 真实换料交接:临时副本 RV05 从4100-CA0000-T7替换至4100-CA0000-T0,RV11保持;真实保存回执自动登记,校验/报告/重启/重校验不新增换料。新现场 `D:/dx-vfy-real-handoff-20261118-v2/acceptance.json` 和其 `verification-loop/acceptance.json` 均通过;替换操作1条且verified,校验阶段增量0,声明属性检查为expected_change,原始样例及库LMC摘要未变。
- [ ] 最终回归:在独立Python环境连续跑一次完整默认suite;XML `D:/dx-vfy-continuous-default-20261118.xml`。失败保留首轮记录,独立复核不能替代连续通过。新增功能引起的缺陷修复并验证;既有执行器问题留给原修复任务。
验收工具新增 `--control-scenario stop|owner-exit`、`--handoff-data`,真实换料入口为 `tools/accept_verification_saved_handoff.py`。后者只接受全新外部输出目录,先原生导出证明固定RV05/RV11前提,使用已有BOM/执行器和实际EXE运行;不通过直接修改SQLite制造回执。
交接场景的before来自不可变历史捕获,不能要求它的源文件在真实替换后仍保留旧字节;`freeze_inputs(..., historical_before=True)`要求冻结预期清单,核验历史副本完整性,以已保存after的源摘要建立校验只读基线。默认独立导入仍要求两个源与导入时摘要相同。
每项完成需:输入名单/摘要和预期在执行前固定;运行及报告身份一致;原始样例/共享库不变;测试副本仅发生一次授权替换;校验阶段新增换料为0;停止/异常状态不能被显示为一致。按[闭环标准](../../testing/verification-closed-loop-standard.md)逐项留passed/failed/not_run。
@@ -1,6 +1,7 @@
import copy
import json
from pathlib import Path
from threading import Event
import pytest
from test_independent_verification_intake import service
@@ -110,5 +111,28 @@ def test_existing_replacement_history_is_allowed_but_new_replacement_is_rejected
operation('before-verification')
task, item, scope, run, report = complete(service, tmp_path, monkeypatch)
assert verify_closed_loop(service, task, scope, run, report, expected_verdicts={item: 'CONSISTENT'})['passed']
with service.repo.store.transaction():
service.repo.connection.execute("UPDATE execution_operations SET generation=1 WHERE operation_key='before-verification'")
assert not verify_closed_loop(service, task, scope, run, report, expected_verdicts={item: 'CONSISTENT'})['passed']
with service.repo.store.transaction():
service.repo.connection.execute("UPDATE execution_operations SET generation=0 WHERE operation_key='before-verification'")
operation('during-verification')
assert not verify_closed_loop(service, task, scope, run, report, expected_verdicts={item: 'CONSISTENT'})['passed']
def test_saved_handoff_freezes_current_source_without_reinventing_historical_before(service, tmp_path):
from tools.verification_closed_loop import freeze_inputs
from test_native_cli_netlist import project_fixture
folder=tmp_path/'live';folder.mkdir();path=project_fixture(folder)
before=service.artifacts.capture(path,stop_event=Event())
(path.parent/'database/icdb.dat').write_bytes(b'saved-after')
after=service.artifacts.capture(path,stop_event=Event())
expected=service.artifacts.put('expectations',{'changes':{}})
from dx_productivity.trial_task_center.verification.contracts import default_plan
task=service.create_task('交接',request_id='handoff')['task_id']
service.publish_inputs(task,({'item_key':'saved','project_key':str(path),'input_version':1,
'before_ref':before,'after_ref':after,'expectation_ref':expected,'check_plan':default_plan()},),submission_id='saved')
with pytest.raises(ValueError):freeze_inputs(service,task,expected_count=1)
scope=freeze_inputs(service,task,expected_count=1,historical_before=True)
assert scope['historical_before'] is True
assert service.artifacts.read(before,'snapshot')['source_hashes']!=scope['source_hashes']
@@ -0,0 +1,30 @@
import pytest
from test_independent_verification_intake import service
from test_independent_verification_runner import imported
from threading import Event
def test_stopped_acceptance_requires_unstarted_members_to_remain_waiting(service, tmp_path):
from tools.verification_control_acceptance import verify_stopped
task, item = imported(service, tmp_path)
attempt = service.repo.create_attempt(item, 1, request_id='attempt')
with service.repo.store.transaction():
service.repo.connection.execute("UPDATE verification_attempts SET state='cancelled',resource_state='released',reason='run_stopped_before_dispatch' WHERE attempt_id=?",(attempt['attempt_id'],))
run = {'members':[{'item_id':item, 'input_version':1, 'attempt_id':attempt['attempt_id']}]}
result = verify_stopped(service, run, unstarted={attempt['attempt_id']})
assert result['passed']
with service.repo.store.transaction():
service.repo.connection.execute("UPDATE verification_attempts SET state='running' WHERE attempt_id=?",(attempt['attempt_id'],))
assert not verify_stopped(service, run, unstarted={attempt['attempt_id']})['passed']
def test_unknown_acceptance_rejects_released_or_automatically_rerun_attempt(service, tmp_path):
from tools.verification_control_acceptance import verify_unknown
task, item = imported(service, tmp_path)
attempt = service.repo.create_attempt(item, 1, request_id='attempt')
service.repo.claim(attempt['attempt_id'], owner_id='lost-owner')
service.recover()
assert verify_unknown(service, attempt['attempt_id'], expected_attempts=1)['passed']
with service.repo.store.transaction():
service.repo.connection.execute("UPDATE verification_attempts SET resource_state='released' WHERE attempt_id=?",(attempt['attempt_id'],))
assert not verify_unknown(service, attempt['attempt_id'], expected_attempts=1)['passed']
+100 -11
View File
@@ -15,6 +15,7 @@ import sys
import time
sys.path.insert(0, str(Path(__file__).resolve().parents[1]/'src'))
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.verification.service import VerificationService
from dx_productivity.trial_task_center.native_netlist import _hash
@@ -28,6 +29,8 @@ def main(argv=None):
parser.add_argument('--expected-items', nargs='+', required=True, help='Exact relative paths, e.g. A/input.prj B/input.prj')
parser.add_argument('--expect-verdict', choices=('CONSISTENT', 'WARNING', 'DIFFERENT'), required=True)
parser.add_argument('--fault-batch', action='store_true', help='Use private copies and prepend one deliberately invalid database fixture')
parser.add_argument('--control-scenario', choices=('stop','owner-exit'), help='Separate C08 scenario; no fault switches in the product')
parser.add_argument('--handoff-data',type=Path,help='Existing disposable data root containing real saved execution receipts; never import a pair')
args = parser.parse_args(argv)
output = args.output.resolve(); exe = args.exe.resolve()
before, after = args.before_root.resolve(), args.after_root.resolve()
@@ -40,11 +43,14 @@ def main(argv=None):
import win32gui
from packaged_window_driver import WindowDriver, window_image
from accept_packaged_ui import wait
data = output/'data'
data = args.handoff_data.resolve(strict=True) if args.handoff_data else output/'data'
if args.handoff_data and (args.fault_batch or args.control_scenario):parser.error('handoff-data is a separate scenario')
report = {'standard': 'verification-closed-loop-v1', 'validation_scope': 'independent-native:C01-C07',
'evidence_kind': 'native-packaged-ui', 'executable': str(exe), 'executable_sha256': _hash(exe),
'expected_items': args.expected_items, 'expected_verdict': args.expect_verdict, 'checks': [],
'not_run': ['C08:packaged-fault-cases', 'actual-successful-replacement-handoff', 'continuous-full-regression']}
if args.handoff_data:report['not_run'].remove('actual-successful-replacement-handoff')
if args.control_scenario:report['not_run'][0]='C08:'+('owner-exit' if args.control_scenario=='stop' else 'stop')
original = {str(p): _hash(p) for root in (before, after) for p in root.rglob('*') if p.is_file()}
failed_name = '00-invalid/input.prj' if args.fault_batch else None
if args.fault_batch:
@@ -132,14 +138,12 @@ def main(argv=None):
report['checks'].extend(validation['checks'])
require(validation['passed'], label+' failed: '+json.dumps(validation['checks'], ensure_ascii=False))
try:
process, driver, main_window = launch()
reduce = driver.find('减少透明度', kind='Button', optional=True)
if reduce: driver.click(reduce)
driver.click(wait(lambda: driver.find(automation_id='verificationNew')))
dialog = wait(lambda: next((w for w in driver.windows() if w.window_text()=='新建校验'), None))
ok = next(b for b in dialog.descendants(control_type='Button') if b.window_text().replace('&', '') in ('OK', '确定'))
driver.click(ok)
def import_pairs_ui(*, create=True):
if create:
driver.click(wait(lambda: driver.find(automation_id='verificationNew')))
dialog = wait(lambda: next((w for w in driver.windows() if w.window_text()=='新建校验'), None))
ok = next(b for b in dialog.descendants(control_type='Button') if b.window_text().replace('&', '') in ('OK', '确定'))
driver.click(ok)
button = wait(lambda: driver.find(automation_id='verificationBatchImport'))
wait(lambda: button.is_enabled()); driver.click(button)
dialog = wait(lambda: next((w for w in driver.windows() if w.window_text()=='批量添加工程对'), None))
@@ -151,15 +155,100 @@ def main(argv=None):
driver.click(button)
wait(lambda: driver.find(f'本批导入完成:已导入 {len(expected_names)} 对,失败 0 对;尚未开始校验。', kind='Text', window=dialog), timeout=120)
driver.click(driver.find('关闭', kind='Button', window=dialog))
try:
process, driver, main_window = launch()
reduce = driver.find('减少透明度', kind='Button', optional=True)
if reduce: driver.click(reduce)
if args.handoff_data:
wait(lambda:len(sql('SELECT item_id FROM verification_items'))==len(args.expected_items),timeout=30)
report['evidence_kind']='native-packaged-real-saved-handoff'
else:
import_pairs_ui()
imported = sql('SELECT * FROM verification_items ORDER BY display_name')
require([r['display_name'] for r in imported]==expected_names, 'Imported names differ from the predeclared scope')
require(not sql('SELECT attempt_id FROM verification_attempts'), 'Import started verification automatically')
task = imported[0]['task_id']
with reader() as service: scope = freeze_inputs(service, task, expected_count=len(expected_names))
with reader() as service: scope = freeze_inputs(service, task, expected_count=len(expected_names),historical_before=bool(args.handoff_data))
(output/'frozen-scope.json').write_text(json.dumps(dict(scope, expected_verdict=args.expect_verdict,
expected_failed_items=[failed_name] if failed_name else []), ensure_ascii=False, indent=2), encoding='utf-8')
driver.click(driver.find('开始全部', kind='Button'))
run_id = wait(lambda: next((r['run_id'] for r in sql('SELECT run_id FROM verification_runs')), None))
if args.control_scenario:
from tools.verification_control_acceptance import verify_stopped, verify_unknown
active = wait(lambda: next((r for r in sql("SELECT * FROM verification_attempts WHERE state='running'")), None), timeout=30)
pending = {r['attempt_id'] for r in sql("SELECT attempt_id FROM verification_attempts WHERE state='queued'")}
require(bool(pending), 'No undispatched member remains; this scenario is inconclusive')
raw_run = sql('SELECT members_json FROM verification_runs WHERE run_id=?', (run_id,))[0]
original_run = {'run_id':run_id,'members':json.loads(raw_run['members_json'])}
if args.control_scenario=='stop':
stop_button = driver.find('停止', kind='Button')
wait(lambda:stop_button.is_enabled(), timeout=10); driver.click(stop_button)
wait(lambda:finished(run_id), timeout=120)
with reader() as service: checked = verify_stopped(service, original_run, unstarted=pending)
require(checked['passed'], str(checked))
report['checks'].append({'check_id':'C08:stop','state':'passed','details':checked})
stopped_snapshot = sql('SELECT attempt_id,state,generation FROM verification_attempts ORDER BY attempt_id')
window_image(main_window.handle).save(output/'stop.png')
close(); process,driver,main_window=launch()
wait(lambda:selected_cell(sorted(args.expected_items)[0]), timeout=30)
time.sleep(2)
require(sql('SELECT attempt_id,state,generation FROM verification_attempts ORDER BY attempt_id')==stopped_snapshot,
'Restart replayed a stopped batch')
old_runs={r['run_id'] for r in sql('SELECT run_id FROM verification_runs')}
driver.click(driver.find('开始全部',kind='Button'))
continuation=wait(lambda:next((r['run_id'] for r in sql('SELECT run_id FROM verification_runs') if r['run_id'] not in old_runs),None),timeout=30)
wait(lambda:finished(continuation),timeout=900)
continued=run_record(continuation)
require({r['item_id'] for r in continued['members']}=={m['item_id'] for m in original_run['members'] if m['attempt_id'] in pending},
'Continue did not run exactly the previously undispatched items')
subset=dict(scope,items=[r for r in scope['items'] if r['item_id'] in {m['item_id'] for m in continued['members']}])
verify_report(subset,continued,export_report(),'continued',selected_only=True)
stopped_ids={r['item_id'] for r in sql("SELECT item_id FROM verification_attempts WHERE state='cancelled' AND reason!='run_stopped_before_dispatch'")}
for item_id in stopped_ids:
name=next(r['display_name'] for r in imported if r['item_id']==item_id)
driver.click(wait(lambda:selected_cell(name),timeout=20))
existing={r['run_id'] for r in sql('SELECT run_id FROM verification_runs')}
button=driver.find('重校验',kind='Button');wait(button.is_enabled,timeout=15);driver.click(button)
new_id=wait(lambda:next((r['run_id'] for r in sql('SELECT run_id FROM verification_runs') if r['run_id'] not in existing),None),timeout=30)
wait(lambda:finished(new_id),timeout=900)
subset=dict(scope,items=[r for r in scope['items'] if r['item_id']==item_id])
verify_report(subset,run_record(new_id),export_report(),'stopped-item-rerun',selected_only=True)
report['checks'].append({'check_id':'C08:continue-and-explicit-rerun','state':'passed'})
else:
import win32api,win32process
owner_path=data/'verification/attempts'/active['attempt_id']/'owner.json'
owner=json.loads(owner_path.read_text(encoding='utf-8'))
require(owner['process']['pid']==process.pid and owner['owner_id']==active['owner_id'], 'Owner does not belong to this test')
require(not (owner_path.parent/'resource-released.json').exists(), 'Too late: resources already released')
handle=win32api.OpenProcess(0x1000|0x100000|1,False,process.pid)
try:
require(str(win32process.GetProcessTimes(handle)['CreationTime'])==owner['process']['creation_time'], 'PID creation identity changed')
require(sql('SELECT state FROM verification_attempts WHERE attempt_id=?',(active['attempt_id'],))[0]['state']=='running','Attempt already finished')
# This Popen handle belongs exclusively to the disposable acceptance instance.
process.terminate();process.wait(30)
finally:handle.Close()
(output/'owner-exit.json').write_text(json.dumps(owner,ensure_ascii=False,indent=2),encoding='utf-8')
attempt_count=len(sql('SELECT attempt_id FROM verification_attempts'))
process,driver,main_window=launch()
wait(lambda:sql('SELECT resource_state FROM verification_attempts WHERE attempt_id=?',(active['attempt_id'],))[0]['resource_state']=='unknown',timeout=30)
with reader() as service: checked=verify_unknown(service,active['attempt_id'],expected_attempts=attempt_count)
require(checked['passed'],str(checked))
# New task creation must remain available while the native executor is blocked.
driver.click(driver.find(automation_id='verificationNew'))
dialog=wait(lambda:next((w for w in driver.windows() if w.window_text()=='新建校验'),None),timeout=15)
ok=next(b for b in dialog.descendants(control_type='Button') if b.window_text().replace('&','') in ('OK','确定'));driver.click(ok)
wait(lambda:len(sql('SELECT task_id FROM verification_tasks'))==2,timeout=15)
import_pairs_ui(create=False)
require(len(sql('SELECT item_id FROM verification_items'))==2*len(args.expected_items), 'Resource protection blocked input registration')
require(len(sql('SELECT attempt_id FROM verification_attempts'))==attempt_count, 'Unknown resources caused an automatic attempt')
require(not any((data/'verification/attempts'/aid).exists() for aid in pending),'Undispatched item launched native export')
window_image(main_window.handle).save(output/'resource-unknown.png')
report['checks'].append({'check_id':'C08:owner-exit-remains-unknown','state':'passed','details':checked})
require(all(_hash(Path(p))==sha for p,sha in original.items()), 'Source inputs changed')
require(sql('SELECT COUNT(*) total FROM execution_operations')[0]['total']==0, 'Replacement operations occurred')
close();report.update(passed=True,validation_scope='C08:'+args.control_scenario)
return 0
wait(lambda: finished(run_id), timeout=900)
run = run_record(run_id)
if failed_name:
@@ -209,7 +298,7 @@ def main(argv=None):
report['checks'].append({'check_id': 'C07:rerun', 'state': 'passed'})
report['rerun_report'] = str(second_report)
require(all(_hash(Path(p))==sha for p, sha in original.items()), 'Input files changed during the loop')
require(sql('SELECT COUNT(*) total FROM execution_operations')[0]['total']==0, 'Replacement operations occurred')
require(sql('SELECT COUNT(*) total FROM execution_operations')[0]['total']==scope['replacement_operations_before'], 'Verification replayed replacement')
close(); report['passed'] = True
except Exception as error:
report.update(passed=False, reason=str(error), error=type(error).__name__)
+138
View File
@@ -0,0 +1,138 @@
"""One real replacement on a NEW disposable copy, then the packaged verification loop."""
import argparse
from contextlib import closing
import json
import os
from pathlib import Path
import re
import shutil
import sqlite3
import subprocess
import sys
ROOT=Path(__file__).resolve().parents[1]
sys.path[:0]=[str(ROOT),str(ROOT/'src'),str(ROOT/'tools')]
from dx_productivity.trial_task_center.native_netlist import capture_project,export_netlist,_hash
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.bom_plan import write_bom_template
from verification_closed_loop import require
def main(argv=None):
parser=argparse.ArgumentParser(description=__doc__)
for name in ('source','library','exe','output'):parser.add_argument('--'+name,type=Path,required=True)
args=parser.parse_args(argv)
source,library,exe=(p.resolve(strict=True) for p in (args.source,args.library,args.exe))
output=args.output.resolve()
require(not output.exists() and not output.is_relative_to(source.parent) and not output.is_relative_to(library.parent), 'Use a new external disposable output directory')
output.mkdir(parents=True)
original={str(p):_hash(p) for p in source.parent.rglob('*') if p.is_file()}
original[str(library)]=_hash(library)
report={'scenario':'actual-saved-replacement-handoff','source':str(source),'library':str(library),
'executable':str(exe),'executable_sha256':_hash(exe), 'expected':{'refdes':'RV05','old':'4100-CA0000-T7','new':'4100-CA0000-T0','keep':'RV11'}}
process=driver=window=None
def rows(query):
with sqlite3.connect(output/'data/task-center.db') as db:
db.row_factory=sqlite3.Row
return [dict(row) for row in db.execute(query)]
try:
project_root=output/'projects'/'sample';shutil.copytree(source.parent,project_root)
project=project_root/source.name
body,count=re.subn(r'(?m)^KEY CentralLibrary "[^"\r\n]*"',lambda _:f'KEY CentralLibrary "{library.as_posix()}"',project.read_text(encoding='utf-8-sig'))
require(count==1,'Expected one explicit central library in the sample')
project.write_text(body,encoding='utf-8')
before=export_netlist(capture_project(project,output/'baseline-capture'),output/'baseline-export')
require(before['status']=='success' and before['complete'],'Baseline native export failed')
components=before['graph']['components']
target=[c for c in components.values() if c['refdes']=='RV05'];keep=[c for c in components.values() if c['refdes']=='RV11']
require(len(target)==len(keep)==1 and target[0]['attributes']['Part Number']=='4100-CA0000-T7'
and keep[0]['attributes']['Part Number']=='4100-CA0000-T7','Sample does not match fixed RV05/RV11 prerequisites')
store=TaskStore(output/'data/task-center.db')
try:
service=TaskCenterService(store,configure_logging(output/'data'),supervised=True)
task,=service.create_project_tasks(output/'projects',selected_paths=(project,))
book=write_bom_template(output/'rv05.xlsx',({'project_path':str(project),'old_part_number':'4100-CA0000-T7',
'new_part_number':'4100-CA0000-T0','refdes':'RV05','enabled':True,'sync_nc':True},))
imported=service.import_bom_drafts(task.task_id,(book,))
require(imported.deferred and imported.failed_rows==0,'Pending BOM was not accepted')
require(not rows('SELECT * FROM execution_operations'),'Preparation unexpectedly executed a replacement')
finally:store.close()
(output/'predeclared.json').write_text(json.dumps(dict(report,original_sha256=original),ensure_ascii=False,indent=2),encoding='utf-8')
import win32gui,win32con
from packaged_window_driver import WindowDriver,window_image
from accept_packaged_ui import wait
env=dict(os.environ)
for key in ('PYTHONPATH','PYTHONHOME','DX_TASK_CENTER_HOME','QT_QPA_PLATFORM'):env.pop(key,None)
process=subprocess.Popen([str(exe),'--data-root',str(output/'data')],cwd=exe.parent,env=env,
stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,creationflags=subprocess.CREATE_NO_WINDOW)
driver=WindowDriver(process.pid,output)
def ready():
try:return driver.main()
except TimeoutError:return None
window=wait(ready,timeout=90)
task_list=wait(lambda:driver.find(automation_id='taskList'),timeout=30)
candidate=wait(lambda:next((c for c in task_list.children() if task.name in c.window_text()),None),timeout=30)
driver.click(candidate)
wait(lambda:source.name in driver.find(automation_id='boundProjectPath').window_text(),timeout=30)
button=wait(lambda:driver.find(automation_id='executeProjectTasks'),timeout=30)
wait(button.is_enabled,timeout=30);driver.click(button)
confirmation=wait(lambda:next((w for w in driver.windows() if w.window_text()=='确认顺序执行本批任务'),None),timeout=30)
yes=next(b for b in confirmation.descendants(control_type='Button') if b.window_text().replace('&','') in ('Yes','是(Y)','是'))
window_image(confirmation.handle).save(output/'execution-confirmation.png');driver.click(yes)
def execution_done():
tasks=rows('SELECT status,error_id FROM tasks')
if any(t['status']=='failed' for t in tasks):raise ValueError('Replacement failed; no automatic replay: '+str(tasks))
return tasks and all(t['status']=='completed' for t in tasks)
wait(execution_done,timeout=1200)
require(rows('SELECT COUNT(*) n FROM execution_operations')[0]['n']==1,'Expected exactly one RV05 replacement operation')
operation=rows('SELECT * FROM execution_operations')[0]
require(operation['state']=='verified','Replacement was not saved and verified')
driver.click(driver.find(automation_id='verification_navigation'))
wait(lambda:len(rows('SELECT item_id FROM verification_items'))==1,timeout=30)
item=rows('SELECT * FROM verification_items')[0]
with closing(TaskStore(output/'data/task-center.db')) as store:
from dx_productivity.trial_task_center.verification.service import VerificationService
verification=VerificationService(store,output/'data')
payload=verification.repo.revision(item['item_id'],1)['payload']
require(payload['input_state']=='ready' and payload['expectation_ref'] is not None,'Real receipt did not deliver frozen before/after/expectations')
window_image(window.handle).save(output/'automatic-handoff.png')
win32gui.PostMessage(window.handle,win32con.WM_CLOSE,0,0);require(process.wait(45)==0,'Replacement window did not close normally')
after=export_netlist(capture_project(project,output/'saved-capture'),output/'saved-export')
require(after['status']=='success' and after['complete'],'Saved readback native export failed')
actual={c['refdes']:c for c in after['graph']['components'].values() if c['refdes'] in ('RV05','RV11')}
require(actual['RV05']['attributes']['Part Number']=='4100-CA0000-T0','RV05 was not replaced')
require(actual['RV11']==keep[0],'Non-target RV11 changed')
# Freeze the saved replacement journal; the verification subprocess must leave it intact.
prior=rows('SELECT * FROM execution_operations')
command=[sys.executable,'-X','utf8',str(ROOT/'tools/accept_verification_closed_loop.py'),
'--exe',str(exe),'--before-root',str(output/'projects'),'--after-root',str(output/'projects'),
'--expected-items',item['display_name'],'--expect-verdict','WARNING','--handoff-data',str(output/'data'),
'--output',str(output/'verification-loop')]
completed=subprocess.run(command,cwd=ROOT,timeout=1200,capture_output=True)
(output/'loop-output.txt').write_bytes(completed.stdout+b'\n'+completed.stderr)
require(completed.returncode==0,'Packaged handoff loop failed; inspect loop-output.txt')
require(rows('SELECT * FROM execution_operations')==prior,'Verification changed the replacement journal')
require(len(rows('SELECT * FROM verification_items'))==1,'Repeated delivery duplicated the project')
report.update(passed=True,item_id=item['item_id'],replacement_operations=1,verification_replacement_delta=0,
rv05_replaced=True,rv11_unchanged=True,loop=str(output/'verification-loop/acceptance.json'))
except Exception as error:
report.update(passed=False,error=type(error).__name__,reason=str(error))
if driver:
for n,w in enumerate(driver.windows()):
try:window_image(w.handle).save(output/f'failure-{n}.png')
except Exception:pass
if process and process.poll() is None and window:
try:
win32gui.PostMessage(window.handle,win32con.WM_CLOSE,0,0);process.wait(45)
except Exception:report['process_left_running']=process.pid
finally:
report['originals_unchanged']=all(_hash(Path(p))==sha for p,sha in original.items())
if not report['originals_unchanged']:report['passed']=False
(output/'acceptance.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8')
print(json.dumps(report,ensure_ascii=False))
return 0 if report.get('passed') else 1
if __name__=='__main__':raise SystemExit(main())
+17 -2
View File
@@ -4,6 +4,7 @@ import json
from pathlib import Path
from dx_productivity.trial_task_center.native_netlist import _hash
from dx_productivity.trial_task_center.verification.contracts import digest
def require(condition, message):
@@ -11,6 +12,12 @@ def require(condition, message):
raise ValueError(message)
def journal_digest(service):
with service.repo.store.transaction():
return digest([dict(row) for row in service.repo.connection.execute(
'SELECT * FROM execution_operations ORDER BY task_id,round_id,operation_key')])
def records(service, task_id):
result, cursor = [], None
while True:
@@ -21,7 +28,7 @@ def records(service, task_id):
return result
def freeze_inputs(service, task_id, *, expected_count):
def freeze_inputs(service, task_id, *, expected_count, historical_before=False):
rows = records(service, task_id)
require(type(expected_count) is int and expected_count>0 and len(rows)==expected_count,
'验收必须事先指定非空、准确的工程数量。')
@@ -29,8 +36,13 @@ def freeze_inputs(service, task_id, *, expected_count):
for row in rows:
require(row['input_state']=='ready', '开始前输入尚未就绪。')
payload = row['payload']
if historical_before:
require(payload['expectation_ref'] is not None, '交接验收需要冻结预期清单。')
for name in ('before_ref', 'after_ref'):
capture = service.artifacts.read(payload[name], 'snapshot')
if historical_before and name=='before_ref':
# Historical before is proven by its immutable capture, not today's live bytes.
continue
for path, sha in capture['source_hashes'].items():
require(path not in sources or sources[path]==sha, '同一源文件出现不同摘要。')
require(_hash(Path(path))==sha, '源文件已偏离导入时的版本。')
@@ -40,7 +52,8 @@ def freeze_inputs(service, task_id, *, expected_count):
'after_ref': payload['after_ref'], 'policy': payload['check_plan'], 'display_name': row['display_name']})
operations = service.repo.connection.execute('SELECT COUNT(*) FROM execution_operations').fetchone()[0]
return {'standard': 'verification-closed-loop-v1', 'task_id': task_id, 'items': items,
'source_hashes': sources, 'replacement_operations_before': operations}
'source_hashes': sources, 'replacement_operations_before': operations,
'replacement_journal_digest':journal_digest(service), 'historical_before':historical_before}
class _ReportHTML(HTMLParser):
@@ -138,6 +151,8 @@ def verify_closed_loop(service, task_id, scope, run, report, *, expected_verdict
count = service.repo.connection.execute('SELECT COUNT(*) FROM execution_operations').fetchone()[0]
# Early v1 standalone fixtures recorded an implicit zero baseline.
require(count==scope.get('replacement_operations_before', 0), '校验期间出现了新的换料操作或历史记录变化。')
if 'replacement_journal_digest' in scope:
require(journal_digest(service)==scope['replacement_journal_digest'], '已有换料回执或执行代次发生变化。')
check('C05:read_only', unchanged)
return {'standard': scope['standard'], 'task_id': task_id, 'run_id': run['run_id'],
'validation_scope': 'single-run:C01-C05', 'not_run': ['C06', 'C07', 'C08'],
+34
View File
@@ -0,0 +1,34 @@
"""Read-only checks for expected stop and resource-unknown protection states."""
from .verification_closed_loop import require
def verify_stopped(service, run, *, unstarted):
errors = []
for member in run['members']:
attempt = service.repo.attempt(member['attempt_id'])
row = service.read_item(member['item_id'])
try:
require(attempt['state'] not in ('queued','running','publishing','stopping','interrupted'), '停止后仍有活动尝试')
require(attempt['resource_state']=='released', '停止后的资源退出未确认')
if member['attempt_id'] in unstarted:
require(attempt['state']=='cancelled' and attempt['reason']=='run_stopped_before_dispatch'
and row['status']=='waiting', '未派发项没有保持待校验')
if attempt['state']=='cancelled' and member['attempt_id'] not in unstarted:
require(row['status']=='stopped', '已开始项取消未显示已停止')
except ValueError as error: errors.append(str(error))
return {'passed':not errors, 'errors':errors, 'unstarted':sorted(unstarted)}
def verify_unknown(service, attempt_id, *, expected_attempts):
from dx_productivity.trial_task_center.verification.runner import can_start_native_export
errors = []
try:
attempt = service.repo.attempt(attempt_id)
row = service.read_item(attempt['item_id'])
require(attempt['state']=='stopping' and attempt['resource_state']=='unknown', '没有保留资源未知状态')
require(row['status'] not in ('consistent','warning','different'), '未知资源被显示成有效结论')
require(not can_start_native_export(service)['allowed'], '未知资源仍允许派发')
count=service.repo.connection.execute('SELECT COUNT(*) FROM verification_attempts').fetchone()[0]
require(count==expected_attempts, '重启后创建了额外尝试')
except ValueError as error: errors.append(str(error))
return {'passed':not errors, 'errors':errors}