fix: guard ICDB diagnostics and exclude READY maintenance targets

This commit is contained in:
阿白叔 committed 2026-11-04 10:27:53 +08:00
1 parent 8180a8a302
commit ef652f3ada
9 files changed
+325 -156

No files matched your search

@@ -16,6 +16,7 @@ def maintenance_counts(results):
and attempt.get('native_status') == 'REPAIRED'
and attempt.get('validation_passed') is False for attempt in attempts)
return {'total': len(results), 'passed': sum(r.status == 'PASS' for r in results),
'checked_without_repair': sum(r.status == 'PASS' and not r.recovery_attempts for r in results),
'skipped': sum(r.status == 'SKIPPED' for r in results),
'repaired': repaired, 'review_required': review,
'version_choice_required': version_choice,
+34 -63
View File
@@ -200,69 +200,44 @@ 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:
checked = lease.maintenance_proof
target, context = checked['target'], checked['context']
record['maintenance_context'] = context
emit('icdb_diagnosis_start', detail='已取得库锁,检查原生启动;不执行集成或保存')
diagnostic_request = replace(request, maintenance=False, auto_repair=False,
diagnostic_only=True, post_repair_proof=None, native_lm_verify=False,
interactive_input=False, libspec='', dms_login_config='', evidence_dir=root/'diagnosis')
diagnosis = verify(diagnostic_request)
record['preflight_diagnosis'] = asdict(diagnosis)
evidence = diagnosis.evidence_path
if (evidence is None or not Path(evidence).is_file()
or not Path(evidence).resolve().is_relative_to((root/'diagnosis').resolve())):
raise ValueError('ICDB_DIAGNOSIS_UNCONFIRMED: 缺少本轮诊断证据,未调用 Repair')
owner_safe = diagnosis.safe_to_continue
if diagnosis.status == 'PASS' and owner_safe:
emit('icdb_diagnosis_complete', detail='本轮启动未发现 ICDB 故障,未调用 Repair')
return save(replace(diagnosis, library_flag='UNKNOWN', library_flag_detail='',
stdout='ICDB 启动检查通过;未执行集成、保存或原生 Repair。', recovery_attempts=()))
if diagnosis.error_category != 'ICDB_REPAIR_REQUIRED' or diagnosis.status in ('BLOCKED', 'TIMEOUT'):
return save(replace(diagnosis, status='BLOCKED' if diagnosis.status == 'PASS' else diagnosis.status,
stderr=(diagnosis.stderr + '\n未确认 ICDB 故障,未调用原生 Repair。').strip(),
recovery_attempts=()))
# Only this run's structured native lost-session diagnosis may
# authorize Repair, and it must identify this exact database.
fault = json.loads((Path(evidence).parent/'diagnostics/icdb-recovery.json').read_text('utf-8'))
if (fault.get('error_code') != 'ICDB_REPAIR_REQUIRED' or fault.get('scope') != 'project'
or not fault.get('session') or not fault.get('database_path')
or Path(fault['database_path']).resolve() != target.database.resolve()):
raise ValueError('ICDB_DIAGNOSIS_UNCONFIRMED: 故障证据未绑定当前数据库')
record['confirmed_fault'] = fault
# A diagnostic worker may have failed to release its native owner.
# Recheck every owner and the exact target before dispatch.
with maintenance_target_guard(request, context): pass
owner_safe = False
emit('icdb_diagnosis_confirmed', detail='本轮原生日志已确认目标数据库失联,进入 Repair')
native_root = root/'native-repair'; native_root.mkdir()
attempt = native_root/'attempt.json'
with attempt.open('x', encoding='utf-8') as stream:
@@ -293,7 +268,8 @@ def run_existing_address_maintenance(request, *, verify, progress=None):
owner_safe = False
proof = PostRepairProof.create(request, target, recovery)
verified = verify(replace(request, maintenance=False, auto_repair=False,
post_repair_proof=proof, interactive_input=False, native_lm_verify=False))
diagnostic_only=False, post_repair_proof=proof,
interactive_input=False, native_lm_verify=False))
owner_safe = verified.safe_to_continue
good = verified.status == 'PASS' and verified.library_flag == 'GREEN' and owner_safe
recovery.update(status='REPAIRED' if good else 'REPAIR_VALIDATION_FAILED',
@@ -322,11 +298,6 @@ 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']))
+46 -6
View File
@@ -690,15 +690,28 @@ def execute_job(job, emit):
launcher_process = None
completed = False
identity_verified = False
diagnostic_close_attempted = False
helper = None
app = doc = pi = None
try:
ensure_pcb_central_library(
job['pcb'],
job['lmc_file'],
evidence_dir=Path(root) / 'diagnostics',
emit=emit,
)
if job.get('diagnostic_only'):
if job.get('native_lm_verify') or job.get('post_repair_consent'):
raise ValueError('DIAGNOSTIC_MODE_INVALID: 诊断不能执行原生校验菜单或恢复确认')
from .backup_recovery import _project_text
from .maintenance_entry import maintenance_project_files
library = Path(job['lmc_file']).resolve()
for config in maintenance_project_files(job['project'], job['pcb']):
for match in _CENTRAL_LIBRARY_KEY.finditer(_project_text(config)):
reference = match[2]
if not reference or (config.parent/reference).resolve() != library:
raise ValueError(f'DIAGNOSTIC_LIBRARY_MISMATCH: {config}: {reference}')
else:
ensure_pcb_central_library(
job['pcb'],
job['lmc_file'],
evidence_dir=Path(root) / 'diagnostics',
emit=emit,
)
emit(
stage='verify_mode',
mode=('library_manager_native' if bool(job.get('native_lm_verify', False))
@@ -762,6 +775,29 @@ def execute_job(job, emit):
error_reader=native_error,
)
identity_verified = True
if job.get('diagnostic_only'):
# The diagnostic opens only to establish current native evidence.
# Do not refresh integration, save/commit Cert, or edit PRJ paths.
pi = doc = app = None
gc.collect()
from .failed_session import close_failed_document
diagnostic_close_attempted = True
closed = close_failed_document(job, emit=emit)
if closed.get('status') != 'CLOSED':
raise RuntimeError(f'DIAGNOSTIC_CLOSE_UNCONFIRMED: {closed}')
release_deadline = time.monotonic() + 30
while True:
released = cleanup_verify_processes(lm_pid, worker_pid, worker_parent_pid,
expected_pcb=job['pcb'], baseline_pids=pcb_before, emit=emit)
if (released and released.get('safe_to_continue')
and not unreleased_addresses(job['lmc_file'], job['project'], job['pcb'])):
break
if time.monotonic() >= release_deadline:
raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED: 原生会话或数据库仍占用')
time.sleep(.2)
completed = True
emit(stage='diagnostic_complete', status='PASS')
return {'status': 'PASS', 'stdout': 'ICDB 启动检查通过;未执行集成或保存,已关闭工程。'}
# Do not acquire MGCPCBAutomationLicensing from this 64-bit Python
# worker. EE7.9 registers that automation class for the 32-bit host;
# the old, working path acquires the token inside the SysWOW64
@@ -847,6 +883,10 @@ def execute_job(job, emit):
pass
if helper is not None and helper.poll() is None:
emit(stage='save_helper_retained', helper_pid=helper.pid)
elif diagnostic_close_attempted:
# A timed-out close helper may still own an in-flight native Close.
# Observe release below, but never start a second close helper.
pass
elif not completed and identity_verified:
try:
from .failed_session import close_failed_document
+8 -24
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('ICDB 检查与修复'); self.icdb_repair_button.clicked.connect(self.repair_icdb_all)
self.icdb_repair_button.setToolTip('先诊断当前可见项目;只有确认 ICDB/会话故障才调用原生 Repair。正常项目不会弹恢复版本窗口。')
self.icdb_repair_button = QPushButton('非 READY ICDB 检查与修复'); self.icdb_repair_button.clicked.connect(self.repair_icdb_all)
self.icdb_repair_button.setToolTip('忽略 READY 项(包括已勾选项);先检查启动,仅本轮日志确认 ICDB 失联时才修复。')
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,22 +399,7 @@ 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):
# 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]
return self._eligible_names(checked_only=bool(self.selected_records()))
def _check_visible(self, state):
self.cbb_table.blockSignals(True)
@@ -631,8 +616,8 @@ class MainWindow(QWidget):
f'{MANUAL_BACKUP_NOTICE}\nMentor 原生修复可能生成自身备份。\n\n当前中心库:{self.loaded_path}\n\n'
f'将检查 {len(names)} 个可见非 READY CBB'
f'{"(仅勾选项)" if self.selected_records() else ""}。未确认状态不等于损坏。\n'
'逐项核对工程身份、所有者和独占访问,再由官方工具检查/修复一次,成功后重新打开校验。'
'没有地址记录也会检查;多个数据库无法明确目标时停止,不猜测或删除地址文件。\n'
'先取得库锁并核对工程与占用,检查启动但不执行集成或保存。仅本轮原生日志确认 ICDB 失联才修复,再重新打开校验。'
'占用、历史版本提示或故障原因未确认时停止,不猜测故障或删除地址文件。READY 项始终忽略。\n'
'仅本地固定磁盘:严格确认修复并重新独占检查后,可一次确认本次异常退出的读写访问提示。'
'网络盘、UNC 或链接路径不自动确认该提示。\n'
'共享符号库不支持自动修复。若原生工具恢复了旧备份,需人工核对版本;'
@@ -644,9 +629,6 @@ class MainWindow(QWidget):
if self.busy or not self.loaded_path or self._maintenance_recovery_view:
return
from .backup_recovery_dialog import BackupRecoveryDialog
# 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
@@ -891,7 +873,8 @@ class MainWindow(QWidget):
from cbb_refresh_verify.icdb_maintenance import maintenance_counts
counts = maintenance_counts(results)
text = ('非 READY ICDB 检查已结束\n'
f'校验通过 {passed},失败/受阻 {failed},队列未执行 {skipped}\n'
f'检查/校验通过 {passed},失败/受阻 {failed},队列未执行 {skipped}\n'
f'启动检查通过、未修复 {counts["checked_without_repair"]}(不等同于 READY)\n'
f'原生修复完成 {counts["repaired"]},恢复备份待复核 {counts["review_required"]},'
f'ICDB已修复/PCB版本待选 {counts["version_choice_required"]},'
f'修复未确认 {counts["repair_unconfirmed"]}\n'
@@ -902,6 +885,7 @@ class MainWindow(QWidget):
status_text = text
if self._global_icdb_run:
status_text = (f'非 READY 检查结束:通过 {passed},失败/受阻 {failed},未执行 {skipped}。\n'
f'启动检查通过、未修复 {counts["checked_without_repair"]};'
f'原生修复 {counts["repaired"]},恢复备份待复核 {counts["review_required"]},'
f'ICDB已修复/PCB版本待选 {counts["version_choice_required"]},'
f'修复未确认 {counts["repair_unconfirmed"]}。')
+4 -2
View File
@@ -65,6 +65,7 @@ class VerifyRequest:
auto_repair: bool = True
maintenance: bool = False
post_repair_proof: object | None = field(default=None, repr=False, compare=False)
diagnostic_only: bool = False
@dataclass(frozen=True)
@@ -757,7 +758,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
return finish(VerifyResult('BLOCKED', safe_to_continue=False,
stderr=f'ICDB_SESSION_UNCONFIRMED: 无法确认数据库所有权:{error}'))
content_check_enabled = bool(str(request.libspec).strip() and str(request.dms_login_config).strip())
content_check_enabled = not request.diagnostic_only and bool(str(request.libspec).strip() and str(request.dms_login_config).strip())
if content_check_enabled:
try:
executable = resolve_importer(request.mentor_bin)
@@ -801,6 +802,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
return finish(VerifyResult('BLOCKED', stderr=ports_detail))
job = {'lmc_file': str(absolute_preserving_drive(request.lmc_file)), 'block_name': request.block_name,
'diagnostic_only': request.diagnostic_only,
'supervisor_pid': os.getpid(),
'project': str(project), 'pcb': str(pcb), 'root': str(root), 'timeout': request.timeout_seconds,
'mentor_bin': str(request.mentor_bin or ''),
@@ -1100,7 +1102,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
win32event.ReleaseMutex(mutex)
mutex.Close()
if result.status == 'PASS':
if result.status == 'PASS' and not request.diagnostic_only:
timing.begin('library_flag')
bridge_records = []
def record_attempt(record):