test(dashboard-testing): validate conserving tests against frozen suite evidence

This commit is contained in:
2026-10-11 09:50:16 +03:00
parent 8abb5c94ce
commit 254c7eaf3d
5 changed files with 699 additions and 2 deletions

View File

@@ -0,0 +1,392 @@
#!/usr/bin/env python3
# #region Tooling.DashboardTestingAccounting [C:3] [TYPE Module] [SEMANTICS accounting,verification,pytest,freeze]
# @BRIEF Resolve the existing combined withdrawal ledger against committed source and one complete frozen suite.
# @PRE Evidence digests come from the reviewed strict-launcher run receipt, independently of these mutable input files; no test, DB or source mutation occurs here.
# @POST Every conserving reference exists at the exact commit and all parameters in the pinned actual collection manifest passed every phase without xfail.
# @INVARIANT This validator does not statically derive dynamic pytest fixture/metafunc parameter inventory or authenticate its caller's receipt.
# @INVARIANT No nearest-name, first-parameter, working-tree or historical-wire fallback; approval is not inferred.
# @RATIONALE The ledger contains chronological explicit overlays; only its named machine records select conserving tests.
# @REJECTED Markdown keyword guesses and a green summary alone cannot establish that the referenced assertions ran.
from __future__ import annotations
import argparse
import ast
from collections import Counter
from hashlib import sha256
import json
from pathlib import Path
import re
import subprocess
import sys
import uuid
import xml.etree.ElementTree as ET
LEDGER = 'specs/050-mcp-interface/plans/2026-10-10-deleted-test-accounting.md'
OWNER = 'Tooling.VerifyDashboardTestingCurrent'
PERIOD_REF = ('backend/tests/services/dashboard_testing/execution/test_start_run_period_receipt.py::'
'test_digest_mismatch_writes_no_receipt')
BLOCKS = (
'<a id="supplemental-api-reachability"></a>Supplemental API reachability — current per-key status',
'Machine-readable original275-key current-status manifest',
'<a id="reference-discovery-selection-20"></a>Reference discovery/capture twenty-key checkpoint',
'<a id="metadata-provenance-restoration"></a>Open/closed metadata and provenance assertion checkpoint',
'<a id="scenario-api-22-assertion-review"></a>Scenario/reference API twenty-two same-name assertion review',
'<a id="registry-29-assertion-review"></a>Registry twenty-nine same-name assertion checkpoint',
'<a id="candidate-kind-assertion-checkpoint"></a>Candidate kind bounded source checkpoint',
'<a id="consumer-four-assertion-checkpoint"></a>Four-owner assertion restoration checkpoint',
'<a id="final-640-key-manifest"></a>Machine-readable final640 current-property manifest',
'Post-proof period fixture and receipt-error privacy checkpoint',
'Post-proof visual reference phase checkpoint', 'Post-proof immutability fixture checkpoint',
'Post-proof synchronous verification fixture checkpoint', 'Post-proof scenario-runs API fixture checkpoint',
'Post-proof inheritance current-source checkpoint', 'Post-proof native metric and single-chart rollback checkpoint',
'Post-proof candidate provenance primary-only checkpoint',
'Final post-proof assertion audit — comparison fault restored',
'Current release-refusal restoration after c99',
'Current faithful public denied-visual consumption restoration',
)
class AccountingError(Exception):
"""Closed public code and safe source/node identities only, never input bodies."""
def __init__(self, code, **facts):
super().__init__(code)
self.code, self.facts = code, facts
def refuse(code, **facts):
raise AccountingError(code, **facts) from None
def require(condition, code='ACCOUNTING_EVIDENCE_CONFLICT', **facts):
if not condition:
refuse(code, **facts)
def strict_json(raw):
def pairs(items):
result = {}
for key, value in items:
require(key not in result, 'ACCOUNTING_JSON_INVALID')
result[key] = value
return result
try:
return json.loads(raw, object_pairs_hook=pairs,
parse_constant=lambda _: refuse('ACCOUNTING_JSON_INVALID'))
except (ValueError, TypeError, UnicodeError):
refuse('ACCOUNTING_JSON_INVALID')
# #region Tooling.DashboardTestingAccounting.Reference [C:2] [TYPE Function]
# @POST A reference resolves only an explicit backend test path and qualified test symbol, with optional exact parameter ID.
def reference(raw):
require(isinstance(raw, str) and len(raw) <= 1024 and not re.search(r'[\x00-\x1f]', raw),
'ACCOUNTING_REF_INVALID')
if raw.startswith(('services/', 'api/')):
raw = 'backend/tests/' + raw
match = re.fullmatch(r'(backend/tests/(?:[A-Za-z0-9_]+/)*test_[A-Za-z0-9_]+\.py)::'
r'((?:[A-Za-z_]\w*\.)*test_\w+)(\[.*\])?', raw)
require(match is not None, 'ACCOUNTING_REF_INVALID')
path, symbol, parameter = match.groups()
return path, symbol, parameter or ''
# #endregion Tooling.DashboardTestingAccounting.Reference
def canonical(raw):
path, symbol, parameter = reference(raw)
return path + '::' + symbol + parameter
def record_refs(row, heading):
fields = [name for name in ('tests', 'replacement', 'current_refs') if name in row]
require(len(fields) <= 1, 'ACCOUNTING_LEDGER_INVALID')
if not fields:
# This named checkpoint explicitly retains same-key current_assertions rather than a refs array.
require(heading == BLOCKS[9] and row.get('key') == PERIOD_REF
and isinstance(row.get('current_assertions'), list) and row['current_assertions']
and all(isinstance(item, str) and item for item in row['current_assertions']),
'ACCOUNTING_LEDGER_INVALID')
return [PERIOD_REF]
values = row[fields[0]]
require(isinstance(values, list), 'ACCOUNTING_LEDGER_INVALID')
return [canonical(value.get('key') if isinstance(value, dict) else value) for value in values]
# #region Tooling.DashboardTestingAccounting.Ledger [C:3] [TYPE Function]
# @POST The exact combined table joins chronological named records; missing/foreign states and duplicate keys refuse.
def parse_ledger(text):
keys, states, seen_blocks, block_keys = [], {}, set(), set()
heading, active, fence = '', None, None
for line in text.splitlines():
if line.startswith('### '):
heading = line[4:]
if line.startswith('```'):
if fence is not None:
require(line == '```', 'ACCOUNTING_LEDGER_INVALID')
fence = active = None
else:
fence = line
if line == '```jsonl':
require(heading in BLOCKS and heading not in seen_blocks, 'ACCOUNTING_LEDGER_INVALID')
seen_blocks.add(heading)
active = heading
block_keys = set()
continue
if active and line.strip():
row = strict_json(line)
require(isinstance(row, dict), 'ACCOUNTING_LEDGER_INVALID')
key = canonical(row.get('supplemental_key', row.get('key')))
require(key not in block_keys, 'ACCOUNTING_LEDGER_INVALID', ref=key)
block_keys.add(key)
state = row.get('state')
require(state in {'PENDING_B', 'RESTORED_SOURCE', 'OPEN_A'}, 'ACCOUNTING_LEDGER_INVALID')
states[key] = state, record_refs(row, active)
if fence is None and heading == 'One combined pending withdrawal list' and line.startswith('| `'):
match = re.match(r'\| `([^`]+)`(?: \*\*[^|`]+\*\*)? \|', line)
require(match is not None, 'ACCOUNTING_LEDGER_INVALID')
keys.append(canonical(match[1]))
require(fence is None and {BLOCKS[0], BLOCKS[1], BLOCKS[8]} <= seen_blocks,
'ACCOUNTING_LEDGER_INVALID')
require(keys and len(keys) == len(set(keys)), 'ACCOUNTING_LEDGER_INVALID')
# The current combined table owns membership; frozen historical manifests can retain a
# removed key whose explicit restoration is recorded in a later prose checkpoint.
require(set(keys) <= {key for key, value in states.items() if value[0] == 'PENDING_B'},
'ACCOUNTING_LEDGER_STATE_CONFLICT')
return {key: states[key][1] for key in keys}
# #endregion Tooling.DashboardTestingAccounting.Ledger
# #region Tooling.DashboardTestingAccounting.Source [C:2] [TYPE Class]
# @POST Source and ledger bytes are read from one existing commit, never checked-out files or imports.
class GitSource:
def __init__(self, root, commit):
require(re.fullmatch(r'[0-9a-f]{40}', commit) is not None, 'ACCOUNTING_COMMIT_INVALID')
self.root, self.commit = root, commit
require(self.git('rev-parse', commit + '^{commit}').decode().strip() == commit,
'ACCOUNTING_COMMIT_INVALID')
def git(self, *args):
result = subprocess.run(['git', *args], cwd=self.root, capture_output=True)
require(result.returncode == 0, 'ACCOUNTING_SOURCE_UNAVAILABLE')
return result.stdout
def read(self, path):
result = subprocess.run(['git', 'show', self.commit + ':' + path], cwd=self.root, capture_output=True)
require(result.returncode == 0, 'ACCOUNTING_REF_MISSING', source_path=path)
return result.stdout
def files(self):
return self.git('ls-tree', '-r', '--name-only', self.commit, '--', 'backend/tests').decode().splitlines()
# #endregion Tooling.DashboardTestingAccounting.Source
def test_symbols(raw):
try:
tree = ast.parse(raw)
except (SyntaxError, ValueError):
refuse('ACCOUNTING_SOURCE_INVALID')
symbols = []
for node in tree.body:
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name.startswith('test_'):
symbols.append(node.name)
elif isinstance(node, ast.ClassDef) and node.name.startswith('Test'):
symbols.extend(node.name + '.' + child.name for child in node.body
if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)) and child.name.startswith('test_'))
return symbols
def imported_symbols(source, path, trail=()):
require(path not in trail, 'ACCOUNTING_SOURCE_IMPORT_CYCLE')
raw = source.read(path)
symbols = test_symbols(raw)
for node in ast.parse(raw).body:
if isinstance(node, ast.ImportFrom) and node.module and node.module.startswith('tests.'):
for alias in node.names:
target = alias.asname or alias.name
if target.startswith(('Test', 'test_')):
imported = imported_symbols(source, 'backend/' + node.module.replace('.', '/') + '.py',
(*trail, path))
symbols.extend(target + name[len(alias.name):] for name in imported
if name == alias.name or name.startswith(alias.name + '.'))
return symbols
def source_nodes(source):
tree = ast.parse(source.read('scripts/verify_dashboard_testing_current.py'))
value = next((node.value for node in tree.body if isinstance(node, ast.Assign)
and any(isinstance(t, ast.Name) and t.id == 'API_FILES' for t in node.targets)), None)
require(isinstance(value, ast.Call) and isinstance(value.func, ast.Attribute)
and value.func.attr == 'split' and isinstance(value.func.value, ast.Constant), 'ACCOUNTING_LAUNCHER_INVALID')
api = {'backend/tests/api/test_' + name + '.py' for name in value.func.value.value.split()}
paths = {p for p in source.files() if p.startswith('backend/tests/services/dashboard_testing/')
and Path(p).name.startswith('test_') and p.endswith('.py')} | api
return {path: imported_symbols(source, path) for path in sorted(paths)}
def node_base(path, symbol):
return path.removeprefix('backend/') + '::' + symbol.replace('.', '::')
def digest_bytes(path, expected):
require(re.fullmatch(r'[0-9a-f]{64}', expected) is not None, 'ACCOUNTING_DIGEST_INVALID')
try:
require(not path.is_symlink() and path.is_file(), 'ACCOUNTING_EVIDENCE_INVALID')
raw = path.read_bytes()
except OSError:
refuse('ACCOUNTING_EVIDENCE_UNAVAILABLE')
require(sha256(raw).hexdigest() == expected, 'ACCOUNTING_EVIDENCE_DIGEST_CONFLICT', artifact=path.name)
return raw
# #region Tooling.DashboardTestingAccounting.Events [C:3] [TYPE Function]
# @POST Every node has one source-owned start trace and unique phase reports with explicit wasxfail; old wire refuses.
def stage_events(raw, nodes):
starts, stages, counts, trace_changes = {}, {}, Counter(), 0
for line in raw.splitlines():
event = strict_json(line)
require(isinstance(event, dict), 'ACCOUNTING_EVIDENCE_SCHEMA_INVALID')
if event.get('src') != OWNER:
continue
require(not event.get('payload_truncated'), 'ACCOUNTING_EVIDENCE_SCHEMA_INVALID')
require(event.get('error_code') not in {'FINAL_COLLECTION_FAILED', 'FINAL_INTERNAL_ERROR',
'FINAL_NODE_FAILED', 'FINAL_UNPLANNED_CONTAINER_FIXTURE'}, 'ACCOUNTING_RUN_NOT_SUCCESSFUL')
payload = event.get('payload', {})
require(isinstance(payload, dict), 'ACCOUNTING_EVIDENCE_SCHEMA_INVALID')
node, trace = payload.get('node_id'), event.get('trace_id')
if event.get('marker') == 'REASON' and event.get('intent') == 'Run frozen suite node':
require(node in nodes and node not in starts and isinstance(trace, str)
and re.fullmatch(r'[0-9a-f]{32}', trace) is not None, 'ACCOUNTING_EVIDENCE_CONFLICT')
starts[node] = trace
elif event.get('marker') == 'REFLECT' and event.get('intent') == 'Frozen suite node stage observed':
phase, outcome = payload.get('stage'), payload.get('outcome')
require(node in starts and isinstance(trace, str) and 0 < len(trace) <= 256
and not re.search(r'[\x00-\x1f]', trace) and phase in {'setup', 'call', 'teardown'}
and outcome in {'passed', 'failed', 'skipped'} and (node, phase) not in stages,
'ACCOUNTING_PHASE_CONFLICT', stage=phase if phase in {'setup', 'call', 'teardown'} else 'invalid')
require(type(payload.get('wasxfail')) is bool, 'ACCOUNTING_EVIDENCE_SCHEMA_INVALID', node_id=node, stage=phase)
preceding = {'setup':None, 'call':'setup', 'teardown':'setup' if (node, 'call') not in stages else 'call'}[phase]
require(preceding is None or (node, preceding) in stages, 'ACCOUNTING_PHASE_CONFLICT', node_id=node, stage=phase)
require(phase != 'teardown' or preceding == 'call' or stages[node, 'setup'][0] == 'skipped',
'ACCOUNTING_PHASE_CONFLICT', node_id=node, stage=phase)
stages[node, phase] = outcome, payload['wasxfail']
trace_changes += trace != starts[node]
counts[phase + ':' + outcome] += 1
require(set(starts) == set(nodes) and len(set(starts.values())) == len(nodes), 'ACCOUNTING_EVIDENCE_CONFLICT')
return stages, counts, trace_changes
# #endregion Tooling.DashboardTestingAccounting.Events
def junit_cases(raw, nodes, counts):
require(b'<!DOCTYPE' not in raw and b'<!ENTITY' not in raw, 'ACCOUNTING_JUNIT_INVALID')
try:
root = ET.fromstring(raw)
except ET.ParseError:
refuse('ACCOUNTING_JUNIT_INVALID')
cases = root.findall('.//testcase')
expected = set()
for node in nodes:
base, sep, parameter = node.partition('[')
parts = base.split('::')
expected.add(('.'.join([parts[0].removesuffix('.py').replace('/', '.'), *parts[1:-1]]),
parts[-1] + (sep + parameter if sep else '')))
observed = [(case.get('classname'), case.get('name')) for case in cases]
require(len(observed) == len(expected) == len(nodes) and set(observed) == expected,
'ACCOUNTING_JUNIT_CONFLICT')
require(not root.findall('.//failure') and not root.findall('.//error'), 'ACCOUNTING_RUN_NOT_SUCCESSFUL')
suites = root.findall('testsuite') if root.tag == 'testsuites' else [root]
try:
require(sum(int(s.get('tests', '-1')) for s in suites) == len(nodes)
and all(int(s.get('failures', '-1')) == int(s.get('errors', '-1')) == 0 for s in suites)
and sum(int(s.get('skipped', '0')) for s in suites) == len(root.findall('.//skipped'))
== counts['setup:skipped'] + counts['call:skipped'],
'ACCOUNTING_JUNIT_CONFLICT')
except ValueError:
refuse('ACCOUNTING_JUNIT_INVALID')
return {key: not list(case) or all(child.tag not in {'skipped', 'failure', 'error'} for child in case)
for key, case in zip(observed, cases, strict=True)}
# #region Tooling.DashboardTestingAccounting.Validate [C:3] [TYPE Function]
# @POST Missing symbols, absent/failed parameters, duplicate/missing phases, xfail and partial/foreign runs cannot satisfy accounting.
def validate(source, evidence, digests, *, expected_keys=347, expected_refs=275):
ledger_raw = source.read(LEDGER)
ledger = parse_ledger(ledger_raw.decode())
refs = {ref for values in ledger.values() for ref in values}
require(len(ledger) == expected_keys and len(refs) == expected_refs, 'ACCOUNTING_LEDGER_COUNT_CONFLICT')
symbols = source_nodes(source)
for ref in sorted(refs):
path, symbol, _ = reference(ref)
require(path in symbols and symbol in symbols[path], 'ACCOUNTING_REF_MISSING', ref=ref)
require(symbols[path].count(symbol) == 1, 'ACCOUNTING_SOURCE_AMBIGUOUS', ref=ref)
raw = {name: digest_bytes(evidence / name, digest) for name, digest in digests.items()}
require(set(raw) == {'summary.json', 'nodes.json', 'molecular.jsonl', 'junit.xml'}, 'ACCOUNTING_EVIDENCE_INVALID')
summary, nodes = strict_json(raw['summary.json']), strict_json(raw['nodes.json'])
require(summary.get('commit') == source.commit, 'ACCOUNTING_COMMIT_CONFLICT')
require(type(summary.get('pytest_exit_code')) is int and summary['pytest_exit_code'] == 0
and type(summary.get('private_failure_diagnostics')) is int
and summary['private_failure_diagnostics'] == 0, 'ACCOUNTING_RUN_NOT_SUCCESSFUL')
require(isinstance(nodes, list) and nodes and all(isinstance(n, str) for n in nodes)
and len(nodes) == len(set(nodes)) and type(summary.get('collected')) is int
and summary['collected'] == len(nodes), 'ACCOUNTING_EVIDENCE_CONFLICT')
expected_bases = {node_base(path, symbol) for path, names in symbols.items() for symbol in names}
require({node.partition('[')[0] for node in nodes} == expected_bases, 'ACCOUNTING_WHOLE_SCOPE_CONFLICT')
stages, counts, trace_changes = stage_events(raw['molecular.jsonl'], set(nodes))
require(dict(counts) == summary.get('outcomes') and counts['teardown:passed'] == len(nodes)
and not any(key.endswith(':failed') for key in counts), 'ACCOUNTING_EVIDENCE_CONFLICT')
for node in nodes:
require((node, 'setup') in stages and ((node, 'call') in stages
or stages[node, 'setup'][0] == 'skipped'), 'ACCOUNTING_PHASE_CONFLICT', node_id=node)
junit = junit_cases(raw['junit.xml'], nodes, counts)
joined = 0
for ref in sorted(refs):
path, symbol, parameter = reference(ref)
base = node_base(path, symbol)
matches = [node for node in nodes if node == base + parameter] if parameter else [
node for node in nodes if node.partition('[')[0] == base]
require(matches, 'ACCOUNTING_REF_NOT_COLLECTED', ref=ref)
for node in matches:
for phase in ('setup', 'call', 'teardown'):
require(stages.get((node, phase)) == ('passed', False),
'ACCOUNTING_REF_NOT_PASSED', ref=ref, node_id=node, stage=phase)
base_parts = base.split('::')
key = ('.'.join([base_parts[0].removesuffix('.py').replace('/', '.'), *base_parts[1:-1]]),
base_parts[-1] + node[len(base):])
require(junit[key], 'ACCOUNTING_REF_NOT_PASSED', ref=ref, node_id=node, stage='junit')
joined += 1
return {'commit': source.commit, 'ledger_sha256': sha256(ledger_raw).hexdigest(),
'pending_keys': len(ledger), 'conserving_refs': len(refs), 'reference_parameter_joins': joined,
'empty_reference_rows': sum(not values for values in ledger.values()), 'collected': len(nodes),
'observed_stage_trace_changes': trace_changes,
'evidence_sha256': digests, 'withdrawal_approval_inferred': False}
# #endregion Tooling.DashboardTestingAccounting.Validate
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--commit', required=True)
parser.add_argument('--evidence-dir', required=True, type=Path)
for name in ('summary', 'nodes', 'molecular', 'junit'):
parser.add_argument('--' + name + '-sha256', required=True)
args = parser.parse_args()
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'backend'))
from src.core.cot_logger import build_cot_event
trace = uuid.uuid4().hex
try:
source = GitSource(Path(__file__).resolve().parents[1], args.commit)
digests = {name + ('.jsonl' if name == 'molecular' else '.xml' if name == 'junit' else '.json'):
getattr(args, name + '_sha256') for name in ('summary', 'nodes', 'molecular', 'junit')}
result = validate(source, args.evidence_dir, digests)
marker, code, facts, status = 'REFLECT', None, result, 0
except AccountingError as exc:
marker, code, facts, status = 'EXPLORE', exc.code, exc.facts, 2
except Exception as exc:
marker, code, facts, status = 'EXPLORE', 'ACCOUNTING_TOOL_UNAVAILABLE', {'failure_type':type(exc).__name__}, 2
print(json.dumps(build_cot_event(src='Tooling.DashboardTestingAccounting', marker=marker,
intent='Frozen accounting reference validation', trace_id=trace, error_code=code,
claim='POST: every explicit conserving reference must pass every collected parameter and phase without xfail',
payload=facts), sort_keys=True))
return status
if __name__ == '__main__':
raise SystemExit(main())
# #endregion Tooling.DashboardTestingAccounting

View File

@@ -415,7 +415,8 @@ def run_suite(root: Path, evidence: Path, commit: str, safe: SafeLogs, diagnosti
if self.active is not None:
self.active.stage = {'setup':'call', 'call':'teardown', 'teardown':'complete'}[report.when]
logger.reflect('Frozen suite node stage observed', src='Tooling.VerifyDashboardTestingCurrent',
payload={'node_id':report.nodeid,'stage':report.when,'outcome':report.outcome})
payload={'node_id':report.nodeid,'stage':report.when,'outcome':report.outcome,
'wasxfail':hasattr(report, 'wasxfail')})
selectors = ['tests/services/dashboard_testing'] + ['tests/api/test_' + n + '.py' for n in API_FILES]
previous = Path.cwd()