diff --git a/docs/releases/2026-11-02-cbb-management.md b/docs/releases/2026-11-02-cbb-management.md index f49c693..00eed36 100644 --- a/docs/releases/2026-11-02-cbb-management.md +++ b/docs/releases/2026-11-02-cbb-management.md @@ -61,6 +61,7 @@ icdb.dat 和 LayoutDB.lyt。全部通过才归档阻止记录并关闭本应用 上述释放检查和未完成任务审查,再使用本工具或旧上传工具继续写入。 备份与来源不能置于目标库内部,来源必须是完整且引用位于工程内的 PRJ/PCB。 +来源工程根目录和目标库根目录也不能相互包含或相同,避免操作嵌套库时改变原始来源。 链接、外部数据库引用、源文件变化、备份失败和同名新增冲突均会阻止写入。 来源先完整复制;工程身份比较使用顶层块、原理图数据库和布局数据库内容指纹, 原生规范化若改变数据库字节则保守拒绝确认,需要进一步语义验证,不能声称等价。 @@ -69,6 +70,9 @@ icdb.dat 和 LayoutDB.lyt。全部通过才归档阻止记录并关闭本应用 已识别原生进程。读取目录遇到旧库升级或 Select flow type 对话框时取消并报错, 绝不将升级作为只读读取的一部分。超时保留原生所有者和证据,不强杀数据库进程; 确认前不继续下一项,不启动最终 Verify。 +通过网络盘租约选择的盘符路径在原生 OpenLibrary、CLI、暂存工程库引用和后续 +Verify 中保持原样;规范化路径仅用于身份、包含关系和锁键比较。工作进程按原 +租约的盘符/共享目录上下文确认映射,不把原生盘符路径改回 UNC。 ## 独立新增诊断 @@ -81,6 +85,10 @@ Reusable Blocks / UIA Logical - Physical 页签和 New 按钮、1103 对话框 可加 `--replacement-source OTHER.prj` 在同一个新建隔离库中验证同名更新: 先备份完整旧库,再原生移除并检查缺失,然后重新导入替换工程。重新导入必须 匹配本次 CreateLibrary 记录的固定路径和随机所有权令牌,不能指向外部库。 +监督进程先创建新的空 fixture 目录并持有库锁,原生工作进程核对准备令牌、 +检查点协议和监督 PID 后才创建 LMC。初次创建、所有复读和替换阶段均按生产 +操作的释放规则持锁;超时或释放异常保留独占句柄和重启阻止记录,必须重新 +通过会话释放检查才能解除。 本阶段单元测试通过注入文件模拟的原生边界执行,不启动 Mentor、不操作实际库。 候选冻结包、最终 Windows 11 原生场景由协调端单独验收。Windows 10 和真实 diff --git a/src/cbb_refresh_verify/management.py b/src/cbb_refresh_verify/management.py index 8501d7b..de85280 100644 --- a/src/cbb_refresh_verify/management.py +++ b/src/cbb_refresh_verify/management.py @@ -27,6 +27,8 @@ class ManagementRequest: evidence_dir: Path = Path('management-evidence') top_level_block: str = '' timeout_seconds: float = 180 + mapped_drive: str = '' + mapped_remote_root: str = '' @dataclass(frozen=True) @@ -187,30 +189,36 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro if request.operation not in ('add', 'update', 'remove'): raise ValueError('不支持的管理操作。') validate_name(request.name); validate_name(request.partition) - library = Path(request.library).resolve(strict=True) + from .network_path import absolute_preserving_drive + library = absolute_preserving_drive(request.library) + canonical_library = library.resolve(strict=True) + library_root = canonical_library.parent if library.suffix.casefold() != '.lmc' or not library.is_file(): raise ValueError('中心库必须为现有 LMC 文件。') evidence = Path(request.evidence_dir).resolve() - if evidence.is_relative_to(library.parent) or library.parent.is_relative_to(evidence): + if evidence.is_relative_to(library_root) or library_root.is_relative_to(evidence): raise ValueError('操作记录与备份必须位于目标中心库之外,且不能包含目标库。') capability = adapter.capabilities().get(request.operation, Capability(False, '未验证的原生接口')) if not capability.supported: return finish('UNSUPPORTED', capability.reason) for unfinished in unfinished_operations(evidence): - if unfinished.get('library') and Path(unfinished['library']).resolve() == library: + if unfinished.get('library') and Path(unfinished['library']).resolve() == canonical_library: return finish('BLOCKED', f'存在未完成/需恢复任务,禁止自动重放:{unfinished["evidence_path"]}', False) source = pcb = None if request.operation in ('add', 'update'): if request.source is None: raise ValueError('新增/更新需要完整来源工程。') source, pcb, top = source_project(request.source, request.top_level_block) - if (source.is_relative_to(library.parent) or evidence.is_relative_to(source.parent) + if (source.parent.is_relative_to(library_root) or library_root.is_relative_to(source.parent) + or evidence.is_relative_to(source.parent) or source.parent.is_relative_to(evidence)): raise ValueError('来源工程、目标库与操作证据必须使用独立目录。') mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795') acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED) if not acquired: return finish('BLOCKED', '已有 CBB 校验/管理/恢复任务运行。', False) + if hasattr(adapter, 'bind_library_mapping'): + adapter.bind_library_mapping(request.mapped_drive, request.mapped_remote_root) with LibraryLock(library, safe_to_release=lambda: owner_safe): root = evidence/('management-' + uuid4().hex) root.mkdir(parents=True, exist_ok=False) @@ -232,7 +240,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro owner_safe = False before = adapter.catalog(library, root/'before') owner_safe = before.safe_to_continue - if not owner_safe or Path(before.library).resolve() != library or before.flow != 1: + if not owner_safe or Path(before.library).resolve() != canonical_library or before.flow != 1: return finish('BLOCKED', '原生目录身份/流程或所有者释放未确认。仅支持已验证 DxDesigner 流程。', owner_safe) same_name = [entry for entry in before.entries if entry.name.casefold() == request.name.casefold()] matches = [entry for entry in same_name if entry.partition == request.partition and entry.name == request.name] @@ -246,7 +254,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro idle_check(library, target_project, target_pcb) scope = ManifestScope.library(request.name, library.name) checkpoint('backup') - original = copy_verified(library.parent, root/'library-before', scope=scope, progress=progress) + original = copy_verified(library_root, root/'library-before', scope=scope, progress=progress) _write_json(root/'library-before-manifest.json', original) staged = request identity = None @@ -258,7 +266,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro identity = engineering_identity(staged.source) if build_manifest(source.parent) != source_manifest: raise OSError('来源工程在暂存期间变化。') - if build_manifest(library.parent, scope=scope) != original: + if build_manifest(library_root, scope=scope) != original: raise OSError('备份后中心库内容变化,停止写入。') if request.operation in ('remove', 'update'): checkpoint('native_remove') @@ -272,7 +280,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro owner_safe = False after = adapter.catalog(library, root/'after-remove') owner_safe = after.safe_to_continue - if (not owner_safe or Path(after.library).resolve() != library or after.flow != 1 + if (not owner_safe or Path(after.library).resolve() != canonical_library or after.flow != 1 or any(e.name == request.name and e.partition == request.partition for e in after.entries)): return finish('RECOVERY_REQUIRED', '原生移除后目录未确认目标缺失。', False) removed = True @@ -292,7 +300,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro owner_safe = after.safe_to_continue matches = [entry for entry in after.entries if entry.name == request.name and entry.partition == request.partition] - if (not owner_safe or Path(after.library).resolve() != library or after.flow != 1 + if (not owner_safe or Path(after.library).resolve() != canonical_library or after.flow != 1 or len(matches) != 1 or matches[0].engineering_identity != identity): return finish('RECOVERY_REQUIRED', '原生新增后名称、分区或来源工程内容未确认一致。', False) uploaded = True @@ -302,7 +310,8 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro # Adapter catalog cannot return until its exact native owner exits. checkpoint('verify') owner_safe = False - verified = verifier(VerifyRequest(library, request.name, root/'verify'), progress=progress) + verified = verifier(VerifyRequest(library, request.name, root/'verify', + mapped_drive=request.mapped_drive, mapped_remote_root=request.mapped_remote_root), progress=progress) owner_safe = verified.safe_to_continue checkpoint('verified', verification=asdict(verified)) good = verified.status == 'PASS' and verified.library_flag == 'GREEN' and owner_safe diff --git a/src/cbb_refresh_verify/native_management.py b/src/cbb_refresh_verify/native_management.py index 2e305d8..3a35f35 100644 --- a/src/cbb_refresh_verify/native_management.py +++ b/src/cbb_refresh_verify/native_management.py @@ -18,6 +18,7 @@ from uuid import uuid4 from .management import (Capability, Catalog, CatalogEntry, NativeOutcome, engineering_identity, validate_name, _write_json) from .scoped_manifest import hash_file +from .network_path import absolute_preserving_drive _retained_workers = [] _BINARY_PROOF = { @@ -55,6 +56,12 @@ class NativeManagementAdapter: self.home = Path(mentor_home) if mentor_home is not None else discover_sdd_home() self.worker_factory = worker_factory self.timeout_seconds = timeout_seconds + self.mapped_drive = '' + self.mapped_remote_root = '' + + def bind_library_mapping(self, drive, remote_root): + self.mapped_drive = drive or '' + self.mapped_remote_root = remote_root or '' def capabilities(self): reason = '' @@ -74,14 +81,36 @@ class NativeManagementAdapter: } def _worker(self, job, evidence): - from .desktop_worker import DesktopWorker evidence = Path(evidence) evidence.mkdir(parents=True, exist_ok=False) - request_path = evidence/'request.json' desktop = 'CbbManagement_' + uuid4().hex[:12] timeout = float(job.get('timeout_seconds', self.timeout_seconds)) job = {**job, 'desktop': desktop, 'mentor_home': str(self.home or ''), + 'mapped_drive': job.get('mapped_drive', self.mapped_drive), + 'mapped_remote_root': job.get('mapped_remote_root', self.mapped_remote_root), 'timeout_seconds': timeout, 'supervisor_pid': os.getpid()} + if job['operation'] == 'probe_create_add': + # Prepare the fixed NEW fixture before a native owner can start. + # The parent owns its sidecar for the entire create/add invocation. + from .library_lock import LibraryLock + library = absolute_preserving_drive(evidence)/'fixture/mentor_lib.lmc' + if Path(job['library']).resolve() != library.resolve() or not job.get('probe_token'): + raise ValueError('隔离创建目标必须为本次工作目录内的新库。') + library.parent.mkdir(exist_ok=False) + _write_json(evidence/'probe-prepared.json', {'library': str(library), 'token': job['probe_token'], + 'supervisor_pid': os.getpid()}) + owner_safe = True + with LibraryLock(library, safe_to_release=lambda: owner_safe): + owner_safe = False + result = self._launch_worker(job, evidence) + owner_safe = result.get('safe_to_continue') is True + return result + return self._launch_worker(job, evidence) + + def _launch_worker(self, job, evidence): + from .desktop_worker import DesktopWorker + request_path = evidence/'request.json' + desktop, timeout = job['desktop'], job['timeout_seconds'] _write_json(request_path, job) command = ([sys.executable] if getattr(sys, 'frozen', False) else [sys.executable, '-m', 'cbb_refresh_verify']) @@ -106,7 +135,7 @@ class NativeManagementAdapter: worker.close() def catalog(self, library, evidence): - result = self._worker({'operation': 'catalog', 'library': str(library)}, evidence) + result = self._worker({'operation': 'catalog', 'library': str(absolute_preserving_drive(library))}, evidence) if not result.get('success') or not result.get('safe_to_continue'): raise RuntimeError(result.get('detail', '原生目录复读未确认,禁止文件夹回退。')) return Catalog(Path(result['library']), int(result['flow']), @@ -119,8 +148,9 @@ class NativeManagementAdapter: removal_input(request.name, request.partition) if request.partition != 'Logical-Physical': return NativeOutcome(False, True, '仅已验证 Logical-Physical 原生移除。') - result = self._worker({'operation': 'remove', 'library': str(request.library), + result = self._worker({'operation': 'remove', 'library': str(absolute_preserving_drive(request.library)), 'name': request.name, 'partition': request.partition, + 'mapped_drive': request.mapped_drive, 'mapped_remote_root': request.mapped_remote_root, 'timeout_seconds': request.timeout_seconds}, evidence) return NativeOutcome(bool(result.get('success')), bool(result.get('safe_to_continue')), result.get('detail', '')) @@ -135,22 +165,36 @@ class NativeManagementAdapter: def prepare_probe_library(job, root): - """Diagnostic create is restricted to a new fixed descendant of this job.""" - expected = Path(root).resolve()/'fixture/mentor_lib.lmc' - if Path(job['library']).resolve() != expected or expected.parent.exists(): - raise ValueError('诊断只能创建当前任务下全新独占 fixture/mentor_lib.lmc。') - expected.parent.mkdir() + """Validate a NEW fixed fixture already guarded by its supervisor.""" + from .library_lock import blocker_path, checkpoint_record + expected = absolute_preserving_drive(root)/'fixture/mentor_lib.lmc' + try: + prepared = json.loads((Path(root)/'probe-prepared.json').read_text(encoding='utf-8')) + guard = checkpoint_record(blocker_path(expected)) + allowed = {'.mentor_lib.cbb-upload.lock', '.mentor_lib.cbb-upload.blocked.json'} + valid = (Path(job['library']).resolve() == expected.resolve() and not expected.exists() + and expected.parent.is_dir() and {p.name for p in expected.parent.iterdir()} == allowed + and prepared.get('token') == job.get('probe_token') and bool(job.get('probe_token')) + and Path(prepared['library']).resolve() == expected.resolve() + and prepared.get('supervisor_pid') == job.get('supervisor_pid') + and guard is not None and guard['pid'] == job.get('supervisor_pid') + and Path(guard['library']).resolve() == expected.resolve() + and guard['status'] == 'OPERATION_IN_PROGRESS') + except (OSError, ValueError, KeyError): + valid = False + if not valid: + raise ValueError('诊断只能创建当前监督进程已持锁的全新 fixture/mentor_lib.lmc。') return expected def validate_probe_readd(job, root): - expected = Path(root).parent.resolve()/'native-add/fixture/mentor_lib.lmc' + expected = absolute_preserving_drive(root).parent/'native-add/fixture/mentor_lib.lmc' try: owner = json.loads((Path(root).parent/'probe-owner.json').read_text(encoding='utf-8')) except (OSError, ValueError) as error: raise ValueError('没有本次原生创建的隔离库所有权记录。') from error - if (Path(job['library']).resolve() != expected or not expected.is_file() - or owner.get('library') != str(expected) or not job.get('probe_token') + if (Path(job['library']).resolve() != expected.resolve() or not expected.is_file() + or not owner.get('library') or Path(owner['library']).resolve() != expected.resolve() or not job.get('probe_token') or owner.get('token') != job['probe_token']): raise ValueError('重新导入诊断仅允许本次原生新建的固定隔离库。') return expected @@ -288,18 +332,19 @@ def run_isolated_probe(source, root, name, *, mentor_home=None, replacement_sour from .scoped_manifest import ManifestScope from .scoped_manifest import copy_verified, build_manifest import pythoncom, win32con, win32event - root = Path(root).resolve() + root = absolute_preserving_drive(root) if root.exists(): raise ValueError('诊断目录必须是全新目录,不能复用现有中心库或旧 fixture。') source, _, top = source_project(source) validate_name(name) - if root.is_relative_to(source.parent) or source.parent.is_relative_to(root): + if root.resolve().is_relative_to(source.parent) or source.parent.is_relative_to(root.resolve()): raise ValueError('诊断目录不能与来源工程相互包含。') mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795') acquired = False token = uuid4().hex record = {'operation': 'isolated_add_probe', 'source': str(source), 'name': name, 'production_capability_enabled': False} + owner_safe = True from .com_runtime import initialize_com, uninitialize_com initialized = initialize_com() try: @@ -314,13 +359,20 @@ def run_isolated_probe(source, root, name, *, mentor_home=None, replacement_sour if not adapter.capabilities()['remove'].supported: raise RuntimeError('诊断要求已识别的 EE7.9.5 原生安装。') library = root/'native-add/fixture/mentor_lib.lmc' + def read_catalog(evidence): + nonlocal owner_safe + owner_safe = False + catalog = adapter.catalog(library, evidence) + owner_safe = catalog.safe_to_continue + return catalog native = adapter._worker({'operation': 'probe_create_add', 'library': str(library), 'source': str(staged), 'name': name, 'top_level_block': top, 'probe_token': token}, root/'native-add') record['native'] = native record['source_unchanged'] = build_manifest(source.parent) == manifest if native.get('success') and native.get('safe_to_continue'): - catalog = adapter.catalog(library, root/'reopen') + with LibraryLock(library, safe_to_release=lambda: owner_safe): + catalog = read_catalog(root/'reopen') record['catalog'] = asdict(catalog) matches = [entry for entry in catalog.entries if entry.name == name and entry.partition == 'Logical-Physical'] record['identity_matches'] = len(matches) == 1 and matches[0].engineering_identity == identity @@ -330,35 +382,39 @@ def run_isolated_probe(source, root, name, *, mentor_home=None, replacement_sour _write_json(root/'probe-result.json', record) if record['accepted'] and replacement_source is not None: replacement, _, replacement_top = source_project(replacement_source) - if replacement.is_relative_to(root) or root.is_relative_to(replacement.parent): + if replacement.is_relative_to(root.resolve()) or root.resolve().is_relative_to(replacement.parent): raise ValueError('更新诊断来源必须位于隔离库与证据目录之外。') replacement_manifest = copy_verified(replacement.parent, root/'source-replacement') staged_replacement = root/'source-replacement'/replacement.name replacement_identity = engineering_identity(staged_replacement) record['update'] = {'stage': 'backup', 'accepted': False, 'source': str(replacement)} record['accepted'] = False - with LibraryLock(library): + with LibraryLock(library, safe_to_release=lambda: owner_safe): copy_verified(library.parent, root/'library-before-update', scope=ManifestScope.library(name, library.name)) request = ManagementRequest('remove', library, name, evidence_dir=root) + owner_safe = False removal = adapter.remove(request, root/'native-remove') + owner_safe = removal.safe_to_continue record['update']['removal'] = asdict(removal) _write_json(root/'probe-result.json', record) if not removal.success or not removal.safe_to_continue: return record - missing = adapter.catalog(library, root/'after-remove') + missing = read_catalog(root/'after-remove') if any(e.name == name for e in missing.entries): record['update']['error'] = '原生移除后条目仍存在' _write_json(root/'probe-result.json', record) return record record['update']['stage'] = 'removed' _write_json(root/'probe-result.json', record) + owner_safe = False readd = adapter._worker({'operation': 'probe_readd', 'library': str(library), 'source': str(staged_replacement), 'name': name, 'top_level_block': replacement_top, 'probe_token': token}, root/'native-readd') + owner_safe = readd.get('safe_to_continue') is True record['update']['readd'] = readd if readd.get('success') and readd.get('safe_to_continue'): - updated = adapter.catalog(library, root/'reopen-update') + updated = read_catalog(root/'reopen-update') record['update']['catalog'] = asdict(updated) entries = [e for e in updated.entries if e.name == name and e.partition == 'Logical-Physical'] record['update']['accepted'] = (len(entries) == 1 @@ -483,7 +539,7 @@ def _catalog_com(job, root): else: if job['operation'] == 'probe_readd': validate_probe_readd(job, root) - library = app.OpenLibrary(str(Path(job['library']).resolve())) + library = app.OpenLibrary(str(absolute_preserving_drive(job['library']))) if refused: raise RuntimeError('目录读取需要升级中心库或选择流程;已拒绝,目标未获准自动升级。') if library is None or Path(str(library.FullName)).resolve() != Path(job['library']).resolve(): @@ -541,6 +597,9 @@ def management_worker_main(request_path): _, desktop = _current_desktop() if desktop != job['desktop'] or not desktop.startswith('CbbManagement_'): raise RuntimeError('原生管理操作仅允许在本次私有桌面执行。') + if job.get('mapped_drive') and job.get('mapped_remote_root'): + from .network_path import ensure_mapped_drive_visible + ensure_mapped_drive_visible(job['mapped_drive'], job['mapped_remote_root']) if job['operation'] in ('catalog', 'probe_create_add', 'probe_readd'): result = _catalog_native(job, root) elif job['operation'] == 'remove': diff --git a/src/cbb_refresh_verify/ui/main_window.py b/src/cbb_refresh_verify/ui/main_window.py index 0e7df00..28bc487 100644 --- a/src/cbb_refresh_verify/ui/main_window.py +++ b/src/cbb_refresh_verify/ui/main_window.py @@ -306,7 +306,9 @@ class MainWindow(QWidget): return def request(name, partition): return ManagementRequest(operation, Path(self.mentor_lmc_path or self.loaded_path), name, - partition, evidence_dir=self.data_root/'management', timeout_seconds=self.timeout_spin.value()) + partition, evidence_dir=self.data_root/'management', timeout_seconds=self.timeout_spin.value(), + mapped_drive=getattr(self.library_lease, 'drive', ''), + mapped_remote_root=getattr(self.library_lease, 'remote_root', '')) requests = ([request('', 'Logical-Physical')] if operation == 'add' else [request(record.name, 'Logical-Physical' if record.logical_type == 'LP' and record.partition_name in ('Reusable Blocks', 'LP') else record.partition_name) diff --git a/tests/test_management.py b/tests/test_management.py index 79adaef..8326d77 100644 --- a/tests/test_management.py +++ b/tests/test_management.py @@ -252,3 +252,52 @@ def test_verify_exception_after_upload_retains_coordination_lock(setup): with pytest.raises(LibraryBusy): with LibraryLock(request.library): pass + + +@pytest.mark.parametrize('nested', [True, False]) +def test_library_inside_source_tree_rejected_before_catalog_or_guard(setup, nested): + request, adapter, source = setup + library = source.parent/('nested/lib.lmc' if nested else 'lib.lmc') + library.parent.mkdir(exist_ok=True) + library.write_bytes(b'library') + adapter.catalog = lambda *a: pytest.fail('overlapping library reached native catalog') + result = execute(replace(request, operation='add', name='New', source=source, library=library), adapter) + assert result.status == 'BLOCKED' and not adapter.calls + assert not library.with_name('.lib.cbb-upload.lock').exists() + assert not request.evidence_dir.exists() + + +def test_mapped_library_spelling_and_context_survive_engine_verify_boundary(setup, monkeypatch): + import shutil + from cbb_refresh_verify.verify_runner import VerifyResult + request, adapter, source = setup + alias_root = request.library.parent + canonical_root = alias_root.with_name('canonical-library') + shutil.copytree(alias_root, canonical_root) + original_resolve = Path.resolve + def resolve(path, *a, **k): + if path.is_relative_to(alias_root): + return original_resolve(canonical_root/path.relative_to(alias_root), *a, **k) + return original_resolve(path, *a, **k) + monkeypatch.setattr(Path, 'resolve', resolve) + catalogs, verified = [], [] + catalog = adapter.catalog + adapter.catalog = lambda library, evidence: (catalogs.append(library) or catalog(library, evidence)) + def verifier(req, **k): + verified.append(req) + return VerifyResult('PASS', library_flag='GREEN') + request = replace(request, operation='add', name='New', source=source, + mapped_drive='S:', mapped_remote_root=r'\\server\share') + result = execute(request, adapter, verifier=verifier) + assert result.status == 'UPLOADED_VERIFIED' + assert catalogs == [request.library, request.library] + assert verified[0].lmc_file == request.library + assert verified[0].mapped_drive == 'S:' and verified[0].mapped_remote_root == r'\\server\share' + + +def test_source_inside_target_library_rejected_before_catalog(setup): + request, adapter, _ = setup + source = request.library.parent/'ReusableBlocksLP/Block/Work/Block.prj' + adapter.catalog = lambda *a: pytest.fail('overlapping source reached native catalog') + result = execute(replace(request, operation='add', name='New', source=source), adapter) + assert result.status == 'BLOCKED' and not request.evidence_dir.exists() diff --git a/tests/test_management_probe_guards.py b/tests/test_management_probe_guards.py new file mode 100644 index 0000000..96cf4a0 --- /dev/null +++ b/tests/test_management_probe_guards.py @@ -0,0 +1,189 @@ +"""Exercise actual guards/snapshots; only the native worker transport is fake.""" +from dataclasses import asdict +import json +from pathlib import Path + +import pytest + + +@pytest.fixture(autouse=True) +def prohibit_native_launch(monkeypatch): + """Backstop independent of the boundary under development: no live apps.""" + import subprocess, win32process, win32com.client + import cbb_refresh_verify.desktop_worker as desktop + def forbidden(*a, **k): + raise AssertionError('Native/process launch is forbidden in probe-guard tests') + monkeypatch.setattr(desktop, 'DesktopWorker', forbidden) + monkeypatch.setattr(win32process, 'CreateProcess', forbidden) + monkeypatch.setattr(subprocess, 'Popen', forbidden) + monkeypatch.setattr(win32com.client, 'Dispatch', forbidden) + monkeypatch.setattr(win32com.client, 'DispatchEx', forbidden) + + +@pytest.fixture +def probe_files(tmp_path): + def source(root, data): + (root/'database').mkdir(parents=True) + (root/'database/icdb.dat').write_bytes(data) + (root/'PCB/Layout').mkdir(parents=True) + (root/'PCB/Layout/LayoutDB.lyt').write_bytes(data) + (root/'PCB/pcb.prj').write_text('KEY CentralLibrary "old.lmc"\n') + (root/'PCB/Block.pcb').write_text('KEY ProjectFile "../Block.prj"\n') + project = root/'Block.prj' + project.write_text('KEY RootBlock "Block"\nKEY iCDBDir "database"\nKEY PCBDesignPath "PCB/Block.pcb"\n') + return project + original = source(tmp_path/'original', b'original') + replacement = source(tmp_path/'replacement', b'replacement') + root = tmp_path/'probe' + yield original, replacement, root + # Only file fakes ran; close this test's deliberately retained OS handle. + import cbb_refresh_verify.library_lock as locks + library = root/'native-add/fixture/mentor_lib.lmc' + with locks._guard: + owner = locks._owners.pop(locks._key(library.with_name('.mentor_lib.cbb-upload.lock')), None) + if owner: + owner['handle'].Close() + + +@pytest.mark.parametrize('fault', ['create_unsafe', 'first_catalog_exception', 'remove_unsafe', + 'remove_exception', 'after_remove_exception', 'readd_unsafe', 'readd_exception', 'final_catalog_exception']) +def test_isolated_probe_retains_guard_on_uncertain_native_lifecycle(probe_files, monkeypatch, fault): + import cbb_refresh_verify.native_management as native + import cbb_refresh_verify.library_lock as locks + from cbb_refresh_verify.management import Capability, CatalogEntry, engineering_identity + original, replacement, root = probe_files + records = [] + monkeypatch.setattr(native.NativeManagementAdapter, 'capabilities', lambda self: + {'remove': Capability(True, 'file transport fixture')}) + def launch(self, job, evidence): + nonlocal records + evidence = Path(evidence) + operation = job['operation'] + library = Path(job['library']) + if operation == 'probe_create_add': + # Directory creation belongs to the real supervising adapter. + assert native.prepare_probe_library(job, evidence) == library + library.write_bytes(b'native-created fixture') + (root/'probe-owner.json').write_text(json.dumps({'library': str(library), 'token': job['probe_token']})) + records = [CatalogEntry(job['name'], 'Logical-Physical', engineering_identity(job['source']))] + if fault == 'create_unsafe': + return {'success': False, 'safe_to_continue': False, 'detail': 'creation owner retained'} + elif operation == 'remove': + if fault == 'remove_exception': + raise TimeoutError('native removal transport disconnected') + if fault == 'remove_unsafe': + return {'success': False, 'safe_to_continue': False, 'detail': 'removal owner retained'} + records = [] + elif operation == 'probe_readd': + if fault == 'readd_exception': + raise TimeoutError('native readd transport disconnected') + if fault == 'readd_unsafe': + return {'success': False, 'safe_to_continue': False, 'detail': 'readd owner retained'} + records = [CatalogEntry(job['name'], 'Logical-Physical', engineering_identity(job['source']))] + elif operation == 'catalog': + stage_fault = {'reopen': 'first_catalog_exception', 'after-remove': 'after_remove_exception', + 'reopen-update': 'final_catalog_exception'}.get(evidence.name) + if stage_fault == fault: + raise TimeoutError('catalog owner release unknown') + return {'success': True, 'safe_to_continue': True, 'library': str(library), 'flow': 1, + 'entries': [asdict(entry) for entry in records], 'detail': 'file fixture result'} + class Worker: + def __init__(self, command, desktop): + request = Path(command[-1]) + job = json.loads(request.read_text(encoding='utf-8')) + result = launch(None, job, request.parent) + (request.parent/'result.json').write_text(json.dumps(result), encoding='utf-8') + def poll(self): return 0 + def close(self): pass + monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker) + try: + native.run_isolated_probe(original, root, 'Block', replacement_source=replacement) + except TimeoutError: + pass + library = root/'native-add/fixture/mentor_lib.lmc' + assert locks.has_blocker(library) + with pytest.raises(locks.LibraryBusy): + with locks.LibraryLock(library): pass + assert (root/'probe-result.json').is_file() + from contextlib import contextmanager + @contextmanager + def denied(*a): + raise locks.LibraryBusy('fresh proof still sees a native owner') + yield + monkeypatch.setattr(locks, '_prove_library_released', denied) + with pytest.raises(locks.LibraryBusy): + locks.release_retained_library(library, root/'release-checks') + assert locks.has_blocker(library) + @contextmanager + def released(*a): + yield {'native_owners': [], 'addresses': [], 'exclusive_files': [str(library)]} + monkeypatch.setattr(locks, '_prove_library_released', released) + assert locks.release_retained_library(library, root/'release-checks')['status'] == 'RELEASE_CONFIRMED' + with locks.LibraryLock(library): pass + + +def test_mapping_context_is_serialized_and_restored_before_catalog(tmp_path, monkeypatch): + import cbb_refresh_verify.native_management as native + import cbb_refresh_verify.network_path as network + captured = [] + class Worker: + def __init__(self, command, desktop): + request = Path(command[-1]) + job = json.loads(request.read_text(encoding='utf-8')) + captured.append(job) + (request.parent/'result.json').write_text(json.dumps({'success': True, 'safe_to_continue': True, + 'library': job['library'], 'flow': 1, 'entries': []}), encoding='utf-8') + def poll(self): return 0 + def close(self): pass + adapter = native.NativeManagementAdapter(worker_factory=Worker) + adapter.bind_library_mapping('S:', r'\\server\share') + library = Path('S:/library/mentor.lmc') + adapter.catalog(library, tmp_path/'catalog') + assert captured[0]['library'] == str(library) + assert captured[0]['mapped_drive'] == 'S:' + order = [] + monkeypatch.setattr(native, '_current_desktop', lambda: (None, captured[0]['desktop'])) + monkeypatch.setattr(network, 'ensure_mapped_drive_visible', lambda drive, remote: + order.append(('mapping', drive, remote))) + monkeypatch.setattr(native, '_catalog_native', lambda job, root: + (order.append(('catalog', job['library'])) or {'success': True, 'safe_to_continue': True})) + assert native.management_worker_main(tmp_path/'catalog/request.json') == 0 + assert order == [('mapping', 'S:', r'\\server\share'), ('catalog', str(library))] + + +def test_removal_cli_keeps_mapped_drive_spelling(tmp_path, monkeypatch): + import cbb_refresh_verify.native_management as native + from cbb_refresh_verify.management import Capability + job = {'operation': 'remove', 'library': 'S:\\library\\mentor.lmc', 'name': 'Block', + 'partition': 'Logical-Physical', 'desktop': 'CbbManagement_fixture', + 'mentor_home': str(tmp_path), 'timeout_seconds': 10} + request = tmp_path/'request.json'; request.write_text(json.dumps(job), encoding='utf-8') + monkeypatch.setattr(native, '_current_desktop', lambda: (None, job['desktop'])) + monkeypatch.setattr(native.NativeManagementAdapter, 'capabilities', lambda self: {'remove': Capability(True, 'fake transport')}) + commands = [] + class Process: + pid = 1234 + def __init__(self, command, *, stdout, **kwargs): + commands.append(command) + stdout.write(b"# Note: Removed REUSE_BLOCK 'Block' from partition 'Logical-Physical'.\n") + stdout.flush() + def wait(self, **kwargs): return 0 + monkeypatch.setattr(native.subprocess, 'Popen', Process) + assert native.management_worker_main(request) == 0 + assert commands[0][1] == job['library'] + + +def test_staged_project_alignment_keeps_selected_mapped_drive(tmp_path, monkeypatch): + from cbb_refresh_verify.backup_recovery import _align_library + project = tmp_path/'Block.prj' + project.write_text('KEY CentralLibrary "old.lmc"\n', encoding='utf-8') + pcb = tmp_path/'PCB/Block.pcb'; pcb.parent.mkdir(); pcb.touch() + pcb_project = pcb.parent/'pcb.prj' + pcb_project.write_text('KEY CentralLibrary "old.lmc"\n', encoding='utf-8') + library = Path('S:/library/mentor.lmc') + original_resolve = Path.resolve + monkeypatch.setattr(Path, 'resolve', lambda path, *a, **k: + Path(r'\\server\share\library\mentor.lmc') if path == library else original_resolve(path, *a, **k)) + _align_library(project, pcb, library) + for path in (project, pcb_project): + assert 'KEY CentralLibrary "S:\\library\\mentor.lmc"' in path.read_text(encoding='utf-8') diff --git a/tests/test_native_management.py b/tests/test_native_management.py index 336a7ce..0597702 100644 --- a/tests/test_native_management.py +++ b/tests/test_native_management.py @@ -78,25 +78,38 @@ def test_probe_cannot_use_existing_fixture_or_mutate_source(tmp_path): def test_probe_requires_owned_new_native_library_path(tmp_path): + import os from cbb_refresh_verify.native_management import prepare_probe_library + from cbb_refresh_verify.library_lock import LibraryLock outside = tmp_path/'production.lmc'; outside.write_bytes(b'unchanged') root = tmp_path/'worker'; root.mkdir() with pytest.raises(ValueError): prepare_probe_library({'library': str(outside)}, root) assert outside.read_bytes() == b'unchanged' owned = root/'fixture/mentor_lib.lmc' - assert prepare_probe_library({'library': str(owned)}, root) == owned - owned.write_bytes(b'first creation') - with pytest.raises(ValueError): - prepare_probe_library({'library': str(owned)}, root) + owned.parent.mkdir() + job = {'library': str(owned), 'probe_token': 'test-token', 'supervisor_pid': os.getpid()} + (root/'probe-prepared.json').write_text(json.dumps({'library': str(owned), 'token': 'test-token', + 'supervisor_pid': os.getpid()}), encoding='utf-8') + with LibraryLock(owned): + assert prepare_probe_library(job, root) == owned + owned.write_bytes(b'first creation') + with pytest.raises(ValueError): + prepare_probe_library(job, root) @pytest.mark.parametrize('records', [[], [('Actual', 'Logical-Physical')]]) -def test_native_catalog_only_uses_com_records_and_checks_exact_process(tmp_path, monkeypatch, records): +@pytest.mark.parametrize('mapped', [False, True]) +def test_native_catalog_only_uses_com_records_and_checks_exact_process(tmp_path, monkeypatch, records, mapped): import cbb_refresh_verify.native_management as native import cbb_refresh_verify.mentor_adapter as mentor import win32com.client library_path = tmp_path/'lib.lmc'; library_path.touch() + if mapped: + original_resolve = Path.resolve + def resolve(path, *a, **k): + return tmp_path/'canonical/lib.lmc' if path == library_path else original_resolve(path, *a, **k) + monkeypatch.setattr(Path, 'resolve', resolve) (tmp_path/'ReusableBlocksLP/Ghost').mkdir(parents=True) class Collection: def __init__(self, items): self.items = items; self.Count = len(items)