20261112 完成#187真实序列录制回放与七指标评估
This commit is contained in:
228
scripts/experiments/reuse_eval/single_formal.py
Normal file
228
scripts/experiments/reuse_eval/single_formal.py
Normal file
@@ -0,0 +1,228 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run one complete formal matrix using a preserved, byte-bound pilot."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import socket
|
||||
import statistics
|
||||
|
||||
from cache_size import profile_from_contract
|
||||
from campaign import SCALARS, require_matrix
|
||||
from common import atomic_json, file_sha256, read_json
|
||||
from sequence_matrix import (EXPECTED_HOST, PROFILE_FLAGS, compare_profile_contracts,
|
||||
require_t2_fallback_bindings, resource_guard, run_pilot)
|
||||
from smoke_matrix import cache_counters, require_comparison
|
||||
|
||||
|
||||
def require_row_proofs(row: dict, matrix: Path) -> None:
|
||||
"""Re-read compact proofs; never open the large report/event streams."""
|
||||
profile, step = row['profile'], row['step']
|
||||
run = matrix / profile / f'step_{step:04d}'
|
||||
benchmark = matrix / profile / f'benchmark_{step:04d}'
|
||||
if row.get('pass') is not True or row.get('path') != str(run):
|
||||
raise ValueError('row identity or success proof differs')
|
||||
if any(type(row.get('counts', {}).get(k)) is not int or row['counts'][k] <= 0
|
||||
for k in ['vrps', 'aspas', 'publication_points']):
|
||||
raise ValueError('empty or missing payload counts')
|
||||
require_comparison(run / 'ccr-comparison.json', 'ccr')
|
||||
require_comparison(run / 'cir-comparison.json', 'cir')
|
||||
equivalent = read_json(benchmark / 'equivalence.json')
|
||||
if (equivalent.get('pass') is not True or equivalent.get('inputs_match') is not True
|
||||
or equivalent.get('ccr', {}).get('stateDigestMatch') is not True):
|
||||
raise ValueError('T1/T2 input or CCR equivalence failed')
|
||||
contract = read_json(run / 'contract.json')
|
||||
baseline = read_json(matrix / 'baseline' / run.name / 'contract.json')
|
||||
if read_json(run / 'contract-comparison.json') != compare_profile_contracts(contract, baseline):
|
||||
raise ValueError('cross-profile contract proof differs from recomputation')
|
||||
require_t2_fallback_bindings(contract, equivalent)
|
||||
if profile_from_contract(contract)[0] != profile or contract['cache']['transportPrefetch'] is not False:
|
||||
raise ValueError('effective reuse profile or disabled prefetch differs')
|
||||
overlay = read_json(benchmark / 'input-overlay.json')
|
||||
proof = overlay.get('overlay', {})
|
||||
if (overlay.get('pre_state_files_verified') is not True or proof.get('background_io_drained') is not True
|
||||
or proof.get('cache_before') != proof.get('cache_after')):
|
||||
raise ValueError('pre-T1 cache or frozen-input overlay proof failed')
|
||||
counters = read_json(run / 'cache-counters.json')
|
||||
if counters['t1'] != counters['t2'] or counters['t1'] != cache_counters(run) or counters['t2'] != cache_counters(benchmark):
|
||||
raise ValueError('T1/T2 raw cache hit/miss counters differ')
|
||||
if read_json(benchmark / 'engine-timing.json') != row['engine']:
|
||||
raise ValueError('engine timing differs from source')
|
||||
if read_json(run / 'cache-size.json')['required_serialized_bytes'] != row['cache_size_bytes']:
|
||||
raise ValueError('cache size differs from source')
|
||||
|
||||
|
||||
def require_prerequisite(config: dict) -> dict:
|
||||
"""Bind an existing pilot to this identical RP and unchanged run engine."""
|
||||
path = Path(config['pilot_summary'])
|
||||
if file_sha256(path) != config['expected_pilot_summary_sha256']:
|
||||
raise ValueError('preserved pilot summary hash differs')
|
||||
pilot = read_json(path)
|
||||
repeat = config['repeat']
|
||||
require_matrix(pilot, repeat['expected_scope_sha256'], formal=False)
|
||||
if (repeat.get('formal_metrics') is not True
|
||||
or repeat.get('profile_order') != list(PROFILE_FLAGS)
|
||||
or repeat.get('run_timeout_secs') != 1800):
|
||||
raise ValueError('requires exactly one full formal matrix under the original execution policy')
|
||||
for key in ['archive', 'scope', 'expected_binary_sha256', 'expected_scope_sha256']:
|
||||
if repeat[key] != pilot['config'][key]:
|
||||
raise ValueError('formal input/build differs from preserved pilot: ' + key)
|
||||
if pilot['tool_sha256'] != config['expected_tools_sha256']:
|
||||
raise ValueError('preserved pilot tool hashes differ')
|
||||
for name, digest in config['expected_tools_sha256'].items():
|
||||
if file_sha256(Path(repeat[name])) != digest:
|
||||
raise ValueError('formal tool differs from preserved pilot: ' + name)
|
||||
if file_sha256(path.parent / 'bin/binary') != repeat['expected_binary_sha256']:
|
||||
raise ValueError('actual preserved pilot RP bytes differ')
|
||||
if file_sha256(Path(repeat['scope'])) != repeat['expected_scope_sha256']:
|
||||
raise ValueError('original repository scope changed')
|
||||
original_scripts = config['expected_pilot_scripts_sha256']
|
||||
if pilot['scripts_sha256'] != original_scripts:
|
||||
raise ValueError('preserved pilot script hashes differ')
|
||||
package = Path(__file__).resolve().parent
|
||||
scripts = {p.name: file_sha256(p) for p in sorted(package.glob('*.py')) if not p.name.startswith('test_')}
|
||||
if scripts != config['expected_scripts_sha256']:
|
||||
raise ValueError('frozen single-formal package differs')
|
||||
if set(scripts) != set(original_scripts) | {'single_formal.py'}:
|
||||
raise ValueError('unexpected controller additions/removals')
|
||||
if any(scripts[name] != digest for name, digest in original_scripts.items() if name != 'formal_metrics.py'):
|
||||
raise ValueError('RP run engine changed; preserved pilot cannot be reused')
|
||||
expected = [(p, step) for p in PROFILE_FLAGS for step in range(13)]
|
||||
if [(r['profile'], r['step']) for r in pilot['runs']] != expected:
|
||||
raise ValueError('preserved pilot order or completeness differs')
|
||||
for row in pilot['runs']:
|
||||
require_row_proofs(row, path.parent)
|
||||
return {'pass': True, 'pilot_summary': str(path), 'pilot_summary_sha256': file_sha256(path),
|
||||
'pairs_checked': 65, 'binary_sha256': repeat['expected_binary_sha256'],
|
||||
'scope_sha256': repeat['expected_scope_sha256'],
|
||||
'reuse_reason': 'same RP/tools/input/policy/resources; only transport measurement collector fixed and single-repeat entry added'}
|
||||
|
||||
|
||||
def require_metrics(metrics: dict, profile: str) -> None:
|
||||
if not isinstance(metrics, dict) or metrics.get('schema') != 'rpki-reuse-seven-metrics-v1' or metrics.get('profile') != profile:
|
||||
raise ValueError('missing seven-metric schema/profile')
|
||||
for key in SCALARS:
|
||||
value = metrics.get(key)
|
||||
if type(value) not in (int, float) or not math.isfinite(value) or value < 0:
|
||||
raise ValueError('missing or invalid metric: ' + key)
|
||||
if any(metrics[key] <= 0 for key in ['rp_validation_ns', 'update_to_payload_ns', 'peak_rss_bytes']):
|
||||
raise ValueError('validation/payload/RSS must be positive')
|
||||
enabled = {'signature': profile == 'signature', 'roa': profile in ('object', 'hybrid'),
|
||||
'child_certificate': profile in ('object', 'hybrid'), 'publication_point': profile in ('pp', 'hybrid')}
|
||||
for layer, on in enabled.items():
|
||||
r = metrics.get('cache_hit_ratio', {}).get(layer, {})
|
||||
hits, queries = r.get('hits'), r.get('queries')
|
||||
if (r.get('enabled') is not on or type(hits) is not int or type(queries) is not int
|
||||
or not 0 <= hits <= queries or (not on and (hits or queries))
|
||||
or r.get('ratio') != (hits / queries if on and queries else None)):
|
||||
raise ValueError('cache hit denominator/profile differs: ' + layer)
|
||||
|
||||
|
||||
def report(summary: dict) -> dict:
|
||||
"""Descriptive statistics for one trajectory, with no repeat CI claims."""
|
||||
require_matrix(summary, summary['scope_sha256'], formal=True)
|
||||
for row in summary['runs']:
|
||||
require_metrics(row['seven_metrics'], row['profile'])
|
||||
selections = {'cold': [0], 'incremental': list(range(1, 13)),
|
||||
'before_manifest_fallback': list(range(1, 11)), 'manifest_fallback': [11], 'native_transport_fallback': [12]}
|
||||
groups = []
|
||||
for profile in PROFILE_FLAGS:
|
||||
for label, steps in selections.items():
|
||||
rows = [r for r in summary['runs'] if r['profile'] == profile and r['step'] in steps]
|
||||
values = [r['seven_metrics'] for r in rows]
|
||||
group = {'profile': profile, 'steps': label, 'logical_steps': steps, 'n_steps': len(rows),
|
||||
'independent_repeats': 1, 'metrics': {}, 'cache_hit_ratio': {},
|
||||
'cache_size_at_end_bytes': max(rows, key=lambda r: r['step'])['seven_metrics']['cache_size_bytes']}
|
||||
for key in SCALARS:
|
||||
data = [m[key] for m in values]
|
||||
group['metrics'][key] = {'mean': statistics.mean(data), 'median': statistics.median(data),
|
||||
'min': min(data), 'max': max(data)}
|
||||
for layer in ['signature', 'roa', 'child_certificate', 'publication_point']:
|
||||
hits = sum(m['cache_hit_ratio'][layer]['hits'] for m in values)
|
||||
queries = sum(m['cache_hit_ratio'][layer]['queries'] for m in values)
|
||||
group['cache_hit_ratio'][layer] = {'hits': hits, 'queries': queries, 'ratio': hits / queries if queries else None}
|
||||
groups.append(group)
|
||||
return {'schema': 'rpki-reuse-single-formal-report-v1', 'pass': True, 'performance_ready': True,
|
||||
'repeats': 1, 'pairs': 65, 'scope_sha256': summary['scope_sha256'],
|
||||
'tool_sha256': summary['tool_sha256'], 'groups': groups,
|
||||
'limitations': ['one replay per profile; logical steps are not independent statistical repetitions',
|
||||
'same 186 host server/RP; shared storage, page cache and CPU siblings',
|
||||
'109 successful repository scope plus eight declared gaps; one-hour capture',
|
||||
'final controlled RRDP failure exercises the recorded native rsync fallback',
|
||||
'all profiles disable transport prefetch; uniform CPU1-3/workers3/5GiB',
|
||||
'cache is required serialized CF key/value plus sidecar copies, not whole DB disk usage']}
|
||||
|
||||
|
||||
def csv_rows(summary: dict) -> list[dict]:
|
||||
result = []
|
||||
for row in summary['runs']:
|
||||
metrics = row['seven_metrics']
|
||||
require_metrics(metrics, row['profile'])
|
||||
result.append({'repeat': 1, 'profile': row['profile'], 'step': row['step'],
|
||||
**{key: metrics[key] for key in SCALARS},
|
||||
**{f'{layer}_{key}': metrics['cache_hit_ratio'][layer][key]
|
||||
for layer in ['signature', 'roa', 'child_certificate', 'publication_point']
|
||||
for key in ['hits', 'queries', 'ratio']}})
|
||||
return result
|
||||
|
||||
|
||||
def run(config: dict) -> dict:
|
||||
if socket.gethostname() != EXPECTED_HOST or os.geteuid() != 0:
|
||||
raise ValueError('single formal is restricted to root on the designated 186 host')
|
||||
output, matrix = Path(config['out']).resolve(), Path(config['repeat']['out']).resolve()
|
||||
parent = Path('/data/rpki187/20261109/results')
|
||||
if output.parent != parent or matrix.parent != parent or output == matrix or output.exists() or matrix.exists():
|
||||
raise ValueError('single formal requires distinct new empty roots under the dedicated results parent')
|
||||
resources = resource_guard(parent)
|
||||
if resources['data_free_bytes'] < config['minimum_available_bytes']:
|
||||
raise ValueError('insufficient capacity for one matrix plus the unchanged guard')
|
||||
prerequisite = require_prerequisite(config)
|
||||
output.mkdir(exist_ok=False)
|
||||
atomic_json(output / 'pilot-prerequisite.json', prerequisite)
|
||||
state = {'status': 'running', 'pass': False, 'performance_ready': False, 'config': config,
|
||||
'repeats': 1, 'pilot_summary_sha256': prerequisite['pilot_summary_sha256'], 'initial_resources': resources}
|
||||
|
||||
def save() -> None:
|
||||
state['updated_utc'] = datetime.now(timezone.utc).isoformat()
|
||||
atomic_json(output / 'single-status.json', state)
|
||||
|
||||
save()
|
||||
try:
|
||||
summary = run_pilot(config['repeat'])
|
||||
result = report(summary)
|
||||
for row in summary['runs']:
|
||||
require_row_proofs(row, matrix)
|
||||
atomic_json(output / 'single-report.json', result)
|
||||
rows = csv_rows(summary)
|
||||
with (output / 'all-steps.csv').open('x', newline='') as stream:
|
||||
writer = csv.DictWriter(stream, fieldnames=list(rows[0]))
|
||||
writer.writeheader()
|
||||
writer.writerows(rows)
|
||||
state.update(status='completed', **{'pass': True}, performance_ready=True, pairs=65,
|
||||
formal_summary_sha256=file_sha256(matrix / 'summary.json'))
|
||||
save()
|
||||
return state
|
||||
except BaseException as error:
|
||||
state.update(status='failed', error=f'{type(error).__name__}: {error}')
|
||||
save()
|
||||
raise
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--config', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
def interrupted(*_):
|
||||
raise KeyboardInterrupt('single formal interrupted')
|
||||
signal.signal(signal.SIGTERM, interrupted)
|
||||
print(json.dumps(run(read_json(args.config))))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user