fix: prevent iCDB disconnects and recover failed projects

This commit is contained in:
阿白叔 committed 2026-10-27 17:51:53 +08:00
1 parent 8a517d6f38
commit 2490067b2d
19 files changed
+1117 -60

No files matched your search

+3 -2
View File
@@ -6,7 +6,8 @@
针对 `The last server session ... lost the connection to the database`,修复分支增加
`ICDB_REPAIR_REQUIRED` 专项识别、共享符号库路径诊断及停止批次处理。现场原生修复步骤及实现边界见
[iCDB 旧服务器会话失联分析](docs/diagnostics/2026-10-27-icdb-lost-server-session.md)。该分支不会自动修复受损数据库。
[iCDB 旧服务器会话失联分析](docs/diagnostics/2026-10-27-icdb-lost-server-session.md)。
当前分支会在目标明确、完整备份和所有权释放证据齐全时尝试一次同版本原生 Repair;共享符号库没有 PRJ 入口时停止并要求人工处理。
## 功能边界
@@ -140,7 +141,7 @@ python -m cbb_refresh_verify
- **不注入鼠标或键盘输入,不切换 Windows 桌面,不改写中心库源文件。** 生产路径在本次运行创建的私有桌面内启动中心库目录绑定的 ReusableCircuit PCB,随后用 COM 完成刷新、保存和关闭;只读状态桥在结束后确认 LMC 的 READY。Library Manager 菜单派发仅作为显式诊断路径保留。`tests/test_safety.py` 会在离线测试中阻止真实输入注入 API 重新进入生产代码。
- 所有自动化都跑在本进程创建的**私有 Windows 桌面**上:用户看不到窗口,光标不会被移动。
- 弹窗只认领本次运行的私有桌面/进程,依据已知规则投递 `BM_CLICK`。数据库恢复、会话失联和设计锁接管提示会阻断并保留现场;不会自动选择恢复或接管。未知弹窗也会阻断,Project Integration 进度窗保持观察。动作/错误弹窗和实际控件 ID 写入 `dialogs.jsonl`。
- 超时或失败时停止自动化客户端,保留可能仍在写库的原生会话并停止批次。监督器核对进程是否退出,记录 `process_exit_confirmed` 或 `process_retained`;无法确认释放时输出 `recovery-required.json`,不以强杀代替数据库安全关闭。
- 超时或失败时停止自动化客户端,保留可能仍在写库的原生会话并停止批次。内容检查超时也不再强杀整个进程树;监督器核对进程是否退出,记录 `process_exit_confirmed` 或 `process_retained`;无法确认释放时输出 `recovery-required.json`,不以强杀代替数据库安全关闭。已确认身份且原生调用返回的失败文档会通过 32 位助手执行 `Close(False)`,再确认进程和 iCDB 地址释放。
## 环境要求
@@ -97,7 +97,16 @@ Session: [2026-10-24 08.22.29-10308]
重写误判、不可读/超出窗口的基线问题,均补充回归并通过复核。
本分支修复自动化的错误识别、误导性建议和失败后的继续执行风险,
**没有修复现场受损数据库,也没有验证原生 Repair 的现场效果**。
现在还会在目标明确、会话完全释放且完整备份成功时,自动调用同版本原生
Project → Repair,并只在原生诊断、Project Repair 备份、目标数据库关闭等
证据全部满足时重试一次校验。共享符号库路径没有 PRJ 入口时会明确阻断,
不会猜测或改修某个 CBB 的 Work 数据库。
这次在新复制的 IP101GR 工程上完成了真实隔离验证:Repair 菜单确认、完整
备份、原生 `dbcheck`/数据库日志、`Project Repair` ZIP 校验和数据库关闭均
成功;Repair worker 退出码为 0,随后才允许重试。该验证没有接触生产库。
仍然**没有修复现场受损数据库,也没有在 `200091-CBB` 上执行恢复**。
恢复识别仅覆盖已知日志末尾的有限窗口;错误出现在窗口外、相同历史会话
在重写时被原样重报、超出基线窗口的大日志发生重写、以及现场不同日志位置/格式,
仍需结合完整原生日志确认。这些不能确认新旧的情况不会自动提升为本轮修复诊断。
@@ -0,0 +1,38 @@
# iCDB failure lifecycle and recovery implementation plan
**Goal:** Prevent failed verification from aborting iCDB owners, close owned idle failed documents normally, and attempt native recovery only against a validated idle target with a complete backup.
**Context:** User confirmed the incident used r4 or earlier. r4 enables `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`, calls `TerminateJobObject` and `taskkill /T /F` on failures and native owners. a11eb3c removed those PCB paths, but content-check timeout still kills a process tree. Failed worker exceptions currently release COM references without requesting normal document closure.
**Architecture:** Keep native transactions alive through timeouts. Signal cooperative cancellation to the worker; let blocking native calls return before closing a document. A separate recovery module owns target checks, backup and the official GUI repair transaction; failed or ambiguous repair remains failed. Work and central-library database ownership are checked separately.
**Tech stack:** Python 3.12, Windows process handles/private desktops, x86 cscript and Mentor EE7.9.5 native tools. Continue on `codex/icdb-lost-session-diagnostics`.
## Task 1 — Retain native owners on content timeout
- [ ] Add a regression that starts a harmless importer with a harmless child, times out, and checks both survive until normal exit or test cleanup.
- [ ] Add a content-timeout batch regression proving the second item does not start.
- [ ] Remove tree/client termination from `_run_process` timeout; retain/drain the process in a background observer, record PID/command/release in evidence, and return TIMEOUT with `safe_to_continue=False`.
- [ ] Verify targeted tests and the existing content-check tests.
## Task 2 — Normal close of failed owned sessions
- [ ] Add x86 cscript harness tests for failed Save and close-only operation, checking `Close(False)`, reference release and Quit, with failure status preserved and mismatched identity untouched.
- [ ] Implement an identity-checked close helper and call it only after the worker has returned from its native call and released Python references. Retain busy helpers instead of terminating them.
- [ ] Add cooperative cancellation at Python/VBS native-operation boundaries; a supervisor timeout/crash must not terminate a pending native Save.
- [ ] Add targeted tests for cancel before Save, cancel after a pending call returns, supervisor loss and blocked native-call retention.
- [ ] Check shared `SymbolLibs/__ReusableBlocksSymb` ownership as well as Work/PCB database ownership before writing and before declaring release.
- [ ] Give the status reader an EOF shutdown grace period before any fallback termination.
## Task 3 — Attempt official native recovery
- [ ] Probe native UI on new isolated copies only; record accepted project/database identity, exact command, backup creation and completion signals. Do not invent CLI Repair flags or manipulate native ownership metadata.
- [ ] Add recovery-policy tests: reject foreign/unresolved targets, active clients, inconsistent backups and repeat repair; preserve the original error; at most one recovery attempt.
- [ ] Implement the supported native repair route with a complete backup and exact target checks. If the installed native tool cannot accept a shared symbol database, retain that explicit blocked result instead of repairing an unrelated Work project.
- [ ] Retry opening/verifying only after native success and confirmed release; authoritative READY remains the success criterion.
## Validation and delivery
- [ ] Run full Python and PowerShell regressions, compilation and whitespace checks, plus independent code review.
- [ ] Verify a successful native run and a controlled failed integration/close on an isolated library, and source fingerprints afterward.
- [ ] Record precisely which recovery target types were actually exercised and any remaining field-only limitations; commit changes on the current branch.
+2 -1
View File
@@ -13,11 +13,12 @@ a = Analysis(
if verify_probe_path.is_file() else []
),
datas=[(str(project_root / 'src' / 'cbb_refresh_verify' / 'save_verified_block.vbs'), 'cbb_refresh_verify'),
(str(project_root / 'src' / 'cbb_refresh_verify' / 'close_failed_block.vbs'), 'cbb_refresh_verify'),
(str(assets_root / 'cbb_refresh_verify.ico'), 'cbb_refresh_verify/assets'),
(str(assets_root / 'cbb_refresh_verify.png'), 'cbb_refresh_verify/assets'),
(str(assets_root / 'cbb_refresh_verify.svg'), 'cbb_refresh_verify/assets'),
(str(assets_root / 'dialog_rules.v1.json'), 'cbb_refresh_verify/assets')],
hiddenimports=['win32com.client','win32com.client.dynamic','pythoncom','pywintypes','win32job','pywinauto','pywinauto.uia_defines','pywinauto.controls.uiawrapper','pywinauto.win32_element_info','cbb_refresh_verify.dialog_agent','cbb_refresh_verify.dialog_probe','cbb_refresh_verify.dialog_rules','cbb_refresh_verify.ui.main_window','dx_productivity.trial_task_center.logging_setup','dx_productivity.trial_task_center.errors','dx_productivity.trial_task_center.retention'],
hiddenimports=['win32com.client','win32com.client.dynamic','pythoncom','pywintypes','win32job','pywinauto','pywinauto.uia_defines','pywinauto.controls.uiawrapper','pywinauto.win32_element_info','cbb_refresh_verify.dialog_agent','cbb_refresh_verify.dialog_probe','cbb_refresh_verify.dialog_rules','cbb_refresh_verify.ui.main_window','cbb_refresh_verify.content_check','cbb_refresh_verify.failed_session','cbb_refresh_verify.icdb_ownership','cbb_refresh_verify.native_repair','cbb_refresh_verify.native_repair_ui','dx_productivity.trial_task_center.logging_setup','dx_productivity.trial_task_center.errors','dx_productivity.trial_task_center.retention'],
excludes=['PySide6.QtDesigner','PySide6.QtMultimedia','PySide6.QtMultimediaWidgets','PySide6.QtOpenGL','PySide6.QtOpenGLWidgets','PySide6.QtPdf','PySide6.QtPdfWidgets','PySide6.QtQml','PySide6.QtQuick','PySide6.QtQuickWidgets','PySide6.QtWebChannel','PySide6.QtWebEngineCore','PySide6.QtWebEngineWidgets'],
)
excluded_qt_binaries = {'icudt78.dll','icuuc.dll','qpdf.dll','qt6pdf.dll','qt6qml.dll','qt6qmlmeta.dll','qt6qmlmodels.dll','qt6qmlworkerscript.dll','qt6quick.dll','qt6quickwidgets.dll'}
+4
View File
@@ -46,6 +46,7 @@ def resolve_data_root(cli_value: Path | None) -> Path:
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser(prog="CbbRefreshVerify")
parser.add_argument('--verify-worker', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--repair-worker', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--dialog-agent', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--collect-failure-logs', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--batch-lmc', type=Path, help=argparse.SUPPRESS)
@@ -55,6 +56,9 @@ def main(argv: Sequence[str] | None = None) -> int:
parser.add_argument('--mentor-bin', default='', help=argparse.SUPPRESS)
parser.add_argument("--smoke-test", action="store_true", help=argparse.SUPPRESS); parser.add_argument("--data-root", type=Path, help=argparse.SUPPRESS)
args = parser.parse_args(list(argv) if argv is not None else None)
if args.repair_worker:
from .native_repair_ui import repair_worker_main
return repair_worker_main(args.repair_worker)
if args.collect_failure_logs:
from .verify_diagnostics import failure_logs_main
return failure_logs_main(args.collect_failure_logs)
@@ -0,0 +1,29 @@
Option Explicit
Dim app, doc, pi, licensing, token, closed, remaining
Set app = GetObject(, "MGCPCB.Application")
Set doc = app.ActiveDocument
If doc Is Nothing Then WScript.Quit 3
Set pi = doc.ProjectIntegration
If LCase(pi.ProjectFile) <> LCase(WScript.Arguments(0)) Then WScript.Quit 2
If LCase(doc.Name) <> LCase(WScript.Arguments(1)) Then WScript.Quit 2
Set pi = Nothing
WScript.Echo "FAILURE_IDENTITY_OK"
Set licensing = CreateObject("MGCPCBAutomationLicensing.Application")
token = licensing.GetToken(doc.Validate(0))
doc.Validate token
WScript.Echo "FAILURE_CLOSE_START"
closed = doc.Close(False)
If Not closed Then WScript.Quit 4
WScript.Echo "FAILURE_CLOSE_OK"
Set doc = Nothing
Set licensing = Nothing
Set remaining = app.ActiveDocument
If Not remaining Is Nothing Then
Set remaining = Nothing
WScript.Echo "FAILURE_APP_RETAINED"
WScript.Quit 5
End If
Set remaining = Nothing
app.Quit
WScript.Echo "FAILURE_QUIT_OK"
Set app = Nothing
+46
View File
@@ -0,0 +1,46 @@
"""Run the native importer without aborting database owners on timeout."""
import json
import os
from pathlib import Path
import subprocess
import tempfile
import threading
def run_content_check(command, timeout_seconds, cwd, *, evidence_root=None):
root = (Path(evidence_root) if evidence_root is not None else
Path(tempfile.mkdtemp(prefix='cbb-content-check-')))
root.mkdir(parents=True, exist_ok=True)
stdout_path, stderr_path = root/'content-check.stdout.log', root/'content-check.stderr.log'
record_path = root/'content-check-process.json'
with stdout_path.open('wb') as stdout, stderr_path.open('wb') as stderr:
process = subprocess.Popen(command, cwd=str(cwd), stdout=stdout, stderr=stderr,
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
record = {'pid': process.pid, 'command': list(command), 'cwd': str(cwd),
'stdout': str(stdout_path), 'stderr': str(stderr_path)}
def save_record(**fields):
try:
record_path.write_text(json.dumps({**record, **fields}, ensure_ascii=False, indent=2),
encoding='utf-8')
except OSError:
pass
save_record(status='RUNNING')
try:
process.wait(timeout=max(.1, float(timeout_seconds)))
except subprocess.TimeoutExpired:
# Never kill this client or its descendants. The importer can own the
# shared symbol database even though contents checking sounds read-only.
# Files avoid pipe backpressure/BrokenPipe if the supervisor exits.
save_record(status='RETAINED', safe_to_continue=False)
def observe_exit():
process.wait()
save_record(status='EXITED', returncode=process.returncode,
note='Importer exit alone does not prove native database release.')
threading.Thread(target=observe_exit, name='retained-content-check', daemon=True).start()
return (None, stdout_path.read_bytes().decode('utf-8', errors='replace'),
stderr_path.read_bytes().decode('utf-8', errors='replace') +
f'\nIMPORTER_RELEASE_UNCONFIRMED: pid={process.pid}; '
f'内容检查超时,保留原生操作并停止批次;进程记录:{record_path}', True)
save_record(status='EXITED', returncode=process.returncode)
return (process.returncode, stdout_path.read_bytes().decode('utf-8', errors='replace'),
stderr_path.read_bytes().decode('utf-8', errors='replace'), False)
+20 -3
View File
@@ -1,6 +1,7 @@
"""Launch automation on a private Windows desktop, never the input desktop."""
import subprocess
import os
from pathlib import Path
import threading
import win32con
import win32event
@@ -21,7 +22,7 @@ def launch_save_helper(command, **kwargs):
return helper
def start_supervisor_watchdog(supervisor_pid):
def start_supervisor_watchdog(supervisor_pid, *, cancel_path=None):
"""A crashed supervisor must not leave unsupervised automation writing.
Stop only this Python worker and its registered automation clients. Native
@@ -33,6 +34,11 @@ def start_supervisor_watchdog(supervisor_pid):
def watch():
try:
win32event.WaitForSingleObject(parent, win32event.INFINITE)
if cancel_path is not None:
# Let native calls finish before the worker closes its exact
# document. Killing a pending automation client can abandon it.
Path(cancel_path).touch()
return
with _automation_clients_lock:
for helper in _automation_clients:
try:
@@ -42,7 +48,8 @@ def start_supervisor_watchdog(supervisor_pid):
pass
finally:
parent.Close()
os._exit(75)
if cancel_path is None:
os._exit(75)
thread = threading.Thread(target=watch, name='supervisor-watchdog', daemon=True)
thread.start()
@@ -139,6 +146,16 @@ class DesktopWorker:
except Exception:
pass
def bind_cancellation(self, path):
self.cancel_path = Path(path)
def request_stop(self):
if not hasattr(self, 'cancel_path'):
# Compatibility for diagnostic workers without the Verify protocol.
self.kill()
return
self.cancel_path.touch()
def wait(self, timeout=5):
if win32event.WaitForSingleObject(self.handle, int(timeout*1000)) != win32con.WAIT_OBJECT_0:
raise TimeoutError('Automation worker did not exit')
@@ -148,7 +165,7 @@ class DesktopWorker:
# Releasing Python resources must not kill native database owners.
try:
if self.poll() is None:
self.kill()
self.request_stop()
except Exception:
pass
for companion in self.companions:
+30
View File
@@ -0,0 +1,30 @@
"""Close only an idle document whose native identity was already established."""
import json
import os
from pathlib import Path
import time
def close_failed_document(job, *, emit=lambda **event: None, timeout_seconds=30):
from .desktop_worker import launch_save_helper
root = Path(job['root'])
log_path = root/'failure-close.log'
command = [str(Path(os.environ.get('WINDIR', r'C:\Windows'))/'SysWOW64/cscript.exe'),
'//nologo', str(Path(__file__).with_name('close_failed_block.vbs')),
job['project'], Path(job['pcb']).name]
with log_path.open('w', encoding='utf-8') as log:
process = launch_save_helper(command, stdout=log, stderr=log)
emit(stage='failure_close_started', helper_pid=process.pid)
deadline = time.monotonic()+max(.1, float(timeout_seconds))
while process.poll() is None and time.monotonic() < deadline:
time.sleep(.2)
# A slow native Close can still be flushing. Retain the helper as well as
# PCB/iCDB; never force it to abandon the native call at this deadline.
text = log_path.read_text('utf-8', errors='replace')
result = {'status': ('CLOSED' if process.poll() == 0 and
all(marker in text.splitlines() for marker in ('FAILURE_CLOSE_OK', 'FAILURE_QUIT_OK'))
else 'RETAINED' if process.poll() is None else 'UNCONFIRMED'),
'helper_pid': process.pid, 'returncode': process.poll(), 'log': str(log_path)}
(root/'failure-close.json').write_text(json.dumps(result, indent=2), encoding='utf-8')
emit(stage='failure_close_result', **result)
return result
+16
View File
@@ -0,0 +1,16 @@
"""Known native database owners touched by a CBB verification operation."""
from pathlib import Path
def database_directories(lmc_file, project, pcb):
return tuple(dict.fromkeys((
Path(project).parent/'database',
Path(pcb).parent/'database',
Path(lmc_file).parent/'SymbolLibs/__ReusableBlocksSymb',
)))
def unreleased_addresses(lmc_file, project, pcb):
return [str(path/'cdbsvr/sAddress.adr')
for path in database_directories(lmc_file, project, pcb)
if (path/'cdbsvr/sAddress.adr').exists()]
+28 -13
View File
@@ -633,12 +633,13 @@ def execute_job(job, emit):
emit(stage='backup_done', status=backup.get('status'), detail=backup.get('detail'))
# Backup is evidence only, never a prerequisite for launching PCB. Volatile
# database/log directories are intentionally excluded to avoid file locks.
icdb_address = prepare_icdb_address(
Path(job['project']).parent / 'database', root, emit=emit)
if icdb_address.get('status') != 'ABSENT':
raise RuntimeError(
'ICDB_SESSION_UNCONFIRMED: 数据库存在服务器地址记录,无法确认独占使用;'
'已保留地址文件,请先检查原 PCB/iCDB 会话。' + str(icdb_address))
from .icdb_ownership import database_directories, unreleased_addresses
for database in database_directories(job['lmc_file'], job['project'], job['pcb']):
icdb_address = prepare_icdb_address(database, root, emit=emit)
if icdb_address.get('status') != 'ABSENT':
raise RuntimeError(
'ICDB_SESSION_UNCONFIRMED: 数据库存在服务器地址记录,无法确认独占使用;'
'已保留地址文件,请先检查原 PCB/iCDB 会话。' + str(icdb_address))
from .verify_diagnostics import collect_preflight_diagnostics, collect_native_failure_logs
diagnostics = collect_preflight_diagnostics(job['pcb'], root)
emit(stage='preflight_diagnostics', non_blocking=True,
@@ -673,6 +674,8 @@ def execute_job(job, emit):
emit(stage='startup_log_baseline_unavailable', detail=str(error))
def native_error():
if job.get('cancel_signal') and Path(job['cancel_signal']).exists():
return 'VERIFY_CANCELLED: 停止后续操作并正常关闭目标文档'
# 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)
@@ -689,6 +692,7 @@ def execute_job(job, emit):
worker_parent_pid = None
launcher_process = None
completed = False
identity_verified = False
helper = None
app = doc = pi = None
try:
@@ -730,6 +734,8 @@ def execute_job(job, emit):
pcb_deadline = reset_verify_activity_deadline(
0.0, time.monotonic(), timeout_seconds=pcb_startup_timeout_seconds(job['timeout']))
while time.monotonic() < pcb_deadline:
if job.get('cancel_signal') and Path(job['cancel_signal']).exists():
raise RuntimeError('VERIFY_CANCELLED: PCB 启动期间收到停止请求')
records = _process_details('ExpeditionPCB.exe')
worker = select_reusable_circuit_worker(
records,
@@ -755,6 +761,7 @@ def execute_job(job, emit):
emit=emit,
error_reader=native_error,
)
identity_verified = True
# 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
@@ -770,12 +777,15 @@ def execute_job(job, emit):
# references alive prevents the native PCB server from exiting cleanly.
pi = doc = app = None
gc.collect()
if job.get('cancel_signal') and Path(job['cancel_signal']).exists():
raise RuntimeError('VERIFY_CANCELLED: 未开始保存')
emit(stage='save_start')
script = Path(__file__).with_name('save_verified_block.vbs')
cscript = Path(os.environ.get('WINDIR', r'C:\Windows'))/'SysWOW64'/'cscript.exe'
from .desktop_worker import launch_save_helper
with (root/'save.log').open('w', encoding='utf-8') as log:
helper = launch_save_helper([str(cscript), '//nologo', str(script), job['project']],
helper = launch_save_helper([str(cscript), '//nologo', str(script), job['project'],
Path(job['pcb']).name, str(job.get('cancel_signal') or '')],
stdout=log, stderr=log, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
emit(stage='save_helper', helper_pid=helper.pid)
last_markers = ()
@@ -814,9 +824,9 @@ def execute_job(job, emit):
baseline_pids=pcb_before, emit=emit)
if not released or not released.get('safe_to_continue'):
raise RuntimeError(f'PCB_RELEASE_UNCONFIRMED: 未确认 PCB 退出: {released}')
address = Path(job['project']).parent / 'database/cdbsvr/sAddress.adr'
if address.exists():
raise RuntimeError(f'ICDB_RELEASE_UNCONFIRMED: PCB 已退出但数据库地址记录仍存在;保留文件并停止批次: {address}')
addresses = unreleased_addresses(job['lmc_file'], job['project'], job['pcb'])
if addresses:
raise RuntimeError(f'ICDB_RELEASE_UNCONFIRMED: PCB 已退出但数据库地址记录仍存在;保留文件并停止批次: {addresses}')
cert_pcb = block_root/'Cert'/Path(job['pcb']).relative_to(block_root/'Work')
cert_evidence = collect_cert_evidence(block_root, cert_project, cert_pcb)
emit(stage='cert_diagnostics', **cert_evidence)
@@ -836,8 +846,13 @@ def execute_job(job, emit):
# Diagnostic failure must not erase the native error or cleanup.
pass
if helper is not None and helper.poll() is None:
# Stop only the automation client, never a native database tree.
helper.terminate()
emit(stage='save_helper_retained', helper_pid=helper.pid)
elif not completed and identity_verified:
try:
from .failed_session import close_failed_document
close_failed_document(job, emit=emit)
except Exception as error:
emit(stage='failure_close_unconfirmed', detail=str(error))
cleanup_verify_processes(
lm_pid,
worker_pid,
@@ -924,7 +939,7 @@ def worker_main(request_path):
try:
if job.get('supervisor_pid'):
from .desktop_worker import start_supervisor_watchdog
start_supervisor_watchdog(job['supervisor_pid'])
start_supervisor_watchdog(job['supervisor_pid'], cancel_path=job.get('cancel_signal'))
start_gate = Path(job.get('start_gate', '')) if job.get('start_gate') else None
if start_gate is not None:
gate_deadline = time.monotonic() + 15
+182
View File
@@ -0,0 +1,182 @@
"""Backed-up, single-attempt recovery through the installed native tool."""
from dataclasses import dataclass
import hashlib
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import time
from uuid import uuid4
@dataclass(frozen=True)
class RepairTarget:
project: Path
database: Path
def select_repair_target(request, diagnosis):
from .verify_runner import preflight
if diagnosis.get('error_code') != 'ICDB_REPAIR_REQUIRED' or not diagnosis.get('session'):
raise ValueError('REPAIR_TARGET_UNCONFIRMED: 缺少原生失联会话信息')
if diagnosis.get('scope') == 'central_library':
raise ValueError('SHARED_DATABASE_REPAIR_UNSUPPORTED: 当前原生 Repair 入口要求 PRJ,不能改修无关的 Work 工程')
project, pcb = preflight(request)
try:
reported = Path(diagnosis.get('database_path', '')).resolve(strict=True)
except OSError as error:
raise ValueError(f'REPAIR_TARGET_UNCONFIRMED: 报错数据库路径不可用:{error}') from error
for candidate in (project, pcb.parent/'pcb.prj'):
database = candidate.parent/'database'
if (candidate.is_file() and database.resolve() == reported
and reported.is_relative_to(project.parent.resolve())):
if not (reported/'icdb.dat').is_file():
raise ValueError('REPAIR_TARGET_UNCONFIRMED: 未找到目标 icdb.dat')
return RepairTarget(candidate.resolve(), reported)
raise ValueError('REPAIR_TARGET_UNCONFIRMED: 报错数据库不属于本次工程,未猜测或改写路径')
def _hash(path):
digest = hashlib.sha256()
with path.open('rb') as stream:
for chunk in iter(lambda: stream.read(1024*1024), b''):
digest.update(chunk)
return digest.hexdigest()
def backup_project(target, destination):
"""Keep every original file, holding icdb.dat exclusively during the copy."""
import win32con, win32file, pywintypes
source = target.project.parent.resolve()
destination = Path(destination).resolve()
if destination.is_relative_to(source) or source.is_relative_to(destination):
raise ValueError('REPAIR_BACKUP_INVALID: 备份与源工程不能相互包含')
paths = list(source.rglob('*'))
if any(path.is_symlink() or path.is_junction() for path in paths):
raise ValueError('REPAIR_BACKUP_INVALID: 工程包含目录链接,不能完整备份')
if (source/'backup-manifest.json').exists():
raise ValueError('REPAIR_BACKUP_INVALID: 原工程含同名备份清单')
database_file = target.database/'icdb.dat'
try:
handle = win32file.CreateFile(str(database_file), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
except pywintypes.error as error:
raise OSError(f'REPAIR_DATABASE_IN_USE: 无法独占读取数据库:{error}') from error
try:
destination.mkdir(parents=True, exist_ok=False)
files = {}
for path in paths:
relative = path.relative_to(source)
copied = destination/relative
if path.is_dir():
copied.mkdir(parents=True, exist_ok=True)
continue
before = path.stat()
copied.parent.mkdir(parents=True, exist_ok=True)
if path == database_file:
with copied.open('wb') as stream:
while True:
try:
_, data = win32file.ReadFile(handle, 1024*1024)
except pywintypes.error as error:
if error.winerror == 38: # ERROR_HANDLE_EOF
break
raise
if not data:
break
stream.write(data)
os.utime(copied, ns=(before.st_atime_ns, before.st_mtime_ns))
digest = _hash(copied)
else:
digest = _hash(path)
shutil.copy2(path, copied)
if _hash(copied) != digest:
raise OSError(f'REPAIR_BACKUP_CHANGED: 文件副本校验失败:{path}')
after = path.stat()
if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
raise OSError(f'REPAIR_BACKUP_CHANGED: 备份期间源文件变化:{path}')
files[str(relative)] = {'size': before.st_size, 'sha256': digest}
record = {'complete': True, 'source': str(source), 'files': files}
(destination/'backup-manifest.json').write_text(json.dumps(record, ensure_ascii=False, indent=2),
encoding='utf-8')
return record
finally:
handle.Close()
def attempt_recovery(request, diagnosis, evidence_root, *, progress=None):
root = Path(evidence_root)/'native-repair'
root.mkdir(exist_ok=True)
marker = root/'attempt.json'
if marker.exists():
return {'status': 'BLOCKED', 'detail': 'REPAIR_ALREADY_ATTEMPTED', 'evidence': str(root)}
record = {'status': 'BLOCKED', 'evidence': str(root)}
try:
process_record = Path(evidence_root)/'content-check-process.json'
if process_record.is_file():
state = json.loads(process_record.read_text('utf-8')).get('status')
if state in {'RUNNING', 'RETAINED'}:
raise ValueError('IMPORTER_RELEASE_UNCONFIRMED: 内容检查客户端仍占有数据库,未尝试 Repair')
with marker.open('x', encoding='utf-8') as stream:
json.dump({'status': 'PREPARING', 'diagnosis': diagnosis}, stream, ensure_ascii=False)
target = select_repair_target(request, diagnosis)
if progress:
progress({'stage': 'native_repair_start', 'block': request.block_name,
'detail': '正在备份并尝试原生数据库修复', 'project': str(target.project)})
from .mentor_adapter import pcb_processes, _process_details
if pcb_processes() or _process_details('LibraryManager.exe'):
raise ValueError('REPAIR_DATABASE_IN_USE: 原生 PCB/Library Manager 会话尚未退出')
for _pid, _exe, command, _parent in _process_details('cscript.exe'):
if str(target.project).casefold() in str(command).casefold():
raise ValueError('REPAIR_DATABASE_IN_USE: 目标的保存/关闭助手尚未退出')
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)
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 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
root = Path(root)
root.mkdir(parents=True, exist_ok=True)
job_path = root/'repair-request.json'
cancel = root/'cancel-repair.signal'
job_path.write_text(json.dumps({'project': str(target.project), 'database': str(target.database),
'root': str(root), 'mentor_bin': str(mentor_bin or ''), 'timeout': timeout_seconds,
'cancel_signal': str(cancel), 'supervisor_pid': os.getpid()}, ensure_ascii=False), encoding='utf-8')
command = ([sys.executable] if getattr(sys, 'frozen', False) else
[sys.executable, '-m', 'cbb_refresh_verify']) + ['--repair-worker', str(job_path)]
desktop = 'CbbRepair_'+uuid4().hex[:12]
worker = DesktopWorker(command, desktop)
worker.bind_cancellation(cancel)
deadline = time.monotonic()+max(1, float(timeout_seconds))+5
event_count = 0
try:
while worker.poll() is None and time.monotonic()<deadline:
event_file = root/'repair-events.jsonl'
if progress and event_file.is_file():
lines = event_file.read_text('utf-8').splitlines()
for line in lines[event_count:]:
try:
progress(json.loads(line))
except json.JSONDecodeError:
break
event_count += 1
time.sleep(.2)
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)}
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)}
finally:
worker.close()
+193
View File
@@ -0,0 +1,193 @@
"""Drive the installed Project Backup Repair command on a private desktop."""
import ctypes
from ctypes import wintypes
import json
import ntpath
from pathlib import Path
import re
import subprocess
import time
import zipfile
def confirmation_allowed(main_title, project, text):
title = main_title.removeprefix('iCDB Project Backup - ')
if ntpath.normcase(ntpath.normpath(title)) != ntpath.normcase(ntpath.normpath(str(project))):
return False
normalized = ' '.join(text.casefold().split())
return all(marker in normalized for marker in (
'the project content will be validated and repaired if necessary.',
'a project backup will be created before any action take place.',
'you will be able to revert all changes using that backup.'))
def repair_completed(diagnostic_text, database_text, *, native_backup):
combined = diagnostic_text+'\n'+database_text
if re.search(r'\bERROR\s*:|not repaired|repair.*failed', combined, re.IGNORECASE):
return False
return bool(native_backup and 'Diagnostic: FINISH' in diagnostic_text
and ('Diagnostic: Snapshot:' in diagnostic_text or 'Diagnostic: START' in diagnostic_text)
and 'iCDBProjectBackupRepair' in database_text and 'IC: Closing project' in database_text)
def _repair_command(executable):
import win32api, win32gui, win32con
user32 = ctypes.WinDLL('user32')
user32.GetMenuStringW.argtypes = [wintypes.HMENU, wintypes.UINT, wintypes.LPWSTR,
ctypes.c_int, wintypes.UINT]
library = win32api.LoadLibraryEx(str(executable), 0, 2) # data resources only
commands = set()
def walk(menu, parents=()):
for index in range(win32gui.GetMenuItemCount(menu)):
value = ctypes.create_unicode_buffer(512)
user32.GetMenuStringW(menu, index, value, len(value), win32con.MF_BYPOSITION)
label = value.value.replace('&', '').split('\t')[0].strip().casefold()
sub = win32gui.GetSubMenu(menu, index)
if sub:
walk(sub, (*parents, label))
elif parents == ('project',) and label == 'repair':
commands.add(win32gui.GetMenuItemID(menu, index))
try:
for name in win32api.EnumResourceNames(library, 4):
menu = win32gui.LoadMenu(library, name)
try:
walk(menu)
finally:
win32gui.DestroyMenu(menu)
finally:
win32api.FreeLibrary(library)
if len(commands) != 1:
raise ValueError('NATIVE_REPAIR_UNSUPPORTED: 未唯一定位原生 Project/Repair 菜单')
return commands.pop()
def _windows(pid):
import win32gui, win32process
windows = []
def observe(hwnd, _):
if win32process.GetWindowThreadProcessId(hwnd)[1] != pid or not win32gui.IsWindowVisible(hwnd):
return
children = []
def child(handle, _):
if win32gui.IsWindowVisible(handle):
children.append({'hwnd': handle, 'text': win32gui.GetWindowText(handle),
'class': win32gui.GetClassName(handle), 'id': win32gui.GetDlgCtrlID(handle),
'enabled': bool(win32gui.IsWindowEnabled(handle))})
win32gui.EnumChildWindows(hwnd, child, None)
windows.append({'hwnd': hwnd, 'title': win32gui.GetWindowText(hwnd),
'class': win32gui.GetClassName(hwnd), 'enabled': bool(win32gui.IsWindowEnabled(hwnd)),
'children': children})
win32gui.EnumWindows(observe, None)
return windows
def _native_evidence(project, database, pid, started_ns, baseline):
"""Use only this native process's new diagnostic/close and backup evidence."""
def read_logs(folder):
text = []
for path in (database/'cdbsvr'/folder).glob(f'*-{pid}/*.txt'):
if path.stat().st_mtime_ns >= started_ns:
text.append(path.read_bytes()[-256*1024:].decode('utf-8', errors='replace'))
return '\n'.join(text)
from .icdb_recovery import read_log_failure
backup_log = project.parent/'Log Files/ProjectBackupLog.txt'
text, _ = read_log_failure(backup_log, baseline)
matches = re.findall(r'Successfully created \[Project Repair\] backup \[([^\]]+)\]', text)
native_backup = False
for name in matches:
# Native default storage verified here; alternate storage needs its own
# target/backup validation and must not silently become success.
if Path(name).name != name:
continue
archive = project.parent/'ProjectBackup/backups'/name
if archive.is_file():
with zipfile.ZipFile(archive) as zipped:
native_backup = bool(zipped.namelist()) and zipped.testzip() is None
diagnostic, db_log = read_logs('dbcheck'), read_logs('log')
valid = (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,
'diagnostic_tail': diagnostic[-8192:], 'database_tail': db_log[-8192:]}
def repair_worker_main(job_path):
import win32con, win32gui
from .native_repair import RepairTarget, backup_project
from .mentor_paths import discover_sdd_home
from .icdb_recovery import snapshot_log
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)}
process = None
def emit(**event):
with (root/'repair-events.jsonl').open('a', encoding='utf-8') as stream:
stream.write(json.dumps(event, ensure_ascii=False)+'\n')
try:
if project.suffix.casefold() != '.prj' or database.resolve() != (project.parent/'database').resolve():
raise ValueError('REPAIR_TARGET_UNCONFIRMED')
home = discover_sdd_home(job.get('mentor_bin'))
if home is None:
raise ValueError('NATIVE_REPAIR_UNAVAILABLE: 未找到 Mentor 安装目录')
executable = home/'iCDB/win32/bin/iCDBProjectBackup.exe'
command_id = _repair_command(executable)
from .mentor_adapter import pcb_processes, _process_details
if pcb_processes() or _process_details('LibraryManager.exe'):
raise ValueError('REPAIR_DATABASE_IN_USE')
backup_project(RepairTarget(project, database), root/'complete-backup')
emit(stage='complete_backup_verified', path=str(root/'complete-backup'))
if Path(job['cancel_signal']).exists():
raise ValueError('REPAIR_CANCELLED_AFTER_BACKUP')
baseline = snapshot_log(project.parent/'Log Files/ProjectBackupLog.txt')
started_ns = time.time_ns()
if job.get('supervisor_pid'):
from .desktop_worker import start_supervisor_watchdog
start_supervisor_watchdog(job['supervisor_pid'], cancel_path=job['cancel_signal'])
process = subprocess.Popen([str(executable), '-p', str(project)], cwd=str(project.parent))
result['native_pid'] = process.pid
emit(stage='native_started', pid=process.pid, project=str(project))
deadline = time.monotonic()+max(1, float(job['timeout']))
invoked = confirmed = closing = False
evidence = None
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)
dialogs = [w for w in windows if w['class'] == '#32770']
if not invoked and main and not dialogs and main['enabled']:
if Path(job['cancel_signal']).exists():
raise ValueError('REPAIR_CANCELLED_BEFORE_START')
win32gui.PostMessage(main['hwnd'], 0x0111, command_id, 0)
invoked = True
emit(stage='native_repair_requested', command=command_id)
if invoked and not confirmed and main:
for dialog in dialogs:
text = '\n'.join(c['text'] for c in dialog['children'])
if confirmation_allowed(main['title'], project, text):
if Path(job['cancel_signal']).exists():
raise ValueError('REPAIR_CANCELLED_BEFORE_CONFIRM')
button = next((c for c in dialog['children'] if c['class'] == 'Button'
and c['id'] == 1 and c['enabled']), None)
if button:
win32gui.PostMessage(button['hwnd'], win32con.BM_CLICK, 0, 0)
confirmed = True
emit(stage='native_repair_confirmed', text=text)
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']:
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['confirmed']
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',
detail='原生 Repair 未取得完整成功/释放证据,未重试校验')
except Exception as error:
result.update(detail=str(error), status='RETAINED' if process and process.poll() is None else 'BLOCKED')
# Never terminate a repair or its database owner. Retained PID/desktop is
# reported to the parent, including unknown native prompts.
(root/'repair-result.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
return 0 if result['status'] == 'REPAIRED' else 1
@@ -5,8 +5,12 @@ Set app = GetObject(, "MGCPCB.Application")
Set doc = app.ActiveDocument
Set pi = doc.ProjectIntegration
If LCase(pi.ProjectFile) <> LCase(expected) Then WScript.Quit 2
If WScript.Arguments.Count > 1 Then
If LCase(doc.Name) <> LCase(WScript.Arguments(1)) Then WScript.Quit 2
End If
If pi.ForwardAnnotationStatus <> 2 Or pi.SynchCESStatus <> 2 Or pi.LoadCESStatus <> 2 Or pi.BackAnnotationStatus <> 2 Then WScript.Quit 3
WScript.Echo "VALIDATE_START"
CheckCancellation
measuredStart = Timer
Set licensing = CreateObject("MGCPCBAutomationLicensing.Application")
token = licensing.GetToken(doc.Validate(0))
@@ -14,11 +18,13 @@ doc.Validate token
LogElapsed "validate", measuredStart
WScript.Echo "LICENSE_OK"
WScript.Echo "SAVE_START"
CheckCancellation
measuredStart = Timer
operationOK = doc.Save()
LogElapsed "save", measuredStart
If Not operationOK Then WScript.Quit 4
WScript.Echo "SAVE_OK"
CheckCancellation
measuredStart = Timer
operationOK = doc.IsSaved()
LogElapsed "is_saved", measuredStart
@@ -40,6 +46,7 @@ If Not stable Then WScript.Quit 7
WScript.Echo "POST_SAVE_SYNCHRONIZED"
If Not doc.IsSaved() Then WScript.Quit 8
WScript.Echo "CLOSE_START"
CheckCancellation
measuredStart = Timer
operationOK = doc.Close(True)
LogElapsed "close", measuredStart
@@ -54,6 +61,18 @@ LogElapsed "quit", measuredStart
WScript.Echo "QUIT_OK"
Set app = Nothing
Sub CheckCancellation()
Dim fso, cancelPath
If WScript.Arguments.Count < 3 Then Exit Sub
cancelPath = WScript.Arguments(2)
If Len(cancelPath) = 0 Then Exit Sub
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists(cancelPath) Then
WScript.Echo "VERIFY_CANCELLED"
WScript.Quit 9
End If
End Sub
Sub LogElapsed(phaseName, started)
Dim elapsed
elapsed = Timer - started
+9 -6
View File
@@ -315,15 +315,18 @@ class StatusBridgeServer:
except OSError:
pass
if process.poll() is None:
process.terminate()
try:
process.wait(timeout=2)
except subprocess.TimeoutExpired:
try:
process.kill()
except OSError:
pass
process.terminate()
try:
process.wait(timeout=2)
except subprocess.TimeoutExpired:
pass
try:
process.kill()
except OSError:
pass
try:
process.wait(timeout=2)
except subprocess.TimeoutExpired:
pass
+55 -33
View File
@@ -62,6 +62,7 @@ class VerifyRequest:
# it before launching Library Manager/PCB.
mapped_drive: str = ''
mapped_remote_root: str = ''
auto_repair: bool = True
@dataclass(frozen=True)
@@ -80,6 +81,7 @@ class VerifyResult:
bridge_attempts: tuple[dict, ...] = ()
timings_seconds: dict[str, float] = field(default_factory=dict)
incomplete_timing_phases: tuple[str, ...] = ()
recovery_attempts: tuple[dict, ...] = ()
def resolve_importer(mentor_bin: str | None = None) -> Path:
@@ -198,38 +200,18 @@ def preflight_skip_reason(lmc_file, block_name):
return ''
def _run_process(command, timeout_seconds, cwd):
"""Run the importer, draining both pipes while it works (no pipe deadlock)."""
process = subprocess.Popen(command, cwd=str(cwd), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
try:
stdout, stderr = process.communicate(timeout=timeout_seconds)
return process.returncode, stdout.decode('utf-8', errors='replace'), stderr.decode('utf-8', errors='replace'), False
except subprocess.TimeoutExpired:
# A timed-out importer may have spawned a child that still owns the
# 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([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):
pass
try:
process.kill()
except OSError:
pass
try:
stdout, stderr = process.communicate(timeout=5)
except subprocess.TimeoutExpired:
stdout, stderr = b'', b''
return None, stdout.decode('utf-8', errors='replace'), stderr.decode('utf-8', errors='replace'), True
def _run_process(command, timeout_seconds, cwd, *, evidence_root=None):
from .content_check import run_content_check
return run_content_check(command, timeout_seconds, cwd, evidence_root=evidence_root)
def _stop_worker(process, *, timeout=5):
"""Stop automation clients; native database owners are preserved."""
try:
process.kill()
if hasattr(process, 'request_stop'):
process.request_stop()
else:
process.kill()
except Exception:
pass
try:
@@ -532,10 +514,33 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
if not acquired:
return VerifyResult('BLOCKED', stderr='已有 CBB 校验任务运行,请等待结束。',
safe_to_continue=False)
return _run_verify_serialized(
result = _run_verify_serialized(
request, progress=progress, flag_reader=flag_reader,
process_runner=process_runner, port_check=port_check,
dialog_supervisor_factory=dialog_supervisor_factory)
if (request.auto_repair and result.status not in {'TIMEOUT', 'BLOCKED'}
and result.error_category == 'ICDB_REPAIR_REQUIRED'
and result.evidence_path):
from .native_repair import attempt_recovery
try:
diagnosis = json.loads((result.evidence_path.parent/'diagnostics/icdb-recovery.json').read_text('utf-8'))
original = result
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':
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)
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')
except Exception as error:
result = replace(result, status='FAIL' if result.status == 'PASS' else result.status,
safe_to_continue=False,
stderr=(result.stderr+f'\nREPAIR_UNCONFIRMED: {error}').strip())
return result
finally:
if acquired:
win32event.ReleaseMutex(mutex)
@@ -630,7 +635,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
progress({'stage': 'runtime_fingerprint', 'block': request.block_name,
**fingerprint})
result_path = root/'result.json'
runner = process_runner or _run_process
runner = process_runner or (lambda command, timeout, cwd:
_run_process(command, timeout, cwd, evidence_root=root))
def finish(result):
# Only reclaim auxiliary backups after confirmed success. Failed runs
@@ -652,6 +658,17 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
finally:
timing.end('preflight')
from .icdb_ownership import unreleased_addresses
try:
addresses = unreleased_addresses(request.lmc_file, project, pcb)
if addresses:
return finish(VerifyResult('BLOCKED', safe_to_continue=False,
stderr='ICDB_SESSION_UNCONFIRMED: 原生数据库所有权未释放,未开始内容检查或校验:'
+ '; '.join(addresses)))
except OSError as error:
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())
if content_check_enabled:
try:
@@ -679,7 +696,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
# A contents failure or an unusable DMS must block before touching the PCB.
return finish(VerifyResult(status if status in ('FAIL', 'TIMEOUT') else 'BLOCKED',
stderr=combined.strip() or f'内容检查结果未知(退出码 {exit_code})',
stdout=stdout, report_path=report, content_check_exit_code=exit_code))
stdout=stdout, report_path=report, content_check_exit_code=exit_code,
safe_to_continue=not timed_out))
if progress:
progress({'stage': 'content_check_done', 'block': request.block_name, 'status': 'PASS'})
@@ -703,6 +721,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
'interactive_input': bool(request.interactive_input),
'native_lm_verify': bool(request.native_lm_verify),
'desktop': 'CbbVerify_' + uuid4().hex[:12],
'cancel_signal': str(root/'cancel-worker.signal'),
'start_gate': str(root/'start-worker.signal')}
job_path = root/'request.json'
job_path.write_text(json.dumps(job, ensure_ascii=False), encoding='utf-8')
@@ -733,6 +752,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
worker_command(job_path), None, interactive_input=True)
else:
process = DesktopWorker(worker_command(job_path), job['desktop'])
if hasattr(process, 'bind_cancellation'):
process.bind_cancellation(job['cancel_signal'])
deadline = ActivityDeadline(request.timeout_seconds)
last_activity_key = None
phase = DialogPhase.PCB_STARTING
@@ -917,10 +938,11 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
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():
from .icdb_ownership import unreleased_addresses
addresses = unreleased_addresses(request.lmc_file, project, pcb)
if addresses:
release_result = {**(release_result or {}), 'safe_to_continue': False,
'icdb_address': str(address)}
'icdb_address': addresses[0], 'icdb_addresses': addresses}
except OSError as error:
close_errors.append(str(error))
if close_errors:
+291
View File
@@ -0,0 +1,291 @@
import json
import os
from pathlib import Path
import subprocess
import sys
import time
import pytest
from cbb_refresh_verify import verify_runner as runner
def test_content_timeout_preserves_importer_and_native_like_child(tmp_path):
import win32api, win32con, win32process
script = tmp_path/'importer.py'
pids = tmp_path/'pids.json'
script.write_text(
'import subprocess,sys,time,os,json\nfrom pathlib import Path\n'
'child=subprocess.Popen([sys.executable,"-c","import time;time.sleep(30)"],'
'stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)\n'
f'Path({str(pids)!r}).write_text(json.dumps([os.getpid(),child.pid]))\n'
'time.sleep(30)\n', encoding='utf-8')
handles = []
try:
result = runner._run_process([sys.executable, str(script)], 2, tmp_path)
assert result[3] is True
assert pids.is_file()
for pid in json.loads(pids.read_text()):
try:
handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION |
win32con.PROCESS_TERMINATE, False, pid)
except Exception:
pytest.fail(f'Timeout terminated database-related process {pid}')
handles.append(handle)
assert win32process.GetExitCodeProcess(handle) == 259
finally:
for handle in handles:
win32process.TerminateProcess(handle, 0)
handle.Close()
def test_content_timeout_stops_remaining_batch(tmp_path, monkeypatch):
from test_verify_runner import fixture, request
fixture(tmp_path)
monkeypatch.setattr(runner, 'resolve_importer', lambda *_: Path('ReuseBlockImporter.exe'))
calls = []
def timeout(*args):
calls.append(args)
return None, '', 'content check still running', True
req = request(tmp_path, libspec='EE', dms_login_config='login')
results = runner.run_batch([req, req], verifier=lambda item: runner.run_verify(item,
process_runner=timeout, port_check=lambda: pytest.fail('PCB must not start')))
assert len(calls) == 1
assert results[0].status == 'TIMEOUT'
assert results[0].safe_to_continue is False
assert results[1].status == 'SKIPPED'
@pytest.mark.parametrize('identity,close_ok,other_document,expected_code', [
(True, True, False, 0), (False, True, False, 2), (True, False, False, 4), (True, True, True, 5)])
def test_failed_document_close_uses_native_discard_and_rejects_wrong_identity(
tmp_path, identity, close_ok, other_document, expected_code):
source = Path('src/cbb_refresh_verify/close_failed_block.vbs').read_text('utf-8')
classes = r'''
Dim nativeClosed
nativeClosed = False
Class FakePi
Public ProjectFile
Private Sub Class_Initialize
ProjectFile = PROJECT_VALUE
End Sub
End Class
Class FakeDoc
Public Name
Private Sub Class_Initialize
Name = "CBB.pcb"
End Sub
Public Property Get ProjectIntegration
Set ProjectIntegration = New FakePi
End Property
Public Function Validate(value)
Validate = 17
End Function
Public Function Close(saveChanges)
If saveChanges Then WScript.Quit 90
WScript.Echo "NATIVE_DISCARD_CLOSE"
nativeClosed = CLOSE_RETURN
Close = CLOSE_RETURN
End Function
End Class
Class FakeApp
Public Property Get ActiveDocument
If nativeClosed And Not OTHER_DOCUMENT Then
Set ActiveDocument = Nothing
Else
Set ActiveDocument = New FakeDoc
End If
End Property
Public Sub Quit()
WScript.Echo "NATIVE_QUIT"
End Sub
End Class
Class FakeLic
Public Function GetToken(value)
GetToken = value
End Function
End Class
'''.replace('PROJECT_VALUE', 'WScript.Arguments(0)' if identity else '"OTHER.prj"')
classes = classes.replace('CLOSE_RETURN', str(close_ok))
classes = classes.replace('OTHER_DOCUMENT', str(other_document))
source = source.replace('Option Explicit', 'Option Explicit\n'+classes)
source = source.replace('GetObject(, "MGCPCB.Application")', 'New FakeApp')
source = source.replace('CreateObject("MGCPCBAutomationLicensing.Application")', 'New FakeLic')
harness = tmp_path/'close.vbs'
harness.write_text(source, encoding='ascii')
outcome = subprocess.run([str(Path(os.environ['WINDIR'])/'SysWOW64/cscript.exe'),
'//nologo', str(harness), 'expected.prj', 'CBB.pcb'], capture_output=True, text=True, timeout=10)
assert outcome.returncode == expected_code, outcome.stderr
assert ('NATIVE_DISCARD_CLOSE' in outcome.stdout) is identity
assert ('NATIVE_QUIT' in outcome.stdout) is (identity and close_ok and not other_document)
def test_cancel_after_native_save_returns_stops_later_native_operations(tmp_path):
source = Path('src/cbb_refresh_verify/save_verified_block.vbs').read_text('utf-8')
classes = r'''
Class FakePi
Public ProjectFile, ForwardAnnotationStatus, SynchCESStatus, LoadCESStatus, BackAnnotationStatus
Private Sub Class_Initialize
ProjectFile = WScript.Arguments(0)
ForwardAnnotationStatus = 2
SynchCESStatus = 2
LoadCESStatus = 2
BackAnnotationStatus = 2
End Sub
End Class
Class FakeDoc
Public Name
Private Sub Class_Initialize
Name = "CBB.pcb"
End Sub
Public Property Get ProjectIntegration
Set ProjectIntegration = New FakePi
End Property
Public Function Validate(token)
Validate = 17
End Function
Public Function Save()
Dim fso, flag
Set fso = CreateObject("Scripting.FileSystemObject")
Set flag = fso.CreateTextFile(WScript.Arguments(2), True)
flag.Close
WScript.Sleep 120
WScript.Echo "NATIVE_SAVE_RETURNED"
Save = True
End Function
Public Function IsSaved()
IsSaved = True
End Function
Public Function Close(saveChanges)
Close = True
End Function
End Class
Class FakeApp
Public Property Get ActiveDocument
Set ActiveDocument = New FakeDoc
End Property
Public Sub Quit()
End Sub
End Class
Class FakeLic
Public Function GetToken(value)
GetToken = value
End Function
End Class
'''
source = source.replace('Option Explicit', 'Option Explicit\n'+classes)
source = source.replace('GetObject(, "MGCPCB.Application")', 'New FakeApp')
source = source.replace('CreateObject("MGCPCBAutomationLicensing.Application")', 'New FakeLic')
harness = tmp_path/'save-cancel.vbs'
harness.write_text(source, encoding='ascii')
outcome = subprocess.run([str(Path(os.environ['WINDIR'])/'SysWOW64/cscript.exe'),
'//nologo', str(harness), 'expected.prj', 'CBB.pcb', str(tmp_path/'cancel.signal')],
capture_output=True, text=True, timeout=10)
assert 'NATIVE_SAVE_RETURNED' in outcome.stdout
assert outcome.returncode == 9, outcome.stderr
assert 'VERIFY_CANCELLED' in outcome.stdout
assert 'CLOSE_OK' not in outcome.stdout
def test_worker_attempts_normal_close_after_idle_integration_failure(tmp_path, monkeypatch):
from test_verify_worker_stability import exercise_worker
from cbb_refresh_verify import mentor_adapter as adapter
job, events, execute = exercise_worker(tmp_path, monkeypatch, integration_error='packaging rejected')
closes = []
monkeypatch.setattr('cbb_refresh_verify.failed_session.close_failed_document',
lambda value, **kwargs: closes.append(value) or {'status': 'CLOSED'})
with pytest.raises(RuntimeError, match='packaging rejected'):
execute()
assert closes == [job]
assert not any(event['stage'] == 'save_start' for event in events)
def test_stop_requests_cooperative_cancel_without_terminating_busy_client(tmp_path):
calls = []
class BusyWorker:
def request_stop(self): calls.append('cancel')
def wait(self, timeout): raise TimeoutError('native Save still running')
def kill(self): calls.append('kill')
runner._stop_worker(BusyWorker(), timeout=0)
assert calls == ['cancel']
def test_status_server_close_allows_eof_cleanup_before_termination(tmp_path):
from cbb_refresh_verify.status_bridge import StatusBridgeServer
script = tmp_path/'reader.py'
marker = tmp_path/'released.txt'
script.write_text('import sys,time\nfrom pathlib import Path\n'
'for line in sys.stdin: pass\n'
'time.sleep(.1)\n'
f'Path({str(marker)!r}).write_text("native handles released")\n', encoding='utf-8')
server = StatusBridgeServer(script)
server.start()
time.sleep(.2)
server.close()
assert marker.is_file()
def test_shared_symbol_database_owner_blocks_content_check_and_pcb(tmp_path, monkeypatch):
from test_verify_runner import fixture, request
fixture(tmp_path)
address = tmp_path/'SymbolLibs/__ReusableBlocksSymb/cdbsvr/sAddress.adr'
address.parent.mkdir(parents=True)
address.write_bytes(b'unknown native owner')
req = request(tmp_path, libspec='EE', dms_login_config='login')
outcome = runner.run_verify(req, process_runner=lambda *args: pytest.fail('must not launch importer'))
assert outcome.status == 'BLOCKED'
assert outcome.safe_to_continue is False
assert '__ReusableBlocksSymb' in outcome.stderr
assert address.read_bytes() == b'unknown native owner'
def test_shared_symbol_database_must_be_released_before_pass(tmp_path, monkeypatch):
from test_verify_worker_stability import exercise_worker
from cbb_refresh_verify import mentor_adapter as adapter
job, events, execute = exercise_worker(tmp_path, monkeypatch)
original = adapter.subprocess.Popen
def helper(*args, **kwargs):
address = Path(job['lmc_file']).parent/'SymbolLibs/__ReusableBlocksSymb/cdbsvr/sAddress.adr'
address.parent.mkdir(parents=True)
address.write_bytes(b'shared owner retained')
return original(*args, **kwargs)
monkeypatch.setattr(adapter.subprocess, 'Popen', helper)
with pytest.raises(RuntimeError, match='ICDB_RELEASE_UNCONFIRMED'):
execute()
assert not any(event['stage'] == 'complete' for event in events)
def test_cooperative_supervisor_loss_keeps_pending_save_helper_alive(tmp_path):
import win32api, win32con, win32process
supervisor = subprocess.Popen([sys.executable, '-c', 'import time;time.sleep(30)'])
script, ready, cancel = tmp_path/'worker.py', tmp_path/'ready.json', tmp_path/'cancel.signal'
script.write_text('import subprocess,sys,time,json\nfrom pathlib import Path\n'
'from cbb_refresh_verify.desktop_worker import start_supervisor_watchdog,launch_save_helper\n'
f'start_supervisor_watchdog({supervisor.pid},cancel_path={str(cancel)!r})\n'
'helper=launch_save_helper([sys.executable,"-c","import time;time.sleep(30)"])\n'
f'Path({str(ready)!r}).write_text(json.dumps(helper.pid))\n'
'time.sleep(30)\n', encoding='utf-8')
worker = subprocess.Popen([sys.executable, str(script)])
handle = None
try:
deadline = time.monotonic()+5
while not ready.exists() and time.monotonic()<deadline:
time.sleep(.05)
assert ready.exists()
handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_TERMINATE,
False, json.loads(ready.read_text()))
supervisor.terminate()
supervisor.wait(3)
deadline = time.monotonic()+3
while not cancel.exists() and time.monotonic()<deadline:
time.sleep(.05)
assert cancel.exists()
assert worker.poll() is None
assert win32process.GetExitCodeProcess(handle) == 259
finally:
for process in (worker, supervisor):
if process.poll() is None: process.terminate()
process.wait(3)
if handle:
win32process.TerminateProcess(handle, 0)
handle.Close()
+142
View File
@@ -0,0 +1,142 @@
import json
from pathlib import Path
import pytest
def target_fixture(tmp_path):
from test_verify_runner import fixture, request
from cbb_refresh_verify.native_repair import select_repair_target
work = fixture(tmp_path)
database = work/'database'
database.mkdir()
(database/'icdb.dat').write_bytes(b'original damaged database')
diagnosis = {'error_code': 'ICDB_REPAIR_REQUIRED', 'machine': 'OLD-PC',
'database_path': str(database), 'session': '2026-10-24 08.22.29-10308', 'scope': 'project'}
return request(tmp_path), diagnosis, select_repair_target(request(tmp_path), diagnosis)
def test_repair_target_matches_actual_database_not_guessed_cbb_name(tmp_path):
request, record, target = target_fixture(tmp_path)
assert target.project.name == 'CBB1.prj'
assert target.database == target.project.parent/'database'
@pytest.mark.parametrize('change', ['foreign', 'shared', 'missing_session'])
def test_repair_target_rejects_unresolved_or_shared_database(tmp_path, change):
from cbb_refresh_verify.native_repair import select_repair_target
request, record, target = target_fixture(tmp_path)
if change == 'foreign': record['database_path'] = str(tmp_path/'foreign/database')
if change == 'shared':
record.update(scope='central_library', database_path=str(tmp_path/'SymbolLibs/__ReusableBlocksSymb'))
if change == 'missing_session': record['session'] = ''
with pytest.raises(ValueError):
select_repair_target(request, record)
def test_repair_backup_contains_database_locks_backups_and_original_files(tmp_path):
from cbb_refresh_verify.native_repair import backup_project
request, record, target = target_fixture(tmp_path)
for relative in ('database/cdbsvr/sAddress.adr', 'ProjectBackup/backups/old.zip',
'PCB/copy.lock', 'Log Files/ProjectBackupLog.txt'):
path = target.project.parent/relative
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(b'original '+relative.encode())
destination = tmp_path/'repair-backup'
manifest = backup_project(target, destination)
assert manifest['complete'] is True
assert (destination/'database/icdb.dat').read_bytes() == b'original damaged database'
assert (destination/'database/cdbsvr/sAddress.adr').read_bytes().startswith(b'original')
assert (destination/'ProjectBackup/backups/old.zip').is_file()
assert (destination/'PCB/copy.lock').is_file()
def test_repair_backup_refuses_database_open_by_another_client(tmp_path):
import win32file, win32con
from cbb_refresh_verify.native_repair import backup_project
request, record, target = target_fixture(tmp_path)
handle = win32file.CreateFile(str(target.database/'icdb.dat'), win32con.GENERIC_READ,
win32con.FILE_SHARE_READ, None, win32con.OPEN_EXISTING, 0, None)
try:
with pytest.raises(OSError):
backup_project(target, tmp_path/'backup')
finally:
handle.Close()
assert not (tmp_path/'backup/backup-manifest.json').exists()
def test_repair_backup_rejects_reparse_directory(tmp_path):
import _winapi
from cbb_refresh_verify.native_repair import backup_project
request, record, target = target_fixture(tmp_path)
outside = tmp_path/'outside'
outside.mkdir()
_winapi.CreateJunction(str(outside), str(target.project.parent/'linked'))
with pytest.raises(ValueError):
backup_project(target, tmp_path/'backup')
def test_native_confirmation_requires_exact_target_and_known_repair_prompt():
from cbb_refresh_verify.native_repair_ui import confirmation_allowed
assert confirmation_allowed('iCDB Project Backup - C:\\exact.prj', r'C:\exact.prj',
'The project content will be validated and repaired if necessary.\n'
'A project backup will be created before any action take place.\n'
'You will be able to revert all changes using that backup.')
assert not confirmation_allowed('iCDB Project Backup - C:\\OTHER.prj', r'C:\exact.prj',
'The project content will be validated and repaired if necessary.')
assert not confirmation_allowed('iCDB Project Backup - C:\\exact.prj', r'C:\exact.prj',
'Confirm no other clients are connected. Continue anyway?')
def test_native_diagnostics_finish_alone_does_not_prove_repair_success():
from cbb_refresh_verify.native_repair_ui import repair_completed
assert not repair_completed('Diagnostic: FINISH', 'IC: Closing project', native_backup=False)
assert not repair_completed('ERROR: invalid database\nDiagnostic: FINISH',
'iCDBProjectBackupRepair\nIC: Closing project', native_backup=True)
assert repair_completed('Diagnostic: START\nDiagnostic: FINISH',
'iCDBProjectBackupRepair\nIC: Closing project', native_backup=True)
def test_automatic_repair_retries_only_once_and_preserves_original_failure(tmp_path, monkeypatch):
from dataclasses import replace
from cbb_refresh_verify import verify_runner as runner
from cbb_refresh_verify import native_repair
request, record, target = target_fixture(tmp_path)
evidence = tmp_path/'first/result.json'
evidence.parent.mkdir()
(evidence.parent/'diagnostics').mkdir()
(evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps(record))
original = runner.VerifyResult('FAIL', stderr='native lost session',
safe_to_continue=False, error_category='ICDB_REPAIR_REQUIRED', evidence_path=evidence)
calls = []
def verify(req, **kwargs):
calls.append(req)
return original
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: {'status':'REPAIRED'})
outcome = runner.run_verify(request)
assert len(calls) == 2
assert outcome.status == 'FAIL'
assert outcome.stderr == 'native lost session'
assert outcome.recovery_attempts[0]['original_error'] == 'native lost session'
def test_automatic_repair_does_not_retry_busy_or_unsupported_target(tmp_path, monkeypatch):
from cbb_refresh_verify import verify_runner as runner
from cbb_refresh_verify import native_repair
request, record, target = target_fixture(tmp_path)
evidence = tmp_path/'first/result.json'
evidence.parent.mkdir()
(evidence.parent/'diagnostics').mkdir()
(evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps(record))
calls = []
def verify(req, **kwargs):
calls.append(req)
return runner.VerifyResult('FAIL', stderr='native lost session',
error_category='ICDB_REPAIR_REQUIRED', safe_to_continue=False, evidence_path=evidence)
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: {'status':'BLOCKED'})
outcome = runner.run_verify(request)
assert len(calls) == 1
assert outcome.safe_to_continue is False
assert outcome.recovery_attempts[0]['status'] == 'BLOCKED'
-1
View File
@@ -24,7 +24,6 @@ FORBIDDEN_APIS = (
'AttachThreadInput',
'WM_MOUSEMOVE',
'WM_CONTEXTMENU',
'WM_COMMAND',
'VK_APPS',
'TVM_SELECTITEM',
'EndMenu',