Files
ss-tools/scripts/verify_dashboard_testing_current.py

743 lines
40 KiB
Python

#!/usr/bin/env python3
# #region Tooling.VerifyDashboardTestingCurrent [C:3] [TYPE Module] [SEMANTICS verification,postgresql,pytest,freeze]
# @BRIEF Run one explicitly selected frozen dashboard/API or whole-backend suite against the owned, already migrated PostgreSQL database.
# @PRE Root has authorized the final functional freeze and Verify has completed both production migration paths. This launcher performs neither operation.
# @POST One node manifest, per-node Molecular JSONL, safe JUnit and summary bind the attempt to an unchanged commit.
# @INVARIANT No migration, database creation, source copy, integration container, selector fallback or repeated pytest invocation.
# @RATIONALE The final recipe owns database preparation; this executable owns only one suite dispatch and privacy-preserving evidence.
# @REJECTED Inheriting a development DSN or printing exception/SQL representations would test another authority or disclose private configuration.
from __future__ import annotations
import argparse
import ast
import base64
from collections import Counter
from copy import copy
from contextlib import contextmanager, redirect_stderr, redirect_stdout
from contextvars import copy_context
from hashlib import sha256
import json
import logging
import os
from pathlib import Path
import re
import secrets
import stat
import subprocess
import sys
import threading
import traceback
API_FILES = (
'catalog_publications_api dashboard_scenarios dashboard_testing '
'dashboard_testing_approval_guards dashboard_testing_closed_period dashboard_testing_feature037 '
'dashboard_testing_inheritance dashboard_testing_openapi dashboard_testing_openapi_yaml '
'dashboard_testing_verification_api dashboard_testing_verification_persistence '
'mcp_parity_baseline_037 reference_discovery_api reference_selection_api scenario_analytics_api '
'scenario_artifact_content_api scenario_artifact_routes scenario_automation_api scenario_editor_routes '
'scenario_live_bindings_api scenario_registry scenario_routes scenario_run_center scenario_runs_api '
'scenario_wire_routes structure_snapshot_routes git_repo_lifecycle_deploy_routes '
'git_repo_lifecycle_deployment_routes git_release_routes'
).split()
HEAD = '0039_baseline_catalog_postgresql'
RECIPE = 'artifacts/stage0/pg-catalog-verify-20261010/final-single-run-recipe.md'
OWNERS = ('backend', 'frontend', 'scripts', 'specs', '.agents', 'pyproject.toml', 'pytest.ini')
def refuse(code: str):
raise RuntimeError(code) from None
# #region Tooling.VerifyDashboardTestingCurrent.SuiteScope [C:2] [TYPE Function]
# @PRE Scope is an explicit closed choice, never an arbitrary pytest selector or inferred fallback.
# @POST Backend targets the complete tests directory; dashboard retains its exact service and 29 API targets.
def suite_selectors(scope: str) -> list[str]:
if scope == 'backend':
return ['tests']
if scope == 'dashboard':
return ['tests/services/dashboard_testing'] + ['tests/api/test_' + n + '.py' for n in API_FILES]
refuse('FINAL_SUITE_SCOPE_INVALID')
# #endregion Tooling.VerifyDashboardTestingCurrent.SuiteScope
# #region Tooling.VerifyDashboardTestingCurrent.Freeze [C:2] [TYPE Function]
# @POST Any relevant tracked change, untracked source or changed HEAD refuses; ignored evidence is outside source identity.
def check_freeze(root: Path, commit: str):
def git(*args):
result = subprocess.run(['git', *args], cwd=root, capture_output=True, text=True)
if result.returncode:
refuse('FINAL_SOURCE_GIT_UNAVAILABLE')
return result.stdout.strip()
if not re.fullmatch(r'[0-9a-f]{40}', commit) or git('rev-parse', 'HEAD') != commit:
refuse('FINAL_SOURCE_COMMIT_CONFLICT')
if git('status', '--porcelain', '--untracked-files=all', '--', *OWNERS):
refuse('FINAL_SOURCE_OWNERS_DIRTY')
ignored = git('ls-files', '--others', '--ignored', '--exclude-standard', '--',
'backend/src', 'backend/tests', 'backend/alembic', 'scripts', 'frontend/src', 'specs')
if any(Path(p).suffix in {'.py', '.js', '.ts', '.svelte', '.json', '.yaml', '.yml'}
for p in ignored.splitlines()):
refuse('FINAL_SOURCE_IGNORED_IMPORTABLE')
versions = root / 'backend/alembic/versions'
assignments = {}
for path in versions.glob('*.py'):
values = {}
for node in ast.parse(path.read_text()).body:
if isinstance(node, ast.Assign) and isinstance(node.value, (ast.Constant, ast.Tuple)):
for target in node.targets:
if isinstance(target, ast.Name) and target.id in {'revision', 'down_revision'}:
values[target.id] = ast.literal_eval(node.value)
if 'revision' in values:
assignments[values['revision']] = values.get('down_revision')
if (assignments.get(HEAD) != '0038_maintenance_start_task_id'
or assignments.get('0038_maintenance_start_task_id') != '0037_visual_capture_hash_width'
or set(assignments) - {p for p in assignments.values() if isinstance(p, str)} != {HEAD}):
refuse('FINAL_MIGRATION_CHAIN_CONFLICT')
# #endregion Tooling.VerifyDashboardTestingCurrent.Freeze
# #region Tooling.VerifyDashboardTestingCurrent.Connection [C:2] [TYPE Function]
# @PRE expected_database is explicitly supplied; it is never inferred from a connection file or default DSN.
# @POST Only the exact requested owned loopback final database is admitted; configuration errors never include its contents.
def read_connection(path: Path, *, expected_database: str):
try:
if stat.S_IMODE(path.stat().st_mode) != 0o600:
refuse('FINAL_CONNECTION_FILE_MODE_INVALID')
config = json.loads(path.read_text())
valid = (isinstance(config, dict)
and all(isinstance(config.get(k), str) and config[k].strip()
for k in ('username', 'password', 'host', 'database'))
and type(config.get('port')) is int
and config['host'] == '127.0.0.1' and config['port'] == 15439
and expected_database in {'catalog_final_empty_20261010', 'catalog_full_current_20261011',
'catalog_backend_current_20261011'}
and config['database'] == expected_database)
except (OSError, ValueError, TypeError):
refuse('FINAL_CONNECTION_CONFIG_INVALID')
if not valid:
refuse('FINAL_CONNECTION_SCOPE_INVALID')
return config
# #endregion Tooling.VerifyDashboardTestingCurrent.Connection
# #region Tooling.VerifyDashboardTestingCurrent.CapacityRows [C:3] [TYPE Function]
# @POST Claimed units remain charged until a terminal status, including leases whose expiry timestamp has passed.
# @INVARIANT Only pair digests and accounting counts leave this boundary; no environment, provider or lease identity is published.
# @RATIONALE The allocator releases counters on status CAS, so a wall-clock expiry alone cannot remove a claimed charge.
# @REJECTED Repairing counters or requiring zero balanced foreign claims would conceal the observed initial/final state.
def capacity_rows(quotas, leases):
pairs, issues = {}, Counter()
for row in quotas:
pair = (row['environment_id'], row['workload_class'])
if pair in pairs:
issues['duplicate_quota'] += 1
pairs[pair] = {'active_units':row['active_units'], 'limit_units':row['limit_units'],
'charged_units':0, 'claimed_leases':0, 'terminal_leases':0, 'quota_present':True}
for row in leases:
pair = (row['environment_id'], row['workload_class'])
facts = pairs.setdefault(pair, {'active_units':None, 'limit_units':None,
'charged_units':0, 'claimed_leases':0, 'terminal_leases':0, 'quota_present':False})
_capacity_lease(facts, row, issues)
projected = [_capacity_pair(pair, facts, issues) for pair, facts in sorted(pairs.items())]
wire = json.dumps({'quotas':sorted(quotas, key=lambda r:json.dumps(r, sort_keys=True)),
'leases':sorted(leases, key=lambda r:json.dumps(r, sort_keys=True))}, sort_keys=True, separators=(',', ':'))
return {'consistent':not issues, 'quota_count':len(quotas), 'lease_count':len(leases),
'pair_count':len(pairs), 'pairs':projected, 'issues':dict(issues),
'active_units':sum(row['active_units'] for row in quotas if type(row['active_units']) is int),
'charged_units':sum(facts['charged_units'] for facts in pairs.values()),
'claimed_leases':sum(facts['claimed_leases'] for facts in pairs.values()),
'rows_sha256':sha256(wire.encode()).hexdigest()}
# #endregion Tooling.VerifyDashboardTestingCurrent.CapacityRows
# #region Tooling.VerifyDashboardTestingCurrent.CapacityLease [C:2] [TYPE Function]
# @POST Only the allocator's claimed state contributes requested units; unknown states never silently disappear.
def _capacity_lease(facts, row, issues):
units = row['requested_units']
if type(units) is not int or not 1 <= units <= 4:
issues['invalid_lease_units'] += 1
return
if row['status'] == 'claimed':
facts['charged_units'] += units
facts['claimed_leases'] += 1
elif row['status'] in {'released', 'expired', 'reconciled'}:
facts['terminal_leases'] += 1
else:
issues['unknown_lease_status'] += 1
# #endregion Tooling.VerifyDashboardTestingCurrent.CapacityLease
# #region Tooling.VerifyDashboardTestingCurrent.CapacityPair [C:2] [TYPE Function]
# @POST Missing charged quota, invalid counter bounds and unequal charged sums are explicit consistency failures.
def _capacity_pair(pair, facts, issues):
if not facts['quota_present']:
if facts['claimed_leases']:
issues['missing_charged_quota'] += 1
else:
active, limit = facts['active_units'], facts['limit_units']
if type(active) is not int or type(limit) is not int or not 0 <= active <= limit or limit <= 0:
issues['invalid_quota_units'] += 1
if active != facts['charged_units']:
issues['charged_units_mismatch'] += 1
return {'pair_sha256':sha256(json.dumps(pair, separators=(',', ':')).encode()).hexdigest(), **facts}
# #endregion Tooling.VerifyDashboardTestingCurrent.CapacityPair
# #region Tooling.VerifyDashboardTestingCurrent.CapacityCheckpoint [C:3] [TYPE Function]
# @PRE The exact owned database/head is read in one repeatable-read read-only snapshot.
# @POST Initial/final receipts and safe Molecular facts survive both consistency success and refusal; no repair is attempted.
def capacity_checkpoint(engine, evidence, commit, phase, database, *, verification_session_id):
from sqlalchemy import text
if phase not in {'initial', 'final'}:
refuse('FINAL_CAPACITY_PHASE_INVALID')
with engine.connect().execution_options(isolation_level='REPEATABLE READ') as connection:
connection.execute(text('SET TRANSACTION READ ONLY'))
if connection.execute(text('SELECT current_database()')).scalar_one() != database:
refuse('FINAL_DATABASE_SCOPE_CONFLICT')
if connection.execute(text('SELECT version_num FROM public.alembic_version')).scalars().all() != [HEAD]:
refuse('FINAL_DATABASE_HEAD_CONFLICT')
quotas = [dict(row) for row in connection.execute(text(
'SELECT environment_id, workload_class, active_units, limit_units FROM public.provider_capacity_quotas')).mappings()]
leases = [dict(row) for row in connection.execute(text(
'SELECT environment_id, workload_class, status, requested_units FROM public.provider_capacity_leases')).mappings()]
observed = capacity_rows(quotas, leases)
connection.rollback()
receipt = {'commit':commit, 'verification_session_id':verification_session_id,
'phase':phase, 'database_head':HEAD, 'read_only':True,
'isolation':'REPEATABLE READ', **observed}
wire = (json.dumps(receipt, sort_keys=True, indent=2) + '\n').encode()
with os.fdopen(os.open(evidence / f'capacity-{phase}.json', os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), 'wb') as handle:
handle.write(wire)
receipt['receipt_sha256'] = sha256(wire).hexdigest()
with VerificationEvents(evidence, SafeLogs([]), verification_session_id) as events:
events.emit('REFLECT' if observed['consistent'] else 'EXPLORE', 'Read-only capacity accounting checkpoint',
src='Tooling.VerifyDashboardTestingCurrent.CapacityCheckpoint',
claim='INVARIANT: quota counters equal all claimed lease units in one read-only snapshot',
error_code=None if observed['consistent'] else f'FINAL_CAPACITY_{phase.upper()}_STATE_INVALID',
payload={key:receipt[key] for key in ('phase', 'consistent', 'quota_count', 'lease_count', 'pair_count',
'active_units', 'charged_units', 'claimed_leases', 'issues', 'rows_sha256', 'receipt_sha256')})
return receipt
# #endregion Tooling.VerifyDashboardTestingCurrent.CapacityCheckpoint
# #region Tooling.VerifyDashboardTestingCurrent.CapacitySummary [C:2] [TYPE Function]
# @POST Actual pytest code remains distinct from overall attempt failure; initial/final baseline facts cannot be mistaken for a repair.
def retain_capacity_summary(evidence, commit, capacity, *, verification_session_id,
suite_scope=None, error_code=None, private_failure_count=0):
path = evidence / 'summary.json'
summary = json.loads(path.read_text()) if path.exists() else {
'commit':commit, 'pytest_exit_code':None, 'collected':0, 'outcomes':{}}
summary.update(verification_session_id=verification_session_id,
capacity_initial=capacity.get('initial'), capacity_final=capacity.get('final'),
capacity_consistent=all(capacity.get(phase, {}).get('consistent', False) for phase in ('initial', 'final')),
capacity_error_code=error_code,
private_failure_diagnostics=private_failure_count,
attempt_exit_code=2 if error_code else summary['pytest_exit_code'])
if suite_scope is not None:
summary.update(suite_scope=suite_scope, targets=suite_selectors(suite_scope))
if set(capacity) == {'initial', 'final'}:
summary['capacity_delta'] = {key:capacity['final'][key] - capacity['initial'][key]
for key in ('quota_count', 'lease_count', 'active_units', 'charged_units', 'claimed_leases')}
summary['capacity_outstanding_claims'] = capacity['final']['claimed_leases'] > 0
path.write_text(json.dumps(summary, indent=2) + '\n')
(evidence / 'suite.stdout').write_text(json.dumps(summary, sort_keys=True) + '\n')
# #endregion Tooling.VerifyDashboardTestingCurrent.CapacitySummary
@contextmanager
def private_output():
"""Drop both Python and native-driver console output; structured evidence remains."""
saved = [os.dup(fd) for fd in (1, 2)]
try:
with open(os.devnull, 'w') as sink:
os.dup2(sink.fileno(), 1)
os.dup2(sink.fileno(), 2)
with redirect_stdout(sink), redirect_stderr(sink):
yield
finally:
for fd, original in zip((1, 2), saved, strict=True):
os.dup2(original, fd)
os.close(original)
def safe_failure(excinfo):
"""Retain exception classification and stack locations, excluding repr/body/SQL."""
return json.dumps({'failure_type': excinfo.type.__name__, 'locations': [
{'path': str(entry.path), 'line': entry.lineno + 1} for entry in excinfo.traceback]}, sort_keys=True)
# #region Tooling.VerifyDashboardTestingCurrent.SkipReport [C:2] [TYPE Function]
# @POST A valid owned skip location keeps pytest's required tuple shape with a fixed public reason; malformed locations refuse.
def safe_skip_report(longrepr, root: Path):
if (not isinstance(longrepr, tuple) or len(longrepr) != 3
or not isinstance(longrepr[0], str) or not longrepr[0]
or type(longrepr[1]) is not int or longrepr[1] < 0
or not isinstance(longrepr[2], str)
or re.search(r'[\x00-\x1f]', longrepr[0])):
refuse('FINAL_SKIP_REPORT_INVALID')
location = Path(longrepr[0])
if location.is_absolute():
try:
location = location.relative_to(root)
except ValueError:
refuse('FINAL_SKIP_REPORT_LOCATION_INVALID')
if '..' in location.parts or location == Path('.'):
refuse('FINAL_SKIP_REPORT_LOCATION_INVALID')
return location.as_posix(), longrepr[1], 'FINAL_NODE_SKIPPED'
# #endregion Tooling.VerifyDashboardTestingCurrent.SkipReport
# #region Tooling.VerifyDashboardTestingCurrent.ReportPrivacy [C:2] [TYPE Function]
# @POST Public reports retain installed pytest/JUnit outcome shapes while private reasons and captured output are removed.
def sanitize_report(report, call, safe, root: Path):
if report.outcome not in {'passed', 'failed', 'skipped'}:
refuse('FINAL_REPORT_OUTCOME_INVALID')
report.sections = []
report.user_properties = [(safe.text(key), safe.value(value)) for key, value in report.user_properties]
if hasattr(report, 'wasxfail'):
if not isinstance(report.wasxfail, str):
refuse('FINAL_XFAIL_REPORT_INVALID')
report.wasxfail = 'FINAL_NODE_XFAIL'
if report.skipped and not hasattr(report, 'wasxfail'):
report.longrepr = safe_skip_report(report.longrepr, root)
elif report.failed and call.excinfo:
report.longrepr = safe_failure(call.excinfo)
elif report.longrepr:
report.longrepr = 'FINAL_NODE_' + report.outcome.upper()
# #endregion Tooling.VerifyDashboardTestingCurrent.ReportPrivacy
# #region Tooling.VerifyDashboardTestingCurrent.PrivateFailures [C:3] [TYPE Class]
# @PRE The evidence directory belongs to this new attempt; diagnostics are never written beside a foreign existing attempt.
# @POST Original failure causes are retained once before report sanitization in one exclusively created private0600 JSONL.
# @INVARIANT Public projection contains only stage/node/type, validated SQLSTATE, digest and retention identity; no message, SQL, values or captured output.
class PrivateFailures:
def __init__(self, evidence):
private = evidence / 'private'
private.mkdir(mode=0o700, exist_ok=False)
self.path = private / 'failures.jsonl'
self.fd = os.open(self.path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_APPEND, 0o600)
self.lock = threading.Lock()
self.index = 0
@staticmethod
def bounded(value, limit=65536):
text = str(value)
return {'text':text[:limit], 'sha256':sha256(text.encode('utf-8', errors='replace')).hexdigest(),
'truncated':len(text) > limit}
def record(self, *, stage, node_id=None, excinfo=None, exception=None, report=None):
if stage not in {'setup', 'call', 'teardown', 'collection', 'internal', 'launcher'}:
refuse('FINAL_PRIVATE_DIAGNOSTIC_STAGE_INVALID')
exception = excinfo.value if excinfo is not None else exception
record = {'stage':stage, 'node_id':node_id}
if exception is not None:
record['failure_type'] = type(exception).__name__
record['message'] = self.bounded(exception)
record['locations'] = [
{'path':entry.filename, 'line':entry.lineno, 'function':entry.name}
for entry in traceback.extract_tb(exception.__traceback__)[-96:]]
chain, seen, current = [], set(), exception
while current is not None and id(current) not in seen and len(chain) < 8:
seen.add(id(current))
item = {'failure_type':type(current).__name__, 'message':self.bounded(current)}
state = getattr(current, 'sqlstate', None) or getattr(current, 'pgcode', None)
if isinstance(state, str) and re.fullmatch(r'[0-9A-Z]{5}', state):
item['sqlstate'] = state
record['sqlstate'] = state
chain.append(item)
current = (getattr(current, 'orig', None) or current.__cause__
or (None if current.__suppress_context__ else current.__context__))
record['exception_chain'] = chain
if report is not None:
record['longrepr'] = self.bounded(report.longrepr, 131072)
crash = getattr(report.longrepr, 'reprcrash', None)
if exception is None:
record['failure_type'] = 'CollectionError' if stage == 'collection' else 'ReportFailure'
record['message'] = self.bounded(getattr(crash, 'message', report.longrepr))
record['sections'] = [
{'name':self.bounded(name, 256), 'content':self.bounded(content, 16384)}
for name, content in report.sections[:4]]
record['sections_truncated'] = len(report.sections) > 4
record.setdefault('failure_type', 'UnknownFailure')
with self.lock:
self.index += 1
record['diagnostic_index'] = self.index
wire = (json.dumps(record, sort_keys=True, ensure_ascii=True) + '\n').encode()
# A buffered duplicate descriptor completes partial writes without closing the owner FD.
with os.fdopen(os.dup(self.fd), 'ab') as handle:
handle.write(wire)
os.fsync(self.fd)
projection = {key:record[key] for key in ('stage', 'node_id', 'failure_type', 'diagnostic_index')}
if 'sqlstate' in record:
projection['sqlstate'] = record['sqlstate']
projection.update(diagnostic_sha256=sha256(wire).hexdigest(), private_retained=True)
return projection
def close(self):
os.close(self.fd)
# #endregion Tooling.VerifyDashboardTestingCurrent.PrivateFailures
# #region Tooling.VerifyDashboardTestingCurrent.SafeLogs [C:3] [TYPE Class]
# @INVARIANT Private credentials/URLs and exception representations never enter published log records.
class SafeLogs(logging.Filter):
def __init__(self, private_values):
super().__init__()
self.private_values = sorted(set(private_values), key=len, reverse=True)
def text(self, value):
text = str(value)
for private in self.private_values:
if private:
text = text.replace(private, '[private]')
return re.sub(r'postgres(?:ql)?(?:\+[a-z0-9_]+)?://[^\s\"<>]+', '[private-database-url]', text)
def value(self, value):
if isinstance(value, dict):
return {self.text(k): self.value(v) for k, v in value.items()}
if isinstance(value, (tuple, list)):
return [self.value(v) for v in value]
return self.text(value) if isinstance(value, str) else value
def filter(self, record):
record.msg = self.text(record.getMessage())
record.args = ()
for key in ('intent', 'error', 'payload'):
if hasattr(record, key):
setattr(record, key, self.value(getattr(record, key)))
if record.exc_info:
record.error = {'failure_type': record.exc_info[0].__name__}
record.exc_info = None
record.exc_text = None
return True
# #endregion Tooling.VerifyDashboardTestingCurrent.SafeLogs
# #region Tooling.VerifyDashboardTestingCurrent.VerificationEvents [C:3] [TYPE Class]
# @POST Verification events carry this invocation's explicit session identity through a private nonpropagating logger.
# @INVARIANT Application handlers, filters, records and formatter methods are never changed by this emitter.
# @RATIONALE Nested tool fixtures must not impersonate the outer pytest dispatch or enter application logger assertions.
# @REJECTED ContextVar stamping or a global app/cot emission would attribute unrelated or nested records to this session.
class VerificationEvents:
def __init__(self, evidence, safe, verification_session_id):
from src.core.cot_formatter import CotJsonFormatter
if not isinstance(verification_session_id, str) or not re.fullmatch(r'[0-9a-f]{32}', verification_session_id):
refuse('FINAL_VERIFICATION_SESSION_INVALID')
self.session_id = verification_session_id
self.logger = logging.Logger('verification.' + verification_session_id, logging.DEBUG)
self.logger.propagate = False
self.handler = logging.FileHandler(evidence / 'molecular.jsonl', encoding='utf-8')
self.handler.addFilter(safe)
self.handler.setFormatter(CotJsonFormatter())
self.logger.addHandler(self.handler)
def emit(self, marker, intent, *, payload=None, src='Tooling.VerifyDashboardTestingCurrent', **fields):
from src.core.cot_logger import build_cot_event
if payload is not None and 'verification_session_id' in payload:
refuse('FINAL_VERIFICATION_SESSION_CONFLICT')
event = build_cot_event(marker=marker, intent=intent, src=src,
payload={'verification_session_id':self.session_id, **(payload or {})},
contract_id=fields.pop('contract_id', src), **fields)
self.logger.log(getattr(logging, event['level']), intent, extra=event)
def reason(self, intent, **fields):
self.emit('REASON', intent, **fields)
def reflect(self, intent, **fields):
self.emit('REFLECT', intent, **fields)
def explore(self, intent, **fields):
self.emit('EXPLORE', intent, **fields)
def __enter__(self):
return self
def __exit__(self, *unused):
self.logger.removeHandler(self.handler)
self.handler.close()
# #endregion Tooling.VerifyDashboardTestingCurrent.VerificationEvents
# #region Tooling.VerifyDashboardTestingCurrent.BusinessTap [C:2] [TYPE Class]
# @POST Only an independent LogRecord copy reaches the safe evidence sink; original exception and nested payload data remain intact.
class BusinessTap(logging.Handler):
def __init__(self, sink):
super().__init__()
self.sink = sink
def emit(self, record):
self.sink.handle(copy(record))
# #endregion Tooling.VerifyDashboardTestingCurrent.BusinessTap
# #region Tooling.VerifyDashboardTestingCurrent.BusinessLogs [C:2] [TYPE Function]
# @POST Cleanup removes only this invocation's two taps, preserving other handlers added or reconfigured during execution.
@contextmanager
def business_logs(events):
owners = [logging.getLogger(name) for name in ('superset_tools_app', 'cot')]
taps = [BusinessTap(events.handler) for _ in owners]
try:
for owner, tap in zip(owners, taps, strict=True):
owner.addHandler(tap)
yield
finally:
for owner, tap in zip(owners, taps, strict=True):
owner.removeHandler(tap)
tap.close()
# #endregion Tooling.VerifyDashboardTestingCurrent.BusinessLogs
# #region Tooling.VerifyDashboardTestingCurrent.DelayedNode [C:3] [TYPE Class]
# @POST A still-running node emits one bounded observation with stack locations only; completion cancels its timer.
# @INVARIANT No locals, source lines, exception text or private filenames are inspected or emitted; a delay neither passes nor retries a node.
class DelayedNode:
def __init__(self, root, node_id, emit, *, timer_factory=threading.Timer, frames=sys._current_frames):
self.root = root.resolve()
self.node_id = node_id
self.emit = emit
self.frames = frames
self.stage = 'setup'
self.finished = False
self.lock = threading.Lock()
context = copy_context()
self.timer = timer_factory(60, lambda: context.run(self.observe))
self.timer.daemon = True
def start(self):
self.timer.start()
def finish(self):
with self.lock:
self.finished = True
self.timer.cancel()
def observe(self):
with self.lock:
if self.finished:
return
locations = []
for frame in list(self.frames().values())[:3]:
for _ in range(2):
if frame is None:
break
code = frame.f_code
path = Path(code.co_filename)
admitted = (path.is_absolute() and path.suffix == '.py'
and any(path.is_relative_to(base) for base in (self.root, Path(sys.base_prefix), Path(sys.prefix))))
locations.append({'file':path.name if admitted and len(path.name) <= 96 else 'outside_source_roots',
'line':frame.f_lineno,
'function':code.co_name if admitted and len(code.co_name) <= 64 else 'unavailable'})
frame = frame.f_back
self.emit('Frozen suite node remains in progress',
src='Tooling.VerifyDashboardTestingCurrent', error_code='FINAL_NODE_DELAYED',
claim='OBSERVED: node has not completed after 60 seconds',
payload={'node_id':self.node_id, 'stage':self.stage, 'locations':locations})
# #endregion Tooling.VerifyDashboardTestingCurrent.DelayedNode
# #region Tooling.VerifyDashboardTestingCurrent.Dispatch [C:3] [TYPE Function]
# @POST Exactly one pytest dispatch; actual node IDs and stage outcomes are retained, raw exception/capture text is excluded from JUnit.
def run_suite(root: Path, evidence: Path, commit: str, safe: SafeLogs, diagnostics: PrivateFailures, *,
suite_scope: str, verification_session_id=None):
selectors = suite_selectors(suite_scope)
import pytest
from src.core.cot_logger import seed_trace_id
counts = Counter()
nodes = []
session_id = secrets.token_hex(16) if verification_session_id is None else verification_session_id
events = VerificationEvents(evidence, safe, session_id)
class SuiteEvidence:
active = None
def pytest_collection_finish(self, session):
items = session.items
forbidden = {'postgres_container', 'superset_container', 'integration_network', 'db_factory'}
nodes.extend(item.nodeid for item in items)
(evidence / 'nodes.json').write_text(json.dumps(nodes, indent=2) + '\n')
events.reflect('Frozen suite collection observed', src='Tooling.VerifyDashboardTestingCurrent',
contract_id='Tooling.VerifyDashboardTestingCurrent.SuiteScope',
claim='OBSERVED: actual collection count for the declared scope',
payload={'suite_scope':suite_scope, 'target_count':len(selectors), 'collected':len(nodes)})
# All collection-modification hooks have completed, including integration skip admission.
# Retain those nodes/stages, but no skipped item can activate a fixture.
observed = sorted({fixture for item in items if not any(item.iter_markers(name='skip'))
for fixture in item.fixturenames} & forbidden)
if observed:
events.explore('Final suite requested an unplanned container fixture',
src='Tooling.VerifyDashboardTestingCurrent', error_code='FINAL_UNPLANNED_CONTAINER_FIXTURE',
claim='PRE: suite uses the already migrated owned database', payload={'fixture_names':observed})
raise pytest.UsageError('FINAL_UNPLANNED_CONTAINER_FIXTURE')
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_protocol(self, item):
seed_trace_id()
events.reason('Run frozen suite node', src='Tooling.VerifyDashboardTestingCurrent',
payload={'node_id':item.nodeid})
self.active = DelayedNode(root, item.nodeid, events.explore)
self.active.start()
try:
yield
finally:
self.active.finish()
self.active = None
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(self, call):
report = (yield).get_result()
if report.failed:
observed = diagnostics.record(stage=report.when, node_id=report.nodeid,
excinfo=call.excinfo, report=report)
events.explore('Frozen suite failure retained privately',
src='Tooling.VerifyDashboardTestingCurrent', error_code='FINAL_NODE_FAILED',
claim='OBSERVED: original failure retained before public report sanitization', payload=observed)
sanitize_report(report, call, safe, root)
def retain_collection_failure(self, report):
if report.failed and not getattr(report, '_verify_private_failure_retained', False):
seed_trace_id()
call = getattr(report, 'call', None)
observed = diagnostics.record(stage='collection', node_id=report.nodeid,
excinfo=getattr(call, 'excinfo', None), report=report)
events.explore('Frozen suite collection failure retained privately',
src='Tooling.VerifyDashboardTestingCurrent', error_code='FINAL_COLLECTION_FAILED',
claim='OBSERVED: original collection report retained before public sanitization', payload=observed)
report.sections = []
report.longrepr = 'FINAL_COLLECTION_FAILED: ' + report.nodeid
report._verify_private_failure_retained = True
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_make_collect_report(self):
# Installed pytest attaches CallInfo here, then removes it before collectreport.
report = (yield).get_result()
self.retain_collection_failure(report)
@pytest.hookimpl(tryfirst=True)
def pytest_collectreport(self, report):
self.retain_collection_failure(report)
@pytest.hookimpl(tryfirst=True)
def pytest_internalerror(self, excrepr, excinfo):
seed_trace_id()
observed = diagnostics.record(stage='internal', excinfo=excinfo)
events.explore('Frozen suite internal error retained privately',
src='Tooling.VerifyDashboardTestingCurrent', error_code='FINAL_INTERNAL_ERROR',
claim='OBSERVED: pytest internal exception retained before exit3', payload=observed)
return True # Suppress pytest's default raw console traceback.
def pytest_runtest_logreport(self, report):
counts[report.when + ':' + report.outcome] += 1
if self.active is not None:
self.active.stage = {'setup':'call', 'call':'teardown', 'teardown':'complete'}[report.when]
events.reflect('Frozen suite node stage observed', src='Tooling.VerifyDashboardTestingCurrent',
payload={'node_id':report.nodeid,'stage':report.when,'outcome':report.outcome,
'wasxfail':hasattr(report, 'wasxfail')})
previous = Path.cwd()
try:
with events, business_logs(events):
seed_trace_id()
events.reason('Dispatch explicitly scoped frozen suite', src='Tooling.VerifyDashboardTestingCurrent',
contract_id='Tooling.VerifyDashboardTestingCurrent.SuiteScope',
claim='PRE: exact declared scope dispatches once without target fallback',
payload={'suite_scope':suite_scope, 'target_count':len(selectors)})
os.chdir(root / 'backend')
code = int(pytest.main(['-q', '--tb=no', '--show-capture=no', '-o', 'addopts=',
'-o', 'junit_logging=no', '--junitxml=' + str(evidence / 'junit.xml'), *selectors],
plugins=[SuiteEvidence()]))
finally:
os.chdir(previous)
check_freeze(root, commit)
summary = {'commit': commit, 'verification_session_id':session_id, '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}
(evidence / 'summary.json').write_text(json.dumps(summary, indent=2) + '\n')
(evidence / 'suite.stdout').write_text(json.dumps(summary, sort_keys=True) + '\n')
return code
# #endregion Tooling.VerifyDashboardTestingCurrent.Dispatch
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--commit', required=True)
parser.add_argument('--suite-scope', required=True, choices=('dashboard', 'backend'))
parser.add_argument('--connection-file', required=True, type=Path)
parser.add_argument('--expected-database', required=True,
choices=('catalog_final_empty_20261010', 'catalog_full_current_20261011', 'catalog_backend_current_20261011'))
parser.add_argument('--evidence-dir', required=True, type=Path)
args = parser.parse_args()
root = Path(__file__).resolve().parents[1]
evidence = args.evidence_dir.resolve()
diagnostics = None
capacity = {}
session_id = secrets.token_hex(16)
try:
check_freeze(root, args.commit)
config = read_connection(args.connection_file.resolve(), expected_database=args.expected_database)
os.umask(0o077)
evidence.mkdir(mode=0o700, parents=False, exist_ok=False)
diagnostics = PrivateFailures(evidence)
for key in tuple(os.environ):
if key.startswith(('TEST_DB', 'DATABASE_', 'PG')) or key in {'PYTEST_ADDOPTS', 'PYTEST_PLUGINS'}:
os.environ.pop(key)
os.environ.update(PG_CONSUMER_CONNECTION_FILE=str(args.connection_file.resolve()),
ENCRYPTION_KEY=base64.urlsafe_b64encode(secrets.token_bytes(32)).decode(),
AUTH_SECRET_KEY=secrets.token_hex(32), SERVICE_JWT=secrets.token_hex(32),
STORAGE_ROOT_PATH=str(evidence / 'storage'))
sys.path[:0] = [str(root / 'backend'), str(root / 'backend/tests')]
os.environ['PYTHONPATH'] = os.pathsep.join(sys.path[:2])
safe = SafeLogs([config['password'], config['username'],
os.environ['AUTH_SECRET_KEY'], os.environ['SERVICE_JWT'], os.environ['ENCRYPTION_KEY']])
with private_output():
from sqlalchemy import create_engine
from sqlalchemy.engine import URL
url = URL.create('postgresql+psycopg2', **config)
os.environ['DATABASE_URL'] = url.render_as_string(hide_password=False)
engine = create_engine(url)
try:
capacity['initial'] = capacity_checkpoint(engine, evidence, args.commit, 'initial', config['database'],
verification_session_id=session_id)
if not capacity['initial']['consistent']:
refuse('FINAL_CAPACITY_INITIAL_STATE_INVALID')
code = run_suite(root, evidence, args.commit, safe, diagnostics, suite_scope=args.suite_scope,
verification_session_id=session_id)
capacity['final'] = capacity_checkpoint(engine, evidence, args.commit, 'final', config['database'],
verification_session_id=session_id)
retain_capacity_summary(evidence, args.commit, capacity, verification_session_id=session_id, suite_scope=args.suite_scope,
private_failure_count=diagnostics.index)
if not capacity['final']['consistent']:
refuse('FINAL_CAPACITY_FINAL_STATE_INVALID')
finally:
engine.dispose()
print(json.dumps({'commit': args.commit, 'verification_session_id':session_id, 'suite_scope':args.suite_scope,
'pytest_exit_code': code, 'evidence': str(evidence)}))
return code
except Exception as exc:
known = str(exc) if type(exc) is RuntimeError else ''
code = known if re.fullmatch(r'FINAL_[A-Z_]+', known) else 'FINAL_LAUNCH_FAILED'
observed = {'failure_type':type(exc).__name__}
if diagnostics is not None:
try:
observed = diagnostics.record(stage='launcher', exception=exc)
retain_capacity_summary(evidence, args.commit, capacity, verification_session_id=session_id,
suite_scope=args.suite_scope, error_code=code,
private_failure_count=diagnostics.index)
with VerificationEvents(evidence, SafeLogs([]), session_id) as events:
events.explore('Frozen suite launcher failure retained privately', error_code=code,
claim='OBSERVED: original launcher failure retained before public classification', payload=observed)
except Exception:
code = 'FINAL_PRIVATE_DIAGNOSTIC_WRITE_FAILED'
print(json.dumps({'error_code': code, 'verification_session_id':session_id, **observed}))
return 2
finally:
if diagnostics is not None:
diagnostics.close()
if __name__ == '__main__':
raise SystemExit(main())
# #endregion Tooling.VerifyDashboardTestingCurrent