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
@@ -0,0 +1,46 @@
|
||||
# 工单 #2:用户实测失败后的修订记录
|
||||
|
||||
分支 `codex/temp-issue-2-icdb-recovery`。本轮修订不能视为现场验收通过;未合并、发布或关闭工单。
|
||||
|
||||
## 用户失败的实际原因
|
||||
|
||||
用户运行 `b26e2f2` 冻结包。真实日志位于程序旁的 `data` 目录。中心库存在有效的未释放会话检查点,应用进入文件系统恢复视图,因此管理按钮被禁用;旧界面没有清楚显示原因,禁用外观也像可用按钮。该次没有启动增删改操作。
|
||||
|
||||
ICDB 批次的首项 `1GPHY_8212` 在预检查报 `MAINTENANCE_TARGET_UNCONFIRMED`,原生 Repair 没有执行。旧检查硬性要求 `PCB/pcb.prj`,但该工程的 PCB 明确反向引用主 `1GPHY_8212.prj`。主 PRJ 指向 `database`;存在的 `PCB/template.prj` 不能当作活动工程猜测使用。后续八项被跳过。
|
||||
|
||||
## 修订
|
||||
|
||||
- 只有 PCB 唯一、精确反向引用主 PRJ 时,允许缺少辅助 `pcb.prj`。预检查、Repair 后重新打开、管理来源身份及库引用核对使用一致规则。`template.prj` 保持原样并参与资产哈希。
|
||||
- 显示库会话阻止横幅、管理禁用原因、灰色禁用按钮及首项具体失败阶段。
|
||||
- 集成校验跳过原生明确禁止调用、且已同步的动作;仍要求四项最终全部同步。必需动作被禁止或原生拒绝时继续判失败,不伪造通过。
|
||||
- 识别原生 EDIF 中数字开头的精确标识符,例如 `&1GPHY_8212`;不放松设计内容比较。
|
||||
- 私有桌面上的原生库编辑器若提示其他已确认缺少 PCB 的条目,只确认准确匹配的已知通知。当前目标、未知弹窗或身份不符的窗口不自动确认。
|
||||
- 原生新增共享明确截止时间;父进程超时发出取消信号。阻塞调用返回后,以及所有日志和证据 I/O 完成、提交 OK 之前,重新检查监督进程、取消状态及期限,防止超时后迟到写入。
|
||||
|
||||
## 隔离原生证据及限制
|
||||
|
||||
证据根目录为 `diagnostics/issue2-user-feedback-20261103/`。
|
||||
|
||||
完整现场库副本保留原生地址和所有工程文件,共 38,954 个文件。原用户库始终不参与写入,完整恢复新增结束后 `source-final-recheck.json` 再次确认 25,214 个主要文件与试验前完全一致。
|
||||
|
||||
`d36b6bc` 冻结程序的实际维护按钮已在该副本完成完整备份、官方 Repair、数据库地址释放及同一 PCB 重新打开。随后原生要求选择历史 PCB 数据,应用返回 `PCB_VERSION_CHOICE_REQUIRED`,没有显示修复完成。
|
||||
|
||||
用户选择最后手动保存版本(2026/9/24 15:15)后,在确切所属的隔离会话中继续。SynchCES 和 LoadCES 成功,但原生 BackAnnotate 仍报已验证工程不允许执行。未保存、未达到 READY,失败 PCB 已正常关闭。这段人工续接不算无人值守自动修复通过。
|
||||
|
||||
空隔离库中的重新导入及工程身份核对通过,但自动校验因目标缺少 PartsDB 分区失败,不能算完整校验通过。完整依赖库中的首次同名替换完成原生移除后,新增被其他条目缺少 PCB 的提示阻塞而超时;该部分失败的检查点及完整旧库备份保留在 `diagnostics/full-update-events/`,没有自动重放。
|
||||
|
||||
完整隔离库中 IP101GR 的旧数据库地址通过官方 Repair 释放,证据为 `dependency-ip101gr-native-only/result.json`。这只是依赖数据库的原生修复诊断,没有重新打开或 READY 验收。
|
||||
|
||||
修订后对缺失的 `1GPHY_8212` 显式执行恢复新增,启用自动校验;独立证据目录为 `diagnostics/full-recovery-events/`。结果为 `UPLOADED_VERIFIED`,`safe_to_continue=true`。已知的其他缺 PCB 条目提示被自动准确确认;新增后独立重读库、三种原生逻辑导出及主要资产比较通过。随后自动执行 ForwardAnnotate、SynchCES、LoadCES、BackAnnotate,四项最终均同步,保存、关闭和进程退出确认完成,权威 `IsVerifiedReuseBlock` 返回 `raw=1 / READY`。自动校验链路耗时 126.422 秒(不含完整备份和新增身份检查)。
|
||||
|
||||
最终结果为 `full-recovery-add-result.json`,完整检查点为 `diagnostics/full-recovery-events/management-03a9dbc537f84e0faaea2ad5a2a732c2/checkpoint.json`。此结果证明修订后**重新导入加校验**的恢复路径有效,不能替代直接 ICDB Repair 后仍被原生 BackAnnotate 拒绝的失败结论,也不把用户选择历史数据后的工程称为无损修复。
|
||||
|
||||
## 尚未满足的门槛
|
||||
|
||||
服务器会话失联经实际按钮触发、自动 Repair、重新打开、保存关闭及权威 READY 的完整链路仍需通过。历史数据选择及重新导入均可能改变恢复版本,不能宣称无损恢复。Windows 10 尚未验证;当前实机为 Windows 11 / Mentor EE7.9.5。
|
||||
|
||||
## 自动化验证
|
||||
|
||||
修订代码全量 `python -X utf8 -m pytest -q`:**1095 passed,171.09 秒**。保留一条已有 pywinauto STA COM 线程模式警告。`compileall`、`git diff --check` 通过。取消发生在日志证据 I/O 中的回归先复现错误提交,再验证修复;相关集中测试 108 项通过。独立审查已复核全部代码修订,最后一项取消时序 P2 已解决,没有剩余实质问题。
|
||||
|
||||
候选包按提交归档构建。最终冻结按钮冒烟结果及构建、压缩包校验记录分别保存在证据目录的 `final-frozen-buttons/result.json`、`build-result.json`、`package-result.json`;按钮冒烟只证明界面响应,不等于现场 ICDB 自动修复验收。
|
||||
@@ -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
|
||||
|
||||
@@ -290,6 +290,45 @@ def test_refresh_integration_skips_native_disabled_green_action():
|
||||
assert pi.actions == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize('ces_allowed', [True, False])
|
||||
def test_partial_sync_respects_protected_green_native_actions(ces_allowed):
|
||||
class RestoredVerifiedBlock(GreenProjectIntegration):
|
||||
IsForwardAnnotationAllowed = False
|
||||
BackAnnotationStatus = 1
|
||||
|
||||
def ForwardAnnotate(self):
|
||||
raise RuntimeError('Forward Annotation is not allowed on verified Reusable Blocks')
|
||||
|
||||
def BackAnnotate(self):
|
||||
super().BackAnnotate()
|
||||
self.BackAnnotationStatus = 2
|
||||
return True
|
||||
|
||||
pi = RestoredVerifiedBlock()
|
||||
pi.IsSynchCESAllowed = pi.IsLoadCESAllowed = ces_allowed
|
||||
events = []
|
||||
result = refresh_integration(pi, settle_seconds=0, emit=lambda **e: events.append(e))
|
||||
assert set(result.values()) == {2}
|
||||
assert pi.actions == (['SynchCES', 'LoadCES', 'BackAnnotate'] if ces_allowed else ['BackAnnotate'])
|
||||
assert [e['action'] for e in events if e['stage'] == 'integration_action'] == pi.actions
|
||||
|
||||
|
||||
def test_skipped_green_action_cannot_hide_a_later_required_native_gate():
|
||||
class ChangedAfterCES(GreenProjectIntegration):
|
||||
IsForwardAnnotationAllowed = False
|
||||
BackAnnotationStatus = 1
|
||||
|
||||
def SynchCES(self):
|
||||
super().SynchCES()
|
||||
self.ForwardAnnotationStatus = 1
|
||||
return True
|
||||
|
||||
pi = ChangedAfterCES()
|
||||
with pytest.raises(IntegrationError, match='ForwardAnnotation: required but not allowed'):
|
||||
refresh_integration(pi, settle_seconds=0)
|
||||
assert pi.actions == ['SynchCES']
|
||||
|
||||
|
||||
def test_refresh_integration_never_counts_rejected_green_action_as_completed():
|
||||
class VerifiedProjectIntegration(GreenProjectIntegration):
|
||||
def _blocked(self, action):
|
||||
|
||||
@@ -25,7 +25,7 @@ def test_raw_dispatch_diagnostics_preserve_hresult_and_known_member_ids(tmp_path
|
||||
|
||||
def test_probe_records_dispatch_before_after_import_and_after_source_alignment(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
import sys
|
||||
import sys, os
|
||||
source = tmp_path/'source/Block.prj'
|
||||
source.parent.mkdir()
|
||||
source.write_text('KEY RootBlock "Block"\nKEY PCBDesignPath "PCB/Block.pcb"\n'
|
||||
@@ -51,7 +51,7 @@ def test_probe_records_dispatch_before_after_import_and_after_source_alignment(t
|
||||
raise AttributeError(name)
|
||||
monkeypatch.setitem(sys.modules, 'pywinauto', Uia('pywinauto'))
|
||||
job = {'operation': 'probe_create_add', 'source': str(source), 'library': str(library),
|
||||
'name': 'Block', 'timeout_seconds': 0}
|
||||
'name': 'Block', 'timeout_seconds': 0, 'supervisor_pid': os.getpid()}
|
||||
with pytest.raises(RuntimeError, match='stop before native UI'):
|
||||
native._probe_add_dialog_impl(App(), job, None, set(), root, library=SimpleNamespace(_oleobj_=Raw()))
|
||||
records = [json.loads(line) for line in (root/'dispatch-diagnostics.jsonl').read_text(encoding='utf-8').splitlines()]
|
||||
@@ -134,7 +134,8 @@ def test_probe_converts_desktop_pyhandle_before_uia_boundary(tmp_path, monkeypat
|
||||
raise RuntimeError('integer UIA boundary reached')
|
||||
monkeypatch.setitem(sys.modules, 'pywinauto', SimpleNamespace(Desktop=Desktop))
|
||||
app = SimpleNamespace(OnReusableBlocksEditor=lambda: None)
|
||||
job = {'operation': 'probe_create_add', 'source': str(source), 'name': 'Block',
|
||||
import os
|
||||
job = {'operation': 'probe_create_add', 'source': str(source), 'name': 'Block', 'supervisor_pid': os.getpid(),
|
||||
'library': str(root/'fixture/mentor_lib.lmc'), 'timeout_seconds': 5}
|
||||
with pytest.raises(RuntimeError, match='integer UIA boundary reached'):
|
||||
native._probe_add_dialog_impl(app, job, desktop, {9}, root)
|
||||
@@ -26,13 +26,21 @@ def test_layout_based_pcb_without_independent_icdb_directory_is_complete(healthy
|
||||
assert engineering_identity(source)['top_level_block'] == 'IP101GR'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('missing', ['database/icdb.dat', 'PCB/Layout/LayoutDB.lyt', 'PCB/pcb.prj'])
|
||||
@pytest.mark.parametrize('missing', ['database/icdb.dat', 'PCB/Layout/LayoutDB.lyt'])
|
||||
def test_optional_pcb_icdb_does_not_relax_required_engineering_files(healthy_source, missing):
|
||||
(healthy_source.parent/missing).unlink()
|
||||
with pytest.raises(ValueError):
|
||||
source_project(healthy_source)
|
||||
|
||||
|
||||
def test_linked_legacy_pcb_uses_explicit_main_project_without_guessing_template(healthy_source):
|
||||
(healthy_source.parent/'PCB/pcb.prj').rename(healthy_source.parent/'PCB/template.prj')
|
||||
assert source_project(healthy_source)[0] == healthy_source
|
||||
(healthy_source.parent/'PCB/IP101GR.pcb').write_text('KEY ProjectFile "../wrong.prj"\n')
|
||||
with pytest.raises(ValueError, match='PCB'):
|
||||
source_project(healthy_source)
|
||||
|
||||
|
||||
def test_main_schematic_icdb_declaration_remains_required(healthy_source):
|
||||
text = healthy_source.read_text(encoding='utf-8').replace('KEY iCDBDir ".\\database"\n', '')
|
||||
healthy_source.write_text(text, encoding='utf-8')
|
||||
|
||||
@@ -7,6 +7,91 @@ import pytest
|
||||
ERROR = b'REUSE BLOCK: INFORMATION: Block\tError! Cannot copy iCDB base of Reusable Block project.\r\n'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('change', ['', 'target', 'pcb_present', 'question', 'extra_button', 'wrong_button', 'escape'])
|
||||
def test_editor_missing_pcb_notice_is_only_for_unrelated_incomplete_entries(tmp_path, change):
|
||||
from cbb_refresh_verify.native_add_failures import missing_other_pcb_notice
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
work = tmp_path/'ReusableBlocksLP/Missing/Work'
|
||||
(work/'PCB/Layout').mkdir(parents=True)
|
||||
(work/'Missing.prj').write_text('KEY PCBDesignPath "PCB/Missing.pcb"\n')
|
||||
text = ('The following Reusable Blocks do not contain PCB files and will not appear in the list of available reusable blocks:'
|
||||
'\n\n\tMissing')
|
||||
buttons = [{'hwnd':123, 'id':2, 'class':'Button', 'text':'确定', 'enabled':True}]
|
||||
target = 'Missing' if change == 'target' else 'Current'
|
||||
if change == 'pcb_present':
|
||||
(work/'PCB/Missing.pcb').touch(); (work/'PCB/Layout/LayoutDB.lyt').touch()
|
||||
if change == 'question': text += '\nOverwrite existing files?'
|
||||
if change == 'extra_button': buttons.append({**buttons[0], 'hwnd':456})
|
||||
if change == 'wrong_button': buttons[0]['text']='Yes'
|
||||
if change == 'escape': text=text.replace('\tMissing', '\t../other')
|
||||
result = missing_other_pcb_notice(library, target, 'Library Manager', text, buttons)
|
||||
assert result == ({'names':['Missing'], 'button':123} if not change else None)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reason', ['cancelled', 'supervisor_exited'])
|
||||
def test_add_cannot_submit_after_timeout_or_supervisor_exit(tmp_path, monkeypatch, reason):
|
||||
from cbb_refresh_verify.native_management import _require_add_supervisor
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
if reason == 'cancelled': (tmp_path/'cancel-native-add.signal').touch()
|
||||
monkeypatch.setattr(locks, '_supervisor_alive', lambda _:reason != 'supervisor_exited')
|
||||
with pytest.raises(RuntimeError, match='NATIVE_ADD_CANCELLED'):
|
||||
_require_add_supervisor({'supervisor_pid':123}, tmp_path)
|
||||
|
||||
|
||||
def test_add_timeout_publishes_cancellation_without_killing_native_owner(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
monkeypatch.setattr(native, '_retained_workers', [])
|
||||
class Running:
|
||||
def __init__(self, *args): pass
|
||||
def poll(self): return None
|
||||
def close(self): pytest.fail('live worker must not be killed')
|
||||
adapter=native.NativeManagementAdapter(worker_factory=Running)
|
||||
result=adapter._launch_worker({'operation':'add','desktop':'CbbManagement_test','timeout_seconds':0},tmp_path)
|
||||
assert not result['safe_to_continue'] and (tmp_path/'cancel-native-add.signal').exists()
|
||||
assert len(native._retained_workers)==1
|
||||
|
||||
|
||||
def test_cancellation_during_log_evidence_prevents_native_submit(tmp_path, monkeypatch):
|
||||
import os,sys
|
||||
from types import SimpleNamespace
|
||||
import win32gui,win32process
|
||||
import cbb_refresh_verify.native_management as native
|
||||
import cbb_refresh_verify.native_add_failures as failures
|
||||
from test_management import project
|
||||
source=project(tmp_path/'source',name='Block')
|
||||
root=tmp_path/'native-add';root.mkdir()
|
||||
library=root/'fixture/lib.lmc';library.parent.mkdir();library.touch()
|
||||
for path in (source,source.parent/'PCB/pcb.prj'):
|
||||
with path.open('a',encoding='utf-8') as stream:stream.write(f'KEY CentralLibrary "{library}"\n')
|
||||
state={'new':False,'posted':[]}
|
||||
tab=SimpleNamespace(window_text=lambda:'Logical - Physical',is_selected=lambda:True)
|
||||
monkeypatch.setitem(sys.modules,'pywinauto',SimpleNamespace(Desktop=lambda **k:SimpleNamespace(
|
||||
window=lambda **k:SimpleNamespace(descendants=lambda **k:[tab]))))
|
||||
monkeypatch.setattr(win32process,'GetWindowThreadProcessId',lambda h:(1,99))
|
||||
monkeypatch.setattr(win32gui,'IsWindowVisible',lambda h:True)
|
||||
monkeypatch.setattr(win32gui,'IsWindowEnabled',lambda h:True)
|
||||
monkeypatch.setattr(win32gui,'GetWindowText',lambda h:{100:'Reusable Blocks',200:'New Reusable Block'}[int(h)])
|
||||
monkeypatch.setattr(win32gui,'GetDlgItem',lambda h,c:110 if h==100 else 210 if c==1083 else c+1000)
|
||||
monkeypatch.setattr(win32gui,'GetClassName',lambda h:'Edit')
|
||||
monkeypatch.setattr(native,'_set_probe_field',lambda *a:None)
|
||||
def post(h,*args):
|
||||
state['posted'].append(h)
|
||||
if h==110:state['new']=True
|
||||
monkeypatch.setattr(win32gui,'PostMessage',post)
|
||||
original=native._write_json
|
||||
def write(path,data):
|
||||
original(path,data)
|
||||
if path.name=='native-add-log-baseline.json':(root/'cancel-native-add.signal').touch()
|
||||
monkeypatch.setattr(native,'_write_json',write)
|
||||
monkeypatch.setattr(failures,'observe_add_failure',lambda *a:(_ for _ in ()).throw(RuntimeError('unsafe OK posted')))
|
||||
desktop=SimpleNamespace(EnumDesktopWindows=lambda:[100,200] if state['new'] else [100])
|
||||
job={'operation':'probe_create_add','source':str(source),'library':str(library),
|
||||
'name':'Block','timeout_seconds':5,'supervisor_pid':os.getpid()}
|
||||
with pytest.raises(RuntimeError,match='NATIVE_ADD_CANCELLED'):
|
||||
native._probe_add_dialog_impl(SimpleNamespace(OnReusableBlocksEditor=lambda:None),job,desktop,{99},root)
|
||||
assert state['posted']==[110]
|
||||
|
||||
|
||||
def test_copy_failure_log_must_be_new_and_match_current_block(tmp_path):
|
||||
from cbb_refresh_verify.native_add_failures import snapshot_add_log, fresh_add_failure
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
|
||||
@@ -72,6 +72,24 @@ def test_assets_require_correct_library_references_and_unknown_bytes(project):
|
||||
asset_identity(source, library)
|
||||
|
||||
|
||||
def test_linked_legacy_identity_preserves_template_bytes_and_aligns_only_active_project(project, tmp_path):
|
||||
from cbb_refresh_verify.native_engineering_identity import asset_identity, project_library
|
||||
from cbb_refresh_verify.backup_recovery import _align_library
|
||||
source, library = project
|
||||
template = source.parent/'PCB/template.prj'
|
||||
(source.parent/'PCB/pcb.prj').rename(template)
|
||||
original = template.read_bytes()
|
||||
before = asset_identity(source, library)
|
||||
assert 'PCB/template.prj' in before['assets']
|
||||
other = tmp_path/'other.lmc'; other.write_bytes(b'other library')
|
||||
_align_library(source, next((source.parent/'PCB').glob('*.pcb')), other)
|
||||
assert template.read_bytes() == original
|
||||
assert project_library(source) == other
|
||||
assert asset_identity(source, other) == before
|
||||
template.write_bytes(original+b'unknown engineering change')
|
||||
assert asset_identity(source, other) != before
|
||||
|
||||
|
||||
@pytest.mark.parametrize('relative', ['database/cdbsvr/persistent.dat',
|
||||
'database/cdbsvr/new-engineering/config.bin', 'database/cdbsvr/events/custom.dat',
|
||||
'database/cdbsvr/plog/unknown-engineering.bin'])
|
||||
@@ -199,3 +217,14 @@ def test_edif_only_normalizes_root_written_timestamp_preserving_geometry_and_pro
|
||||
for bad in [first[:-1], first.replace(b'(edifVersion 2 0 0)', b'(edifVersion 1 0 0)'),
|
||||
first.replace(b'(cellRef Top', b'(cellRef Other'), first.replace(b'(pt 1 2)', b'')]:
|
||||
with pytest.raises(ValueError): normalize_edif(bad, 'Top')
|
||||
|
||||
|
||||
def test_edif_binds_native_escaped_digit_initial_root_without_changing_design_bytes():
|
||||
from cbb_refresh_verify.native_engineering_identity import normalize_edif
|
||||
report = edif_report().replace(b'cell Top', b'cell &1GPHY_8212').replace(b'cellRef Top', b'cellRef &1GPHY_8212')
|
||||
normalized = normalize_edif(report, '1GPHY_8212')
|
||||
assert b'(cell &1GPHY_8212' in normalized and b'(cellRef &1GPHY_8212' in normalized
|
||||
for wrong in ('1GPHY_8211', '&1GPHY_8212'):
|
||||
with pytest.raises(ValueError): normalize_edif(report, wrong)
|
||||
with pytest.raises(ValueError):
|
||||
normalize_edif(report.replace(b'&1GPHY_8212', b'1GPHY_8212'), '1GPHY_8212')
|
||||
Reference in new issue
Block a user