feat: define independent verification contracts and verdicts
This commit is contained in:
1 parent
dbb264f679
commit
0406028a02
3 files changed
+189
No files matched your search
@@ -0,0 +1 @@
|
||||
"""Independent, read-only project verification and traceable evidence."""
|
||||
@@ -0,0 +1,109 @@
|
||||
"""Versioned input contracts and conclusions independent of execution status."""
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
|
||||
from ..errors import TaskCenterError
|
||||
|
||||
CHECKS = frozenset(('inputs','coverage','components','physical_pins','connections','net_names',
|
||||
'declared_attributes','attribute_changes','pin_text','pin_semantics','footprint_mapping','export_identity'))
|
||||
STATES = frozenset(('equal','expected_change','warning','error','unknown','not_requested'))
|
||||
ACTIVE = ('queued','running','publishing','stopping')
|
||||
TERMINAL = ('succeeded','failed','cancelled','interrupted')
|
||||
|
||||
|
||||
def fail(message, code='verification_input'):
|
||||
raise TaskCenterError(code, message)
|
||||
|
||||
|
||||
def digest(value):
|
||||
return hashlib.sha256(json.dumps(value, sort_keys=True, ensure_ascii=False,
|
||||
separators=(',', ':'), allow_nan=False).encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def identifier(value):
|
||||
if not isinstance(value, str) or not value.strip() or len(value) > 256 or any(ord(c) < 32 for c in value):
|
||||
fail('标识不能为空或包含控制字符。')
|
||||
return value
|
||||
|
||||
|
||||
def artifact_ref(value):
|
||||
if value is None:
|
||||
return None
|
||||
if (not isinstance(value, dict) or set(value) != {'manifest_id','sha256'}
|
||||
or re.fullmatch('[0-9a-f]{32}', str(value['manifest_id'])) is None
|
||||
or re.fullmatch('[0-9a-f]{64}', str(value['sha256'])) is None):
|
||||
fail('校验证据引用无效。')
|
||||
return dict(value)
|
||||
|
||||
|
||||
def default_plan():
|
||||
return {'policy_version': 'verification-v1',
|
||||
'required_checks': ['inputs','coverage','components','physical_pins','connections','net_names'],
|
||||
'optional_checks': ['attribute_changes','pin_text','pin_semantics','export_identity'],
|
||||
'excluded_checks': ['footprint_mapping']}
|
||||
|
||||
|
||||
def validate_plan(plan):
|
||||
if not isinstance(plan, dict) or set(plan) != {'policy_version','required_checks','optional_checks','excluded_checks'}:
|
||||
fail('检查计划字段不完整。')
|
||||
if plan['policy_version'] != 'verification-v1':
|
||||
fail('不支持的校验策略版本。')
|
||||
groups = [plan[key] for key in ('required_checks','optional_checks','excluded_checks')]
|
||||
if any(not isinstance(group, (list,tuple)) for group in groups):
|
||||
fail('检查范围必须为列表。')
|
||||
flat = [key for group in groups for key in group]
|
||||
if not groups[0] or any(not isinstance(key,str) or key not in CHECKS for key in flat) or len(set(flat)) != len(flat):
|
||||
fail('检查范围为空、重复或包含未知项目。')
|
||||
return copy.deepcopy(plan)
|
||||
|
||||
|
||||
def validate_input(value):
|
||||
allowed = {'item_key','project_key','input_version','before_ref','after_ref','expectation_ref',
|
||||
'check_plan','display_name','unavailable_reason'}
|
||||
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('校验输入字段不完整或包含不支持字段。')
|
||||
result = copy.deepcopy(value)
|
||||
for key in ('item_key','project_key'):
|
||||
identifier(result[key])
|
||||
if type(result['input_version']) is not int or not 1 <= result['input_version'] <= 2**31-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'])
|
||||
result['display_name'] = identifier(result.get('display_name') or result['project_key'])
|
||||
reason = result.get('unavailable_reason','')
|
||||
if not isinstance(reason,str) or len(reason)>4000:
|
||||
fail('不可用原因无效。')
|
||||
if not result['before_ref'] or not result['after_ref']:
|
||||
reason = reason or '缺少替换前或替换后的可信副本。'
|
||||
result.update(input_state='unavailable' if reason else 'ready', unavailable_reason=reason)
|
||||
result['payload_digest'] = digest(result)
|
||||
return result
|
||||
|
||||
|
||||
def rollup_results(checks, *, required_checks, optional_checks=()):
|
||||
if not required_checks or any(key not in CHECKS for key in (*required_checks,*optional_checks)):
|
||||
fail('必查项目不能为空。', 'verification_check_plan')
|
||||
states = {}
|
||||
for row in checks:
|
||||
key, state = row.get('check_id'), row.get('state')
|
||||
if key not in CHECKS or state not in STATES or key in states:
|
||||
fail('检查结果包含重复或未知项目。', 'verification_result')
|
||||
states[key] = state
|
||||
requested = tuple(dict.fromkeys((*required_checks,*optional_checks)))
|
||||
unknown = [key for key in requested if states.get(key, 'unknown') in {'unknown','not_requested'}]
|
||||
if any(state=='error' for state in states.values()):
|
||||
verdict = 'DIFFERENT'
|
||||
elif any(states.get(key,'unknown') in {'unknown','not_requested'} for key in required_checks):
|
||||
verdict = 'INCOMPLETE'
|
||||
elif any(state=='warning' for state in states.values()):
|
||||
verdict = 'WARNING'
|
||||
else:
|
||||
verdict = 'CONSISTENT'
|
||||
return {'verdict': verdict, 'coverage': 'partial' if unknown else 'complete',
|
||||
'unknown_checks': unknown, 'checked': [key for key in requested if key not in unknown],
|
||||
'warnings': sum(state=='warning' for state in states.values()),
|
||||
'errors': sum(state=='error' for state in states.values())}
|
||||
@@ -0,0 +1,79 @@
|
||||
import copy
|
||||
import pytest
|
||||
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
|
||||
|
||||
def payload():
|
||||
return {'item_key': 'board', 'project_key': 'board', 'input_version': 1,
|
||||
'before_ref': {'manifest_id': 'a' * 32, 'sha256': '1' * 64},
|
||||
'after_ref': {'manifest_id': 'b' * 32, 'sha256': '2' * 64},
|
||||
'expectation_ref': None,
|
||||
'check_plan': {'policy_version': 'verification-v1', 'required_checks': ['connections'],
|
||||
'optional_checks': ['pin_text'], 'excluded_checks': ['footprint_mapping']}}
|
||||
|
||||
|
||||
@pytest.mark.parametrize('state,want', [('equal','CONSISTENT'), ('warning','WARNING'),
|
||||
('error','DIFFERENT'), ('unknown','INCOMPLETE'),
|
||||
('not_requested','INCOMPLETE')])
|
||||
def test_required_checks_determine_verdict_without_hiding_missing_checks(state, want):
|
||||
from dx_productivity.trial_task_center.verification.contracts import rollup_results
|
||||
result = rollup_results(({'check_id': 'connections', 'state': state, 'issues': []},),
|
||||
required_checks=('connections',))
|
||||
assert result['verdict'] == want
|
||||
|
||||
|
||||
def test_error_wins_but_unknown_coverage_remains_visible():
|
||||
from dx_productivity.trial_task_center.verification.contracts import rollup_results
|
||||
result = rollup_results(({'check_id':'connections','state':'error','issues':[]},),
|
||||
required_checks=('connections','physical_pins'))
|
||||
assert result['verdict'] == 'DIFFERENT'
|
||||
assert result['coverage'] == 'partial'
|
||||
assert result['unknown_checks'] == ['physical_pins']
|
||||
|
||||
|
||||
def test_empty_or_duplicate_checks_cannot_be_consistency():
|
||||
from dx_productivity.trial_task_center.verification.contracts import rollup_results
|
||||
assert rollup_results((), required_checks=('connections',))['verdict'] == 'INCOMPLETE'
|
||||
with pytest.raises(TaskCenterError):
|
||||
rollup_results((), required_checks=())
|
||||
row = {'check_id':'connections','state':'equal','issues':[]}
|
||||
with pytest.raises(TaskCenterError):
|
||||
rollup_results((row,row), required_checks=('connections',))
|
||||
|
||||
|
||||
def test_optional_unknown_is_explicit_without_erasing_core_result():
|
||||
from dx_productivity.trial_task_center.verification.contracts import rollup_results
|
||||
result = rollup_results(({'check_id':'connections','state':'equal','issues':[]},),
|
||||
required_checks=('connections',), optional_checks=('pin_text',))
|
||||
assert result['verdict'] == 'CONSISTENT'
|
||||
assert result['coverage'] == 'partial'
|
||||
assert result['unknown_checks'] == ['pin_text']
|
||||
|
||||
|
||||
def test_input_is_detached_and_cannot_contain_source_or_arbitrary_paths():
|
||||
from dx_productivity.trial_task_center.verification.contracts import validate_input
|
||||
value = payload()
|
||||
result = validate_input(value)
|
||||
value['check_plan']['required_checks'].clear()
|
||||
assert result['check_plan']['required_checks'] == ['connections']
|
||||
for name in ('source','output_path'):
|
||||
bad = payload(); bad[name] = 'anything'
|
||||
with pytest.raises(TaskCenterError): validate_input(bad)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('field,value', [('input_version', True), ('input_version',0),
|
||||
('before_ref', {'manifest_id':'../outside','sha256':'1'*64}),
|
||||
('after_ref', {'manifest_id':'b'*32,'sha256':'invalid'})])
|
||||
def test_invalid_input_never_enters_storage(field,value):
|
||||
from dx_productivity.trial_task_center.verification.contracts import validate_input
|
||||
bad = payload(); bad[field] = value
|
||||
with pytest.raises(TaskCenterError): validate_input(bad)
|
||||
|
||||
|
||||
def test_missing_capture_stays_recordable_as_unavailable():
|
||||
from dx_productivity.trial_task_center.verification.contracts import validate_input
|
||||
value = payload(); value['before_ref'] = None
|
||||
result = validate_input(value)
|
||||
assert result['input_state'] == 'unavailable'
|
||||
assert result['unavailable_reason']
|
||||
Reference in new issue
Block a user