fix(verification): bind accounting to complete scoped sessions

This commit is contained in:
2026-10-11 19:25:47 +03:00
parent c0d561afb5
commit 5cb146d488
5 changed files with 368 additions and 29 deletions

View File

@@ -17,6 +17,7 @@ tool = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(tool)
COMMIT = '7' * 40
SESSION = 'a' * 32
REF = 'backend/tests/services/dashboard_testing/test_current.py::test_current'
CLASS_REF = 'backend/tests/services/dashboard_testing/test_current.py::TestOwner.test_current'
OLD = 'services/dashboard_testing/test_removed.py::test_old'
@@ -74,29 +75,41 @@ class LiteralSource:
@pytest.fixture
def wire(tmp_path):
events = []
events = [
{'src':tool.OWNER, 'marker':'REASON', 'intent':'Dispatch explicitly scoped frozen suite',
'payload':{'verification_session_id':SESSION, 'suite_scope':'dashboard', 'target_count':2}},
{'src':tool.OWNER, 'marker':'REFLECT', 'intent':'Frozen suite collection observed',
'payload':{'verification_session_id':SESSION, 'suite_scope':'dashboard', 'target_count':2, 'collected':4}},
]
for index, node in enumerate(NODES, 1):
trace = f'{index:032x}'
events.append({'src':'Tooling.VerifyDashboardTestingCurrent', 'marker':'REASON',
'intent':'Run frozen suite node', 'trace_id':trace, 'payload':{'node_id':node}})
'intent':'Run frozen suite node', 'trace_id':trace, 'payload':{'verification_session_id':SESSION,'node_id':node}})
for phase in ('setup', 'call', 'teardown'):
events.append({'src':'Tooling.VerifyDashboardTestingCurrent', 'marker':'REFLECT',
'intent':'Frozen suite node stage observed', 'trace_id':trace,
'payload':{'node_id':node, 'stage':phase, 'outcome':'passed', 'wasxfail':False}})
'payload':{'verification_session_id':SESSION,'node_id':node, 'stage':phase, 'outcome':'passed', 'wasxfail':False}})
junit = ('<testsuites><testsuite tests="4" failures="0" errors="0" skipped="0">'
'<testcase classname="tests.services.dashboard_testing.test_current" name="test_current[alpha]"/>'
'<testcase classname="tests.services.dashboard_testing.test_current" name="test_current[beta]"/>'
'<testcase classname="tests.services.dashboard_testing.test_current.TestOwner" name="test_current"/>'
'<testcase classname="tests.api.test_current" name="test_api"/>'
'</testsuite></testsuites>')
return SimpleNamespace(source=LiteralSource(), events=events, nodes=list(NODES), junit=junit,
summary={'commit':COMMIT, 'pytest_exit_code':0, 'collected':4, 'private_failure_diagnostics':0},
evidence=tmp_path)
capacity = {'commit':COMMIT,'verification_session_id':SESSION,'consistent':True,'read_only':True,
'isolation':'REPEATABLE READ','database_head':'0039_baseline_catalog_postgresql'}
return SimpleNamespace(source=LiteralSource(), events=events, nodes=list(NODES), junit=junit, scope='dashboard',
summary={'commit':COMMIT, 'verification_session_id':SESSION,'completed':True,
'suite_scope':'dashboard','targets':['tests/services/dashboard_testing','tests/api/test_current.py'],
'pytest_exit_code':0, 'collected':4, 'private_failure_diagnostics':0,
'capacity_consistent':True,'capacity_initial':{**capacity,'phase':'initial'},
'capacity_final':{**capacity,'phase':'final'}}, evidence=tmp_path)
def persist(wire):
counts = Counter(event['payload']['stage'] + ':' + event['payload']['outcome']
for event in wire.events if event['marker'] == 'REFLECT')
for event in wire.events if event.get('src') == tool.OWNER
and event.get('intent') == 'Frozen suite node stage observed'
and event['payload'].get('verification_session_id') == SESSION)
data = {'summary.json':json.dumps({**wire.summary, 'outcomes':dict(counts)}).encode(),
'nodes.json':json.dumps(wire.nodes).encode(), 'junit.xml':wire.junit.encode(),
'molecular.jsonl':('\n'.join(json.dumps(event) for event in wire.events) + '\n').encode()}
@@ -106,7 +119,8 @@ def persist(wire):
def validate(wire, digests=None):
return tool.validate(wire.source, wire.evidence, digests or persist(wire), expected_keys=3, expected_refs=2)
return tool.validate(wire.source, wire.evidence, digests or persist(wire), suite_scope=wire.scope,
expected_keys=3, expected_refs=2)
def test_exact_chronological_ledger_resolves_class_and_all_parameters(wire):
@@ -134,6 +148,7 @@ def test_missing_or_ambiguous_current_symbol_is_typed_without_importing(wire, mu
def test_parameter_cannot_disappear_from_collected_manifest(wire):
wire.nodes.remove(NODES[1])
wire.summary['collected'] = 3
wire.events[1]['payload']['collected'] = 3
with pytest.raises(tool.AccountingError, match='^ACCOUNTING_EVIDENCE_CONFLICT$'):
validate(wire)
@@ -144,7 +159,7 @@ def test_phase_and_parameter_negatives_never_hide_behind_green_summary(wire, mut
target = next(e for e in wire.events if e['payload'].get('node_id') == NODES[1]
and e['payload'].get('stage') == ('teardown' if mutation == 'missing_teardown' else 'call'))
if mutation == 'missing_parameter_reports':
wire.events = [e for e in wire.events if e['marker'] != 'REFLECT' or e['payload']['node_id'] != NODES[1]]
wire.events = [e for e in wire.events if e['marker'] != 'REFLECT' or e['payload'].get('node_id') != NODES[1]]
elif mutation == 'missing_teardown':
wire.events.remove(target)
elif mutation == 'duplicate_phase':
@@ -263,7 +278,7 @@ def test_consistent_parameter_omission_cannot_match_independently_reviewed_manif
reviewed_digests = persist(wire)
wire.nodes.remove(NODES[1])
wire.summary['collected'] = 3
wire.events = [event for event in wire.events if event['payload']['node_id'] != NODES[1]]
wire.events = [event for event in wire.events if event['payload'].get('node_id') != NODES[1]]
wire.junit = wire.junit.replace('tests="4"', 'tests="3"').replace(
'<testcase classname="tests.services.dashboard_testing.test_current" name="test_current[beta]"/>', '')
persist(wire)
@@ -295,4 +310,216 @@ def test_xfail_boolean_is_present_in_actual_launcher_stage_projection():
expression = ast.Expression(payload.values[position])
for authored, expected in [(SimpleNamespace(), False), (SimpleNamespace(wasxfail='PRIVATE_REASON'), True)]:
assert eval(compile(expression, '<owned-stage-projection>', 'eval'), {'report':authored}) is expected
def _declare_backend(wire):
wire.scope = wire.summary['suite_scope'] = 'backend'
wire.summary['targets'] = ['tests']
for event in wire.events[:2]:
event['payload'].update(suite_scope='backend', target_count=1)
# #region Test.DashboardTestingAccounting.Backend [C:2] [TYPE Function]
# @TEST_INVARIANT Trusted backend collection includes generated parameters and inherited tests without equating the inventory to AST declarations.
def test_backend_admits_actual_dynamic_parameters_and_inherited_nodes(wire):
_declare_backend(wire)
path = 'backend/tests/test_dynamic.py'
wire.source.values[path] = b'''class SharedChecks:
def test_inherited(self): pass
class TestDerived(SharedChecks): pass
def test_generated(request): pass
def pytest_generate_tests(metafunc): pass
'''
extra = ['tests/test_dynamic.py::TestDerived::test_inherited',
'tests/test_dynamic.py::test_generated[left]', 'tests/test_dynamic.py::test_generated[right]']
for index, node in enumerate(extra, 10):
wire.nodes.append(node)
wire.events.append({'src':tool.OWNER,'marker':'REASON','intent':'Run frozen suite node',
'trace_id':f'{index:032x}','payload':{'verification_session_id':SESSION,'node_id':node}})
for phase in ('setup','call','teardown'):
wire.events.append({'src':tool.OWNER,'marker':'REFLECT','intent':'Frozen suite node stage observed',
'trace_id':f'{index:032x}','payload':{'verification_session_id':SESSION,
'node_id':node,'stage':phase,'outcome':'passed','wasxfail':False}})
wire.summary['collected'] = wire.events[1]['payload']['collected'] = 7
wire.junit = wire.junit.replace('tests="4"','tests="7"').replace('</testsuite>',
'<testcase classname="tests.test_dynamic.TestDerived" name="test_inherited"/>'
'<testcase classname="tests.test_dynamic" name="test_generated[left]"/>'
'<testcase classname="tests.test_dynamic" name="test_generated[right]"/></testsuite>')
result = validate(wire)
assert result['suite_scope'] == 'backend' and result['collected'] == 7
assert result['conserving_refs'] == 2 and result['reference_parameter_joins'] == 3
# #endregion Test.DashboardTestingAccounting.Backend
# #region Test.DashboardTestingAccounting.Completion [C:2] [TYPE Function]
# @TEST_INVARIANT A nominal pytest exit0 never overrides a timeout, incomplete current summary or inconsistent capacity.
@pytest.mark.parametrize('mutation', ['missing_completed','false_completed','integer_completed',
'nonzero_attempt','boolean_attempt','capacity_false','capacity_error','final_capacity_foreign_session',
'initial_capacity_not_readonly','short_head_alias','watchdog_timeout','watchdog_process_failure','capacity_failure_event'])
def test_current_completion_and_timeout_fail_closed_even_with_pytest_zero(wire, mutation):
if mutation == 'missing_completed':
del wire.summary['completed']
elif mutation in {'false_completed','integer_completed'}:
wire.summary['completed'] = False if mutation == 'false_completed' else 1
elif mutation in {'nonzero_attempt','boolean_attempt'}:
wire.summary['attempt_exit_code'] = 137 if mutation == 'nonzero_attempt' else False
elif mutation == 'capacity_false':
wire.summary['capacity_consistent'] = False
elif mutation == 'capacity_error':
wire.summary['capacity_error_code'] = 'FINAL_CAPACITY_FINAL_STATE_INVALID'
elif mutation == 'final_capacity_foreign_session':
wire.summary['capacity_final']['verification_session_id'] = 'b'*32
elif mutation == 'initial_capacity_not_readonly':
wire.summary['capacity_initial']['read_only'] = False
elif mutation == 'short_head_alias':
wire.summary['capacity_final']['database_head'] = '0039'
elif mutation == 'capacity_failure_event':
wire.events.append({'src':tool.OWNER + '.CapacityCheckpoint','marker':'EXPLORE',
'error_code':'FINAL_CAPACITY_FINAL_STATE_INVALID',
'payload':{'verification_session_id':SESSION,'consistent':False}})
else:
wire.events.append({'src':'Tooling.PytestWatchdog','marker':'EXPLORE',
'error_code':'FINAL_SUITE_OR_TEST_TIMEOUT' if mutation == 'watchdog_timeout' else 'FINAL_WATCHDOG_PROCESS_FAILED',
'payload':{'verification_session_id':SESSION}})
with pytest.raises(tool.AccountingError) as failure:
validate(wire)
assert failure.value.code == ('ACCOUNTING_CAPACITY_CONFLICT' if mutation in {
'final_capacity_foreign_session','initial_capacity_not_readonly','short_head_alias'} else 'ACCOUNTING_RUN_NOT_SUCCESSFUL')
assert wire.summary['pytest_exit_code'] == 0
# #endregion Test.DashboardTestingAccounting.Completion
# #region Test.DashboardTestingAccounting.Declarations [C:2] [TYPE Function]
# @TEST_INVARIANT Explicit expected scope, exact targets and unique ordered declarations cannot be inferred from green stage totals.
@pytest.mark.parametrize('mutation', ['wrong_scope','wrong_targets','missing_dispatch','duplicate_dispatch',
'missing_collection','duplicate_collection','reordered','wrong_target_count','wrong_collection_count',
'wrong_collection_scope','missing_session','malformed_session','foreign_session','summary_session'])
def test_scope_and_session_declarations_are_mandatory(wire, mutation):
if mutation == 'wrong_scope':
wire.summary['suite_scope'] = 'backend'
elif mutation == 'wrong_targets':
wire.summary['targets'] = ['tests']
elif mutation in {'missing_dispatch','missing_collection'}:
wire.events.pop(0 if mutation == 'missing_dispatch' else 1)
elif mutation in {'duplicate_dispatch','duplicate_collection'}:
wire.events.insert(0,wire.events[0 if mutation == 'duplicate_dispatch' else 1])
elif mutation == 'reordered':
wire.events[0],wire.events[1] = wire.events[1],wire.events[0]
elif mutation == 'wrong_target_count':
wire.events[0]['payload']['target_count'] = 1
elif mutation == 'wrong_collection_count':
wire.events[1]['payload']['collected'] = 3
elif mutation == 'wrong_collection_scope':
wire.events[1]['payload']['suite_scope'] = 'backend'
elif mutation == 'summary_session':
wire.summary['verification_session_id'] = 'PRIVATE_INVALID_SESSION'
else:
payload = wire.events[-1]['payload']
if mutation == 'missing_session':
del payload['verification_session_id']
else:
payload['verification_session_id'] = 'PRIVATE_INVALID_SESSION' if mutation == 'malformed_session' else 'b'*32
with pytest.raises(tool.AccountingError) as failure:
validate(wire)
expected = 'ACCOUNTING_SCOPE_DECLARATION_INVALID'
if mutation in {'wrong_scope','wrong_targets'}:
expected = 'ACCOUNTING_WHOLE_SCOPE_CONFLICT'
elif mutation in {'missing_session','malformed_session','summary_session'}:
expected = 'ACCOUNTING_SESSION_INVALID'
assert failure.value.code == expected
assert 'PRIVATE_INVALID_SESSION' not in str(failure.value)
# #endregion Test.DashboardTestingAccounting.Declarations
# #region Test.DashboardTestingAccounting.ForeignSession [C:2] [TYPE Function]
# @TEST_INVARIANT Declared foreign verification phases never fill a missing current phase; sessionless business events never enter the join.
@pytest.mark.parametrize('missing_current', [False,True])
def test_explicit_foreign_session_is_separated_and_cannot_supply_current_phase(wire, missing_current):
import copy
nested = copy.deepcopy(wire.events)
for event in nested:
event['payload']['verification_session_id'] = 'b'*32
wire.events.extend(nested)
wire.events.append({'src':'BaselineEngine.BusinessOwner','marker':'REFLECT',
'intent':'Frozen suite node stage observed','payload':{'node_id':NODES[0],
'stage':'call','outcome':'failed'}})
if missing_current:
wire.events = [event for event in wire.events if not (event['payload'].get('verification_session_id') == SESSION
and event['payload'].get('node_id') == NODES[0] and event['payload'].get('stage') == 'call')]
with pytest.raises(tool.AccountingError):
validate(wire)
else:
result = validate(wire)
assert result['separated_foreign_verification_sessions'] == 1
assert result['reference_parameter_joins'] == 3
# #endregion Test.DashboardTestingAccounting.ForeignSession
# #region Test.DashboardTestingAccounting.DefaultSkip [C:2] [TYPE Function]
# @TEST_INVARIANT An unreferenced default integration skip is retained, while any skipped conserving parameter refuses.
def test_unreferenced_default_skip_does_not_claim_a_preserving_test_pass(wire):
node = NODES[3]
wire.events = [event for event in wire.events if not (event['payload'].get('node_id') == node
and event['payload'].get('stage') == 'call')]
next(event for event in wire.events if event['payload'].get('node_id') == node
and event['payload'].get('stage') == 'setup')['payload']['outcome'] = 'skipped'
wire.junit = wire.junit.replace('skipped="0"','skipped="1"').replace('name="test_api"/>',
'name="test_api"><skipped message="FINAL_NODE_SKIPPED"/></testcase>')
result = validate(wire)
assert result['conserving_refs'] == 2 and result['reference_parameter_joins'] == 3
assert result['collected'] == 4 and result['collected_skip_reports'] == 1
# #endregion Test.DashboardTestingAccounting.DefaultSkip
# #region Test.DashboardTestingAccounting.ActualProducer [C:2] [TYPE Function]
# @TEST_INVARIANT Actual installed pytest and the current strict emitter produce explicit completed/session/scope evidence accepted by the real accounting join without SQL.
def test_real_strict_backend_producer_joins_dynamic_and_inherited_collection(wire, monkeypatch, tmp_path):
spec = importlib.util.spec_from_file_location('accounting_strict', ROOT / 'scripts/verify_dashboard_testing_current.py')
launcher = importlib.util.module_from_spec(spec)
spec.loader.exec_module(launcher)
_declare_backend(wire)
wire.source.values['backend/tests/api/test_accounting_api.py'] = wire.source.values.pop('backend/tests/api/test_current.py')
wire.source.values['scripts/verify_dashboard_testing_current.py'] = b"API_FILES = 'accounting_api'.split()\n"
wire.source.values['backend/tests/services/dashboard_testing/test_current.py'] = b'''import pytest
@pytest.mark.parametrize('selection', ['alpha', 'beta'])
def test_current(selection): assert selection in {'alpha', 'beta'}
class TestOwner:
def test_current(self): assert 2 + 3 == 5
'''
wire.source.values['backend/tests/test_dynamic.py'] = b'''class SharedChecks:
def test_inherited(self): assert 8 == 8
class TestDerived(SharedChecks): pass
def test_generated(selection): assert selection in {'left', 'right'}
def pytest_generate_tests(metafunc):
if 'selection' in metafunc.fixturenames:
metafunc.parametrize('selection', ['left', 'right'])
'''
project = tmp_path / 'actual-project'
for name, raw in wire.source.values.items():
if name.startswith('backend/tests/'):
path = project / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(raw)
(project / 'backend/pytest.ini').write_text('[pytest]\n')
evidence = tmp_path / 'actual-evidence'
evidence.mkdir(mode=0o700)
monkeypatch.setattr(launcher, 'check_freeze', lambda *unused: None)
monkeypatch.setenv('PYTEST_DISABLE_PLUGIN_AUTOLOAD','1')
diagnostics = launcher.PrivateFailures(evidence)
try:
with launcher.private_output():
code = launcher.run_suite(project, evidence, COMMIT, launcher.SafeLogs([]), diagnostics,
suite_scope='backend', verification_session_id=SESSION)
finally:
diagnostics.close()
actual = json.loads((evidence / 'summary.json').read_text())
assert code == 0 and actual['completed'] is True and actual['collected'] == 7
summary = {**wire.summary, **actual}
(evidence / 'summary.json').write_text(json.dumps(summary))
digests = {name:sha256((evidence / name).read_bytes()).hexdigest()
for name in ('summary.json','nodes.json','molecular.jsonl','junit.xml')}
result = tool.validate(wire.source, evidence, digests, suite_scope='backend', expected_keys=3, expected_refs=2)
assert result['collected'] == 7 and result['reference_parameter_joins'] == 3
assert result['verification_session_id'] == SESSION and result['collected_skip_reports'] == 0
# #endregion Test.DashboardTestingAccounting.ActualProducer
# #endregion Test.DashboardTestingAccounting

View File

@@ -210,13 +210,27 @@ def imported_symbols(source, path, trail=()):
return symbols
def source_nodes(source):
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')
api = {'backend/tests/api/test_' + name + '.py' for name in value.func.value.value.split()}
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)}
@@ -237,13 +251,99 @@ def digest_bytes(path, expected):
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
# #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') == '0039_baseline_catalog_postgresql',
'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')
@@ -307,7 +407,7 @@ def junit_cases(raw, nodes, counts):
# #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):
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}
@@ -320,16 +420,18 @@ def validate(source, evidence, digests, *, expected_keys=347, expected_refs=275)
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')
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')
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))
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:
@@ -352,9 +454,12 @@ def validate(source, evidence, digests, *, expected_keys=347, expected_refs=275)
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(),
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
@@ -363,6 +468,7 @@ def validate(source, evidence, digests, *, expected_keys=347, expected_refs=275)
def main():
parser = argparse.ArgumentParser(description=__doc__)
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'):
parser.add_argument('--' + name + '-sha256', required=True)
@@ -374,7 +480,7 @@ def main():
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)
result = validate(source, args.evidence_dir, digests, suite_scope=args.suite_scope)
marker, code, facts, status = 'REFLECT', None, result, 0
except AccountingError as exc:
marker, code, facts, status = 'EXPLORE', exc.code, exc.facts, 2

View File

@@ -652,7 +652,7 @@ def run_suite(root: Path, evidence: Path, commit: str, safe: SafeLogs, diagnosti
finally:
os.chdir(previous)
check_freeze(root, commit)
summary = {'commit': commit, 'verification_session_id':session_id, 'pytest_exit_code': code, 'collected': len(nodes),
summary = {'commit': commit, 'verification_session_id':session_id, 'completed':True, 'pytest_exit_code': code, 'collected': len(nodes),
'suite_scope':suite_scope, 'targets':selectors,
'outcomes': dict(counts), 'recipe': RECIPE, 'raw_output_retained': False,
'private_failure_diagnostics': diagnostics.index}

View File

@@ -1274,4 +1274,10 @@ Before editing the active preview test, its complete decorated baseline949 body
Actual reference-preview-classes passed both current nodes/all6phases/private0 with unchanged frozen source/launcher4124cd4; RR READ ONLY capacity stayed1quota/0leases/0active/0charged consistent. Actual wire retains identity-index facts and CONTEXT_NOT_PINNED for unpinned chart56, not silently empty or numeric truth. Summary4d0c2e109e8fc0560de4744a069669bee719cd5b799e87ed553576c26ea65c3f/wireb2f889b2560506e0c4c8909f13ce8d641f15f0e6bc9cbf933cbe1c518575d51a/JUnit942cd13ef08f26c36efc1b196cb6e8049513d449b5bbfd3940976aedbb0cbe77; causal-receipte83fa386e353807fc53a8a2d77e2bc888c0395fb4737301596336a28d4c94dc6. Curate independently matched exact archived bytes, all source/artifact hashes and node/trace joins. Original120 adds owner disposition26 only; its current guard is not double-counted. Original121 adds targeted success102. Immutable224 join leaves96/62; no fresh fullbackend/347 acceptance, N120 unchanged. Default Ruff/compile/diff PASS.
### 2026-10-11 — backend/session accounting refuses partial or stale successful evidence
The existing validator now requires explicit backend/dashboard scope and exact same-commit targets, normal completed=True, trusted verification-session declarations, phase/JUnit joins, externally reviewed four original digests and consistent capacity facts. Committed275 source references remain separate from the actual unfiltered collection inventory; every actually collected referenced parameter requires three passed phases/wasxfailFalse. Foreign declared sessions cannot fill missing current phases; unknown/unscoped verification evidence and same-session watchdog/partial/capacity failures refuse. Strict producer changes only one normal summary field, completed=True; no observed OS-exit/argv claim or legacy summary fallback.
Verify's first64 SQL-free proof used a misleading synthetic short database head0039. Curate caught the mismatch with actual producer0039_baseline_catalog_postgresql; exact full-literal admission and explicit short-alias ACCOUNTING_CAPACITY_CONFLICT negative corrected it. Final65 SQL-free guards passed, including actual strict mini7-node dynamic/inherited collection/parser/JUnit/session integration and existing stale-PASS watchdog/privacy guards. Mini capacity is synthetic, not PostgreSQL evidence. All14 original test-oracle AST sets unchanged. Final validatorSHAf64fffd69e753c5956fc5310caf76df6664a5b260eb412b8be5be8e7f5fee76b/testSHAbf3c7b18474633a1e39c11d6f65d7da95e20c507bab51e44e06684ff4210f48f/producerSHA4124cd4df6b8c9462f8c47d884c4a5ec209a98331f9e99d6f1be6c224ab47bd3 independently matched; Curate revised source YES, default Ruff/compile/diff PASS. A/B/C52 receipts used the same unchanged producer4124 bytes. No fullsuite or automatic347 acceptance performed; N120/96remaining/62classes unchanged. No accounting-document expansion.
## @} Stage2.ChartTypeStabilizationJournal20261010

View File

@@ -35,8 +35,8 @@
- **Готово:** каталог PostgreSQL, разрешённый сброс и миграции с сохранением защищённых данных; повторять миграции не нужно. Запись операций провайдера, конкурентные переходы и рекомендательная VLM-оценка проверены целевыми тестами. Исправлены два тестовых kind черновика и сохранение валидного чарта в generic detail; строгая проверка данных capture сохранена.
- **Последний полный backend:** на94921069 собрано14690 узлов:14137 прошли,210 упали при выполнении,14 при подготовке,329 пропущены; все этапы завершения прошли, exit1. Исходные224 причины сохранены. Квоты согласованы до и после, активных аренд нет. Целевые исправления не заменяют новый полный green; прежние75b dashboard+29API и1eed collection-stop — отдельная история.
- **Решением владельца из мержа выведены 26 из 224 падений:14 положительных,11 будущих/смешанных SDK-transform случаев и числовая SDK-ветка preview; живые защиты сохраняются. Архив14 функций и смешанного preview завершён; ещё11 архивов и проверки явного отказа в работе.** Текущий типизированный unavailable этих возможностей не дефект; проверки должны доказывать явный отказ, отсутствие PASS и видимость причины, без skip/xfail. Список347 не расширяется.
- **Остальные причины:** после26 решений о границах мержа и102 целевых успешных проверок остаются96 исходных случаев в62 группах. Восемь проверок inheritance/profile явно задают ревизии; пять проверок моделей задают обязательные метаданные. Две проверки preview сохраняют выбор чарта/метрики и отказ при неподдерживаемом datasource; числа preview отложены, текущий ответ требует capture и не вызывает SDK. Крупнейшие группы: события обслуживания5, подготовка верификации5, REST/MCP-паритет ошибок5. Шесть исходных проверок logger прошли через настоящий инструмент запуска; таймауты ограничивают тесты. Два старых запуска сейчас завершились нормально, причина исторических зависаний неизвестна. Полного green нет; инструмент учёта дорабатывается до итогового freeze.
- **Далее:** исправить оставшиеся классы и инструмент учёта, затем полный backend со штатными integration skips и Ruff репозитория на чистом SHA. Выполнить API-чарт8: PASS→разрешённая когерентная мутация→FAIL с названной ячейкой→finally восстановление→PASS с той же ревизией. До мутации подтвердить сохранённый evaluation_mode=advisory; приложить текущий снимок и рекомендательный VLM, без эталона.
- **Остальные причины:** после26 решений о границах мержа и102 целевых успешных проверок остаются96 исходных случаев в62 группах. Восемь проверок inheritance/profile явно задают ревизии; пять проверок моделей задают обязательные метаданные. Две проверки preview сохраняют выбор чарта/метрики и отказ при неподдерживаемом datasource; числа preview отложены, текущий ответ требует capture и не вызывает SDK. Крупнейшие группы: события обслуживания5, подготовка верификации5, REST/MCP-паритет ошибок5. Шесть исходных проверок logger прошли через настоящий инструмент запуска; таймауты ограничивают тесты. Два старых запуска сейчас завершились нормально, причина исторических зависаний неизвестна. Полного green нет; проверенный инструмент учёта ждёт итоговых результатов.
- **Далее:** исправить оставшиеся классы, затем полный backend со штатными integration skips и Ruff репозитория на чистом SHA. Инструмент учёта проверен отдельно; автоматическое принятие347 ещё требует итоговых полных результатов того же SHA. Выполнить API-чарт8: PASS→разрешённая когерентная мутация→FAIL с названной ячейкой→finally восстановление→PASS с той же ревизией. До мутации подтвердить сохранённый evaluation_mode=advisory; приложить текущий снимок и рекомендательный VLM, без эталона.
D17 не блокирует мерж. Отклонённый PNGd8c01a0d не переснимать, не принимать и не публиковать; вопрос о новом PNG снят. После мержа: tolerance→canonical hash→VLM вне verdict→SDK→один сброс лаборатории→Stage2a→transforms→Stage2b/c. Текущий pin чарта8 не пересоздавать. Подробности — в [журнале](2026-10-10-chart-type-stabilization-journal.md).