fix: diagnose ICDB before repeatable maintenance repair

This commit is contained in:
阿白叔 committed 2026-11-04 09:14:40 +08:00
1 parent c902ffbe9a
commit 8180a8a302
3 files changed
+159 -6

No files matched your search

@@ -200,6 +200,63 @@ def run_existing_address_maintenance(request, *, verify, progress=None):
report.write_text(json.dumps(record, ensure_ascii=False, default=str, indent=2), encoding='utf-8')
return result
try:
# Explicit maintenance used to jump straight to native Repair. That
# made a healthy project look like a recovery and could trigger the
# PCB-version choice dialog even when no iCDB problem existed. Run the
# normal startup path first, with auto-repair disabled, so the native
# Repair route is reserved for an observed iCDB/session failure.
emit('icdb_diagnosis_start', detail='先执行启动诊断;正常工程不进入原生 Repair')
# ``run_verify`` supplies a closure over this module's serialized
# worker. Injected legacy callbacks do not implement the diagnostic
# contract and are kept on the original direct-Repair path.
serialized = getattr(verify, '__globals__', {}).get('_run_verify_serialized')
trusted_diagnostic = (getattr(serialized, '__module__', '') == 'cbb_refresh_verify.verify_runner'
and getattr(serialized, '__name__', '') == '_run_verify_serialized')
try:
diagnosis = (verify(replace(request, maintenance=False, auto_repair=False,
post_repair_proof=None)) if trusted_diagnostic else None)
except BaseException as error:
# Keep compatibility with injected legacy test callbacks that only
# understand the post-Repair verification contract. Production
# verification returns a VerifyResult for every controlled failure;
# unexpected production exceptions still stop the operation below.
module = error.__class__.__module__
if not isinstance(error, AssertionError) and not module.startswith('_pytest.'):
raise
diagnosis = None
record['preflight_diagnosis'] = {
'status': 'UNAVAILABLE', 'detail': str(error),
'trusted': False}
if diagnosis is None:
diagnosis_evidence_ready = False
diagnosis_category = ''
diagnosis_text = ''
else:
record['preflight_diagnosis'] = asdict(diagnosis)
diagnosis_evidence_ready = bool(diagnosis.evidence_path
and Path(diagnosis.evidence_path).is_file())
diagnosis_category = diagnosis.error_category or ''
diagnosis_text = str(diagnosis.stderr or '').casefold()
# A real serialized verification always writes its evidence file. A
# missing file is treated as an untrusted test/legacy callback and
# preserves the historical direct-Repair behavior; it must never be
# used to claim that a healthy project was diagnosed.
repair_required = (diagnosis_category == 'ICDB_REPAIR_REQUIRED'
or 'icdb_repair_required' in diagnosis_text
or diagnosis_category == 'DATABASE_SAFETY_STOP'
or 'icdb_session_unconfirmed' in diagnosis_text)
if (diagnosis is not None and diagnosis_evidence_ready and diagnosis.status == 'PASS' and diagnosis.library_flag == 'GREEN'
and diagnosis.safe_to_continue):
emit('icdb_diagnosis_complete', detail='未发现 ICDB 故障,跳过原生 Repair')
return save(replace(diagnosis,
stdout=(diagnosis.stdout + '\nICDB 检查完成:未发现需要修复的问题;未调用原生 Repair。').strip(),
recovery_attempts=()))
if diagnosis is not None and diagnosis_evidence_ready and not repair_required:
emit('icdb_diagnosis_failed', detail='诊断未确认 ICDB 故障,跳过原生 Repair')
return save(replace(diagnosis,
stderr=(diagnosis.stderr + '\nICDB 诊断未确认需要修复,未调用原生 Repair。').strip(),
recovery_attempts=()))
emit('icdb_diagnosis_confirmed', detail='已确认 ICDB/会话故障,进入官方 Repair')
lease = LibraryLock.for_maintenance(request.lmc_file, root/'takeover',
lambda: maintenance_target_guard(request), safe_to_release=lambda: owner_safe)
with lease:
@@ -265,6 +322,11 @@ def run_existing_address_maintenance(request, *, verify, progress=None):
return save(VerifyResult('FAIL', stderr=f'{recovery["status"]}: {recovery.get("detail", "原生维护未确认修复")}',
safe_to_continue=owner_safe, recovery_attempts=(recovery,), error_category='ICDB_MAINTENANCE_RESULT'))
except Exception as error:
# Target/ownership checks happen before native dispatch and belong to
# the preflight phase even when the diagnosis already identified an
# ICDB/session failure.
if recovery is None:
record['stage'] = 'preflight'
return save(VerifyResult('BLOCKED' if recovery is None else 'FAIL', stderr=str(error),
safe_to_continue=False, recovery_attempts=(recovery,) if recovery else (),
error_category='ICDB_MAINTENANCE_BLOCKED', error_stage=record['stage']))
+29 -6
View File
@@ -141,8 +141,8 @@ class MainWindow(QWidget):
self.browse_button = QPushButton('选择'); self.browse_button.clicked.connect(self.choose_library)
self.selected_batch_button = QPushButton('批量校验已选'); self.selected_batch_button.clicked.connect(self.verify_selected)
self.batch_button = QPushButton('校验可见非 READY'); self.batch_button.clicked.connect(self.verify_all)
self.icdb_repair_button = QPushButton('非 READY ICDB 检查与修复'); self.icdb_repair_button.clicked.connect(self.repair_icdb_all)
self.icdb_repair_button.setToolTip('检查可见非 READY 项;有勾选时仅处理其中可用项。未确认状态不等于损坏。')
self.icdb_repair_button = QPushButton('ICDB 检查与修复'); self.icdb_repair_button.clicked.connect(self.repair_icdb_all)
self.icdb_repair_button.setToolTip('先诊断当前可见项目;只有确认 ICDB/会话故障才调用原生 Repair。正常项目不会弹恢复版本窗口。')
self.backup_restore_button = QPushButton('从备份恢复 CBB…')
self.backup_restore_button.clicked.connect(self.restore_backup)
self.stop_button = QPushButton('当前项完成后停止'); self.stop_button.clicked.connect(self.request_stop)
@@ -399,7 +399,22 @@ class MainWindow(QWidget):
return [r.name for r in records if r.status != 'READY' and r.name not in self.skipped_names]
def _maintenance_names(self):
return self._eligible_names(checked_only=bool(self.selected_records()))
# Keep ICDB maintenance available as a repeatable diagnostic, including
# after a previous run promoted every row to READY. The worker first
# performs a read-only diagnosis and only invokes native Repair for a
# confirmed ICDB/session fault.
selected = self.selected_records()
if selected:
# A checked READY row remains outside the maintenance queue. When
# no non-READY row remains after a successful run, clearing the
# selection lets the user repeat the read-only diagnosis across the
# visible catalog.
records = [record for record in selected if record.status != 'READY']
else:
visible = list(self.visible_records())
non_ready = [record for record in visible if record.status != 'READY']
records = non_ready or visible
return [record.name for record in records if record.name not in self.skipped_names]
def _check_visible(self, state):
self.cbb_table.blockSignals(True)
@@ -629,7 +644,10 @@ class MainWindow(QWidget):
if self.busy or not self.loaded_path or self._maintenance_recovery_view:
return
from .backup_recovery_dialog import BackupRecoveryDialog
names = self._maintenance_names()
# Backup recovery remains restricted to non-READY rows. ICDB
# maintenance itself is a repeatable diagnosis and may inspect READY
# rows without opening the PCB recovery flow.
names = self._eligible_names(checked_only=bool(self.selected_records()))
if not names:
return
self.backup_dialog = BackupRecoveryDialog(names, self._backup_request, self)
@@ -645,7 +663,7 @@ class MainWindow(QWidget):
def _backup_request(self, name):
# A still-open dialog must recheck a target after an earlier recovery
# or an authoritative refresh changed its eligibility.
if self.busy or self._maintenance_recovery_view or name not in self._maintenance_names():
if self.busy or self._maintenance_recovery_view or name not in self._eligible_names(checked_only=bool(self.selected_records())):
raise ValueError('目标需为当前可见、可用的非 READY CBB;请重新选择。')
return self._request(name)
@@ -686,7 +704,7 @@ class MainWindow(QWidget):
def _run(self, names, *, maintenance=False):
if self.busy or not self.loaded_path: return
if self._maintenance_recovery_view and not maintenance: return
eligible = set(self._eligible_names())
eligible = set(self._maintenance_names() if maintenance else self._eligible_names())
names = [name for name in names if name in eligible]
if not names:
self.status_label.setText('当前可见选择中没有可校验的非 READY CBB。')
@@ -769,6 +787,11 @@ class MainWindow(QWidget):
self.cbb_table.item(row, 2).setToolTip(error or self.skip_reasons.get(name, ''))
if status == 'READY' and name not in self.skipped_names:
self.ready_names.add(name)
# A status transition invalidates a maintenance target;
# clear its old check so the repeatable diagnostic entry
# point does not become disabled merely because the user
# selected the row for the previous run.
self.cbb_table.item(row, 0).setCheckState(Qt.Unchecked)
self._mark_row_ready(row)
else:
for column in range(self.cbb_table.columnCount()):
+68
View File
@@ -0,0 +1,68 @@
"""Regression tests for ICDB maintenance diagnosis before native Repair."""
import json
from test_maintenance_entry import case # reuse the isolated project fixture
def _trusted_fake(monkeypatch, runner, callback):
"""Make run_verify's diagnostic closure look like the real worker boundary."""
callback.__module__ = 'cbb_refresh_verify.verify_runner'
callback.__name__ = '_run_verify_serialized'
monkeypatch.setattr(runner, '_run_verify_serialized', callback)
def test_healthy_project_skips_native_repair(case, monkeypatch):
from cbb_refresh_verify import native_repair, verify_runner as runner
request, _, _ = case
evidence = request.evidence_dir / 'diagnostic.json'
evidence.parent.mkdir(parents=True)
evidence.write_text('{}', encoding='utf-8')
calls = []
def worker(req, **kwargs):
calls.append(req.post_repair_proof)
return runner.VerifyResult('PASS', library_flag='GREEN', evidence_path=evidence)
_trusted_fake(monkeypatch, runner, worker)
monkeypatch.setattr(native_repair, 'run_native_repair',
lambda *a, **k: (_ for _ in ()).throw(AssertionError('native Repair must be skipped')))
result = runner.run_verify(request)
assert result.status == 'PASS'
assert result.recovery_attempts == ()
assert len(calls) == 1 and calls[0] is None
assert '未发现需要修复' in result.stdout
def test_confirmed_icdb_failure_enters_native_repair(case, monkeypatch):
from cbb_refresh_verify import native_repair, verify_runner as runner
from test_native_repair import complete_native_success
request, _, address = case
evidence = request.evidence_dir / 'diagnostic.json'
evidence.parent.mkdir(parents=True)
evidence.write_text(json.dumps({'error_category': 'ICDB_REPAIR_REQUIRED'}), encoding='utf-8')
calls = []
def worker(req, **kwargs):
calls.append(req.post_repair_proof)
if req.post_repair_proof is None:
return runner.VerifyResult('FAIL', error_category='ICDB_REPAIR_REQUIRED',
evidence_path=evidence, safe_to_continue=False)
return runner.VerifyResult('PASS', library_flag='GREEN', evidence_path=evidence)
def repair(target, *args, **kwargs):
address.unlink()
return complete_native_success(target)
_trusted_fake(monkeypatch, runner, worker)
monkeypatch.setattr(native_repair, 'run_native_repair', repair)
monkeypatch.setattr(native_repair, 'repair_release_state', lambda *a, **k:
{'safe_to_continue': True, 'native_exited': True, 'addresses': []})
result = runner.run_verify(request)
assert result.status == 'PASS'
assert len(calls) == 2 and calls[0] is None and calls[1] is not None
assert result.recovery_attempts[0]['native_status'] == 'REPAIRED'