fix: harden PCB and iCDB verification lifecycle for beta release

This commit is contained in:
阿白叔 committed 2026-10-26 15:32:01 +08:00
1 parent 11a2b2e46e
commit a11eb3c766
33 files changed
+1226 -267

No files matched your search

+89 -33
View File
@@ -127,7 +127,7 @@ 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'
if SUCCESS_TEXT.search(output) and not ERROR_TEXT.search(output):
if exit_code == 0 and SUCCESS_TEXT.search(output) and not ERROR_TEXT.search(output):
return 'PASS'
if ERROR_TEXT.search(output):
return 'FAIL'
@@ -156,6 +156,14 @@ def preflight(request):
pcb = absolute_preserving_drive(project.parent/refs[0])
if not pcb.is_relative_to(absolute_preserving_drive(work)):
raise ValueError(f'{name}: PCB 引用越出当前 CBB,停止操作: {pcb}')
real_work = work.resolve()
expected_work = library.parent.resolve() / 'ReusableBlocksLP' / name / 'Work'
if os.path.normcase(str(real_work)) != os.path.normcase(str(expected_work)):
raise ValueError(f'{name}: Work 路径通过链接指向其他工程,停止操作')
for candidate in (project, pcb, pcb.parent/'pcb.prj', pcb.parent/'Layout',
pcb.parent/'Layout'/'LayoutDB.lyt', work/'database', work/'CES'):
if not candidate.resolve().is_relative_to(real_work):
raise ValueError(f'{name}: 文件或目录链接越出当前 CBB,停止操作: {candidate}')
if not pcb.is_file() or not (pcb.parent/'Layout'/'LayoutDB.lyt').is_file():
raise ValueError(f'{name}: 缺少 PCB 或布局数据库: {pcb}')
return project, pcb
@@ -199,7 +207,7 @@ def _run_process(command, timeout_seconds, cwd):
# pipes. Bound both tree termination and the final drain so a hung
# helper cannot turn a 30-second item timeout into an unbounded wait.
try:
subprocess.run(['taskkill', '/PID', str(process.pid), '/T', '/F'],
subprocess.run([str(Path(os.environ.get('WINDIR', r'C:\Windows'))/'System32'/'taskkill.exe'), '/PID', str(process.pid), '/T', '/F'],
capture_output=True, timeout=5,
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
except (OSError, subprocess.TimeoutExpired):
@@ -216,7 +224,7 @@ def _run_process(command, timeout_seconds, cwd):
def _stop_worker(process, *, timeout=5):
"""Best-effort worker tree termination that never masks the item result."""
"""Stop automation clients; native database owners are preserved."""
try:
process.kill()
except Exception:
@@ -269,6 +277,10 @@ def read_library_flag_with_retry(reader, library, block_name, *, attempts=3,
def classify_failure_category(detail):
text = str(detail or '')
lower = text.casefold()
if any(code in lower for code in (
'pcb_release_unconfirmed', 'icdb_release_unconfirmed',
'icdb_session_unconfirmed', 'pcb_session_active', 'database_recovery_required')):
return 'DATABASE_SAFETY_STOP'
if 'tf_floatinglangbar_wndtitle' in lower or 'cicerouiwndframe' in lower:
return 'TOOL_FALSE_DIALOG'
if 'could not load job preferences db' in lower or 'unable to create local cell library' in lower:
@@ -472,13 +484,7 @@ def native_lm_verify_enabled():
def _cleanup_session_processes(root, *, lm_pid, target_pid, pcb, pcb_baseline,
progress=None):
"""Reap Mentor processes after the worker can no longer run its ``finally``.
The outer supervisor owns the worker lifetime. A timeout or an unknown
dialog may therefore terminate the worker while its child LMC/PCB processes
remain alive. Delegate the same target-filtered cleanup used by the worker
and persist its events before the batch advances.
"""
"""Record native release or retention after automation has stopped."""
from .mentor_adapter import cleanup_verify_processes
event_path = Path(root) / 'events.jsonl'
@@ -497,7 +503,7 @@ def _cleanup_session_processes(root, *, lm_pid, target_pid, pcb, pcb_baseline,
if progress:
progress(event)
cleanup_verify_processes(
return cleanup_verify_processes(
lm_pid,
target_pid,
None,
@@ -509,6 +515,29 @@ def _cleanup_session_processes(root, *, lm_pid, target_pid, pcb, pcb_baseline,
def run_verify(request, *, progress=None, flag_reader=None, process_runner=None, port_check=None,
dialog_supervisor_factory=None):
# Cover contents checking, native work and final state reads with one
# session-wide mutex. The worker-stage lock below is reentrant on Windows.
import win32event, win32con
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
acquired = False
try:
acquired = win32event.WaitForSingleObject(mutex, 0) in (
win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
if not acquired:
return VerifyResult('BLOCKED', stderr='已有 CBB 校验任务运行,请等待结束。',
safe_to_continue=False)
return _run_verify_serialized(
request, progress=progress, flag_reader=flag_reader,
process_runner=process_runner, port_check=port_check,
dialog_supervisor_factory=dialog_supervisor_factory)
finally:
if acquired:
win32event.ReleaseMutex(mutex)
mutex.Close()
def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_runner=None,
port_check=None, dialog_supervisor_factory=None):
timing = RunTimings()
result = _run_verify(request, timing=timing, progress=progress, flag_reader=flag_reader,
process_runner=process_runner, port_check=port_check,
@@ -573,12 +602,12 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
runner = process_runner or _run_process
def finish(result):
# Backups are transient protection for the active worker. Keep the
# small, actionable evidence files but reclaim the copied CBB tree so
# large libraries do not accumulate tens of megabytes per item.
# Only reclaim auxiliary backups after confirmed success. Failed runs
# retain every available original file for incident investigation.
try:
from .mentor_adapter import cleanup_evidence_backup
cleanup_evidence_backup(root)
if result.status == 'PASS' and result.safe_to_continue:
cleanup_evidence_backup(root)
except Exception:
# Cleanup must never hide or change the verification result.
pass
@@ -635,6 +664,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,
'supervisor_pid': os.getpid(),
'project': str(project), 'pcb': str(pcb), 'root': str(root), 'timeout': request.timeout_seconds,
'mentor_bin': str(request.mentor_bin or ''),
'mapped_drive': str(request.mapped_drive or ''),
@@ -789,11 +819,11 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
'FAIL',
stderr=f'{dialog_result.error_code}: {dialog_result.detail}',
error_stage=phase.value,
safe_to_continue=True,
safe_to_continue=False,
))
if deadline.expired():
_write_failure_windows(root, latest_snapshots)
# Kills the worker's whole job: worker, PCB and cscript helper.
# Stop automation without killing PCB/iCDB during a write.
_write_process_tree(root, process, target_pid)
if last_post_verify_observation:
(root/'post_verify_observations.jsonl').write_text(json.dumps({
@@ -817,8 +847,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
'detail': detail,
'observation': last_post_verify_observation,
})
return finish(VerifyResult(status, stderr=detail, safe_to_continue=True))
return finish(VerifyResult('TIMEOUT', stderr='操作超时;已记录现场,跳过当前 CBB。', error_stage=phase.value, safe_to_continue=True))
return finish(VerifyResult(status, stderr=detail, safe_to_continue=False))
return finish(VerifyResult('TIMEOUT', stderr='操作超时;已停止自动化并保留原生会话,停止批次,请检查恢复记录。', error_stage=phase.value, safe_to_continue=False))
time.sleep(.2)
worker_result = root/'outcome.json'
if not worker_result.exists():
@@ -832,12 +862,20 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
_stop_worker(process)
return finish(VerifyResult('FAIL', stderr=str(error), safe_to_continue=False))
finally:
close_errors = []
if 'dialog_agent' in locals() and dialog_agent is not None:
dialog_agent.close()
if 'process' in locals(): process.close()
try:
dialog_agent.close()
except Exception as error:
close_errors.append(str(error))
if 'process' in locals():
try:
_cleanup_session_processes(
process.close()
except Exception as error:
close_errors.append(str(error))
if 'process' in locals():
try:
release_result = _cleanup_session_processes(
root,
lm_pid=lm_pid,
target_pid=target_pid,
@@ -845,11 +883,30 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
pcb_baseline=pcb_baseline,
progress=progress,
)
except Exception:
# Cleanup is best effort; the original Verify result remains
# authoritative and the evidence directory records everything
# that was successfully reaped.
pass
except Exception as error:
release_result = {'safe_to_continue': False, 'error': str(error)}
try:
address = Path(project).parent / 'database/cdbsvr/sAddress.adr'
if address.exists():
release_result = {**(release_result or {}), 'safe_to_continue': False,
'icdb_address': str(address)}
except OSError as error:
close_errors.append(str(error))
if close_errors:
release_result = {**(release_result or {}), 'safe_to_continue': False,
'close_errors': close_errors}
if not release_result or not release_result.get('safe_to_continue'):
if 'result' in locals():
result = replace(result, status='FAIL', safe_to_continue=False,
stderr=(result.stderr + '\nPCB_RELEASE_UNCONFIRMED: 未确认原生会话退出').strip())
recovery = {'desktop': job['desktop'], 'project': str(project),
'pcb': str(pcb), 'release': release_result,
'action': '停止批次;检查原生会话及数据库;不要删除锁文件或自动恢复。'}
try:
(root/'recovery-required.json').write_text(
json.dumps(recovery, ensure_ascii=False, indent=2), encoding='utf-8')
except OSError:
pass # Evidence failure must not prevent mutex release.
# Drain the timing tail even when the worker exited before a poll.
# This is optional telemetry: an unreadable log must not mask failure
# or prevent releasing the serial-operation mutex.
@@ -891,7 +948,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=None):
"""Run CBBs serially; one item's failure never aborts the queue."""
"""Run serially and stop when database/session safety is unconfirmed."""
if max_workers != 1:
raise ValueError('Only serial Verify is supported for the shared Library Manager session')
if verifier is None:
@@ -905,13 +962,12 @@ def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=Non
try:
result = verifier(request)
except Exception as error:
# An unexpected worker exception is a failed item, not a batch abort.
# An unexpected exception cannot establish database safety.
result = VerifyResult('FAIL', stderr=str(error), safe_to_continue=False)
results.append(result)
# Failure status and safe_to_continue describe this item, not the batch;
# the queue is skipped only after an explicit stop signal.
queue_stop = queue_stop or result.status == 'QUEUE_STOP'
if result.status == 'QUEUE_STOP' and stop is not None:
# Never start another writer after an unconfirmed native shutdown.
queue_stop = queue_stop or result.status == 'QUEUE_STOP' or not result.safe_to_continue
if queue_stop and stop is not None:
stop.set()
if progress: progress(request.block_name, result)
return results