feat: add ICDB maintenance and verified CBB backup recovery dialog

This commit is contained in:
阿白叔 committed 2026-10-28 19:43:07 +08:00
1 parent a851e47eca
commit cdb8a6a28b
23 files changed
+1868 -23

No files matched your search

+52
View File
@@ -0,0 +1,52 @@
"""Destructive probe restricted to a fresh copy of the local test fixture."""
from pathlib import Path
import argparse
import hashlib
import json
import shutil
from cbb_refresh_verify.native_repair import RepairTarget, run_native_repair
def main():
base = Path(__file__).resolve().parents[1]
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output', default='icdb-corruption-probe-20261028-r2')
parser.add_argument('--without-history', action='store_true',
help='Exclude historical ProjectBackup/cdbback data from the new test copy')
args = parser.parse_args()
source = base / 'diagnostics/icdb-auto-recovery-20261027/project-copy'
root = (base/'diagnostics'/args.output).resolve()
if root.parent != (base/'diagnostics').resolve():
raise ValueError('Output must be a new direct child of the diagnostics directory')
root.mkdir(parents=True, exist_ok=False)
project_dir = root / 'project'
if any(p.is_symlink() or p.is_junction() for p in source.rglob('*')):
raise RuntimeError('Fixture contains links')
shutil.copytree(source, project_dir, ignore=(
shutil.ignore_patterns('ProjectBackup', 'cdbback') if args.without_history else None))
if args.without_history:
storage = project_dir/'ProjectBackup'
(storage/'backups').mkdir(parents=True)
shutil.copy2(source/'ProjectBackup/ProjectBackup.cfg', storage/'ProjectBackup.cfg')
if list(project_dir.rglob('*.zip')):
raise RuntimeError('Historical archives remain in the no-history test copy')
database = project_dir / 'database/icdb.dat'
original = database.read_bytes()
damaged = bytes(64) + original[64:]
database.write_bytes(damaged)
record = {'source_sha256': hashlib.sha256(original).hexdigest(),
'damaged_sha256': hashlib.sha256(damaged).hexdigest(),
'damage': 'first 64 bytes zeroed in isolated copy',
'without_historical_backups': args.without_history}
(root/'damage.json').write_text(json.dumps(record, indent=2), encoding='utf-8')
result = run_native_repair(RepairTarget(project_dir/'IP101GR.prj', database.parent),
root/'repair', timeout_seconds=180)
result['database_sha256_after'] = hashlib.sha256(database.read_bytes()).hexdigest()
result['damaged_bytes_unchanged'] = result['database_sha256_after'] == record['damaged_sha256']
(root/'probe-result.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
print(json.dumps(result, ensure_ascii=False))
if __name__ == '__main__':
main()
+147
View File
@@ -0,0 +1,147 @@
"""Real damaged-open / popup recovery / reopened-target comparison.
All damage and recovery are confined to a fresh diagnostics fixture. The popup
uses the production backend and native verifier without injected substitutes.
"""
from dataclasses import asdict
import argparse
import json
from pathlib import Path
import shutil
import subprocess
from cbb_refresh_verify.backup_recovery import _manifest
from cbb_refresh_verify.verify_runner import VerifyRequest, run_verify, read_library_flag_if_available
def write(path, value):
path.write_text(json.dumps(value, ensure_ascii=False, default=str, indent=2), encoding='utf-8')
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('phase', choices=('setup', 'open-before', 'restore', 'compare'))
args = parser.parse_args()
base = Path(__file__).resolve().parents[1]
root = base/'diagnostics/icdb-backup-dialog-live-20261028'
library = root/'library/mentor_lib.lmc'
source = base/'diagnostics/icdb-auto-recovery-20261027/verify-library'
project = library.parent/'ReusableBlocksLP/IP101GR/Work/IP101GR.prj'
if args.phase == 'setup':
root.mkdir(parents=True, exist_ok=False)
if any(p.is_symlink() or p.is_junction() for p in source.rglob('*')):
raise ValueError('Source contains links')
copied = subprocess.run(['robocopy', str(source), str(library.parent), '/E', '/COPY:DAT',
'/DCOPY:T', '/MT:8', '/R:1', '/W:1', '/NFL', '/NDL', '/NJH', '/NJS', '/NP'],
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}')
# Remove historical backups only in this new, resolved fixture Work.
for path in sorted(project.parent.rglob('*'), reverse=True):
if path.is_dir() and path.name in {'ProjectBackup', 'cdbback'}:
resolved = path.resolve()
if not resolved.is_relative_to((root/'library').resolve()):
raise ValueError('History cleanup escaped test fixture')
shutil.rmtree(resolved)
database = project.parent/'database/icdb.dat'
healthy = database.read_bytes()
if healthy[:64] == bytes(64):
raise ValueError('Fixture baseline is not healthy')
database.write_bytes(bytes(64) + healthy[64:])
write(root/'source-before.json', _manifest(source))
write(root/'setup.json', {'project': project, 'database': database,
'damage': 'First 64 bytes zeroed in isolated Work database',
'historical_backups_removed': True})
print('SETUP_DONE', flush=True)
return
request = VerifyRequest(library, 'IP101GR', root/args.phase, timeout_seconds=300, auto_repair=False)
if args.phase == 'open-before':
result = run_verify(request, progress=lambda e: print(json.dumps(e, ensure_ascii=True), flush=True),
flag_reader=read_library_flag_if_available)
write(root/'open-before.json', asdict(result))
log = project.parent/'PCB/LogFiles/PCBLogFile.txt'
if log.is_file():
(root/'open-before-PCBLogFile.txt').write_bytes(log.read_bytes())
print(json.dumps(asdict(result), default=str, ensure_ascii=True), flush=True)
return
if args.phase == 'restore':
before = json.loads((root/'open-before.json').read_text('utf-8'))
log = (root/'open-before-PCBLogFile.txt').read_text('utf-8', errors='replace')
if before['status'] != 'FAIL' or 'Database cannot be loaded' not in log:
raise ValueError('Actual damaged target opening failure must be confirmed first')
from PySide6.QtCore import QTimer, Qt
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication
from cbb_refresh_verify.application import configure_qt_application
from cbb_refresh_verify.ui.main_window import MainWindow
app = QApplication([]); configure_qt_application(app)
window = MainWindow(data_root=root/'data'); window.resize(1060, 860)
window.show(); window.lmc_edit.setText(str(library))
window.libspec_edit.clear(); window.dms_edit.clear()
state = {'phase': 'loading'}
def tick():
if state['phase'] == 'loading' and not window.busy:
if not window.loaded_path:
raise RuntimeError(window.status_label.text())
state['phase'] = 'restoring'
QTest.mouseClick(window.backup_restore_button, Qt.LeftButton)
dialog = window.backup_dialog
def progress(event):
print(json.dumps(event, ensure_ascii=True, default=str), flush=True)
if event.get('stage') == 'validate_source':
candidates = list((root/'data/evidence').glob('backup-restore-*/recovery-request.json'))
current = max(candidates, key=lambda p: p.stat().st_mtime_ns)
config = json.loads(current.read_text('utf-8'))
flag = read_library_flag_if_available(Path(config['validation_library']), 'IP101GR')
write(current.parent/'source-before-native-flag.json', asdict(flag))
dialog.signals.progress.connect(progress)
dialog.source_edit.setText(str(source/'ReusableBlocksLP/IP101GR/Work/IP101GR.prj'))
dialog.grab().save(str(root/'dialog-before.png'))
def done(name, result):
write(root/'restore-ui-result.json', asdict(result))
state['phase'] = 'finishing'
QTimer.singleShot(200, finish)
dialog.completed.connect(done)
QTest.mouseClick(dialog.restore_button, Qt.LeftButton)
def finish():
timer.stop()
dialog = window.backup_dialog
dialog.grab().save(str(root/'dialog-after.png'))
window.grab().save(str(root/'window-after.png'))
write(root/'ui-state.json', {'status': dialog.status_label.text(),
'target_ready': 'IP101GR' in window.ready_names, 'busy': dialog.busy})
dialog.reject(); window.close(); app.quit()
timer=QTimer(); timer.setInterval(100); timer.timeout.connect(tick)
window.load_library(); timer.start(); app.exec()
print((root/'restore-ui-result.json').read_text('utf-8'), flush=True)
return
before = json.loads((root/'open-before.json').read_text('utf-8'))
restored = json.loads((root/'restore-ui-result.json').read_text('utf-8'))
record = json.loads(Path(restored['evidence_path']).read_text('utf-8'))
final = record['result']
retained = Path(record.get('retained_work', ''))
after_evidence = Path(final['evidence_path']).parent
events = [json.loads(line) for line in (after_evidence/'events.jsonl').read_text('utf-8').splitlines()]
native_log = project.parent/'PCB/LogFiles/PCBLogFile.txt'
text = native_log.read_text('utf-8', errors='replace')
checks = {
'real_open_failed_before': before['status'] == 'FAIL' and before['error_category'] == 'MENTOR_DATABASE_LOAD_FAILED',
'source_copy_verified': record['source_validation']['status'] == 'PASS'
and record['source_validation']['library_flag'] == 'GREEN',
'same_target_opened_after': any(e.get('stage') == 'identity_verified'
and e.get('project') == str(project) for e in events),
'restored_target_passed': final['status'] == 'PASS' and final['library_flag'] == 'GREEN'
and final['safe_to_continue'],
'old_damaged_work_retained': (retained/'database/icdb.dat').read_bytes()[:64] == bytes(64),
'original_source_unchanged': _manifest(source) == json.loads((root/'source-before.json').read_text('utf-8')),
'load_error_absent_after': 'Database cannot be loaded' not in text,
}
write(root/'comparison.json', {'checks': checks, 'passed': all(checks.values())})
print(json.dumps(checks), flush=True)
if not all(checks.values()):
raise RuntimeError('Real recovery comparison failed')
if __name__ == '__main__':
main()
+99
View File
@@ -0,0 +1,99 @@
"""Exercise the real Qt button and native verifier on a fresh local fixture copy.
Run with PYTHONPATH=src. No verifier/reader stubs or synthetic errors are used.
The source library is fingerprinted before and after the run.
"""
from pathlib import Path
import hashlib
import json
import shutil
import time
from PySide6.QtCore import QTimer, Qt
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QMessageBox
from cbb_refresh_verify.application import configure_qt_application
from cbb_refresh_verify.ui.main_window import MainWindow
def fingerprint(root):
result = {}
for path in root.rglob('*'):
if path.is_symlink() or path.is_junction():
raise ValueError('Test source contains links')
if path.is_file():
with path.open('rb') as stream:
result[str(path.relative_to(root))] = hashlib.file_digest(stream, 'sha256').hexdigest()
return result
def main():
base = Path(__file__).resolve().parents[1]
source = base/'diagnostics/icdb-auto-recovery-20261027/verify-library'
root = base/'diagnostics/icdb-button-live-20261028'
root.mkdir(parents=True, exist_ok=False)
before = fingerprint(source)
(root/'source-before.json').write_text(json.dumps(before), encoding='utf-8')
library = root/'library'
shutil.copytree(source, library)
app = QApplication([])
configure_qt_application(app)
window = MainWindow(data_root=root/'data')
window.resize(1060, 820)
window.show()
window.libspec_edit.clear()
window.dms_edit.clear()
window.lmc_edit.setText(str(library/'mentor_lib.lmc'))
state = {'phase': 'loading', 'started': time.monotonic()}
def event(record):
if record.get('stage') in {'icdb_check_start', 'native_repair_start', 'PASS', 'FAIL', 'BLOCKED', 'TIMEOUT'}:
print(json.dumps(record, ensure_ascii=True), flush=True)
window.signals.event.connect(event)
def tick():
for widget in app.topLevelWidgets():
if isinstance(widget, QMessageBox) and widget.isVisible() and widget.windowTitle() == '全库 ICDB 检查与修复':
widget.grab().save(str(root/'confirmation.png'))
state['confirmation'] = widget.text()
QTest.mouseClick(widget.button(QMessageBox.Yes), Qt.LeftButton)
if state['phase'] == 'loading' and not window.busy:
if not window.loaded_path:
state.update(phase='load_failed', detail=window.status_label.text())
finish()
return
state.update(phase='running', rows=window.cbb_table.rowCount(),
ready_before=len(window.ready_names), preflight_skipped=len(window.skipped_names))
window.grab().save(str(root/'loaded.png'))
QTimer.singleShot(0, lambda: QTest.mouseClick(window.icdb_repair_button, Qt.LeftButton))
elif state['phase'] == 'running' and not window.busy and hasattr(window, 'summary'):
state.update(phase='finished', detail=window.status_label.text(), ready_after=len(window.ready_names))
window.grab().save(str(root/'finished.png'))
window.summary.grab().save(str(root/'summary.png'))
finish()
elif time.monotonic()-state['started'] > 900 and not window.stop.is_set():
window.request_stop()
def finish():
timer.stop()
after = fingerprint(source)
state.update(source_unchanged=before == after, source_file_count=len(before),
elapsed_seconds=time.monotonic()-state['started'])
(root/'outcome.json').write_text(json.dumps(state, ensure_ascii=False, indent=2), encoding='utf-8')
print(json.dumps(state, ensure_ascii=True), flush=True)
if hasattr(window, 'summary'):
window.summary.close()
window.close()
app.quit()
timer = QTimer()
timer.setInterval(100)
timer.timeout.connect(tick)
window.load_library()
timer.start()
app.exec()
if __name__ == '__main__':
main()
+136
View File
@@ -0,0 +1,136 @@
"""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()