fix: diagnose iCDB lost sessions and stop unsafe verification
This commit is contained in:
1 parent
a11eb3c766
commit
8a517d6f38
9 files changed
+685
-14
No files matched your search
@@ -193,6 +193,10 @@ def decide(snapshot: WindowSnapshot, rules: Sequence[DialogRule]) -> RuleDecisio
|
||||
and not snapshot.controls):
|
||||
return RuleDecision(rule_id='ime-floating-language-bar', category='OBSERVE_PROGRESS')
|
||||
combined = normalize_text(' '.join((snapshot.title, *snapshot.texts)))
|
||||
from .icdb_recovery import ERROR_CODE, parse_session_loss
|
||||
if parse_session_loss(combined):
|
||||
return RuleDecision(error_code=ERROR_CODE,
|
||||
detail=' | '.join(snapshot.texts) or snapshot.title)
|
||||
# These prompts require knowledge of database ownership or a recovery
|
||||
# choice. A generic Yes/restore rule cannot establish either fact.
|
||||
if any(marker in combined for marker in (
|
||||
|
||||
@@ -351,6 +351,11 @@ def classify_dialog(snapshot: DialogSnapshot) -> DialogDecision:
|
||||
joined = " ".join(snapshot.texts).casefold()
|
||||
combined = f"{title} {joined}"
|
||||
|
||||
from .icdb_recovery import ERROR_CODE, parse_session_loss
|
||||
if parse_session_loss(combined):
|
||||
return DialogDecision(error_code=ERROR_CODE,
|
||||
detail=' | '.join(snapshot.texts) or snapshot.title)
|
||||
|
||||
if ("problem encountered while opening one of the database files" in combined
|
||||
and "loading of the job has failed" in combined):
|
||||
return DialogDecision(action="decline_database_log",
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
"""Recognize native iCDB recovery requests without changing database state."""
|
||||
import hashlib
|
||||
import ntpath
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
|
||||
ERROR_CODE = 'ICDB_REPAIR_REQUIRED'
|
||||
LOG_LIMIT = 128 * 1024
|
||||
RECOVERY_ACTION = (
|
||||
'停止批次并确认原服务器及其他客户端已正常关闭;保留完整一致副本后,'
|
||||
"使用同版本 iCDB Project Backup 的 Repair project 检查并修复正确目标。"
|
||||
'共享符号库问题需核对中心库,不能只修复单个 CBB 的 Work 工程。'
|
||||
'不要删除 sAddress.adr/锁文件;修复后重新打开、校验并确认权威 READY。'
|
||||
)
|
||||
_SESSION_LOSS = re.compile(
|
||||
r'\bthe\s+last\s+server\s+session\s+on\s+different\s+server\s+machine\s+'
|
||||
r'lost\s+the\s+connection\s+to\s+the\s+database\b', re.IGNORECASE)
|
||||
|
||||
|
||||
def parse_session_loss(text):
|
||||
"""Keep the native target verbatim; never infer a local repair target."""
|
||||
text = str(text or '')
|
||||
match = _SESSION_LOSS.search(text)
|
||||
if match is None:
|
||||
return None
|
||||
# A log may contain several sessions. Use the identity following this
|
||||
# error, never an unrelated Machine/Path header earlier in the log.
|
||||
message = text[match.start():]
|
||||
next_error = _SESSION_LOSS.search(message, 1)
|
||||
if next_error:
|
||||
message = message[:next_error.start()]
|
||||
record = {'error_code': ERROR_CODE, 'native_message': message,
|
||||
'machine': '', 'database_path': '', 'session': '', 'scope': 'unknown'}
|
||||
for native_key, key in (('machine', 'machine'), ('path', 'database_path'),
|
||||
('session', 'session')):
|
||||
field = re.search(
|
||||
rf'\b{native_key}\s*:\s*(?:\[([^\]]*)\]|([^\r\n]*?)(?=\s+\b(?:machine|path|session)\s*:|[\r\n]|$))',
|
||||
message, re.IGNORECASE)
|
||||
if field:
|
||||
record[key] = (field.group(1) if field.group(1) is not None else field.group(2)).strip()
|
||||
parts = ntpath.normpath(record['database_path']).casefold().split('\\')
|
||||
if 'symbollibs' in parts:
|
||||
record['scope'] = 'central_library'
|
||||
elif 'work' in parts and parts[-1] == 'database':
|
||||
record['scope'] = 'project'
|
||||
return record
|
||||
|
||||
|
||||
def recovery_detail(record):
|
||||
target = ('中心库共享符号数据库' if record['scope'] == 'central_library' else
|
||||
'工程数据库' if record['scope'] == 'project' else '报错中指定的数据库')
|
||||
return (
|
||||
f"{ERROR_CODE}: {target}的上次服务器会话失联。\n"
|
||||
f"{record['native_message']}\n"
|
||||
f'{RECOVERY_ACTION}'
|
||||
)
|
||||
|
||||
|
||||
def snapshot_log(path):
|
||||
"""Fingerprint a bounded tail before launch, including a missing log."""
|
||||
try:
|
||||
with Path(path).open('rb') as stream:
|
||||
stream.seek(0, 2)
|
||||
size = stream.tell()
|
||||
stream.seek(max(0, size-LOG_LIMIT))
|
||||
tail = stream.read(LOG_LIMIT)
|
||||
losses = [_session_identity(record) for record in _session_losses(decode_log(tail))]
|
||||
return {'size': size, 'tail_sha256': hashlib.sha256(tail).hexdigest(),
|
||||
'truncated': size > LOG_LIMIT,
|
||||
'session_losses': losses}
|
||||
except FileNotFoundError:
|
||||
return {'size': 0, 'tail_sha256': hashlib.sha256(b'').hexdigest()}
|
||||
except OSError as error:
|
||||
return {'error': str(error)}
|
||||
|
||||
|
||||
def _read_log_delta(path, baseline):
|
||||
"""Read new bytes, detecting truncate/rewrite as well as append.
|
||||
|
||||
Unknown baselines cannot prove freshness. At most two bounded tails are
|
||||
read, even when a native log is large or located on a network share.
|
||||
"""
|
||||
if not baseline or 'error' in baseline:
|
||||
return b'', False
|
||||
old_size = int(baseline['size'])
|
||||
try:
|
||||
with Path(path).open('rb') as stream:
|
||||
stream.seek(0, 2)
|
||||
size = stream.tell()
|
||||
offset = 0
|
||||
appended = False
|
||||
if size >= old_size:
|
||||
stream.seek(max(0, old_size-LOG_LIMIT))
|
||||
old_tail = stream.read(min(old_size, LOG_LIMIT))
|
||||
if hashlib.sha256(old_tail).hexdigest() == baseline['tail_sha256']:
|
||||
offset = old_size
|
||||
appended = True
|
||||
stream.seek(max(offset, size-LOG_LIMIT))
|
||||
return stream.read(LOG_LIMIT), appended
|
||||
except OSError:
|
||||
return b'', False
|
||||
|
||||
|
||||
def _session_losses(text):
|
||||
matches = list(_SESSION_LOSS.finditer(text))
|
||||
for index, match in enumerate(matches):
|
||||
end = matches[index+1].start() if index+1 < len(matches) else len(text)
|
||||
yield parse_session_loss(text[match.start():end])
|
||||
|
||||
|
||||
def _session_identity(record):
|
||||
return [record[key] for key in ('machine', 'database_path', 'session')]
|
||||
|
||||
|
||||
def read_log_failure(path, baseline):
|
||||
"""Return new log text and a recovery request with evidence of freshness.
|
||||
|
||||
A rewritten header does not prove that a retained old session failed
|
||||
again. In that ambiguous case keep the generic failure; a verified append
|
||||
can report even the same old session as a current native error.
|
||||
"""
|
||||
data, appended = _read_log_delta(path, baseline)
|
||||
text = decode_log(data)
|
||||
if not appended and baseline and baseline.get('truncated'):
|
||||
# A rewrite may expose an old error outside our bounded baseline.
|
||||
# Without positive append evidence its age cannot be established.
|
||||
return text, None
|
||||
historical = baseline.get('session_losses', []) if baseline else []
|
||||
recovery = next((record for record in _session_losses(text)
|
||||
if appended or _session_identity(record) not in historical), None)
|
||||
return text, recovery
|
||||
|
||||
|
||||
def decode_log(data):
|
||||
if data.startswith((b'\xff\xfe', b'\xfe\xff')):
|
||||
return data.decode('utf-16', errors='replace')
|
||||
# Appended UTF-16 bytes and bounded tails no longer contain a BOM.
|
||||
sample = data[:200]
|
||||
if sample[1::2].count(0) > len(sample)//8:
|
||||
return data.decode('utf-16-le', errors='replace')
|
||||
if sample[::2].count(0) > len(sample)//8:
|
||||
return data.decode('utf-16-be', errors='replace')
|
||||
return data.decode('utf-8', errors='replace')
|
||||
@@ -647,10 +647,8 @@ def execute_job(job, emit):
|
||||
evidence=str(root/'diagnostics/preflight.json'))
|
||||
cert_project = block_root/'Cert'/Path(job['project']).name
|
||||
pcb_log = Path(job['pcb']).parent/'LogFiles'/'PCBLogFile.txt'
|
||||
try:
|
||||
pcb_log_offset = pcb_log.stat().st_size
|
||||
except OSError:
|
||||
pcb_log_offset = 0
|
||||
from .icdb_recovery import snapshot_log
|
||||
pcb_log_offset = snapshot_log(pcb_log)
|
||||
integration_log_dir = Path(job['pcb']).parent / 'LogFiles'
|
||||
integration_offsets = {}
|
||||
for name in ('ForwardAnnotation.txt', 'MsgBoxResponse.log', 'PartPkg.log'):
|
||||
@@ -664,6 +662,26 @@ def execute_job(job, emit):
|
||||
}
|
||||
except OSError:
|
||||
integration_offsets[path] = {'size': 0, 'mtime_ns': None, 'digest': ''}
|
||||
integration_offsets[path]['icdb_baseline'] = snapshot_log(path)
|
||||
try:
|
||||
(root/'diagnostics/startup-log-baseline.json').write_text(json.dumps({
|
||||
'source': str(pcb_log), 'baseline': pcb_log_offset,
|
||||
'integration_logs': {str(path): value['icdb_baseline']
|
||||
for path, value in integration_offsets.items()},
|
||||
}, ensure_ascii=False), encoding='utf-8')
|
||||
except OSError as error:
|
||||
emit(stage='startup_log_baseline_unavailable', detail=str(error))
|
||||
|
||||
def native_error():
|
||||
# Inspect every source before returning a generic server/packager
|
||||
# failure: either can be a consequence of a lost library session.
|
||||
startup = pcb_log_reports_missing_server(job['pcb'], offset=pcb_log_offset)
|
||||
integration = pcb_log_reports_integration_error(job['pcb'], offsets=integration_offsets)
|
||||
if 'ICDB_REPAIR_REQUIRED' in startup:
|
||||
return startup
|
||||
if 'ICDB_REPAIR_REQUIRED' in integration:
|
||||
return integration
|
||||
return startup or integration
|
||||
emit(stage='pcb_baseline', pids=sorted(pcb_before))
|
||||
lm_session = None
|
||||
lm_pid = None
|
||||
@@ -735,7 +753,7 @@ def execute_job(job, emit):
|
||||
process_alive=lambda: any(candidate_pid in {lm_pid, worker_pid, worker_parent_pid}
|
||||
for candidate_pid, _, _ in pcb_processes()),
|
||||
emit=emit,
|
||||
error_reader=lambda: pcb_log_reports_missing_server(job['pcb'], offset=pcb_log_offset),
|
||||
error_reader=native_error,
|
||||
)
|
||||
# Do not acquire MGCPCBAutomationLicensing from this 64-bit Python
|
||||
# worker. EE7.9 registers that automation class for the 32-bit host;
|
||||
@@ -746,7 +764,7 @@ def execute_job(job, emit):
|
||||
pi,
|
||||
emit=emit,
|
||||
timeout_seconds=job['timeout'],
|
||||
error_reader=lambda: pcb_log_reports_integration_error(job['pcb'], offsets=integration_offsets),
|
||||
error_reader=native_error,
|
||||
)
|
||||
# The x86 helper acquires its own COM references. Keeping these Python
|
||||
# references alive prevents the native PCB server from exiting cleanly.
|
||||
@@ -1040,17 +1058,27 @@ def icdb_ports_bindable(ports=(10000, 10050, 10100)):
|
||||
|
||||
|
||||
def pcb_log_reports_missing_server(pcb_path, *, offset=0):
|
||||
"""Detect the same failure from ExpeditionPCB's own log, as a second signal."""
|
||||
"""Detect startup failure from this run, preserving native recovery causes."""
|
||||
from .icdb_recovery import (decode_log, parse_session_loss, read_log_failure,
|
||||
recovery_detail)
|
||||
log = Path(pcb_path).parent/'LogFiles'/'PCBLogFile.txt'
|
||||
try:
|
||||
with log.open('rb') as stream:
|
||||
stream.seek(max(0, offset))
|
||||
text = stream.read().decode('utf-8', errors='replace')
|
||||
if isinstance(offset, dict):
|
||||
text, recovery = read_log_failure(log, offset)
|
||||
else:
|
||||
# Retain the byte-offset interface for existing diagnostic callers.
|
||||
with log.open('rb') as stream:
|
||||
stream.seek(max(0, offset))
|
||||
text = decode_log(stream.read())
|
||||
recovery = parse_session_loss(text)
|
||||
except Exception:
|
||||
return ''
|
||||
if recovery:
|
||||
return recovery_detail(recovery)
|
||||
for marker in ("could not bring it alive", 'Could not run server'):
|
||||
if marker.lower() in text.lower():
|
||||
return RESERVED_PORT_MESSAGE
|
||||
return (f'DESIGN_SERVER_FAILED: {marker}。请检查本轮原生日志中的数据库/服务器原因;'
|
||||
'此信息本身不能证明端口被系统保留。')
|
||||
return ''
|
||||
|
||||
|
||||
@@ -1065,6 +1093,7 @@ _INTEGRATION_ERROR_LINE = re.compile(
|
||||
|
||||
def pcb_log_reports_integration_error(pcb_path, *, offsets=None):
|
||||
"""Read explicit Project Integration errors produced by this run."""
|
||||
from .icdb_recovery import parse_session_loss, read_log_failure, recovery_detail
|
||||
log_dir = Path(pcb_path).parent / 'LogFiles'
|
||||
offsets = offsets or {}
|
||||
details = []
|
||||
@@ -1073,6 +1102,19 @@ def pcb_log_reports_integration_error(pcb_path, *, offsets=None):
|
||||
try:
|
||||
size = path.stat().st_size
|
||||
baseline = offsets.get(path, offsets.get(str(path), 0))
|
||||
has_icdb_baseline = isinstance(baseline, dict) and any(
|
||||
key in baseline for key in ('icdb_baseline', 'tail_sha256', 'error'))
|
||||
icdb_baseline = baseline.get('icdb_baseline', baseline) if isinstance(baseline, dict) else None
|
||||
if icdb_baseline and 'tail_sha256' in icdb_baseline:
|
||||
text, recovery = read_log_failure(path, icdb_baseline)
|
||||
if recovery:
|
||||
return recovery_detail(recovery)
|
||||
if 'tail_sha256' in baseline:
|
||||
# New bounded checkpoints can also be supplied directly.
|
||||
details.extend(line.strip() for line in text.splitlines()
|
||||
if _INTEGRATION_ERROR_LINE.search(line.strip())
|
||||
and not parse_session_loss(line))
|
||||
continue
|
||||
if isinstance(baseline, dict):
|
||||
baseline_size = int(baseline.get('size', 0) or 0)
|
||||
baseline_mtime = baseline.get('mtime_ns')
|
||||
@@ -1103,8 +1145,17 @@ def pcb_log_reports_integration_error(pcb_path, *, offsets=None):
|
||||
text = stream.read().decode('utf-8', errors='replace')
|
||||
except OSError:
|
||||
continue
|
||||
# Legacy byte offsets/digests remain accepted by offline callers.
|
||||
if not has_icdb_baseline:
|
||||
recovery = parse_session_loss(text)
|
||||
if recovery:
|
||||
return recovery_detail(recovery)
|
||||
for line in text.splitlines():
|
||||
cleaned = line.strip()
|
||||
if has_icdb_baseline and parse_session_loss(cleaned):
|
||||
# read_log_failure already rejected this retained old session.
|
||||
# Do not let the generic ERROR filter promote it again.
|
||||
continue
|
||||
if _INTEGRATION_ERROR_LINE.search(cleaned) and cleaned not in details:
|
||||
details.append(cleaned)
|
||||
return ' | '.join(details[:8])
|
||||
|
||||
@@ -113,6 +113,8 @@ def collect_native_failure_logs(pcb_path, evidence_root, *, max_bytes=NATIVE_LOG
|
||||
target = destination/(label+'-'+source.name)
|
||||
target.write_bytes(data)
|
||||
item.update(evidence=str(target), copied_bytes=len(data))
|
||||
if label == 'pcb-logfiles' and source.name != 'ReusableBlock.txt':
|
||||
_collect_icdb_recovery(source, evidence_root)
|
||||
except FileNotFoundError:
|
||||
item['exists'] = False
|
||||
except OSError as error:
|
||||
@@ -120,6 +122,23 @@ def collect_native_failure_logs(pcb_path, evidence_root, *, max_bytes=NATIVE_LOG
|
||||
return _write_record(destination.parent/'native-logs.json', record)
|
||||
|
||||
|
||||
def _collect_icdb_recovery(source, evidence_root):
|
||||
"""Only promote a native error whose log changed after this launch."""
|
||||
from .icdb_recovery import read_log_failure
|
||||
root = Path(evidence_root)/'diagnostics'
|
||||
try:
|
||||
baseline = json.loads((root/'startup-log-baseline.json').read_text('utf-8'))
|
||||
checkpoint = (baseline['baseline'] if baseline['source'] == str(source) else
|
||||
baseline.get('integration_logs', {}).get(str(source)))
|
||||
if checkpoint is None:
|
||||
return
|
||||
_, recovery = read_log_failure(source, checkpoint)
|
||||
if recovery:
|
||||
_write_record(root/'icdb-recovery.json', {**recovery, 'source': str(source)})
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
pass # Unknown freshness must not replace the original failure.
|
||||
|
||||
|
||||
|
||||
def failure_logs_main(request_path):
|
||||
job = json.loads(Path(request_path).read_text(encoding='utf-8'))
|
||||
|
||||
@@ -127,6 +127,9 @@ def classify_output(exit_code: int | None, output: str, *, timed_out: bool = Fal
|
||||
"""Never invent success: PASS needs the success text and no error marker."""
|
||||
if timed_out:
|
||||
return 'TIMEOUT'
|
||||
from .icdb_recovery import parse_session_loss
|
||||
if parse_session_loss(output):
|
||||
return 'FAIL'
|
||||
if exit_code == 0 and SUCCESS_TEXT.search(output) and not ERROR_TEXT.search(output):
|
||||
return 'PASS'
|
||||
if ERROR_TEXT.search(output):
|
||||
@@ -277,6 +280,9 @@ def read_library_flag_with_retry(reader, library, block_name, *, attempts=3,
|
||||
def classify_failure_category(detail):
|
||||
text = str(detail or '')
|
||||
lower = text.casefold()
|
||||
from .icdb_recovery import ERROR_CODE, parse_session_loss
|
||||
if ERROR_CODE.casefold() in lower or parse_session_loss(text):
|
||||
return ERROR_CODE
|
||||
if any(code in lower for code in (
|
||||
'pcb_release_unconfirmed', 'icdb_release_unconfirmed',
|
||||
'icdb_session_unconfirmed', 'pcb_session_active', 'database_recovery_required')):
|
||||
@@ -554,6 +560,31 @@ def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_
|
||||
pass
|
||||
finally:
|
||||
timing.end('failure_diagnostics')
|
||||
if result.status not in {'PASS', 'SKIPPED', 'QUEUE_STOP'}:
|
||||
from .icdb_recovery import ERROR_CODE, RECOVERY_ACTION, parse_session_loss, recovery_detail
|
||||
recovery = parse_session_loss(result.stderr)
|
||||
if recovery is None and result.evidence_path:
|
||||
try:
|
||||
saved = json.loads(result.evidence_path.with_name('diagnostics').joinpath(
|
||||
'icdb-recovery.json').read_text('utf-8'))
|
||||
recovery = parse_session_loss(saved.get('native_message', ''))
|
||||
except (OSError, ValueError, AttributeError):
|
||||
pass
|
||||
if recovery or ERROR_CODE.casefold() in result.stderr.casefold():
|
||||
detail = result.stderr
|
||||
if recovery and RECOVERY_ACTION not in detail:
|
||||
detail = (detail + '\n' + recovery_detail(recovery)).strip()
|
||||
result = replace(result, safe_to_continue=False, stderr=detail,
|
||||
error_category=ERROR_CODE)
|
||||
if recovery and result.evidence_path:
|
||||
try:
|
||||
record_path = result.evidence_path.parent/'diagnostics/icdb-recovery.json'
|
||||
record_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if not record_path.is_file():
|
||||
record_path.write_text(json.dumps(recovery, ensure_ascii=False, indent=2),
|
||||
encoding='utf-8')
|
||||
except OSError:
|
||||
pass
|
||||
durations, unfinished = timing.snapshot()
|
||||
result = replace(result, timings_seconds=durations, incomplete_timing_phases=unfinished,
|
||||
error_category=(result.error_category or classify_failure_category(result.stderr)
|
||||
|
||||
Reference in new issue
Block a user