Files
cbb-refresh-verify-795/tools/validate_icdb_open_repair_reopen.py

137 lines
7.9 KiB
Python

"""Real before/repair/after test, confined to a newly cloned local fixture.
Run each phase separately so the actual native failure can be reviewed before
repair. The opening phases use the production verifier with auto repair off.
"""
import argparse
from dataclasses import asdict
import hashlib
import json
from pathlib import Path
import subprocess
from cbb_refresh_verify.native_repair import RepairTarget, run_native_repair
from cbb_refresh_verify.verify_runner import VerifyRequest, preflight, run_verify, read_library_flag_if_available
def write(path, record):
path.write_text(json.dumps(record, ensure_ascii=False, default=str, indent=2), encoding='utf-8')
def require_released():
from cbb_refresh_verify.mentor_adapter import pcb_processes, _process_details
if pcb_processes() or _process_details('LibraryManager.exe'):
raise RuntimeError('Native PCB or Library Manager remains open; stop before repair/reopen')
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('phase', choices=('setup', 'open-before', 'repair', 'open-after', 'compare'))
parser.add_argument('--output', default='icdb-open-repair-reopen-20261028')
args = parser.parse_args()
base = Path(__file__).resolve().parents[1]
root = (base/'diagnostics'/args.output).resolve()
if root.parent != (base/'diagnostics').resolve():
raise ValueError('Output must be a direct child of diagnostics')
require_released()
if args.phase == 'setup':
root.mkdir(parents=True, exist_ok=False)
source = base/'diagnostics/icdb-auto-recovery-20261027/verify-library'
if any(p.is_symlink() or p.is_junction() for p in source.rglob('*')):
raise ValueError('Source contains directory/file links')
command = ['robocopy', str(source), str(root/'library'), '/E', '/COPY:DAT', '/DCOPY:T',
'/MT:8', '/R:1', '/W:1', '/NFL', '/NDL', '/NJH', '/NJS', '/NP']
copied = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
(root/'copy.log').write_bytes(copied.stdout)
if copied.returncode > 7:
raise RuntimeError(f'Fixture copy failed: {copied.returncode}')
request = VerifyRequest(root/'library/mentor_lib.lmc', 'IP101GR', root/'preflight')
project, pcb = preflight(request)
database = project.parent/'database/icdb.dat'
original = database.read_bytes()
if not original or original[:64] == bytes(64):
raise ValueError('Source is not a healthy baseline')
(root/'original-icdb.dat').write_bytes(original)
damaged = bytes(64)+original[64:]
database.write_bytes(damaged)
write(root/'setup.json', {'source': source, 'library': request.lmc_file,
'project': project, 'pcb': pcb, 'database': database,
'source_sha256': hashlib.sha256(original).hexdigest(),
'damaged_sha256': hashlib.sha256(damaged).hexdigest(),
'damage': 'Zero first 64 bytes in the new isolated Work database',
'auto_repair_during_open': False})
print('SETUP_DONE', flush=True)
return
config = json.loads((root/'setup.json').read_text('utf-8'))
project, database = Path(config['project']), Path(config['database'])
if not project.resolve().is_relative_to(root) or not database.resolve().is_relative_to(root):
raise ValueError('Target escaped the isolated test directory')
if args.phase == 'compare':
before = json.loads((root/'open-before.json').read_text('utf-8'))
after = json.loads((root/'open-after.json').read_text('utf-8'))
repair = json.loads((root/'repair/repair-result.json').read_text('utf-8'))
before_job = json.loads(Path(before['evidence_path']).with_name('request.json').read_text('utf-8'))
after_job = json.loads(Path(after['evidence_path']).with_name('request.json').read_text('utf-8'))
before_log = (root/'open-before-PCBLogFile.txt').read_text('utf-8', errors='replace')
after_log = (root/'open-after-PCBLogFile.txt').read_text('utf-8', errors='replace')
events = [json.loads(line) for line in
Path(after['evidence_path']).with_name('events.jsonl').read_text('utf-8').splitlines()]
source_database = Path(config['source'])/'ReusableBlocksLP/IP101GR/Work/database/icdb.dat'
checks = {
'same_project': before_job['project'] == after_job['project'] == str(project),
'same_database_repaired': repair['database'] == str(database.parent),
'native_icdb_error_confirmed_before': before['status'] == 'FAIL'
and str(database) in before_log and 'iCDB Project Backup' in before_log,
'identity_verified_after': any(e.get('stage') == 'identity_verified'
and e.get('project') == str(project) for e in events),
'opening_error_absent_after': 'Database cannot be loaded' not in after_log and not after['stderr'],
'verification_passed_after': after['status'] == 'PASS' and after['safe_to_continue']
and after['library_flag'] == 'GREEN',
'original_source_database_unchanged': hashlib.sha256(source_database.read_bytes()).hexdigest()
== config['source_sha256'],
}
result = {'checks': checks, 'comparison_passed': all(checks.values()),
'before_error_category': before['error_category'],
'native_repair_status': repair['status'],
'restored_from_backup': repair.get('evidence', {}).get('restored_from_backup', ''),
'after_library_flag': after['library_flag_detail'],
'server_session_loss_reproduced': 'last server session' in before_log.casefold()}
write(root/'comparison.json', result)
print(json.dumps(result, ensure_ascii=True), flush=True)
if not result['comparison_passed']:
raise RuntimeError('Before/repair/reopen comparison did not pass every check')
return
from cbb_refresh_verify.icdb_ownership import unreleased_addresses
addresses = unreleased_addresses(config['library'], project, config['pcb'])
if addresses:
raise RuntimeError(f'Database ownership not released: {addresses}')
if args.phase == 'repair':
before = json.loads((root/'open-before.json').read_text('utf-8'))
if before['status'] in {'PASS', 'TIMEOUT'}:
raise RuntimeError('No confirmed opening failure available for a repair comparison')
native_error = (root/'open-before-PCBLogFile.txt').read_text('utf-8', errors='replace')
if str(database).casefold() not in native_error.casefold() or 'iCDB Project Backup' not in native_error:
raise RuntimeError('Native log does not confirm an iCDB repair request for the damaged target')
result = run_native_repair(RepairTarget(project, database.parent), root/'repair', timeout_seconds=240)
write(root/'repair-summary.json', result)
else:
if args.phase == 'open-after':
repaired = json.loads((root/'repair-summary.json').read_text('utf-8'))
if repaired['status'] not in {'REPAIRED', 'RESTORED_REVIEW_REQUIRED'}:
raise RuntimeError('Repair did not reach a completed native result')
request = VerifyRequest(Path(config['library']), 'IP101GR', root/args.phase,
timeout_seconds=300, auto_repair=False)
def progress(event):
print(json.dumps(event, ensure_ascii=True, default=str), flush=True)
result = asdict(run_verify(request, progress=progress,
flag_reader=read_library_flag_if_available))
write(root/(args.phase+'.json'), result)
native_log = Path(config['pcb']).parent/'LogFiles/PCBLogFile.txt'
if native_log.is_file():
(root/(args.phase+'-PCBLogFile.txt')).write_bytes(native_log.read_bytes())
print(json.dumps(result, ensure_ascii=True, default=str), flush=True)
if __name__ == '__main__':
main()