Files
ss-tools/scripts/validate_dashboard_testing_accounting.py

639 lines
38 KiB
Python

#!/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 and source/command provenance come from the independently reviewed run receipt; no test, DB or source mutation occurs here.
# @POST Every conserving reference exists at the exact commit and all its actual parameters 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 api_names(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')
names = value.func.value.value.split()
require(names and len(names) == len(set(names))
and all(re.fullmatch(r'[a-z0-9_]+', name) for name in names), 'ACCOUNTING_LAUNCHER_INVALID')
return names
def scope_targets(source, scope):
require(scope in {'backend', 'dashboard'}, 'ACCOUNTING_SCOPE_INVALID')
if scope == 'backend':
return ['tests']
return ['tests/services/dashboard_testing'] + ['tests/api/test_' + name + '.py' for name in api_names(source)]
def source_nodes(source):
api = {'backend/tests/api/test_' + name + '.py' for name in api_names(source)}
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(isinstance(expected, str) and 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.Completion [C:3] [TYPE Function]
# @POST Only explicit current completion with matching scope/session and consistent read-only capacity facts can enter phase accounting.
# @INVARIANT An attempt_exit_code is validated if present, never invented or described as an independently observed OS exit.
def successful_summary(summary, commit, scope, targets):
require(isinstance(summary, dict), 'ACCOUNTING_EVIDENCE_SCHEMA_INVALID')
require(summary.get('commit') == commit, 'ACCOUNTING_COMMIT_CONFLICT')
session = summary.get('verification_session_id')
require(isinstance(session, str) and re.fullmatch(r'[0-9a-f]{32}', session) is not None,
'ACCOUNTING_SESSION_INVALID')
require(summary.get('suite_scope') == scope and summary.get('targets') == targets, 'ACCOUNTING_WHOLE_SCOPE_CONFLICT')
require(summary.get('completed') is True and 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 and summary.get('error_code') is None,
'ACCOUNTING_RUN_NOT_SUCCESSFUL')
if 'attempt_exit_code' in summary:
require(type(summary['attempt_exit_code']) is int and summary['attempt_exit_code'] == 0,
'ACCOUNTING_RUN_NOT_SUCCESSFUL')
require(summary.get('capacity_consistent') is True and summary.get('capacity_error_code') is None,
'ACCOUNTING_RUN_NOT_SUCCESSFUL')
for phase in ('initial', 'final'):
facts = summary.get('capacity_' + phase)
require(isinstance(facts, dict) and facts.get('commit') == commit
and facts.get('verification_session_id') == session and facts.get('phase') == phase
and facts.get('consistent') is True and facts.get('read_only') is True
and facts.get('isolation') == 'REPEATABLE READ'
and facts.get('database_head') == '0040_deployment_verification',
'ACCOUNTING_CAPACITY_CONFLICT')
return session
# #endregion Tooling.DashboardTestingAccounting.Completion
# #region Tooling.DashboardTestingAccounting.Declarations [C:3] [TYPE Function]
# @POST Each verification session has one ordered explicit scope dispatch and collection declaration; no argv observation is inferred.
def session_declarations(events, source):
dispatch = [(index, event['payload']) for index, event in enumerate(events)
if event.get('src') == OWNER and event.get('marker') == 'REASON'
and event.get('intent') == 'Dispatch explicitly scoped frozen suite']
collection = [(index, event['payload']) for index, event in enumerate(events)
if event.get('src') == OWNER and event.get('marker') == 'REFLECT'
and event.get('intent') == 'Frozen suite collection observed']
require(len(dispatch) == len(collection) == 1, 'ACCOUNTING_SCOPE_DECLARATION_INVALID')
before, declaration = dispatch[0]
after, observed = collection[0]
scope = declaration.get('suite_scope')
targets = scope_targets(source, scope)
require(before < after and observed.get('suite_scope') == scope
and type(declaration.get('target_count')) is int and declaration['target_count'] == len(targets)
and type(observed.get('target_count')) is int and observed['target_count'] == len(targets)
and type(observed.get('collected')) is int and observed['collected'] > 0,
'ACCOUNTING_SCOPE_DECLARATION_INVALID')
require(all(index > after for index, event in enumerate(events) if event.get('src') == OWNER
and event.get('intent') in {'Run frozen suite node', 'Frozen suite node stage observed'}),
'ACCOUNTING_SCOPE_DECLARATION_INVALID')
return scope, observed['collected']
# #endregion Tooling.DashboardTestingAccounting.Declarations
# #region Tooling.DashboardTestingAccounting.Sessions [C:3] [TYPE Function]
# @POST Only the trusted explicit session supplies phase evidence; declared foreign sessions are separated and cannot repair it.
# @REJECTED Sessionless business logs are not verification records, while sessionless verification-owner records cannot be guessed into a session.
def verification_events(raw, source, summary, session):
groups = {}
for line in raw.splitlines():
event = strict_json(line)
require(isinstance(event, dict), 'ACCOUNTING_EVIDENCE_SCHEMA_INVALID')
owner = event.get('src')
if not (isinstance(owner, str) and (owner == OWNER or owner.startswith(OWNER + '.')
or owner == 'Tooling.PytestWatchdog')):
continue
payload = event.get('payload')
require(isinstance(payload, dict) and not event.get('payload_truncated'), 'ACCOUNTING_EVIDENCE_SCHEMA_INVALID')
identity = payload.get('verification_session_id')
require(isinstance(identity, str) and re.fullmatch(r'[0-9a-f]{32}', identity) is not None,
'ACCOUNTING_SESSION_INVALID')
groups.setdefault(identity, []).append(event)
require(session in groups, 'ACCOUNTING_SESSION_CONFLICT')
for identity, events in groups.items():
scope, collected = session_declarations(events, source)
if identity == session:
require(scope == summary['suite_scope'] and collected == summary['collected'],
'ACCOUNTING_SCOPE_DECLARATION_INVALID')
require(not any(event.get('src') in {'Tooling.PytestWatchdog', OWNER + '.CapacityCheckpoint'}
and (event.get('error_code') or event['payload'].get('consistent') is False)
for event in events), 'ACCOUNTING_RUN_NOT_SUCCESSFUL')
return groups[session], len(groups) - 1
# #endregion Tooling.DashboardTestingAccounting.Sessions
# #region Tooling.DashboardTestingAccounting.Events [C:3] [TYPE Function]
# @POST Every node has one source-owned start trace and unique phase reports within the trusted session, with explicit wasxfail; old wire refuses.
def stage_events(events, nodes):
starts, stages, counts, trace_changes = {}, {}, Counter(), 0
for event in events:
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, *, suite_scope, 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'])
session = successful_summary(summary, source.commit, suite_scope, scope_targets(source, suite_scope))
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')
if suite_scope == 'dashboard':
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')
else:
paths = {path.removeprefix('backend/') for path in source.files() if path.startswith('backend/tests/')}
require(all('::' in node and node.split('::')[0] in paths for node in nodes), 'ACCOUNTING_WHOLE_SCOPE_CONFLICT')
events, foreign_sessions = verification_events(raw['molecular.jsonl'], source, summary, session)
stages, counts, trace_changes = stage_events(events, 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, 'verification_session_id':session, 'suite_scope':suite_scope,
'separated_foreign_verification_sessions':foreign_sessions, '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),
'collected_skip_reports':counts['setup:skipped'] + counts['call:skipped'],
'collected_xfail_reports':sum(wasxfail for _, wasxfail in stages.values()),
'observed_stage_trace_changes': trace_changes,
'evidence_sha256': digests, 'withdrawal_approval_inferred': False}
# #endregion Tooling.DashboardTestingAccounting.Validate
# #region Tooling.DashboardTestingAccounting.Standard [C:3] [TYPE Function]
# @PRE Official reportlog/JUnit, native stdout/OS exit and independently reviewed clean-source provenance belong to one ordinary unfiltered backend pytest process.
# @POST Native collected count, actual report node union and JUnit agree; every preserving reference joins all actual parameters and three successful non-xfail reports.
# @INVARIANT CollectReport.result=None is not an item inventory; no phase, session identity, capacity or legacy launcher event is synthesized.
# @RATIONALE Standard pytest owns execution and official plugins own observation; this consumer only checks their immutable outputs.
# @REJECTED Inferring missing calls from JUnit aggregates or silently selecting historical evidence cannot close preserving-property accounting.
def validate_standard(source, evidence, digests, *, expected_keys=347, expected_refs=275):
names = {'reportlog.jsonl', 'junit.xml', 'stdout.txt', 'process-exit.txt', 'provenance.json'}
require(set(digests) == names, 'ACCOUNTING_EVIDENCE_INVALID')
raw = {name: digest_bytes(evidence / name, digest) for name, digest in digests.items()}
provenance = strict_json(raw['provenance.json'])
require(isinstance(provenance, dict) and provenance.get('producer') == 'standard-pytest'
and provenance.get('schema_version') == 1, 'ACCOUNTING_PRODUCER_INVALID')
require(provenance.get('commit') == source.commit, 'ACCOUNTING_COMMIT_CONFLICT')
tree = source.git('rev-parse', source.commit + '^{tree}').decode().strip()
require(isinstance(provenance.get('source_freeze'), dict), 'ACCOUNTING_SOURCE_FREEZE_CONFLICT')
for phase in ('start', 'end'):
freeze = provenance.get('source_freeze', {}).get(phase, {})
require(isinstance(freeze, dict) and freeze.get('commit') == source.commit
and freeze.get('tree') == tree and freeze.get('clean') is True,
'ACCOUNTING_SOURCE_FREEZE_CONFLICT')
argv = provenance.get('argv')
require(isinstance(argv, list) and len(argv) == 3 and isinstance(argv[0], str)
and Path(argv[0]).is_absolute() and Path(argv[0]).name.startswith('python')
and argv[1:] == ['-m', 'pytest']
and provenance.get('cwd') == str((Path(source.root) / 'backend').resolve()),
'ACCOUNTING_WHOLE_SCOPE_CONFLICT')
environment = provenance.get('pytest_environment', {})
require(isinstance(environment, dict) and set(environment) == {
'PYTEST_ADDOPTS', 'PYTEST_PLUGINS', 'PYTEST_DISABLE_PLUGIN_AUTOLOAD'}
and environment['PYTEST_ADDOPTS'] == [
'--report-log=' + str((evidence / 'reportlog.jsonl').resolve()),
'--junitxml=' + str((evidence / 'junit.xml').resolve())]
and environment['PYTEST_PLUGINS'] is None and environment['PYTEST_DISABLE_PLUGIN_AUTOLOAD'] is None,
'ACCOUNTING_WHOLE_SCOPE_CONFLICT')
require(provenance.get('reports_sha256') == {name: digests[name] for name in names - {'provenance.json'}},
'ACCOUNTING_EVIDENCE_DIGEST_CONFLICT')
require(provenance.get('os_exit_saved_before_parse') is True and raw['process-exit.txt'].strip() == b'0',
'ACCOUNTING_RUN_NOT_SUCCESSFUL')
try:
stdout = raw['stdout.txt'].decode('utf-8')
records = [strict_json(line) for line in raw['reportlog.jsonl'].splitlines() if line.strip()]
except UnicodeError:
refuse('ACCOUNTING_EVIDENCE_SCHEMA_INVALID')
collected = re.findall(r'^collected ([0-9]+) items?\s*$', stdout, flags=re.MULTILINE)
require(len(collected) == 1 and int(collected[0]) > 0, 'ACCOUNTING_COLLECTION_CONFLICT')
require(records and all(isinstance(record, dict) for record in records), 'ACCOUNTING_EVIDENCE_SCHEMA_INVALID')
starts = [i for i, record in enumerate(records) if record.get('$report_type') == 'SessionStart']
finishes = [i for i, record in enumerate(records) if record.get('$report_type') == 'SessionFinish']
require(len(starts) == len(finishes) == 1 and starts[0] < finishes[0]
and type(records[finishes[0]].get('exitstatus')) is int
and records[finishes[0]]['exitstatus'] == 0, 'ACCOUNTING_RUN_NOT_SUCCESSFUL')
stages, counts, nodes = {}, Counter(), set()
paths = {path.removeprefix('backend/') for path in source.files() if path.startswith('backend/tests/')}
collection_seen = False
for index, record in enumerate(records):
kind = record.get('$report_type')
require(kind in {'SessionStart', 'SessionFinish', 'CollectReport', 'TestReport', 'WarningMessage'},
'ACCOUNTING_EVIDENCE_SCHEMA_INVALID')
if kind not in {'CollectReport', 'TestReport'}:
continue
require(starts[0] < index < finishes[0], 'ACCOUNTING_SESSION_CONFLICT')
if kind == 'CollectReport':
collection_seen = True
require(record.get('outcome') == 'passed' and record.get('result') is None,
'ACCOUNTING_COLLECTION_CONFLICT')
continue
node, phase, outcome = (record.get(key) for key in ('nodeid', 'when', 'outcome'))
require(isinstance(node, str) and '::' in node and node.split('::')[0] in paths
and isinstance(phase, str) and phase in {'setup', 'call', 'teardown'}
and isinstance(outcome, str) and outcome in {'passed', 'skipped', 'failed'},
'ACCOUNTING_EVIDENCE_SCHEMA_INVALID')
require('wasxfail' not in record or isinstance(record['wasxfail'], str),
'ACCOUNTING_EVIDENCE_SCHEMA_INVALID')
require((node, phase) not in stages, 'ACCOUNTING_PHASE_CONFLICT', node_id=node, stage=phase)
require(outcome != 'failed', 'ACCOUNTING_RUN_NOT_SUCCESSFUL', node_id=node, stage=phase)
previous = [p for p in ('setup', 'call', 'teardown') if (node, p) in stages]
require((phase == 'setup' and not previous) or (phase == 'call' and previous == ['setup']
and stages[node, 'setup'][0] == 'passed') or (phase == 'teardown'
and (previous == ['setup', 'call'] or previous == ['setup']
and stages[node, 'setup'][0] == 'skipped')), 'ACCOUNTING_PHASE_CONFLICT', node_id=node)
stages[node, phase] = (outcome, 'wasxfail' in record)
counts[phase + ':' + outcome] += 1
nodes.add(node)
require(collection_seen and len(nodes) == int(collected[0]), 'ACCOUNTING_COLLECTION_CONFLICT')
for node in nodes:
require((node, 'setup') in stages and stages.get((node, 'teardown'), (None,))[0] == 'passed'
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)
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 = {reference(ref)[0]: None for ref in refs}
for path in symbols:
symbols[path] = imported_symbols(source, path)
joined = 0
for ref in sorted(refs):
path, symbol, parameter = reference(ref)
require(symbol in symbols[path], 'ACCOUNTING_REF_MISSING', ref=ref)
require(symbols[path].count(symbol) == 1, 'ACCOUNTING_SOURCE_AMBIGUOUS', ref=ref)
base = node_base(path, symbol)
matches = sorted(node for node in nodes if node == base + parameter) if parameter else sorted(
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)
parts = base.split('::')
key = ('.'.join([parts[0].removesuffix('.py').replace('/', '.'), *parts[1:-1]]),
parts[-1] + node[len(base):])
require(junit[key], 'ACCOUNTING_REF_NOT_PASSED', ref=ref, node_id=node, stage='junit')
joined += 1
return {'producer': 'standard-pytest', 'commit': source.commit, 'suite_scope': 'backend',
'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),
'collected_skip_reports': counts['setup:skipped'] + counts['call:skipped'],
'collected_xfail_reports': sum(wasxfail for _, wasxfail in stages.values()),
'evidence_sha256': digests, 'withdrawal_approval_inferred': False}
# #endregion Tooling.DashboardTestingAccounting.Standard
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--producer', required=True, choices=('standard-pytest', 'historical-launcher'))
parser.add_argument('--commit', required=True)
parser.add_argument('--suite-scope', required=True, choices=('backend', 'dashboard'))
parser.add_argument('--evidence-dir', required=True, type=Path)
for name in ('summary', 'nodes', 'molecular', 'junit', 'reportlog', 'stdout', 'process-exit', 'provenance'):
parser.add_argument('--' + name + '-sha256')
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)
if args.producer == 'standard-pytest':
require(args.suite_scope == 'backend', 'ACCOUNTING_SCOPE_INVALID')
mapping = {'reportlog': 'reportlog.jsonl', 'junit': 'junit.xml', 'stdout': 'stdout.txt',
'process_exit': 'process-exit.txt', 'provenance': 'provenance.json'}
else:
mapping = {'summary': 'summary.json', 'nodes': 'nodes.json', 'molecular': 'molecular.jsonl', 'junit': 'junit.xml'}
require(all(getattr(args, name + '_sha256') for name in mapping), 'ACCOUNTING_DIGEST_INVALID')
require(all(not value for name, value in vars(args).items()
if name.endswith('_sha256') and name.removesuffix('_sha256') not in mapping),
'ACCOUNTING_PRODUCER_INVALID')
digests = {filename: getattr(args, name + '_sha256') for name, filename in mapping.items()}
if args.producer == 'standard-pytest':
result = validate_standard(source, args.evidence_dir, digests)
else:
result = validate(source, args.evidence_dir, digests, suite_scope=args.suite_scope)
result['producer'] = 'historical-launcher-diagnostic-only'
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