fix: address independent verification review findings
Core regression / Python core, intervention UI and release configuration (push) Successful in 12m44s
Core regression / JavaScript syntax (push) Successful in 10s
Core regression / Python core, intervention UI and release configuration (pull_request) Failing after 24m33s
Core regression / JavaScript syntax (pull_request) Successful in 10s

This commit is contained in:
阿白叔 committed 2026-11-19 14:44:52 +08:00
1 parent 7597e98eef
commit b2a84404d8
18 files changed
+514 -97

No files matched your search

+6 -1
View File
@@ -157,7 +157,12 @@ def _finish_execution_run(service, root, task_ids, stop, run_id, result, *, base
try:
verification = getattr(service, 'verification', None)
if verification is not None:
verification.receive_successful_results(receipt, submission_id='run:' + run_id)
from ..trial_task_center.verification.contracts import digest
delivery = verification.receive_successful_results(
receipt, submission_id=f'run:{run_id}:{digest(receipt)}')
if delivery['rejected']:
receipt['reporting_errors'].append({'code': 'verification_delivery_pending',
'rejected': delivery['rejected']})
except Exception as error:
receipt['reporting_errors'].append({'code': 'verification_delivery_pending',
'error': type(error).__name__})
@@ -5,7 +5,7 @@ from PySide6.QtCore import QSignalBlocker
from PySide6.QtGui import QColor,QPainter,QPen
from PySide6.QtWidgets import (QWidget,QLabel,QVBoxLayout,QHBoxLayout,QComboBox,QTableWidget,
QTableWidgetItem,QHeaderView,QTabWidget,QScrollArea,QPlainTextEdit,QPushButton)
from ..verification.evidence import verify_evidence
from ..verification.evidence import PIN_FACT_COLORS,pin_fact,verify_evidence
ATTEMPTS={'queued':'排队中','running':'执行中','publishing':'保存结果中','stopping':'安全收尾中',
'succeeded':'执行完成','failed':'执行失败','cancelled':'已停止','interrupted':'已中断'}
@@ -28,10 +28,10 @@ def pin_text(pin):
class ConnectionDiagram(QWidget):
def __init__(self,parent=None):
super().__init__(parent);self.pins=[];self.setMinimumSize(320,220)
super().__init__(parent);self.pins=[];self.facts=[];self.setMinimumSize(320,220)
def set_pins(self,pins):
self.pins=pins;self.setMinimumHeight(max(220,100+len(pins)*100));self.update()
def set_pins(self,pins,facts):
self.pins=pins;self.facts=facts;self.setMinimumHeight(max(220,100+len(pins)*100));self.update()
def paintEvent(self,event):
painter=QPainter(self);painter.setRenderHint(QPainter.RenderHint.Antialiasing)
@@ -42,9 +42,12 @@ class ConnectionDiagram(QWidget):
painter.setPen(QPen(QColor('#dfe6ef'),1));painter.drawRoundedRect(QRectF(x,40,w-24,self.height()-55),9,9)
for n,row in enumerate(self.pins):
y=64+n*100;pin=row[phase]
color=QColor('#bf3f4a' if row['connection_changed'] else '#b37925' if row['text_changed'] else '#438a89')
label,state=self.facts[n]
color=QColor(PIN_FACT_COLORS[state])
name=pin['logical_name'] if pin else ('不存在' if label.startswith('器件') else '未覆盖')
change=f' · {label}' if state!='equal' else ''
painter.setPen(color);painter.drawText(QRectF(x+12,y,w-46,24),Qt.AlignmentFlag.AlignLeft,
f"脚 {row['endpoint'][2]} {pin['logical_name'] if pin else '未覆盖'}")
f"脚 {row['endpoint'][2]} {name}{change}")
painter.drawLine(int(x+18),int(y+37),int(x+40),int(y+37))
painter.setPen(QColor('#516078'))
font=painter.font();font.setPointSizeF(8.5);painter.setFont(font)
@@ -69,7 +72,7 @@ class VerificationInspector(QWidget):
self.tabs=QTabWidget();layout.addWidget(self.tabs,1)
self.diagram=ConnectionDiagram();scroll=QScrollArea();scroll.setWidgetResizable(True);scroll.setWidget(self.diagram)
self.tabs.addTab(scroll,'前后接线图')
self.pin_table=QTableWidget(0,5);self.pin_table.setHorizontalHeaderLabels(['脚号','前名称','后名称','前连接','后连接'])
self.pin_table=QTableWidget(0,6);self.pin_table.setHorizontalHeaderLabels(['脚号','前名称','后名称','前连接','后连接','变化'])
self.pin_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
self.pin_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.ResizeToContents)
self.tabs.addTab(self.pin_table,'逐脚事实')
@@ -130,10 +133,17 @@ class VerificationInspector(QWidget):
def _component(self):
key=self.components.currentData()
pins=[p for p in (self.evidence or {}).get('pins',[]) if tuple(p['endpoint'][:2])==key]
self.diagram.set_pins(pins);self.pin_table.setRowCount(len(pins))
evidence=self.evidence or {}
pins=[p for p in evidence.get('pins',[]) if tuple(p['endpoint'][:2])==key]
issues={issue['issue_id']:issue for issue in evidence.get('issues',())}
facts=[pin_fact(pin,issues) for pin in pins]
self.diagram.set_pins(pins,facts);self.pin_table.setRowCount(len(pins))
for n,row in enumerate(pins):
l,r=row['before'],row['after']
for col,value in enumerate((row['endpoint'][2],l['logical_name'] if l else '未知',r['logical_name'] if r else '未知',pin_text(l),pin_text(r))):
self.pin_table.setItem(n,col,QTableWidgetItem(value))
label,state=facts[n]
cell=QTableWidgetItem(label)
cell.setForeground(QColor(PIN_FACT_COLORS[state]))
self.pin_table.setItem(n,5,cell)
self.pin_table.resizeRowsToContents()
@@ -22,6 +22,9 @@ class VerificationWorkspace(QWidget):
self.title.setStyleSheet('font-size:20px;font-weight:600;color:#34445b')
self._scroll_to_selection=False;self._view_version=None;self._view_attempt=None;self._selected_attempt=None
self._page_cursor=None
self._task_list_cursor=None
self._next_tasks_cursor=None
self._previous_tasks_cursors=[]
self.new_button=QPushButton('新建校验',objectName='verificationNew');self.import_button=QPushButton('添加工程对')
self.batch_button=QPushButton('批量添加',objectName='verificationBatchImport');self._batch_dialog=None
head.addWidget(self.import_button);head.addWidget(self.batch_button);head.addWidget(self.new_button);layout.addLayout(head)
@@ -29,6 +32,14 @@ class VerificationWorkspace(QWidget):
self.splitter=QSplitter();layout.addWidget(self.splitter,1)
left=QWidget();ll=QVBoxLayout(left);ll.setContentsMargins(0,0,8,0);ll.addWidget(QLabel('校验任务'))
self.tasks=QListWidget();ll.addWidget(self.tasks,1)
task_paging=QHBoxLayout()
self.previous_tasks_button=QPushButton('上一页')
self.next_tasks_button=QPushButton('下一页')
self.previous_tasks_button.setAccessibleName('校验任务上一页')
self.next_tasks_button.setAccessibleName('校验任务下一页')
task_paging.addWidget(self.previous_tasks_button)
task_paging.addWidget(self.next_tasks_button)
ll.addLayout(task_paging)
self.state_filter=QComboBox();self.state_filter.addItem('全部工程','')
for key,value in LABELS.items():self.state_filter.addItem(value,key)
ll.addWidget(self.state_filter);self.splitter.addWidget(left)
@@ -49,6 +60,8 @@ class VerificationWorkspace(QWidget):
self.new_button.clicked.connect(self._new);self.import_button.clicked.connect(self._import)
self.batch_button.clicked.connect(self._batch_import)
self.tasks.currentItemChanged.connect(self._task_selected);self.table.itemSelectionChanged.connect(self._item_selected)
self.previous_tasks_button.clicked.connect(lambda:self._turn_tasks_page(False))
self.next_tasks_button.clicked.connect(lambda:self._turn_tasks_page(True))
self.state_filter.currentIndexChanged.connect(self._filters_changed);self.search.textChanged.connect(self._search_changed)
self.more_button.clicked.connect(lambda:self.refresh_task(append=True));self.start_button.clicked.connect(lambda:self._start(False))
self.selected_button.clicked.connect(lambda:self._start(True));self.stop_button.clicked.connect(self._stop)
@@ -71,6 +84,9 @@ class VerificationWorkspace(QWidget):
self.batch_button.setEnabled(has)
self.rerun_button.setEnabled(item);self.export_button.setEnabled(has)
self.stop_button.setEnabled(bool(self._run_id))
can_page=not self.controller.tasks_query.current_busy
self.previous_tasks_button.setEnabled(can_page and bool(self._previous_tasks_cursors))
self.next_tasks_button.setEnabled(can_page and self._next_tasks_cursor is not None)
self.busy_changed.emit()
def set_active(self,active):
@@ -81,16 +97,42 @@ class VerificationWorkspace(QWidget):
def refresh(self):
if self._closed:return
self.controller.tasks_query.request(lambda control:self.service.list_tasks(read_control=control),self._tasks_received,self._error,cancellable=True)
self._refresh_tasks()
if self.controller.task_id:self.refresh_task()
self._gates()
def _refresh_tasks(self):
cursor=self._task_list_cursor
self.controller.tasks_query.request(
lambda control:self.service.list_tasks(cursor=cursor,read_control=control),
self._tasks_received,self._tasks_failed,cancellable=True)
def _turn_tasks_page(self,forward):
if forward and self._next_tasks_cursor is not None:
self._previous_tasks_cursors.append(self._task_list_cursor)
self._task_list_cursor=self._next_tasks_cursor
elif not forward and self._previous_tasks_cursors:
self._task_list_cursor=self._previous_tasks_cursors.pop()
else:
return
self._refresh_tasks()
self._gates()
def _tasks_failed(self,error):
if self._task_list_cursor is not None and getattr(error,'code',None)=='verification_cursor':
self._task_list_cursor=None
self._previous_tasks_cursors.clear()
self._refresh_tasks()
else:
self._error(error)
def _poll(self):
# Let a slow current read finish; periodic ticks must not keep cancelling it.
queries=(self.controller.tasks_query,self.controller.task_query,self.controller.item_query)
if not self._debounce.isActive() and not any(q.current_busy for q in queries):self.refresh()
def _tasks_received(self,result):
self._next_tasks_cursor=result['cursor']
with QSignalBlocker(self.tasks):
self.tasks.clear()
for row in result['tasks']:
@@ -176,7 +218,13 @@ class VerificationWorkspace(QWidget):
def _new(self):
name,ok=QInputDialog.getText(self,'新建校验','任务名称',text='校验任务')
if ok and name.strip():self.controller.command(lambda:self.service.create_task(name.strip(),request_id=uuid4().hex),lambda row:self.open_task(row['task_id']))
if ok and name.strip():
self.controller.command(lambda:self.service.create_task(name.strip(),request_id=uuid4().hex),self._open_new_task)
def _open_new_task(self,row):
self._task_list_cursor=None
self._previous_tasks_cursors.clear()
self.open_task(row['task_id'])
def _import(self):
task=self.controller.task_id
@@ -61,7 +61,7 @@ def validate_plan(plan):
def validate_input(value):
allowed = {'item_key','project_key','input_version','before_ref','after_ref','expectation_ref',
'check_plan','display_name','unavailable_reason'}
'check_plan','display_name','unavailable_reason','handoff_saved_items'}
required = {'item_key','project_key','input_version','before_ref','after_ref','expectation_ref','check_plan'}
if not isinstance(value,dict) or set(value) - allowed or not required <= set(value):
fail('校验输入字段不完整或包含不支持字段。')
@@ -70,6 +70,9 @@ def validate_input(value):
identifier(result[key])
if type(result['input_version']) is not int or not 1 <= result['input_version'] <= 2**31-1:
fail('输入版本必须为正整数。')
if 'handoff_saved_items' in result:
count=result['handoff_saved_items']
if type(count) is not int or count<1:fail('交接回执的已保存数量无效。')
for key in ('before_ref','after_ref','expectation_ref'):
result[key] = artifact_ref(result[key])
result['check_plan'] = validate_plan(result['check_plan'])
@@ -27,6 +27,9 @@ class VerificationControl:
active=self.repo.connection.execute("SELECT * FROM verification_runs WHERE task_id=? AND state IN ('queued','running','stopping') ORDER BY created LIMIT 1",(task_id,)).fetchone()
if active:
result={'run_id':active['run_id'],'members':json.loads(active['members_json'])}
members={(row['item_id'],row['input_version']) for row in result['members']}
if selection is not None and not all(tuple(value) in members for value in selection):
fail('当前校验正在运行,未包含所选工程或版本。请等本次运行结束后再启动。','verification_run_active')
else:
rows=self.service.queries._rows(task_id)
wanted=set(tuple(v) for v in selection) if selection is not None else None
@@ -34,6 +34,31 @@ def verify_evidence(evidence):
fail('证据包摘要不符。','verification_evidence')
def pin_fact(pin, issues_by_id):
"""Interpret stored issues without changing the historical evidence digest."""
checks={issue['check_id'] for identity in pin['issue_ids']
if (issue:=issues_by_id.get(identity)) and issue['state']=='error'}
labels=[]
if 'components' in checks:
labels.append('器件新增' if pin['before'] is None else '器件删除')
if 'physical_pins' in checks:
labels.append('物理脚变化')
if 'connections' in checks:
labels.append('连接变化')
if 'net_names' in checks:
labels.append('网名变化')
if pin['text_changed']:
labels.append('引脚名称变化')
if labels:
return '、'.join(labels),'error' if checks else 'warning'
if pin['before'] is None or pin['after'] is None:
return '无法确认','unknown'
return '未发现变化','equal'
PIN_FACT_COLORS={'error':'#b83d4a','warning':'#9c6b1e','unknown':'#61758e','equal':'#39817d'}
def connection_view(evidence,issue_id):
verify_evidence(evidence)
issue=next((i for i in evidence['issues'] if i['issue_id']==issue_id),None)
@@ -1,5 +1,6 @@
"""Managed immutable inputs; native tools never receive arbitrary live paths."""
import json
import logging
from pathlib import Path
import shutil
from uuid import uuid4
@@ -8,6 +9,7 @@ from .. import native_netlist
from ..batch_resources import write_record
from ..operation_control import check_cancelled
from ..native_inventory import _project_options
from ..path_access import internal_path
from .contracts import artifact_ref, fail
@@ -52,18 +54,28 @@ class ArtifactStore:
except (OSError,ValueError,KeyError,TypeError) as error:
fail(f'校验证据不可用:{error}', 'verification_evidence')
def capture(self, project, *, stop_event):
def discard(self, identity):
"""Remove a directory allocated by this operation before publication."""
directory=internal_path(self.directory(identity))
try:
shutil.rmtree(directory)
except FileNotFoundError:
pass
except OSError:
logging.getLogger(__name__).warning('Cannot remove unpublished verification artifact %s',identity,exc_info=True)
def capture(self, project, *, stop_event, identity=None):
check_cancelled(stop_event)
identity = uuid4().hex
identity = identity or uuid4().hex
capture = native_netlist.capture_project(Path(project),self.directory(identity)/'capture')
check_cancelled(stop_event)
return self.put('snapshot',capture,identity=identity)
def adopt(self, capture):
def adopt(self, capture, *, identity=None):
root = Path(capture['root']).resolve()
if not root.is_relative_to(self.data_root): fail('交接副本不属于当前任务库。')
native_netlist._check_capture(capture)
identity = uuid4().hex
identity = identity or uuid4().hex
destination = self.directory(identity)/'capture'
destination.mkdir(parents=True)
for relative, sha in capture['capture_hashes'].items():
@@ -84,9 +84,11 @@ class VerificationQueries:
checkpoint(read_control)
row=dict(row)
if query.casefold() in row['name'].casefold():
row['_rows']=self._rows(row['task_id'],read_control);tasks.append(row)
binding=digest([query,[(r['task_id'],r['view_revision']) for r in tasks]])
tasks.append(row)
binding=digest([query,[r['task_id'] for r in tasks]])
page,next_cursor=paginate(tasks,cursor,limit,binding,50)
for row in page:
row['_rows']=self._rows(row['task_id'],read_control)
for row in page:row['summary']=summarize_items(self.validate_rows(row.pop('_rows'),read_control))
return {'tasks':page,'cursor':next_cursor}
@@ -1,13 +1,13 @@
"""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 ..path_access import internal_path
from .contracts import fail,digest
from .evidence import verify_evidence
from .evidence import PIN_FACT_COLORS,pin_fact,verify_evidence
def validate_result(result,root=None):
@@ -30,23 +30,26 @@ def text(value):
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):
def diagram(pins,issues):
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>')
y=60+n*90;row=pin[phase];fact,state=pin_fact(pin,issues);color=PIN_FACT_COLORS[state]
out.append(f'<g><title>{text(fact)}</title>')
name=row['logical_name'] if row else ('不存在' if fact.startswith('器件') else '未知')
out.append(f'<text x="{x}" y="{y}" fill="{color}">脚 {text(pin["endpoint"][2])} · {text(name)}</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>')
label=';'.join(net['name']+' · '+', '.join(e[1]+'.'+e[2] for e in net['endpoints']) for net in nets) or ('明确未连接' if row else name)
out.append(f'<text x="{x+36}" y="{y+26}" fill="#516078" font-size="11">{text(label)}</text></g>')
return ''.join(out)+'</svg>'
def item_html(result):
validate_result(result)
evidence=result.get('evidence') or {};pins=evidence.get('pins',[])
issues={issue['issue_id']:issue for issue in evidence.get('issues',())}
verdict=result.get('verdict','未完成')
label={'CONSISTENT':'一致','WARNING':'需关注','DIFFERENT':'异常','INCOMPLETE':'无法完整校验'}.get(verdict,'未完成')
out=[f'<h1>{text(result.get("display_name","工程校验"))}</h1>',f'<h2>{label} · {text(verdict)}</h2>',
@@ -54,14 +57,15 @@ def item_html(result):
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(f'<h3>{text(key[1])} · {text(key[0])}</h3>');out.append(diagram(subset,issues))
out.append('<table><tr><th>物理脚</th><th>修改前</th><th>修改后</th><th>事实</th></tr>')
for pin in subset:
def description(row):
if row is None:return '不存在/未覆盖'
nets=';'.join(n['name']+' → '+', '.join(e[1]+'.'+e[2] for e in n['endpoints'] if e!=pin['endpoint']) for n in row['nets'])
return '名称:'+row['logical_name']+'\n'+(nets or '明确未连接')
out.append(f'<tr><td>{text(pin["endpoint"][2])}</td><td><pre>{text(description(pin["before"]))}</pre></td><td><pre>{text(description(pin["after"]))}</pre></td><td>{"连接变化" if pin["connection_changed"] else "文字变化" if pin["text_changed"] else "未发现变化"}</td></tr>')
label,_=pin_fact(pin,issues)
out.append(f'<tr><td>{text(pin["endpoint"][2])}</td><td><pre>{text(description(pin["before"]))}</pre></td><td><pre>{text(description(pin["after"]))}</pre></td><td>{text(label)}</td></tr>')
out.append('</table>')
out.append('<h2>判断依据</h2><ul>')
for issue in result.get('issues',[]):
@@ -75,19 +79,20 @@ def item_html(result):
def render_item_report(result_ref,destination):
destination=Path(destination)
if destination.exists():fail('报告文件已存在,请换一个名称。')
target=internal_path(destination)
if target.exists():fail('报告文件已存在,请换一个名称。')
fields={'item-id':result_ref.get('item_id'),'attempt-id':result_ref.get('attempt_id'),
'input-version':result_ref.get('input_version'),'generation':result_ref.get('generation'),
'input-digest':result_ref.get('input_digest'),'evidence-digest':(result_ref.get('evidence') or {}).get('digest')}
binding=' '.join(f'data-{key}="{text(value)}"' for key,value in fields.items())
html='<!doctype html><html lang="zh-CN"><meta charset="utf-8"><title>工程校验报告</title><style>'+STYLE+'</style><main '+binding+'>'+item_html(result_ref)+'</main></html>'
destination.parent.mkdir(parents=True,exist_ok=True)
temporary=destination.with_name(destination.name+'.'+uuid4().hex+'.tmp')
target.parent.mkdir(parents=True,exist_ok=True)
temporary=target.with_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)
if target.exists():fail('报告文件已存在。')
temporary.rename(target)
finally:temporary.unlink(missing_ok=True)
return destination
@@ -99,7 +104,7 @@ def export_task(service,task_id,destination,*,request_id):
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('先前导出的报告已丢失,请重新导出。')
if not internal_path(path).is_dir():fail('先前导出的报告已丢失,请重新导出。')
return path
with service.repo.store.transaction():
task=service.repo.task(task_id);rows=service.queries._rows(task_id)
@@ -108,10 +113,11 @@ def export_task(service,task_id,destination,*,request_id):
for row in records:
service.queries._validate(row,row['attempt'])
if row.get('evidence_error'):fail('证据不可用,不能导出为有效报告:'+row['evidence_error'])
root=Path(destination).resolve();root.mkdir(parents=True,exist_ok=True)
root=Path(destination).resolve();internal_path(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()
target=internal_path(output)
if target.exists():fail('报告目录已存在。')
staging=internal_path(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:
@@ -125,6 +131,6 @@ def export_task(service,task_id,destination,*,request_id):
(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)
staging.rename(target)
with service.repo.store.transaction():service.repo._remember('export',request_id,body,{'path':str(output)})
return output
@@ -74,7 +74,11 @@ def evaluate(before,after,*,expectations,check_plan,pin_metadata=None):
if field:row['field']=field
row['issue_id']=digest(row)[:24];issues.append(row)
states['inputs']='equal'
complete=all(e.get('status')=='success' and e.get('complete') is True and e.get('graph',{}).get('components') for e in (before,after))
complete=all(
e.get('status')=='success' and e.get('complete') is True
and e.get('graph',{}).get('components') and e['graph'].get('nets')
for e in (before,after)
)
left=before.get('graph',{});right=after.get('graph',{})
states['coverage']='equal' if complete else 'unknown'
if not complete:
@@ -1,12 +1,16 @@
"""One interface for standalone verification and successful-result handoff."""
from contextlib import ExitStack
from hashlib import sha256
import json
from pathlib import Path
from threading import RLock
from uuid import uuid4
from ..batch_resources import write_record
from ..native_netlist import _check_capture
from ..path_access import canonical_path, internal_path
from ..errors import TaskCenterError
from ..operation_control import check_cancelled
from .contracts import default_plan, digest, fail, identifier
from .contracts import default_plan, digest, fail, identifier, validate_input
from .intake import ArtifactStore, validate_pair
from .store import VerificationRepository
@@ -123,22 +127,43 @@ class VerificationService:
self.repo.task(task_id)
try: before,after=validate_pair(before,after)
except OSError as error: fail(f'工程文件不可用:{error}')
left=self.artifacts.capture(before,stop_event=stop_event)
right=self.artifacts.capture(after,stop_event=stop_event)
row={'item_key':uuid4().hex,'project_key':digest([str(before),str(after)]),
'display_name':after.stem if display_name is None else display_name,'input_version':1,'before_ref':left,'after_ref':right,
'expectation_ref':None,'check_plan':default_plan()}
check_cancelled(stop_event)
normalized=self._validated_inputs((row,))
with self.repo.store.transaction():
result=self.repo.publish(task_id,tuple(normalized),submission_id='import:'+request_id)
return self.repo._remember('import',request_id,body,result)
project_key=digest([str(before),str(after)])
name=after.stem if display_name is None else display_name
try:
identifier(name or project_key)
except TaskCenterError as error:
result={'accepted':[],'duplicates':[],'stale_ignored':[],
'rejected':[{'index':0,'code':error.code,'reason':error.message}]}
with self.repo.store.transaction():
old=self.repo._request('import',request_id,body)
return old if old is not None else self.repo._remember('import',request_id,body,result)
with ExitStack() as unpublished:
refs={}
for phase,project in (('before',before),('after',after)):
identity=uuid4().hex
unpublished.callback(self.artifacts.discard,identity)
refs[phase]=self.artifacts.capture(project,stop_event=stop_event,identity=identity)
row={'item_key':uuid4().hex,'project_key':project_key,'display_name':name,
'input_version':1,'before_ref':refs['before'],'after_ref':refs['after'],
'expectation_ref':None,'check_plan':default_plan()}
normalized=self._validated_inputs((row,))
with self.repo.store.transaction():
old=self.repo._request('import',request_id,body)
if old is not None:return old
check_cancelled(stop_event)
result=self.repo.publish(task_id,tuple(normalized),submission_id='import:'+request_id)
self.repo._remember('import',request_id,body,result)
if result['accepted']:
unpublished.pop_all()
return result
def receive_successful_results(self, result_ref, *, submission_id):
with self._intake_lock:
with self.repo.store._lock:
completed=self.repo._request('handoff-complete',submission_id,result_ref)
if completed is not None:return completed
old=self.repo._request('handoff',submission_id,result_ref)
if old is not None:return old
if old is not None and not old['rejected']:return old
reports=result_ref.get('netlist_verification') or {}
candidates=[]
for key,report in reports.items():
@@ -149,48 +174,149 @@ class VerificationService:
for task in result_ref.get('tasks',()):
if task.get('state')=='completed' and (task.get('saved_items') or 0)>0 and task['task_id'] not in reports:
candidates.append((task['task_id'],{'execution':{'state':'completed','saved_items':task['saved_items']},
'project_path':task.get('name',task['task_id'])}))
'task_name':task.get('name',task['task_id'])}))
empty={key:[] for key in ('accepted','duplicates','stale_ignored','rejected')}
if not candidates:return empty
with self.repo.store.transaction():
if self.repo._request('handoff-receipt',submission_id,result_ref) is None:
self.repo._remember('handoff-receipt',submission_id,result_ref,True)
run_key=identifier(str(result_ref.get('queue_id') or result_ref.get('run_id') or submission_id))
task=self.create_task('校验任务',request_id='handoff-task:'+run_key)['task_id']
rows=[]
for key,report in candidates:
delivery_key=digest([run_key,key,report])
with self.repo.store._lock:
prior=self.repo._request('handoff-row',delivery_key,report)
if prior is not None:
rows.append(prior)
continue
refs={}; reason=''
result=dict(empty,task_id=task)
for index,(key,report) in enumerate(candidates):
try:
for phase in ('before','after'):
evidence=report.get(phase) or {}
path=Path(evidence.get('export_path','')).resolve()
if not path.is_relative_to(self.data_root) or not path.is_file(): fail('缺少可信前后副本。')
from ..native_netlist import _hash
if _hash(path)!=evidence.get('export_sha256'):fail('交接导出摘要不符。')
exported=json.loads(path.read_text(encoding='utf-8'))
refs[phase]=self.artifacts.adopt(exported['capture'])
except (ValueError,OSError,KeyError,TypeError) as error: reason=str(error)
expected=None
if not reason and 'expected_changes' in report:
expected=self.artifacts.put('expectations',{'changes':report['expected_changes'],
'symbols':report.get('expected_symbols',{}),'execution':report.get('execution',{})})
plan=default_plan()
if expected:plan['required_checks'].append('declared_attributes')
row={'item_key':str(key),'project_key':str(report.get('project_path') or key),
'display_name':Path(str(report.get('project_path') or key)).stem,'input_version':1,
'before_ref':refs.get('before'),'after_ref':refs.get('after'),
'expectation_ref':expected,'check_plan':plan,'unavailable_reason':reason}
with self.repo.store.transaction():
self.repo._remember('handoff-row',delivery_key,report,row)
rows.append(row)
normalized=self._validated_inputs(rows)
delivery_key=digest([run_key,key,report])
status,reference=self._deliver_project(task,str(key),report,delivery_key)
except (ValueError,OSError,KeyError,TypeError) as error:
result['rejected'].append({'index':index,'code':getattr(error,'code','verification_evidence'),
'reason':str(error)})
else:
result[status].append(reference)
if result['rejected']:
return result
with self.repo.store.transaction():
result=self.repo.publish(task,tuple(normalized),submission_id='handoff:'+submission_id)
result['task_id']=task
return self.repo._remember('handoff',submission_id,result_ref,result)
completed=self.repo._request('handoff-complete',submission_id,result_ref)
return completed if completed is not None else self.repo._remember(
'handoff-complete',submission_id,result_ref,result)
def _deliver_project(self, task, key, report, delivery_key):
for _ in range(3):
with self.repo.store._lock:
known=self.repo._request('handoff-input',delivery_key,report)
if known is not None:
return 'duplicates',known
current=self.repo.current_input(task,key)
legacy=self.repo._request('handoff-row',delivery_key,report)
if current and legacy:
first=self.repo.revision(current['item_id'],1)
if first['payload_digest']==validate_input(legacy)['payload_digest']:
return 'duplicates',{'item_id':first['item_id'],'input_version':1}
with ExitStack() as unpublished:
row=self._prepare_handoff_input(key,report,current,unpublished)
with self.repo.store.transaction():
known=self.repo._request('handoff-input',delivery_key,report)
if known is not None:
return 'duplicates',known
if self.repo.current_input(task,key)!=current:
continue
if row is None:
reference={field:current[field] for field in ('item_id','input_version')}
return 'stale_ignored',reference
if current and row['input_version']==current['input_version']:
status='duplicates'
reference={field:current[field] for field in ('item_id','input_version')}
else:
if current and row['project_key']!=current['payload']['project_key']:
self.repo.connection.execute(
'UPDATE verification_items SET project_key=? WHERE item_id=? AND before_id IS NULL',
(row['project_key'],current['item_id']))
published=self.repo.publish(task,(row,),submission_id='handoff-input:'+delivery_key)
if published['rejected']:
rejection=published['rejected'][0]
fail(rejection['reason'],rejection['code'])
status='accepted'
reference=published['accepted'][0]
self.repo._remember('handoff-input',delivery_key,report,reference)
if status=='accepted':
unpublished.pop_all()
return status,reference
fail('交接项正在更新,请稍后重试。','verification_conflict')
def _prepare_handoff_input(self, key, report, current, unpublished):
previous=current['payload'] if current else {}
project=str(report.get('project_path') or previous.get('project_key') or key)
saved_items=report['execution']['saved_items']
project_changed=bool(current and previous['project_key']!=project)
expected=None
previous_expected=None
if previous.get('expectation_ref'):
previous_expected=self.artifacts.read(previous['expectation_ref'],'expectations')
previous_count=previous.get('handoff_saved_items') or (
(previous_expected or {}).get('execution',{}).get('saved_items') or 0)
if saved_items<previous_count:
return None
captures={}
reason=''
for phase in ('before','after'):
try:
captures[phase]=self._handoff_capture(report.get(phase) or {})
except (ValueError,OSError,KeyError,TypeError) as error:
reason=reason or str(error)
if current and previous['input_state']=='ready' and reason and saved_items<=previous_count:
return None
if project_changed and (previous.get('before_ref') or not captures.get('before')):
fail('交接工程身份变化,请新增比较项。','verification_conflict')
refs={}
for phase in ('before','after'):
field=phase+'_ref'
ref=previous.get(field)
capture=captures.get(phase)
if capture and ref:
original=self.artifacts.read(ref,'snapshot')
if (capture['project'],capture['capture_hashes'])!=(original['project'],original['capture_hashes']):
if phase=='before':
fail('交接原始基线变化,请新增比较项。','verification_conflict')
ref=None
if capture and not ref:
identity=uuid4().hex
unpublished.callback(self.artifacts.discard,identity)
ref=self.artifacts.adopt(capture,identity=identity)
refs[field]=ref if capture or phase=='before' else None
if not reason and 'expected_changes' in report:
value={'changes':report['expected_changes'],'symbols':report.get('expected_symbols',{}),
'execution':report['execution']}
expected=previous.get('expectation_ref') if value==previous_expected else None
if expected is None:
identity=uuid4().hex
unpublished.callback(self.artifacts.discard,identity)
expected=self.artifacts.put('expectations',value,identity=identity)
plan=default_plan()
if expected:plan['required_checks'].append('declared_attributes')
name=previous.get('display_name') or report.get('task_name') or Path(project).stem
row=dict(refs,item_key=key,project_key=project,display_name=name,
expectation_ref=expected,check_plan=plan,unavailable_reason=reason,
handoff_saved_items=saved_items)
version=previous.get('input_version',0)
if saved_items>previous_count or any(previous.get(field)!=value for field,value in row.items()
if field!='handoff_saved_items'):
version+=1
row['input_version']=version
return row
def _handoff_capture(self, evidence):
path=canonical_path(evidence.get('export_path',''))
if not path.is_relative_to(self.data_root) or not internal_path(path).is_file():
fail('缺少可信前后副本。')
content=internal_path(path).read_bytes()
if sha256(content).hexdigest()!=evidence.get('export_sha256'):
fail('交接导出摘要不符。')
capture=json.loads(content)['capture']
if not canonical_path(capture['root']).is_relative_to(self.data_root):
fail('交接副本不属于当前任务库。')
_check_capture(capture)
return capture
def reconcile_deliveries(self, *, limit=100):
result={'accepted':0,'errors':[]}
@@ -202,6 +328,8 @@ class VerificationService:
value.setdefault('run_id',path.stem)
record=self.receive_successful_results(value,submission_id='checkpoint:'+digest(value))
result['accepted']+=len(record['accepted'])
for rejection in record['rejected']:
result['errors'].append({'record':path.name,'reason':rejection['reason']})
except (ValueError,OSError,KeyError,TypeError) as error:
result['errors'].append({'record':path.name,'reason':str(error)})
return result
@@ -83,6 +83,13 @@ class VerificationRepository:
def task(self, task_id): return self._one('verification_tasks','task_id',task_id)
def item(self, item_id): return self._one('verification_items','item_id',item_id)
def current_input(self,task_id,item_key):
with self.store._lock:
item=self.connection.execute(
'SELECT item_id,current_version FROM verification_items WHERE task_id=? AND item_key=?',
(task_id,item_key)).fetchone()
return self.revision(*item) if item else None
def revision(self, item_id, version):
with self.store._lock:
row = self.connection.execute('SELECT * FROM verification_input_revisions WHERE item_id=? AND input_version=?',
+20 -8
View File
@@ -192,10 +192,11 @@ def test_legacy_rule_retry_cannot_create_a_replacement_before_baseline(rule_run)
assert receipt['execution_status'] == 'completed' and receipt['acceptance']['status'] == 'unavailable'
def test_retry_receipt_refresh_preserves_other_task_without_dispatch(tmp_path, monkeypatch):
def test_retry_receipt_refresh_preserves_other_task_without_dispatch(tmp_path, monkeypatch, request):
from types import SimpleNamespace as NS
from dx_productivity.dsh.execution_runs import execute_incident_retry
from dx_productivity.dsh.execution_runs import _finish_execution_run, execute_incident_retry
from dx_productivity.trial_task_center import netlist_verification, task_queue
from dx_productivity.trial_task_center.verification.service import VerificationService
selected, other, run_id = 'a' * 32, 'b' * 32, 'c' * 32
hashes = {selected: 'd' * 64, other: 'e' * 64}
monkeypatch.setattr(task_queue, '_plan_hash', lambda child, key: hashes[key])
@@ -206,22 +207,32 @@ def test_retry_receipt_refresh_preserves_other_task_without_dispatch(tmp_path, m
def execute(key, **options):
dispatch.append(key)
return NS(paused=False)
service = NS(for_project_task=lambda key: service, task_context=context, execute_quick_run_queue=execute)
store = TaskStore(tmp_path / 'tasks.db')
request.addfinalizer(store.close)
verification_service = VerificationService(store, tmp_path)
service = NS(for_project_task=lambda key: service, task_context=context, execute_quick_run_queue=execute,
verification=verification_service)
class Checks:
def __init__(self, *args): self.tasks = {}
def __enter__(self): return self
def __exit__(self, *args): pass
def before_task(self, child, key, *, existing_only): assert existing_only
def after_task(self, key, **options): assert key == selected
def finish(self): return {selected: {'status': 'verified', 'verified': True, 'report_path': 'new.json'}}
def finish(self):
return {selected: {'status': 'verified', 'verified': True, 'report_path': 'new.json',
'execution': {'state': 'completed', 'saved_items': 1}}}
monkeypatch.setattr(netlist_verification, 'NetlistVerification', Checks)
journal = RunJournal(tmp_path)
journal.begin(run_id, [selected, other], hashes)
old_other = {'task_id': other, 'state': 'completed', 'message': 'original saved result'}
old_report = {'status': 'verified', 'verified': True, 'report_path': 'original.json'}
journal.finish(run_id, {'status': 'failed', 'entries': [
{'task_id': selected, 'state': 'failed', 'message': 'safe failure'}, old_other],
'netlist_verification': {other: old_report}})
old_report = {'status': 'verified', 'verified': True, 'report_path': 'original.json',
'execution': {'state': 'completed', 'saved_items': 1}}
initial = task_queue.TaskQueueResult(run_id, (
task_queue.TaskQueueEntry(selected, 'failed', 'safe failure'),
task_queue.TaskQueueEntry(**old_other)), False, netlist_verification={other: old_report})
_finish_execution_run(service, tmp_path, [selected, other], Event(), run_id, initial, baseline={})
verification_task = verification_service.list_tasks()['tasks'][0]['task_id']
assert verification_service.read_task(verification_task)['summary']['total'] == 1
checkpoint = tmp_path / 'task-queues' / (run_id + '.json')
checkpoint.parent.mkdir()
checkpoint.write_text(json.dumps({'version': 1, 'phase': 'finished', 'task_ids': [selected, other],
@@ -234,6 +245,7 @@ def test_retry_receipt_refresh_preserves_other_task_without_dispatch(tmp_path, m
assert next(row for row in receipt['entries'] if row['task_id'] == other) == old_other
assert receipt['netlist_verification'][other] == old_report
assert json.loads(checkpoint.read_text())['entries'][other] == {'state': 'completed', 'message': 'original saved result'}
assert {row['item_key'] for row in verification_service.read_task(verification_task)['items']} == {selected, other}
@pytest.mark.parametrize('scheduled', [False, True])
+17
View File
@@ -62,3 +62,20 @@ def test_engineering_pages_remain_bounded_and_keep_the_current_page(ui,qtbot):
page.search.setText('Board000')
qtbot.waitUntil(lambda:page.table.rowCount()==1)
assert page.table.item(0,0).text()=='Board000'
def test_older_verification_task_can_be_opened_after_paging(ui,qtbot):
page=ui.window.verification_panel
tasks=[page.service.create_task(f'任务 {n}',request_id=f'page-{n}')['task_id'] for n in range(51)]
page.open_task(tasks[-1])
qtbot.waitUntil(lambda:page.tasks.count()==50 and not page.controller.tasks_query.busy)
page.next_tasks_button.click()
qtbot.waitUntil(lambda:page.tasks.count()==1)
assert page.tasks.item(0).data(Qt.ItemDataRole.UserRole)==tasks[0]
page.tasks.setCurrentRow(0)
qtbot.waitUntil(lambda:page.controller.task_id==tasks[0] and not page.controller.tasks_query.busy)
page.refresh()
qtbot.waitUntil(lambda:not page.controller.tasks_query.busy)
assert page.tasks.currentItem().data(Qt.ItemDataRole.UserRole)==tasks[0]
page.previous_tasks_button.click()
qtbot.waitUntil(lambda:page.tasks.count()==50)
@@ -108,3 +108,81 @@ def test_import_evidence_validation_does_not_hold_store_lock(service,tmp_path,mo
try:assert created.wait(.5)
finally:release.set();worker.join(5);creator.join(5)
assert not errors
@pytest.mark.parametrize('failure',['cancel','invalid_name','second_capture'])
def test_unsuccessful_import_does_not_leave_unreferenced_captures(service,tmp_path,monkeypatch,failure):
folders=[tmp_path/phase for phase in ('before','after')]
for folder in folders:
folder.mkdir()
before,after=map(project_fixture,folders)
task=service.create_task('导入',request_id='task')['task_id']
stop=Event()
from dx_productivity.trial_task_center import native_netlist
capture=native_netlist.capture_project
def interrupt(project,destination):
result=capture(project,destination)
if failure=='cancel':
stop.set()
if failure=='second_capture' and project==after:
raise OSError('after capture failed before publication')
return result
monkeypatch.setattr(native_netlist,'capture_project',interrupt)
if failure=='invalid_name':
result=service.import_pair(task,before,after,request_id='pair',stop_event=stop,display_name='x'*257)
assert result['rejected'] and not result['accepted']
else:
with pytest.raises(TaskCenterError if failure=='cancel' else OSError):
service.import_pair(task,before,after,request_id='pair',stop_event=stop)
assert service.read_task(task)['items']==[]
assert not list(service.artifacts.root.glob('*'))
@pytest.mark.parametrize('initial',['ready','missing_evidence','fallback'])
def test_handoff_updates_same_project_and_never_replays_an_old_notification(service,tmp_path,initial):
from dx_productivity.trial_task_center.native_netlist import capture_project, _hash
evidence={}
for phase in ('before','after','retry'):
source=tmp_path/phase
source.mkdir()
project=project_fixture(source)
if phase=='retry':
(project.parent/'database/icdb.dat').write_bytes(b'after retry')
capture=capture_project(project,service.data_root/phase/'capture')
path=service.data_root/phase/'export.json'
path.write_text(json.dumps({'capture':capture}),encoding='utf-8')
evidence[phase]={'export_path':str(path),'export_sha256':_hash(path)}
report={'project_path':'board.prj','execution':{'state':'completed','saved_items':1}}
if initial=='ready':
report.update(before=evidence['before'],after=evidence['after'],expected_changes={})
first_receipt={'run_id':'run','netlist_verification':{'board':report}}
if initial=='fallback':
first_receipt={'run_id':'run','tasks':[{'task_id':'board','name':'Board task',
'state':'completed','saved_items':1}]}
first=service.receive_successful_results(first_receipt,submission_id='initial')
item=first['accepted'][0]['item_id']
retry_report=dict(report,before=evidence['before'],after=evidence['retry'],
expected_changes={'u1':{'Value':'NEW'}},execution={'state':'completed','saved_items':2})
retry_receipt=dict(first_receipt,netlist_verification={'board':retry_report})
if initial=='ready':
with service.repo.store.transaction():
service.repo._remember('handoff','retry',retry_receipt,
{'accepted':[],'rejected':[{'code':'verification_conflict'}]})
second=service.receive_successful_results(retry_receipt,submission_id='retry')
assert second['accepted']==[{'item_id':item,'input_version':2}]
original=service.read_item(item,version=1)['payload']
current=service.read_item(item)['payload']
if initial=='ready':
assert current['before_ref']==original['before_ref']
assert current['after_ref']!=original['after_ref']
assert current['input_state']=='ready'
assert service.receive_successful_results(retry_receipt,submission_id='checkpoint')['duplicates']==second['accepted']
service.receive_successful_results(first_receipt,submission_id='late-checkpoint')
assert service.read_item(item)['versions']==[2,1]
updated_report=dict(retry_report,expected_changes={'u1':{'Value':'NEWER'}})
updated_receipt=dict(first_receipt,netlist_verification={'board':updated_report})
third=service.receive_successful_results(updated_receipt,submission_id='latest')
assert third['accepted']==[{'item_id':item,'input_version':3}]
assert service.read_item(item)['payload']['before_ref']==current['before_ref']
@@ -78,6 +78,15 @@ def test_missing_required_mapping_never_passes_and_duplicate_ref_is_unknown():
assert evaluate(a,b)['verdict']=='INCOMPLETE'
def test_empty_native_networks_cannot_prove_coverage():
value=export()
value['graph']['nets']=[]
for component in value['graph']['components'].values():
for pin in component['pins'].values():
pin['nets']=[]
assert evaluate(value,value)['verdict']=='INCOMPLETE'
def test_missing_pin_number_cannot_prove_equal_and_error_beats_unknown():
a=export();b=copy.deepcopy(a);b['graph']['components']['a']['pins']['loop']['number']=''
assert evaluate(a,b)['verdict']=='INCOMPLETE'
+9 -1
View File
@@ -1,5 +1,7 @@
import time
from threading import Event
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from test_independent_verification_intake import service
from test_independent_verification_runner import imported
from test_native_cli_netlist import graph
@@ -25,7 +27,13 @@ def test_start_idempotency_and_frozen_members_do_not_swallow_new_version(service
payload=service.repo.revision(item,1)['payload']
newer={k:v for k,v in payload.items() if k not in {'input_state','payload_digest'}};newer['input_version']=2
service.publish_inputs(task,(newer,),submission_id='new')
release.set();wait_idle(service)
try:
assert service.start(task,selection=((item,1),),request_id='same-member')==first
with pytest.raises(TaskCenterError,match='当前校验'):
service.rerun(item,2,request_id='start-new-version')
finally:
release.set()
wait_idle(service)
assert len(calls)==2 and service.read_item(item)['status']=='waiting'
assert service.read_item(item,version=1)['status']=='consistent'
+40
View File
@@ -30,6 +30,46 @@ def test_task_export_is_immutable_and_incomplete_items_are_explicit(service,tmp_
assert (output/'index.html').is_file()
@pytest.mark.parametrize('change,label',[('rename','网名变化'),('add','器件新增'),('remove','器件删除')])
def test_historical_pin_evidence_reports_the_detected_change(tmp_path,change,label):
from dx_productivity.trial_task_center.verification.report import render_item_report
from dx_productivity.trial_task_center.verification.evidence import build_evidence
a,b=export(),export()
if change=='rename':
b['graph']['nets'][0]['name']='RENAMED'
for uid,pin in [('a','loop'),('b','out')]:
b['graph']['components'][uid]['pins'][pin]['nets']=['RENAMED']
else:
graph=(b if change=='add' else a)['graph']
graph['components']['isolated']={'refdes':'R99','attributes':{'Part Number':'PART'},
'pins':{'open':{'number':'1','nets':[]}}}
result=evaluate(a,b)
result['evidence']=build_evidence(a['graph'],b['graph'],result['issues'],binding={})
path=render_item_report(result,tmp_path/'report.html')
html=path.read_text(encoding='utf-8')
assert result['verdict']=='DIFFERENT'
assert f'<td>{label}</td>' in html and '#b83d4a' in html.split('<svg',1)[1]
def test_report_filename_limit_does_not_depend_on_destination_name(tmp_path):
from dx_productivity.trial_task_center.verification.report import render_item_report
path=tmp_path/('r'*235+'.html')
assert render_item_report({},path)==path
assert path.read_text(encoding='utf-8').startswith('<!doctype html>')
assert list(tmp_path.iterdir())==[path]
def test_task_report_can_be_written_beyond_windows_legacy_path_limit(service,tmp_path):
from dx_productivity.trial_task_center.path_access import internal_path
task=service.create_task('报告',request_id='task')['task_id']
destination=tmp_path
while len(str(destination))<270:
destination=destination/('report-folder-'+'a'*30)
output=service.export_task(task,destination,request_id='export')
assert internal_path(output/'index.html').is_file()
assert service.export_task(task,destination,request_id='export')==output
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