fix: complete legacy CBB import recovery and guard late native submission
This commit is contained in:
1 parent
d36b6bcad0
commit
7527800128
12 files changed
+326
-25
No files matched your search
@@ -86,17 +86,18 @@ def _source_check(source, name, original):
|
||||
|
||||
|
||||
def _align_library(project, pcb, library):
|
||||
from .mentor_adapter import ensure_project_central_library, ensure_pcb_central_library
|
||||
for path in (project, pcb.parent/'pcb.prj'):
|
||||
from .mentor_adapter import ensure_project_central_library
|
||||
from .maintenance_entry import maintenance_project_files
|
||||
projects = maintenance_project_files(project, pcb)
|
||||
for path in projects:
|
||||
if not re.findall(r'^KEY CentralLibrary "([^"]*)"', _project_text(path), re.M):
|
||||
raise ValueError('备份工程缺少 CentralLibrary 引用。')
|
||||
def already_references(path):
|
||||
return all((path.parent/value).resolve() == Path(library).resolve()
|
||||
for value in re.findall(r'^KEY CentralLibrary "([^"]*)"', _project_text(path), re.M))
|
||||
if not already_references(project):
|
||||
ensure_project_central_library(project, library)
|
||||
if not already_references(pcb.parent/'pcb.prj'):
|
||||
ensure_pcb_central_library(pcb, library)
|
||||
for path in projects:
|
||||
if not already_references(path):
|
||||
ensure_project_central_library(path, library)
|
||||
|
||||
|
||||
def recover_from_backup(request, source, *, progress=None, verifier=None, idle_check=None):
|
||||
|
||||
@@ -41,6 +41,7 @@ def refresh_integration(pi, *, emit=lambda **event: None, settle_seconds=5, time
|
||||
deadline = ActivityDeadline(timeout_seconds, clock=clock) if timeout_seconds is not None else None
|
||||
in_flight = {}
|
||||
executed = set()
|
||||
protected_green = set()
|
||||
action_history = []
|
||||
green_entry = None
|
||||
previous_state = None
|
||||
@@ -65,6 +66,8 @@ def refresh_integration(pi, *, emit=lambda **event: None, settle_seconds=5, time
|
||||
# NoCES=3 is recorded as unsupported, never claimed green.
|
||||
if status not in (1, 2):
|
||||
raise IntegrationError(f'{name}: unsupported status {status}')
|
||||
if status != 2:
|
||||
protected_green.discard(name)
|
||||
for name in tuple(in_flight):
|
||||
if state[name] == 2:
|
||||
started, call_elapsed = in_flight.pop(name)
|
||||
@@ -74,11 +77,14 @@ def refresh_integration(pi, *, emit=lambda **event: None, settle_seconds=5, time
|
||||
# When all four lamps start green, mirror the manual refresh: one
|
||||
# ForwardAnnotate, then only repair statuses that actually become Required.
|
||||
# Non-green entry keeps the previously validated four-action route.
|
||||
refreshed = ('ForwardAnnotation' in executed if green_entry
|
||||
else len(executed) == len(ACTIONS))
|
||||
checked = executed | protected_green
|
||||
refreshed = ('ForwardAnnotation' in checked if green_entry
|
||||
else len(checked) == len(ACTIONS))
|
||||
if refreshed and not in_flight and all(status == 2 for status in state.values()):
|
||||
emit(stage='integration_complete', statuses=state, actions=action_history,
|
||||
policy='green_first_only' if green_entry else 'required_full_sequence')
|
||||
policy='green_first_only' if green_entry else
|
||||
'required_with_native_gates' if protected_green else 'required_full_sequence',
|
||||
skipped_synchronized=sorted(protected_green))
|
||||
return state
|
||||
if deadline is not None and deadline.expired():
|
||||
raise IntegrationError('Project Integration timeout')
|
||||
@@ -87,14 +93,19 @@ def refresh_integration(pi, *, emit=lambda **event: None, settle_seconds=5, time
|
||||
continue
|
||||
action_started = False
|
||||
for name, method in ACTIONS:
|
||||
if state[name] == 2 and (name in executed or
|
||||
if state[name] == 2 and (name in checked or
|
||||
(green_entry and name != 'ForwardAnnotation')):
|
||||
continue
|
||||
allowed = bool(value(pi, 'Is' + name + 'Allowed'))
|
||||
# A green item still has to receive one Verify refresh attempt.
|
||||
# Mentor may report the capability as false for that item; this
|
||||
# flag is a gate only for a genuinely Required (status=1) item.
|
||||
if state[name] != 2 and not allowed:
|
||||
# Restored, previously verified CBBs can forbid a synchronized
|
||||
# action even while another action is Required. Do not invoke a
|
||||
# native-prohibited method or misreport the skip as a performed call.
|
||||
if state[name] == 2 and not allowed:
|
||||
protected_green.add(name)
|
||||
emit(stage='integration_action_skipped', action=method, initial_status=2,
|
||||
reason='synchronized_native_action_disallowed')
|
||||
continue
|
||||
if not allowed:
|
||||
emit(stage='integration_action_unavailable', action=method,
|
||||
initial_status=state[name], reason='mentor_not_allowed')
|
||||
raise IntegrationError(f'{name}: required but not allowed')
|
||||
|
||||
@@ -103,7 +103,8 @@ def source_project(source, top_level_block=''):
|
||||
pcb = reference(source, 'PCBDesignPath')
|
||||
if not pcb.is_file() or reference(pcb, 'ProjectFile') != source:
|
||||
raise ValueError('PCB 未引用所选来源工程。')
|
||||
for path in (source, pcb.parent/'pcb.prj'):
|
||||
from .maintenance_entry import maintenance_project_files
|
||||
for path in maintenance_project_files(source, pcb):
|
||||
if not path.is_file():
|
||||
raise ValueError('工程缺少 PCB 工程配置。')
|
||||
# Healthy Expedition PCB projects can use Layout/LayoutDB.lyt without
|
||||
|
||||
@@ -9,6 +9,36 @@ _COPY_ERROR = b'Error! Cannot copy iCDB base of Reusable Block project.'
|
||||
_LOG_LIMIT = 2*1024*1024
|
||||
|
||||
|
||||
def missing_other_pcb_notice(library, target, title, text, buttons):
|
||||
"""Only the observed editor-open information about unrelated missing PCBs."""
|
||||
from .management import validate_name
|
||||
from .verify_runner import preflight_skip_reason
|
||||
heading = ('The following Reusable Blocks do not contain PCB files and will not appear '
|
||||
'in the list of available reusable blocks:')
|
||||
if title != 'Library Manager' or len(text) > 131072 or len(buttons) != 1:
|
||||
return None
|
||||
button = buttons[0]
|
||||
if (button.get('id') != 2 or button.get('class') != 'Button'
|
||||
or button.get('text') not in ('OK', '确定') or button.get('enabled') is not True):
|
||||
return None
|
||||
lines = text.strip().splitlines()
|
||||
if not lines or lines[0] != heading:
|
||||
return None
|
||||
names = []
|
||||
for line in lines[1:]:
|
||||
if not line.strip(): continue
|
||||
if not line.startswith('\t'): return None
|
||||
name = line[1:]
|
||||
try: validate_name(name)
|
||||
except ValueError: return None
|
||||
if name.casefold() == str(target).casefold() or not preflight_skip_reason(library, name):
|
||||
return None
|
||||
names.append(name)
|
||||
if not names or len(names) != len({name.casefold() for name in names}):
|
||||
return None
|
||||
return {'names': names, 'button': button['hwnd']}
|
||||
|
||||
|
||||
def snapshot_add_log(library):
|
||||
path = Path(library).parent/'LogFiles/ReuseBlockLogLO.txt'
|
||||
try:
|
||||
|
||||
@@ -129,7 +129,17 @@ def normalize_edif(data, top):
|
||||
raise ValueError('Malformed EDIF header timestamp.')
|
||||
datetime(*(int(v) for v in values))
|
||||
design = one(root, b'design')
|
||||
if one(design, b'cellRef')['items'][1] != top.encode('mbcs'):
|
||||
top_bytes = top.encode('mbcs')
|
||||
if re.fullmatch(rb'[A-Za-z][A-Za-z0-9_]*', top_bytes):
|
||||
expected_identifier = top_bytes
|
||||
elif re.fullmatch(rb'[0-9][A-Za-z0-9_]*', top_bytes):
|
||||
# The installed exporter encodes digit-initial EDIF identifiers with
|
||||
# '&' (observed cellRef &1GPHY_8212). Retain all report bytes; this is
|
||||
# an exact identity check, not general name stripping or normalization.
|
||||
expected_identifier = b'&' + top_bytes
|
||||
else:
|
||||
raise ValueError('Unsupported native EDIF RootBlock identifier representation.')
|
||||
if one(design, b'cellRef')['items'][1] != expected_identifier:
|
||||
raise ValueError('EDIF top design differs from the requested RootBlock.')
|
||||
if (not any(n['items'] == [b'viewType', b'SCHEMATIC'] for n in nodes)
|
||||
or any(not any(n['items'][0] == tag for n in nodes) for tag in (b'page', b'figure', b'pt'))):
|
||||
@@ -163,8 +173,9 @@ def project_library(source):
|
||||
"""Require one existing approved source library across every project ref."""
|
||||
from .backup_recovery import _project_text
|
||||
source, pcb, _ = source_project(source)
|
||||
from .maintenance_entry import maintenance_project_files
|
||||
libraries = set()
|
||||
for path in (source, pcb.parent/'pcb.prj'):
|
||||
for path in maintenance_project_files(source, pcb):
|
||||
values = re.findall(r'^KEY CentralLibrary "([^"\r\n]+)"', _project_text(path), re.M)
|
||||
if not values: raise ValueError('Project lacks CentralLibrary references.')
|
||||
for value in values:
|
||||
@@ -192,7 +203,8 @@ def asset_identity(source, expected_library):
|
||||
expected_library = Path(expected_library)
|
||||
if not expected_library.is_file(): raise ValueError('Approved CentralLibrary is missing.')
|
||||
root = source.parent
|
||||
projects = (source, pcb.parent/'pcb.prj')
|
||||
from .maintenance_entry import maintenance_project_files
|
||||
projects = maintenance_project_files(source, pcb)
|
||||
databases = []
|
||||
for project in projects:
|
||||
values = re.findall(r'^KEY iCDBDir "([^"\r\n]+)"', _project_text(project), re.M)
|
||||
|
||||
@@ -161,17 +161,22 @@ class NativeManagementAdapter:
|
||||
from .desktop_worker import DesktopWorker
|
||||
request_path = evidence/'request.json'
|
||||
desktop, timeout = job['desktop'], job['timeout_seconds']
|
||||
deadline = time.monotonic() + timeout
|
||||
add_job = job['operation'] in ('add', 'probe_create_add', 'probe_readd')
|
||||
if add_job:
|
||||
job = {**job, 'native_add_deadline': deadline}
|
||||
_write_json(request_path, job)
|
||||
command = ([sys.executable] if getattr(sys, 'frozen', False)
|
||||
else [sys.executable, '-m', 'cbb_refresh_verify'])
|
||||
worker = (self.worker_factory or DesktopWorker)(command + ['--management-worker', str(request_path)], desktop)
|
||||
deadline = time.monotonic() + timeout
|
||||
while worker.poll() is None and time.monotonic() < deadline:
|
||||
time.sleep(.1)
|
||||
if worker.poll() is None:
|
||||
# DesktopWorker.close() requests a kill without a cancellation file.
|
||||
# Keep this exact worker alive until its native call returns normally.
|
||||
_retained_workers.append(worker)
|
||||
if add_job:
|
||||
(evidence/'cancel-native-add.signal').touch()
|
||||
return {'success': False, 'safe_to_continue': False,
|
||||
'detail': f'TIMEOUT: 原生调用尚未返回,保留私有桌面 {desktop},请检查 {evidence}'}
|
||||
try:
|
||||
@@ -278,12 +283,14 @@ class NativeManagementAdapter:
|
||||
target, pcb, _ = source_project(projects[0], request.top_level_block)
|
||||
_idle_check(request.library, target, pcb)
|
||||
owner_safe = False
|
||||
before_refs = {str(p): hash_file(p) for p in (target, pcb.parent/'pcb.prj')}
|
||||
from .maintenance_entry import maintenance_project_files
|
||||
project_files = maintenance_project_files(target, pcb)
|
||||
before_refs = {str(p): hash_file(p) for p in project_files}
|
||||
_align_library(target, pcb, request.library)
|
||||
if project_library(target) != Path(request.library).resolve():
|
||||
raise ValueError('Registered project references do not resolve to the exact target library.')
|
||||
_write_json(evidence/'reference-alignment.json', {'before': before_refs,
|
||||
'after': {str(p): hash_file(p) for p in (target, pcb.parent/'pcb.prj')}, 'library': job['library']})
|
||||
'after': {str(p): hash_file(p) for p in project_files}, 'library': job['library']})
|
||||
catalog = self.catalog(request.library, evidence/'reopen-aligned')
|
||||
owner_safe = catalog.safe_to_continue
|
||||
entries = [entry for entry in catalog.entries if entry.name == request.name and entry.partition == request.partition]
|
||||
@@ -614,6 +621,15 @@ def _probe_add_dialog(app, job, desktop, owned_pids, root, *, library=None):
|
||||
_close_probe_dialogs(desktop, owned_pids)
|
||||
|
||||
|
||||
def _require_add_supervisor(job, root):
|
||||
from .library_lock import _supervisor_alive
|
||||
deadline = job.get('native_add_deadline')
|
||||
if ((Path(root)/'cancel-native-add.signal').exists()
|
||||
or deadline is not None and time.monotonic() >= deadline
|
||||
or not _supervisor_alive(job['supervisor_pid'])):
|
||||
raise RuntimeError('NATIVE_ADD_CANCELLED: 操作已超时、停止或监督进程退出,未提交新的导入。')
|
||||
|
||||
|
||||
def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None):
|
||||
"""Submit the proven Logical-Physical Add dialog on an owned library."""
|
||||
import pythoncom, win32con, win32gui, win32process
|
||||
@@ -649,7 +665,9 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None)
|
||||
return hwnd
|
||||
pythoncom.PumpWaitingMessages(); time.sleep(.1)
|
||||
raise TimeoutError(f'原生窗口未出现:{title}')
|
||||
_require_add_supervisor(job, root)
|
||||
app.OnReusableBlocksEditor()
|
||||
_require_add_supervisor(job, root)
|
||||
editor = await_window('Reusable Blocks')
|
||||
tabs = Desktop(backend='uia').window(handle=editor).descendants(control_type='TabItem')
|
||||
physical = [tab for tab in tabs if tab.window_text() == 'Logical - Physical']
|
||||
@@ -680,9 +698,11 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None)
|
||||
ok = win32gui.GetDlgItem(dialog, 1083)
|
||||
if not ok:
|
||||
raise RuntimeError('原生新增确认按钮缺失。')
|
||||
_require_add_supervisor(job, root)
|
||||
log_baseline = snapshot_add_log(job['library'])
|
||||
_write_json(root/'native-add-log-baseline.json', log_baseline)
|
||||
observed_failures = {}
|
||||
_require_add_supervisor(job, root)
|
||||
win32gui.PostMessage(ok, win32con.BM_CLICK, 0, 0)
|
||||
success = None
|
||||
while time.monotonic() < deadline:
|
||||
@@ -900,6 +920,7 @@ def _catalog_com(job, root):
|
||||
stop = threading.Event()
|
||||
refused = []
|
||||
observed = []
|
||||
acknowledged_notices = set()
|
||||
owned_pids = set()
|
||||
def observe_dialogs():
|
||||
while not stop.wait(.1):
|
||||
@@ -920,6 +941,23 @@ def _catalog_com(job, root):
|
||||
cancel = win32gui.GetDlgItem(hwnd, 2)
|
||||
if cancel:
|
||||
win32gui.PostMessage(cancel, win32con.BM_CLICK, 0, 0)
|
||||
elif (job['operation'] in ('add', 'probe_create_add', 'probe_readd')
|
||||
and win32gui.GetClassName(hwnd) == '#32770'):
|
||||
from .native_add_failures import missing_other_pcb_notice
|
||||
controls = [{'hwnd': int(child), 'id': win32gui.GetDlgCtrlID(child),
|
||||
'class': win32gui.GetClassName(child), 'text': win32gui.GetWindowText(child),
|
||||
'enabled': bool(win32gui.IsWindowEnabled(child))} for child in children]
|
||||
notice = missing_other_pcb_notice(job['library'], job.get('name'), title,
|
||||
'\n'.join(c['text'] for c in controls if c['class'] == 'Static'),
|
||||
[c for c in controls if c['class'] == 'Button'])
|
||||
key = (int(hwnd), text)
|
||||
if notice and key not in acknowledged_notices:
|
||||
acknowledged_notices.add(key)
|
||||
with (root/'native-information.jsonl').open('a', encoding='utf-8') as stream:
|
||||
stream.write(json.dumps({'pid': pid, 'hwnd': int(hwnd), 'text': text,
|
||||
'missing_names': notice['names'], 'action': 'acknowledge_unrelated_missing_pcb'},
|
||||
ensure_ascii=False)+'\n')
|
||||
win32gui.PostMessage(notice['button'], win32con.BM_CLICK, 0, 0)
|
||||
except Exception:
|
||||
continue
|
||||
app = library = None
|
||||
|
||||
Reference in new issue
Block a user