Files
ss-tools/scripts/verify_dashboard_testing_current.py

471 lines
24 KiB
Python

#!/usr/bin/env python3
# #region Tooling.VerifyDashboardTestingCurrent [C:3] [TYPE Module] [SEMANTICS verification,postgresql,pytest,freeze]
# @BRIEF Run the frozen dashboard-testing service/API suite once against the explicitly owned, already migrated final 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 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.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]
# @POST Only the named owned loopback final database is admitted; configuration errors never include its contents.
def read_connection(path: Path):
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 config['database'] == 'catalog_final_empty_20261010')
except (OSError, ValueError, TypeError):
refuse('FINAL_CONNECTION_CONFIG_INVALID')
if not valid:
refuse('FINAL_CONNECTION_SCOPE_INVALID')
return config
# #endregion Tooling.VerifyDashboardTestingCurrent.Connection
@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.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.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):
import pytest
from src.core.cot_formatter import CotJsonFormatter
from src.core.cot_logger import seed_trace_id
from src.core.logger import logger
counts = Counter()
nodes = []
handler = logging.FileHandler(evidence / 'molecular.jsonl', encoding='utf-8')
handler.addFilter(safe)
handler.setFormatter(CotJsonFormatter())
for name in ('superset_tools_app', 'cot'):
owner = logging.getLogger(name)
owner.addFilter(safe)
owner.addHandler(handler)
class SuiteEvidence:
active = None
def pytest_collection_modifyitems(self, 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')
observed = sorted({fixture for item in items for fixture in item.fixturenames} & forbidden)
if observed:
logger.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()
logger.reason('Run frozen suite node', src='Tooling.VerifyDashboardTestingCurrent',
payload={'node_id':item.nodeid})
self.active = DelayedNode(root, item.nodeid, logger.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)
logger.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)
report.sections = []
report.user_properties = [(safe.text(key), safe.value(value)) for key, value in report.user_properties]
if report.failed and call.excinfo:
report.longrepr = safe_failure(call.excinfo)
elif report.longrepr:
report.longrepr = 'FINAL_NODE_' + report.outcome.upper()
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)
logger.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)
logger.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]
logger.reflect('Frozen suite node stage observed', src='Tooling.VerifyDashboardTestingCurrent',
payload={'node_id':report.nodeid,'stage':report.when,'outcome':report.outcome})
selectors = ['tests/services/dashboard_testing'] + ['tests/api/test_' + n + '.py' for n in API_FILES]
previous = Path.cwd()
os.chdir(root / 'backend')
try:
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)
handler.close()
check_freeze(root, commit)
summary = {'commit': commit, 'pytest_exit_code': code, 'collected': len(nodes),
'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('--connection-file', required=True, type=Path)
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
try:
check_freeze(root, args.commit)
config = read_connection(args.connection_file.resolve())
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']])
# Before application/pytest imports: third-party traceback formatting is type-only.
logging.Formatter.formatException = lambda self, exc: exc[0].__name__
for name in ('superset_tools_app', 'cot'):
logging.getLogger(name).addFilter(safe)
with private_output():
from sqlalchemy import create_engine, text
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:
with engine.connect() as connection:
connection.execute(text('SET TRANSACTION READ ONLY'))
if connection.execute(text('SELECT current_database()')).scalar_one() != config['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')
finally:
engine.dispose()
code = run_suite(root, evidence, args.commit, safe, diagnostics)
print(json.dumps({'commit': args.commit, '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)
except Exception:
code = 'FINAL_PRIVATE_DIAGNOSTIC_WRITE_FAILED'
print(json.dumps({'error_code': code, **observed}))
return 2
finally:
if diagnostics is not None:
diagnostics.close()
if __name__ == '__main__':
raise SystemExit(main())
# #endregion Tooling.VerifyDashboardTestingCurrent