302 lines
15 KiB
Python
302 lines
15 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
|
|
import json
|
|
import logging
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import secrets
|
|
import stat
|
|
import subprocess
|
|
import sys
|
|
|
|
|
|
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
|
|
|
|
|
|
class PrivateOutput:
|
|
"""Discard uncategorized process output; publish structured reports instead."""
|
|
encoding = 'utf-8'
|
|
|
|
def write(self, value):
|
|
return len(value)
|
|
|
|
def flush(self):
|
|
return None
|
|
|
|
|
|
@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(PrivateOutput()), redirect_stderr(PrivateOutput()):
|
|
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.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.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):
|
|
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:
|
|
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})
|
|
yield
|
|
|
|
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
|
|
def pytest_runtest_makereport(self, call):
|
|
report = (yield).get_result()
|
|
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 pytest_collectreport(self, report):
|
|
if report.failed:
|
|
report.longrepr = 'FINAL_COLLECTION_FAILED: ' + report.nodeid
|
|
|
|
def pytest_runtest_logreport(self, report):
|
|
counts[report.when + ':' + report.outcome] += 1
|
|
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}
|
|
(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()
|
|
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)
|
|
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)
|
|
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'
|
|
print(json.dumps({'error_code': code, 'failure_type': type(exc).__name__}))
|
|
return 2
|
|
|
|
|
|
if __name__ == '__main__':
|
|
raise SystemExit(main())
|
|
# #endregion Tooling.VerifyDashboardTestingCurrent
|