feat: export verification evidence and preserve result history
This commit is contained in:
1 parent
b9712ed651
commit
ec677a2864
9 files changed
+234
-3
No files matched your search
@@ -0,0 +1,13 @@
|
||||
# 工程校验
|
||||
|
||||
在第四个“工程校验”页面随时新建任务。选择修改前、修改后两份已保存的 `.prj` 工程添加比较项,不能选择同一文件或共用数据库的两个工程。已有替换任务不影响新建;替换已保存的成功项会自动交接,缺少前后副本的项显示无法校验,不能用当前工程补造历史版本。
|
||||
|
||||
“开始全部”处理当前任务中当时待校验/中断的工程;筛选不会缩小这个范围。“校验所选”和“重校验”明确处理所选工程当前版本。运行期间后到的新项或新版本留待下次开始。校验只读副本,不会重新换料或自动换脚。
|
||||
|
||||
一致表示已覆盖的必查项未发现差异;需关注表示有文字或属性变化需要人工判断;异常表示已证明位号、物理脚号、连接或声明目标等不符合;无法校验表示证据不足。没有固定换料清单时始终显示“未核对换料规则”。执行结束不等于工程一致。
|
||||
|
||||
选择工程,在右侧选择位号查看固定脚号的前后接线图和逐脚事实。红线对应连接变化;纯名称变化以关注提示。图由网表生成,不是原理图截图。原始证据入口会核对摘要;历史版本仅供查看,不改变当前结论。导出报告包含同一份图表、检查范围、输入和尝试摘要,不复制整个工程。
|
||||
|
||||
停止采用安全收尾。未派发项保留待校验,已开始项保留停止记录。重启不会自动重跑;缺少进程退出证明的项保留现场并暂停新的原生导出,不按 PID 猜测或终止其他进程。
|
||||
|
||||
首版未证明引脚级 Value 读取和确切库内部引脚→焊盘映射,页面明确未覆盖。电气类型按原生码展示,不臆造语义。本网表比较不宣称完成 ERC、PCB 或封装库内部正确性验证。普通操作历史清空和运行日志保留不会删除校验快照与证据。
|
||||
@@ -18,6 +18,7 @@ STATES={'verified':'已核验完成','no_match':'未命中','failed':'失败','f
|
||||
'uncertain':'待核验','saved_unverified':'保存待核验','skipped':'已跳过','recorded':'已记录',
|
||||
'running':'执行中','paused':'已暂停','pending':'待执行','restored':'已恢复'}
|
||||
OPERATIONS={'quick_run_executed':'替换执行','quick_run_prepared':'准备执行',
|
||||
'verification_completed':'工程校验',
|
||||
'quick_run_recovered':'核验恢复','quick_run_queue_paused':'暂停执行',
|
||||
'quick_run_retry_prepared':'准备失败项重试','create_project_tasks':'创建工程任务',
|
||||
'create_task':'新建任务','update_task':'编辑任务','delete_task':'归档任务',
|
||||
|
||||
@@ -72,6 +72,9 @@ class VerificationInspector(QWidget):
|
||||
self.versions.addItem(f'输入 v{version}',version)
|
||||
self.versions.setCurrentIndex(self.versions.findData(record['input_version']));self.versions.blockSignals(False)
|
||||
result=((record.get('attempt') or {}).get('result') or {})
|
||||
if record.get('evidence_error'):
|
||||
self.set_evidence(None);self.heading.setText(record['display_name']+' · 证据不可用')
|
||||
self.facts.setPlainText(record['evidence_error']);return
|
||||
self.set_evidence(result.get('evidence'))
|
||||
self.heading.setText(record['display_name']+' · '+{'CONSISTENT':'一致','WARNING':'需关注','DIFFERENT':'异常','INCOMPLETE':'无法完整校验'}.get(result.get('verdict'),'待校验'))
|
||||
self.facts.setPlainText(json.dumps({'范围':result.get('scope',record['scope']),'检查':result.get('checks',[]),
|
||||
|
||||
@@ -43,7 +43,14 @@ def paginate(rows,cursor,limit,binding,maximum):
|
||||
|
||||
|
||||
class VerificationQueries:
|
||||
def __init__(self,repo):self.repo=repo
|
||||
def __init__(self,repo):self.repo=repo;self.validator=None
|
||||
|
||||
def _validate(self,row,attempt):
|
||||
if self.validator and attempt and attempt['state']=='succeeded':
|
||||
try:self.validator(attempt)
|
||||
except (ValueError,OSError,KeyError,TypeError) as error:
|
||||
row.update(status='unavailable',verdict='INCOMPLETE',evidence_error=str(error))
|
||||
return row
|
||||
|
||||
def _rows(self,task_id,control=None):
|
||||
checkpoint(control)
|
||||
@@ -58,7 +65,12 @@ class VerificationQueries:
|
||||
LEFT JOIN verification_attempts a ON a.attempt_id=(SELECT attempt_id FROM verification_attempts
|
||||
WHERE item_id=i.item_id AND input_version=i.current_version ORDER BY generation DESC LIMIT 1)
|
||||
WHERE i.task_id=? ORDER BY i.rowid''',(task_id,)).fetchall()
|
||||
return [project(row) for row in rows]
|
||||
result=[]
|
||||
for row in rows:
|
||||
checkpoint(control);row=project(row)
|
||||
if self.validator and row['attempt_state']=='succeeded':self._validate(row,self.repo.attempt(row['attempt_id']))
|
||||
result.append(row)
|
||||
return result
|
||||
|
||||
def list_tasks(self,*,query='',cursor=None,limit=50,read_control=None):
|
||||
with self.repo.store.transaction():
|
||||
@@ -97,7 +109,7 @@ class VerificationQueries:
|
||||
attempt_state=attempt['state'] if attempt else None,reason=attempt['reason'] if attempt else '',
|
||||
verdict=(attempt['result'] or {}).get('verdict') if attempt else None)
|
||||
history=[dict(r) for r in self.repo.connection.execute('SELECT input_version,generation,attempt_id,state FROM verification_attempts WHERE item_id=? ORDER BY input_version DESC,generation DESC',(item_id,))]
|
||||
return dict(project(row),payload=revision['payload'],attempt=attempt,history=history)
|
||||
return dict(self._validate(project(row),attempt),payload=revision['payload'],attempt=attempt,history=history)
|
||||
|
||||
def read_issues(self,attempt_id,*,kind='',cursor=None,limit=100,read_control=None):
|
||||
checkpoint(read_control)
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
"""HTML and JSON views of the exact immutable evidence shown in the workspace."""
|
||||
from html import escape
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
from ..native_netlist import _hash
|
||||
from ..batch_resources import write_record
|
||||
from .contracts import fail,digest
|
||||
from .evidence import verify_evidence
|
||||
|
||||
|
||||
def validate_result(result,root=None):
|
||||
evidence=result.get('evidence')
|
||||
if evidence:
|
||||
verify_evidence(evidence)
|
||||
for raw in evidence['binding'].get('raw',()):
|
||||
path=Path(raw['path']).resolve()
|
||||
if root is not None and not path.is_relative_to(Path(root).resolve()):fail('证据文件不属于本任务库。')
|
||||
try:
|
||||
if _hash(path)!=raw['sha256']:fail('原始证据已损坏。','verification_evidence')
|
||||
except OSError:fail('原始证据已丢失。','verification_evidence')
|
||||
|
||||
|
||||
def text(value):
|
||||
if isinstance(value,(dict,list,tuple)):value=json.dumps(value,ensure_ascii=False,sort_keys=True)
|
||||
return escape(str(value if value is not None else '未知'))
|
||||
|
||||
|
||||
STYLE='body{font:14px "Segoe UI","Microsoft YaHei",sans-serif;color:#34445b;background:#f5f7fa;margin:24px}main{background:white;padding:24px;border-radius:12px}table{border-collapse:collapse;width:100%;margin:16px 0}td,th{border:1px solid #dae2eb;padding:9px;text-align:left;vertical-align:top}pre{white-space:pre-wrap;overflow-wrap:anywhere}.error{color:#b83d4a}.warning{color:#9c6b1e}svg{max-width:100%;height:auto}'
|
||||
|
||||
|
||||
def diagram(pins):
|
||||
height=max(100,70+len(pins)*90);out=[f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 900 {height}" role="img" aria-label="由网表生成的前后连接对照">']
|
||||
for col,phase,title in ((0,'before','修改前'),(1,'after','修改后')):
|
||||
x=col*450+16;out.append(f'<text x="{x}" y="24" fill="#34445b">{title}</text>')
|
||||
for n,pin in enumerate(pins):
|
||||
y=60+n*90;row=pin[phase];color='#b83d4a' if pin['connection_changed'] else '#9c6b1e' if pin['text_changed'] else '#39817d'
|
||||
out.append(f'<text x="{x}" y="{y}" fill="{color}">脚 {text(pin["endpoint"][2])} · {text(row["logical_name"] if row else None)}</text>')
|
||||
out.append(f'<line x1="{x+4}" y1="{y+22}" x2="{x+30}" y2="{y+22}" stroke="{color}"/>')
|
||||
nets=row['nets'] if row else []
|
||||
label=';'.join(net['name']+' · '+', '.join(e[1]+'.'+e[2] for e in net['endpoints']) for net in nets) or ('明确未连接' if row else '未知')
|
||||
out.append(f'<text x="{x+36}" y="{y+26}" fill="#516078" font-size="11">{text(label)}</text>')
|
||||
return ''.join(out)+'</svg>'
|
||||
|
||||
|
||||
def item_html(result):
|
||||
validate_result(result)
|
||||
evidence=result.get('evidence') or {};pins=evidence.get('pins',[])
|
||||
out=[f'<h1>{text(result.get("display_name","工程校验"))}</h1>',f'<h2>{text(result.get("verdict","未完成"))}</h2>',
|
||||
f'<p>{text(result.get("scope","未核对换料规则"))} · 由网表生成 · 未覆盖:封装库内部映射、引脚级 Value</p>']
|
||||
keys=sorted({tuple(p['endpoint'][:2]) for p in pins})
|
||||
for key in keys:
|
||||
subset=[p for p in pins if tuple(p['endpoint'][:2])==key]
|
||||
out.append(f'<h3>{text(key[1])} · {text(key[0])}</h3>');out.append(diagram(subset))
|
||||
out.append('<table><tr><th>物理脚</th><th>修改前</th><th>修改后</th><th>事实</th></tr>')
|
||||
for pin in subset:
|
||||
out.append(f'<tr><td>{text(pin["endpoint"][2])}</td><td><pre>{text(pin["before"])}</pre></td><td><pre>{text(pin["after"])}</pre></td><td>{"连接变化" if pin["connection_changed"] else "文字变化" if pin["text_changed"] else "未发现变化"}</td></tr>')
|
||||
out.append('</table>')
|
||||
out.append('<h2>判断依据与范围</h2><pre>'+text({key:result.get(key) for key in ('checks','issues','uncovered','attempt_id','input_version','input_digest','policy')})+'</pre>')
|
||||
out.append('<h2>原始证据定位与摘要</h2><pre>'+text(evidence.get('binding',{}))+'</pre>')
|
||||
return ''.join(out)
|
||||
|
||||
|
||||
def render_item_report(result_ref,destination):
|
||||
destination=Path(destination)
|
||||
if destination.exists():fail('报告文件已存在,请换一个名称。')
|
||||
html='<!doctype html><html lang="zh-CN"><meta charset="utf-8"><title>工程校验报告</title><style>'+STYLE+'</style><main>'+item_html(result_ref)+'</main></html>'
|
||||
destination.parent.mkdir(parents=True,exist_ok=True)
|
||||
temporary=destination.with_name(destination.name+'.'+uuid4().hex+'.tmp')
|
||||
try:
|
||||
temporary.write_text(html,encoding='utf-8')
|
||||
# On Windows rename does not overwrite an existing destination.
|
||||
if destination.exists():fail('报告文件已存在。')
|
||||
temporary.rename(destination)
|
||||
finally:temporary.unlink(missing_ok=True)
|
||||
return destination
|
||||
|
||||
|
||||
def export_task(service,task_id,destination,*,request_id):
|
||||
body=[task_id,str(Path(destination).resolve())]
|
||||
with service._intake_lock:
|
||||
with service.repo.store._lock:
|
||||
old=service.repo._request('export',request_id,body)
|
||||
if old is not None:
|
||||
path=Path(old['path'])
|
||||
if not path.is_file() and not path.is_dir():fail('先前导出的报告已丢失,请重新导出。')
|
||||
return path
|
||||
with service.repo.store.transaction():
|
||||
task=service.repo.task(task_id);rows=service.queries._rows(task_id)
|
||||
records=[service.read_item(row['item_id']) for row in rows]
|
||||
for row in records:
|
||||
if row.get('evidence_error'):fail('证据不可用,不能导出为有效报告:'+row['evidence_error'])
|
||||
snapshot=dict(task,items=records)
|
||||
root=Path(destination).resolve();root.mkdir(parents=True,exist_ok=True)
|
||||
output=root/f'verification-{task_id[:12]}-v{task["view_revision"]}-{digest(request_id)[:8]}'
|
||||
if output.exists():fail('报告目录已存在。')
|
||||
staging=root/('.verification-'+uuid4().hex);staging.mkdir()
|
||||
write_record(staging/'task.json',snapshot)
|
||||
content=[f'<h1>{text(task["name"])}</h1><p>视图版本 {task["view_revision"]} · 生成时冻结,待校验/运行中项尚未完成。</p><ul>']
|
||||
for row in records:
|
||||
filename=row['item_id']+f'-v{row["input_version"]}.html'
|
||||
result=((row.get('attempt') or {}).get('result') or {})
|
||||
if result:
|
||||
render_item_report(dict(result,display_name=row['display_name']),staging/filename)
|
||||
content.append(f'<li><a href="{filename}">{text(row["display_name"])}</a> · {text(row["status"])}</li>')
|
||||
else:content.append(f'<li>{text(row["display_name"])} · {text(row["status"])} · 未完成/无法校验</li>')
|
||||
content.append('</ul>')
|
||||
(staging/'index.html').write_text('<!doctype html><html lang="zh-CN"><meta charset="utf-8"><style>'+STYLE+'</style><main>'+''.join(content)+'</main></html>',encoding='utf-8')
|
||||
# Roundtrip before publication; the destination never contains a partial report.
|
||||
json.loads((staging/'task.json').read_text(encoding='utf-8'))
|
||||
staging.rename(output)
|
||||
with service.repo.store.transaction():service.repo._remember('export',request_id,body,{'path':str(output)})
|
||||
return output
|
||||
@@ -19,6 +19,7 @@ class VerificationService:
|
||||
self._intake_lock = RLock()
|
||||
from .queries import VerificationQueries
|
||||
self.queries = VerificationQueries(self.repo)
|
||||
self.queries.validator = self.validate_attempt
|
||||
from .control import VerificationControl
|
||||
self.control = VerificationControl(self)
|
||||
self._recovered=False
|
||||
@@ -47,6 +48,30 @@ class VerificationService:
|
||||
def read_item(self, item_id, **kwargs): return self.queries.read_item(item_id, **kwargs)
|
||||
def read_issues(self, attempt_id, **kwargs): return self.queries.read_issues(attempt_id, **kwargs)
|
||||
|
||||
def export_task(self, task_id, destination, *, request_id):
|
||||
from .report import export_task
|
||||
return export_task(self,task_id,destination,request_id=request_id)
|
||||
|
||||
def validate_attempt(self, attempt):
|
||||
result=attempt.get('result') or {}
|
||||
if not result.get('result_ref'): return
|
||||
stored=self.artifacts.read(result['result_ref'],'result')
|
||||
if stored!={k:v for k,v in result.items() if k!='result_ref'}:fail('结果记录与不可变证据不符。')
|
||||
from .report import validate_result
|
||||
validate_result(stored,self.data_root)
|
||||
payload=self.repo.revision(attempt['item_id'],attempt['input_version'])['payload']
|
||||
for key in ('before_ref','after_ref'):self.artifacts.read(payload[key],'snapshot')
|
||||
|
||||
def open_evidence(self, attempt_id, artifact_id):
|
||||
attempt=self.repo.attempt(attempt_id);self.validate_attempt(attempt)
|
||||
raw=next((r for r in (attempt['result'] or {}).get('evidence',{}).get('binding',{}).get('raw',[]) if r['artifact_id']==artifact_id),None)
|
||||
if raw is None:fail('原始证据标识不存在。')
|
||||
path=Path(raw['path']).resolve()
|
||||
if not path.is_relative_to(self.data_root/'verification'):fail('原始证据越界。')
|
||||
import os
|
||||
os.startfile(path)
|
||||
return path
|
||||
|
||||
def create_task(self, name, *, request_id):
|
||||
return self.repo.create_task(name,request_id=request_id)
|
||||
|
||||
|
||||
@@ -182,4 +182,13 @@ class VerificationRepository:
|
||||
self.connection.execute('UPDATE verification_attempts SET state=?,result_json=?,resource_state=?,updated=? WHERE attempt_id=?',
|
||||
(state,encode(result),'released',now(),attempt_id))
|
||||
self._touch(self.item(attempt['item_id'])['task_id'])
|
||||
from ..history_store import HistoryRepository
|
||||
item=self.item(attempt['item_id']);task=self.task(item['task_id'])
|
||||
HistoryRepository(self.store).append(task_id=task['task_id'],task_name=task['name'],
|
||||
project_path=item['project_key'],operation='verification_completed',
|
||||
state='verified' if result.get('verdict')=='CONSISTENT' else 'failed' if result.get('verdict')=='DIFFERENT' else 'uncertain',
|
||||
summary='工程校验:'+str(result.get('verdict','INCOMPLETE')),
|
||||
details={'attempt_id':attempt_id,'input_version':attempt['input_version'],'generation':generation,
|
||||
'verdict':result.get('verdict'),'scope':result.get('scope')},
|
||||
source_key='verification:'+attempt_id)
|
||||
return True
|
||||
@@ -0,0 +1,5 @@
|
||||
def test_report_action_available_for_empty_task_without_cad(ui,qtbot):
|
||||
task=ui.service.verification.create_task('报告',request_id='report')['task_id']
|
||||
page=ui.window.verification_panel;page.open_task(task)
|
||||
qtbot.waitUntil(lambda:not page.controller.task_query.busy)
|
||||
assert page.export_button.isEnabled() and page.new_button.isEnabled()
|
||||
@@ -0,0 +1,49 @@
|
||||
import copy
|
||||
import json
|
||||
from threading import Event
|
||||
import pytest
|
||||
from test_independent_verification_intake import service
|
||||
from test_independent_verification_runner import imported
|
||||
from test_independent_verification_rules import export,evaluate
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
|
||||
|
||||
def test_html_escapes_and_uses_same_fixed_pin_facts(tmp_path):
|
||||
from dx_productivity.trial_task_center.verification.report import render_item_report
|
||||
from dx_productivity.trial_task_center.verification.evidence import build_evidence
|
||||
a=export();b=copy.deepcopy(a);b['graph']['components']['a']['pins']['loop']['number']='2';b['graph']['components']['a']['pins']['GND']['number']='1'
|
||||
result=evaluate(a,b);result['evidence']=build_evidence(a['graph'],b['graph'],result['issues'],binding={})
|
||||
result['display_name']='<script>alert(1)</script>'
|
||||
path=render_item_report(result,tmp_path/'report.html')
|
||||
html=path.read_text(encoding='utf-8')
|
||||
assert '<script>' not in html and '<script>' in html
|
||||
assert 'R12' in html and 'LOOP' in html and 'GND' in html and 'DIFFERENT' in html
|
||||
with pytest.raises(TaskCenterError):render_item_report(result,path)
|
||||
|
||||
|
||||
def test_task_export_is_immutable_and_incomplete_items_are_explicit(service,tmp_path):
|
||||
task,item=imported(service,tmp_path)
|
||||
output=service.export_task(task,tmp_path/'reports',request_id='export')
|
||||
value=json.loads((output/'task.json').read_text(encoding='utf-8'))
|
||||
assert value['items'][0]['status']=='waiting'
|
||||
assert service.export_task(task,tmp_path/'reports',request_id='export')==output
|
||||
assert (output/'index.html').is_file()
|
||||
|
||||
|
||||
def test_corrupt_evidence_cannot_remain_green_or_export(service,tmp_path,monkeypatch):
|
||||
from test_native_cli_netlist import graph
|
||||
from dx_productivity.trial_task_center import netlist_verification
|
||||
from dx_productivity.trial_task_center.verification.runner import run_attempt
|
||||
task,item=imported(service,tmp_path)
|
||||
def native(capture,output,*,stop_event):
|
||||
output.mkdir(parents=True,exist_ok=True);g=graph(output)
|
||||
return {'status':'success','complete':True,'graph':g,'outputs':{'effective':str(output/'effective.txt')}}
|
||||
monkeypatch.setattr(netlist_verification,'_export_saved_capture',native)
|
||||
attempt=service.repo.create_attempt(item,1,request_id='a');run_attempt(service,attempt['attempt_id'],stop_event=Event())
|
||||
assert service.read_item(item)['status']=='consistent'
|
||||
raw=service.repo.attempt(attempt['attempt_id'])['result']['evidence']['binding']['raw'][0]
|
||||
from pathlib import Path
|
||||
Path(raw['path']).write_text('corrupt')
|
||||
assert service.read_item(item)['status']=='unavailable'
|
||||
assert service.read_task(task)['summary']['consistent']==0
|
||||
with pytest.raises(TaskCenterError):service.export_task(task,tmp_path/'reports',request_id='bad')
|
||||
Reference in new issue
Block a user