fix(dashboard-testing): retain private final-run failure diagnostics
This commit is contained in:
@@ -14,6 +14,7 @@ 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
|
||||
@@ -24,6 +25,7 @@ import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import traceback
|
||||
|
||||
|
||||
API_FILES = (
|
||||
@@ -135,6 +137,78 @@ def safe_failure(excinfo):
|
||||
{'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):
|
||||
@@ -220,7 +294,7 @@ class 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):
|
||||
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
|
||||
@@ -266,6 +340,12 @@ def run_suite(root: Path, evidence: Path, commit: str, safe: SafeLogs):
|
||||
@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:
|
||||
@@ -273,9 +353,37 @@ def run_suite(root: Path, evidence: Path, commit: str, safe: SafeLogs):
|
||||
elif report.longrepr:
|
||||
report.longrepr = 'FINAL_NODE_' + report.outcome.upper()
|
||||
|
||||
def pytest_collectreport(self, report):
|
||||
if report.failed:
|
||||
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
|
||||
@@ -296,7 +404,8 @@ def run_suite(root: Path, evidence: Path, commit: str, safe: SafeLogs):
|
||||
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}
|
||||
'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
|
||||
@@ -311,11 +420,13 @@ def main():
|
||||
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)
|
||||
@@ -346,14 +457,23 @@ def main():
|
||||
refuse('FINAL_DATABASE_HEAD_CONFLICT')
|
||||
finally:
|
||||
engine.dispose()
|
||||
code = run_suite(root, evidence, args.commit, safe)
|
||||
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'
|
||||
print(json.dumps({'error_code': code, 'failure_type': type(exc).__name__}))
|
||||
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__':
|
||||
|
||||
Reference in New Issue
Block a user