fix: classify ICDB repair outcomes and gate released recovery

This commit is contained in:
阿白叔 committed 2026-11-02 18:14:38 +08:00
1 parent 44b808b8e2
commit aa760c2839
12 files changed
+751 -27

No files matched your search

+19 -3
View File
@@ -25,7 +25,7 @@ def _command_args(command):
def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event: None,
timeout_seconds=20):
timeout_seconds=20, launcher_process=None):
"""Normally close our empty PCB after a diagnosed database startup failure.
No COM attach: there is no document, and the global ROT can name another
@@ -38,6 +38,10 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
from .icdb_ownership import unreleased_addresses
root = Path(job['root'])
result = {'status': 'RETAINED', 'pcb_pid': pcb_pid}
result['release'] = {'pcb_exited': False, 'launcher_exited': launcher_process is None,
'safe_to_continue': False}
if launcher_process is not None:
result['launcher_pid'] = launcher_process.pid
try:
diagnosed = False
diagnosis_path = root/'diagnostics/icdb-recovery.json'
@@ -68,8 +72,20 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
while True:
records = [r for r in _process_details('ExpeditionPCB.exe') if r[0] == pcb_pid]
if not records:
result['status'] = 'CLOSED'
break
addresses = unreleased_addresses(job['lmc_file'], job['project'], job['pcb'])
launcher_exited = launcher_process is None or launcher_process.poll() is not None
result['release'] = {'pcb_exited': True, 'launcher_exited': launcher_exited,
'addresses': addresses,
'safe_to_continue': launcher_exited and not addresses}
if result['release']['safe_to_continue']:
result['status'] = 'CLOSED'
result.pop('detail', None)
break
result['detail'] = 'STARTUP_RELEASE_UNCONFIRMED: 等待启动器退出和数据库地址释放'
if time.monotonic() >= deadline:
break
time.sleep(.2)
continue
_, executable, command, _ = records[0]
args = _command_args(command)
if (Path(executable).name.casefold() != 'expeditionpcb.exe'
+6 -1
View File
@@ -5,7 +5,12 @@ import json
def maintenance_counts(results):
attempts = [attempt for result in results for attempt in result.recovery_attempts]
repaired = sum(attempt.get('status') == 'REPAIRED' for attempt in attempts)
repaired = sum(attempt.get('status') == 'REPAIRED'
and attempt.get('native_status') == 'REPAIRED'
and attempt.get('validation_passed') is True
and result.status == 'PASS' and result.library_flag == 'GREEN'
and result.safe_to_continue
for result in results for attempt in result.recovery_attempts)
review = sum(attempt.get('status') == 'RESTORED_REVIEW_REQUIRED' for attempt in attempts)
return {'total': len(results), 'passed': sum(r.status == 'PASS' for r in results),
'skipped': sum(r.status == 'SKIPPED' for r in results),
+2 -1
View File
@@ -866,7 +866,8 @@ def execute_job(job, emit):
elif not completed and worker_pid is not None:
try:
from .failed_session import close_failed_startup
failed_close = close_failed_startup(job, worker_pid, baseline_pids=pcb_before, emit=emit)
failed_close = close_failed_startup(job, worker_pid, baseline_pids=pcb_before, emit=emit,
launcher_process=launcher_process)
if failed_close.get('status') == 'CLOSED' and lm_session is not None:
lm_session.close()
except Exception as error:
+47 -4
View File
@@ -23,6 +23,8 @@ def select_repair_target(request, diagnosis):
raise ValueError('REPAIR_TARGET_UNCONFIRMED: 缺少原生失联会话信息')
if diagnosis.get('scope') == 'central_library':
raise ValueError('SHARED_DATABASE_REPAIR_UNSUPPORTED: 当前原生 Repair 入口要求 PRJ,不能改修无关的 Work 工程')
if diagnosis.get('scope') != 'project':
raise ValueError('REPAIR_TARGET_UNCONFIRMED: 数据库所有权范围未知')
project, pcb = preflight(request)
try:
reported = Path(diagnosis.get('database_path', '')).resolve(strict=True)
@@ -115,7 +117,8 @@ def attempt_recovery(request, diagnosis, evidence_root, *, progress=None):
marker = root/'attempt.json'
if marker.exists():
return {'status': 'BLOCKED', 'detail': 'REPAIR_ALREADY_ATTEMPTED', 'evidence': str(root)}
record = {'status': 'BLOCKED', 'evidence': str(root)}
record = {'status': 'BLOCKED', 'evidence_path': str(root),
'release': {'safe_to_continue': False}}
try:
process_record = Path(evidence_root)/'content-check-process.json'
if process_record.is_file():
@@ -137,12 +140,51 @@ def attempt_recovery(request, diagnosis, evidence_root, *, progress=None):
callback = (lambda event: progress({'block': request.block_name, **event})) if progress else None
record = run_native_repair(target, root, mentor_bin=request.mentor_bin,
timeout_seconds=max(60, request.timeout_seconds), progress=callback)
record['release'] = repair_release_state(request, target, record)
record['evidence_path'] = str(root)
except Exception as error:
record['detail'] = str(error)
marker.write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
return record
def repair_release_state(request, target, native_result):
"""Require normal exit, owner/address absence and exclusive database access."""
from .mentor_adapter import pcb_processes, _process_details
from .icdb_ownership import database_directories, unreleased_addresses
from .verify_runner import preflight
result = {**native_result.get('release', {}), 'safe_to_continue': False,
'database_exclusive': False}
try:
project, pcb = preflight(request)
owners = [int(r[0]) for r in pcb_processes()]
for name in ('LibraryManager.exe', 'iCDBProjectBackup.exe', 'ReuseBlockImporter.exe'):
owners.extend(int(r[0]) for r in _process_details(name))
for pid, _exe, command, _parent in _process_details('cscript.exe'):
if (not command or str(project).casefold() in command.casefold()
or str(pcb).casefold() in command.casefold()):
owners.append(int(pid))
result.update(remaining_pids=sorted(set(owners)),
addresses=unreleased_addresses(request.lmc_file, project, pcb))
if (native_result.get('release', {}).get('safe_to_continue') is not True
or owners or result['addresses']):
return result
import win32con, win32file
files = [target.database/'icdb.dat']
files.extend(folder/'icdb.dat' for folder in database_directories(request.lmc_file, project, pcb)
if (folder/'icdb.dat').is_file())
result['exclusive_databases'] = []
for database_file in dict.fromkeys(files):
handle = win32file.CreateFile(str(database_file), win32con.GENERIC_READ,
0, None, win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
handle.Close()
result['exclusive_databases'].append(str(database_file))
result.update(database_exclusive=True, safe_to_continue=True)
except Exception as error:
result['error'] = str(error)
return result
def run_native_repair(target, root, *, mentor_bin='', timeout_seconds=300, progress=None):
"""Supervise the GUI on its own desktop; a repair timeout never kills it."""
from .desktop_worker import DesktopWorker
@@ -176,11 +218,12 @@ def run_native_repair(target, root, *, mentor_bin='', timeout_seconds=300, progr
outcome = root/'repair-result.json'
if worker.poll() is None or not outcome.is_file():
worker.request_stop()
return {'status': 'RETAINED', 'worker_pid': worker.pid, 'desktop': desktop,
'detail': '原生修复尚未确认结束,保留操作并停止批次', 'evidence': str(root)}
return {'status': 'TIMEOUT_UNRELEASED', 'worker_pid': worker.pid, 'desktop': desktop,
'release': {'safe_to_continue': False},
'detail': '原生修复尚未确认结束,保留操作并停止批次', 'evidence_path': str(root)}
result = json.loads(outcome.read_text('utf-8'))
if worker.returncode != 0 and result.get('status') == 'REPAIRED':
result['status'] = 'UNCONFIRMED'
return {**result, 'evidence': str(root)}
return {**result, 'evidence_path': str(root)}
finally:
worker.close()
+104 -14
View File
@@ -5,6 +5,7 @@ import json
import ntpath
from pathlib import Path
import re
import shutil
import subprocess
import time
import zipfile
@@ -30,6 +31,23 @@ def repair_completed(diagnostic_text, database_text, *, native_backup):
and 'iCDBProjectBackupRepair' in database_text and 'IC: Closing project' in database_text)
def classify_repair_evidence(diagnostic, database, restore, output):
"""Classify this invocation only; an error alone does not prove native idle."""
combined = '\n'.join((diagnostic, database, restore, output))
terminal_error = bool(re.search(r'Repair project error\s*\[[^\r\n]+\]', output, re.I))
closed_error = ('Diagnostic: FINISH' in diagnostic and 'IC: Closing project' in database)
if re.search(r'project is in use|database.*(?:in use|busy)|other clients are connected', combined, re.I):
outcome = 'DATABASE_BUSY'
elif re.search(r'there is no backup of (?:missing )?iCDB|no (?:healthy|valid) backup', combined, re.I):
outcome = 'MISSING_HEALTHY_BACKUP'
elif re.search(r'\bERROR\s*:|not repaired|repair.*failed|Repair project error', combined, re.I):
outcome = 'NATIVE_REPAIR_FAILED'
else:
outcome = 'UNCONFIRMED'
return {'outcome': outcome, 'failure_complete': bool(
outcome != 'UNCONFIRMED' and (terminal_error or closed_error))}
def _current_desktop_name():
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
user32 = ctypes.WinDLL('user32', use_last_error=True)
@@ -97,12 +115,36 @@ def _windows(pid):
return windows
def _native_evidence(project, database, pid, started_ns, baseline):
def _native_output(windows):
"""Read Output without UI activation; a hung control has a bounded deadline."""
user32 = ctypes.WinDLL('user32', use_last_error=True)
user32.SendMessageTimeoutW.argtypes = [wintypes.HWND, wintypes.UINT, wintypes.WPARAM,
wintypes.LPARAM, wintypes.UINT, wintypes.UINT, ctypes.POINTER(ctypes.c_size_t)]
user32.SendMessageTimeoutW.restype = wintypes.LPARAM
texts = []
for window in windows:
for child in window['children']:
if not child['class'].casefold().startswith('richedit'):
continue
buffer = ctypes.create_unicode_buffer(131072)
copied = ctypes.c_size_t()
if not user32.SendMessageTimeoutW(child['hwnd'], 0x000D, len(buffer),
ctypes.addressof(buffer), 0x0002, 200, ctypes.byref(copied)):
return None
if copied.value >= len(buffer)-1:
return None # A truncated prefix cannot establish the current operation.
texts.append(buffer.value)
return '\n'.join(texts) if texts else None
def _native_evidence(project, database, pid, started_ns, baseline, *, output_text=''):
"""Use only this native process's new diagnostic/close and backup evidence."""
log_paths = []
def read_logs(folder):
text = []
for path in (database/'cdbsvr'/folder).glob(f'*-{pid}/*.txt'):
if path.stat().st_mtime_ns >= started_ns:
log_paths.append(str(path))
text.append(path.read_bytes()[-256*1024:].decode('utf-8', errors='replace'))
return '\n'.join(text)
from .icdb_recovery import read_log_failure
@@ -122,9 +164,13 @@ def _native_evidence(project, database, pid, started_ns, baseline):
diagnostic, db_log = read_logs('dbcheck'), read_logs('log')
restore_log = read_logs('dbrestore')
restored = re.search(r'iCDB database restored from backup:\s*([^\r\n]+)', restore_log)
valid = (not restored and str(database).casefold() in db_log.casefold()
classification = classify_repair_evidence(diagnostic, db_log, restore_log, output_text)
valid = (classification['outcome'] == 'UNCONFIRMED' and not restored
and str(database).casefold() in db_log.casefold()
and repair_completed(diagnostic, db_log, native_backup=native_backup))
return {'confirmed': bool(valid), 'native_backup': native_backup,
return {**classification, 'confirmed': bool(valid), 'native_backup': native_backup,
'output_tail': output_text[-8192:], 'log_paths': log_paths,
'backup_log_tail': text[-8192:],
'diagnostic_tail': diagnostic[-8192:], 'database_tail': db_log[-8192:],
'restored_from_backup': restored.group(1).strip() if restored else '',
'restore_complete': bool(restored and '[0] DONE' in restore_log
@@ -140,7 +186,8 @@ def repair_worker_main(job_path):
job = json.loads(Path(job_path).read_text('utf-8'))
root = Path(job['root'])
project, database = Path(job['project']), Path(job['database'])
result = {'status': 'BLOCKED', 'project': str(project), 'database': str(database)}
result = {'status': 'BLOCKED', 'project': str(project), 'database': str(database),
'release': {'safe_to_continue': False}}
process = None
def emit(**event):
with (root/'repair-events.jsonl').open('a', encoding='utf-8') as stream:
@@ -175,19 +222,38 @@ def repair_worker_main(job_path):
deadline = time.monotonic()+max(1, float(job['timeout']))
invoked = confirmed = closing = False
evidence = None
output_baseline = None
output = ''
while process.poll() is None and time.monotonic()<deadline:
windows = _windows(process.pid)
main = next((w for w in windows if w['class'].startswith('Afx:')
and w['title'].casefold() == ('iCDB Project Backup - '+str(project)).casefold()), None)
mains = [w for w in windows if w['class'].startswith('Afx:')
and w['title'].casefold() == ('iCDB Project Backup - '+str(project)).casefold()]
main = mains[0] if len(mains) == 1 else None
dialogs = [w for w in windows if w['class'] == '#32770']
if not invoked and main and not dialogs and main['enabled']:
unknown = [w for w in windows if w is not main and w not in dialogs]
current_output = _native_output(windows)
busy_before_start = (not invoked and current_output is not None
and classify_repair_evidence('', '', '', current_output)['outcome'] == 'DATABASE_BUSY')
if busy_before_start:
output = current_output
result.update(status='DATABASE_BUSY', detail='原生工具加载工程时报告占用;未请求 Repair')
if not invoked and not busy_before_start and main and not dialogs and not unknown and main['enabled']:
if Path(job['cancel_signal']).exists():
raise ValueError('REPAIR_CANCELLED_BEFORE_START')
output_baseline = current_output
win32gui.PostMessage(main['hwnd'], win32con.WM_COMMAND, command_id, 0)
invoked = True
emit(stage='native_repair_requested', command=command_id)
if invoked and not confirmed and main:
for dialog in dialogs:
if dialogs or unknown:
known = [d for d in dialogs if invoked and not confirmed and main
and confirmation_allowed(main['title'], project,
'\n'.join(c['text'] for c in d['children']))]
if unknown or len(dialogs) != 1 or len(known) != 1:
result.update(status='UNKNOWN_DIALOG', unknown_dialogs=[*unknown, *dialogs],
detail='未知原生弹窗;未发送操作,保留原生工具')
# Capture evidence below before stopping supervision.
else:
dialog = known[0]
text = '\n'.join(c['text'] for c in dialog['children'])
if confirmation_allowed(main['title'], project, text):
if Path(job['cancel_signal']).exists():
@@ -198,16 +264,40 @@ def repair_worker_main(job_path):
win32gui.PostMessage(button['hwnd'], win32con.BM_CLICK, 0, 0)
confirmed = True
emit(stage='native_repair_confirmed', text=text)
if (invoked and output_baseline is not None and current_output is not None
and current_output.startswith(output_baseline)):
output = current_output[len(output_baseline):]
evidence = _native_evidence(project, database, process.pid, started_ns, baseline,
output_text=output)
(root/'native-output.json').write_text(json.dumps({
'native_pid': process.pid, 'baseline': output_baseline, 'current': current_output,
'invocation_output': output}, ensure_ascii=False, indent=2), encoding='utf-8')
if result['status'] == 'UNKNOWN_DIALOG' or busy_before_start:
break
if confirmed and not closing and main and not dialogs and main['enabled']:
evidence = _native_evidence(project, database, process.pid, started_ns, baseline)
if (evidence['confirmed'] or (evidence.get('restore_complete')
if (not (database/'cdbsvr/sAddress.adr').exists() and (
evidence['failure_complete'] or evidence['confirmed'] or (evidence.get('restore_complete')
and evidence['native_backup']
and not (database/'cdbsvr/sAddress.adr').exists())):
and evidence['outcome'] == 'UNCONFIRMED'))):
win32gui.PostMessage(main['hwnd'], win32con.WM_CLOSE, 0, 0)
closing = True
emit(stage='native_repair_finished', **evidence)
time.sleep(.2)
if (closing and process.poll() == 0 and evidence and evidence.get('restore_complete')
if evidence:
result['evidence'] = evidence
for log_path in evidence['log_paths']:
source = Path(log_path)
destination = root/'native-logs'/source.relative_to(database/'cdbsvr')
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, destination)
addresses = [str(database/'cdbsvr/sAddress.adr')] if (database/'cdbsvr/sAddress.adr').exists() else []
result['release'] = {'native_exited': process.poll() is not None, 'addresses': addresses,
'safe_to_continue': process.poll() is not None and not addresses}
if result['status'] == 'UNKNOWN_DIALOG':
pass
elif evidence and evidence['outcome'] != 'UNCONFIRMED':
result.update(status=evidence['outcome'], detail='原生 Repair 失败;详见本次日志和 Output')
elif (closing and process.poll() == 0 and evidence and evidence.get('restore_complete')
and not (database/'cdbsvr/sAddress.adr').exists()):
result.update(status='RESTORED_REVIEW_REQUIRED', evidence=evidence,
detail='原生工具从已有备份恢复数据库;需核对恢复版本和工程内容,未自动重试校验')
@@ -215,7 +305,7 @@ def repair_worker_main(job_path):
and not (database/'cdbsvr/sAddress.adr').exists()):
result.update(status='REPAIRED', evidence=evidence)
else:
result.update(status='RETAINED' if process.poll() is None else 'UNCONFIRMED',
result.update(status='TIMEOUT_UNRELEASED' if process.poll() is None else 'UNCONFIRMED',
detail='原生 Repair 未取得完整成功/释放证据,未重试校验')
except Exception as error:
result.update(detail=str(error), status='RETAINED' if process and process.poll() is None else 'BLOCKED')
+5
View File
@@ -103,6 +103,11 @@ def wait_for_target_document(job, app_provider, *, process_alive, emit=lambda **
try:
app = app_provider()
document = app.ActiveDocument
if not document:
observation = ('PCB_DOCUMENT_NOT_READY', 'COM 已连接,尚无目标文档')
if observation != last_observation:
emit(stage='pcb_document_wait', error_code=observation[0], detail=observation[1])
last_observation = observation
if document:
try:
integration = require_document_identity(document, job)
+48 -2
View File
@@ -525,14 +525,54 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
try:
diagnosis = json.loads((result.evidence_path.parent/'diagnostics/icdb-recovery.json').read_text('utf-8'))
original = result
snapshot = original.evidence_path.with_name('pre-repair-result.json')
snapshot.write_text(json.dumps(asdict(original), ensure_ascii=False, default=str, indent=2),
encoding='utf-8')
recovery = attempt_recovery(request, diagnosis, result.evidence_path.parent, progress=progress)
recovery = {**recovery, 'original_error': original.stderr,
'original_evidence': str(original.evidence_path)}
if recovery.get('status') == 'REPAIRED':
'original_evidence': str(original.evidence_path),
'original_result_snapshot': str(snapshot),
'original_stage': original.error_stage,
'native_status': recovery.get('status'), 'validation_passed': False}
if (recovery.get('status') == 'REPAIRED'
and recovery.get('release', {}).get('safe_to_continue') is True):
result = replace(original, recovery_attempts=(recovery,))
recovery['status'] = 'REPAIR_VALIDATION_FAILED'
result = _run_verify_serialized(
replace(request, auto_repair=False), progress=progress, flag_reader=flag_reader,
process_runner=process_runner, port_check=port_check,
dialog_supervisor_factory=dialog_supervisor_factory)
recovery['validation_evidence'] = str(result.evidence_path or '')
recovery['validation_passed'] = (result.status == 'PASS'
and result.library_flag == 'GREEN' and result.safe_to_continue)
if not recovery['validation_passed']:
recovery['status'] = 'REPAIR_VALIDATION_FAILED'
if result.status == 'PASS':
result = replace(result, status='FAIL',
stderr=(result.stderr+'\nREPAIR_VALIDATION_UNCONFIRMED: 未取得校验 GREEN').strip())
else:
recovery['status'] = 'REPAIRED'
elif recovery.get('status') == 'REPAIRED':
recovery['status'] = 'REPAIR_RELEASE_UNCONFIRMED'
result = replace(result, safe_to_continue=False)
else:
# A failed local database must not block unrelated CBBs once
# every owner is released. Re-check target ownership here so
# an incomplete repair record cannot authorize the queue.
safe = False
if (recovery.get('status') in {'MISSING_HEALTHY_BACKUP', 'NATIVE_REPAIR_FAILED'}
and recovery.get('evidence', {}).get('failure_complete') is True
and recovery.get('release', {}).get('safe_to_continue') is True):
from .native_repair import select_repair_target
try:
target = select_repair_target(request, diagnosis)
safe = (Path(recovery.get('project', '')).resolve() == target.project
and Path(recovery.get('database', '')).resolve() == target.database)
except (ValueError, OSError):
pass
result = replace(result, safe_to_continue=safe, stderr=(result.stderr + '\n'
+ str(recovery.get('status', 'REPAIR_UNCONFIRMED')) + ': '
+ str(recovery.get('detail', '原生 Repair 未完成恢复'))).strip())
result = replace(result, recovery_attempts=(recovery,))
result.evidence_path.write_text(json.dumps({'block_name': request.block_name, **asdict(result)},
ensure_ascii=False, default=str, indent=2), encoding='utf-8')
@@ -540,6 +580,12 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
result = replace(result, status='FAIL' if result.status == 'PASS' else result.status,
safe_to_continue=False,
stderr=(result.stderr+f'\nREPAIR_UNCONFIRMED: {error}').strip())
if result.evidence_path:
try:
result.evidence_path.write_text(json.dumps({'block_name': request.block_name, **asdict(result)},
ensure_ascii=False, default=str, indent=2), encoding='utf-8')
except OSError:
pass # Keep the native/repair errors even if evidence storage fails.
return result
finally:
if acquired: