feat: read authoritative cell catalogs from owned library clones

This commit is contained in:
阿白叔 committed 2026-10-19 15:06:36 +08:00
1 parent bb506a3550
commit d10356ee3d
4 files changed
+821

No files matched your search

@@ -34,6 +34,7 @@ def _parse_arguments(argv: Sequence[str] | None) -> argparse.Namespace:
parser.add_argument("--data-root", type=Path, help=argparse.SUPPRESS)
parser.add_argument("--native-helper", action="store_true", help=argparse.SUPPRESS)
parser.add_argument("--snapshot", type=Path, help=argparse.SUPPRESS)
parser.add_argument('--cell-catalog-worker', type=Path, help=argparse.SUPPRESS)
parser.add_argument("--sceneos-cli", action="store_true", help=argparse.SUPPRESS)
parser.add_argument('--private-cad-action', choices=('probe', 'quit'), help=argparse.SUPPRESS)
parser.add_argument('--private-cad-evidence', type=Path, help=argparse.SUPPRESS)
@@ -98,6 +99,9 @@ def _flush(context: LoggingContext) -> None:
def main(argv: Sequence[str] | None = None) -> int:
"""Run the Qt shell, returning a conventional process status code."""
arguments = _parse_arguments(argv)
if arguments.cell_catalog_worker is not None:
from dx_productivity.trial_task_center.cell_catalog_worker import run
return run(arguments.cell_catalog_worker)
if arguments.private_cad_action:
if arguments.private_cad_evidence is None or arguments.private_cad_pid is None:
return 2
@@ -0,0 +1,402 @@
"""Authoritative part-to-cell associations, read only from owned library clones."""
from __future__ import annotations
from dataclasses import dataclass
from contextlib import contextmanager
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import sys
import uuid
from .errors import TaskCenterError
@dataclass(frozen=True, slots=True)
class CellChoice:
partition: str
name: str
@dataclass(frozen=True, slots=True)
class CellCatalog:
library_path: Path
part_partition: str
part_number: str
cells: tuple[CellChoice, ...]
source_fingerprint: str
evidence_path: Path
def _fail(message):
raise TaskCenterError('cell_catalog', message)
def _json_bytes(value):
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode('utf-8')
def _write_json(path, value):
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name(path.name + '.' + uuid.uuid4().hex + '.tmp')
temporary.write_bytes(_json_bytes(value))
temporary.replace(path)
def _hash(path):
with path.open('rb') as stream:
return hashlib.file_digest(stream, 'sha256').hexdigest()
def _hidden(path):
return path.name.startswith('.') or bool(getattr(path.stat(), 'st_file_attributes', 0) & 2)
def _library_manifest(library):
"""Complete proven clone recipe: all root metadata and every physical PDB/CEL."""
library = Path(library).resolve()
if library.suffix.lower() != '.lmc' or not library.is_file():
_fail('Central library LMC does not exist')
root = library.parent
paths = [p for p in root.iterdir() if p.is_file() and not _hidden(p)
and p.suffix.lower() not in {'.log', '.idb'}]
for directory, extension in (('PartsDBLibs', '.pdb'), ('CellDBLibs', '.cel')):
folder = root / directory
if not folder.is_dir() or folder.is_symlink():
_fail(f'missing physical dependency directory: {directory}')
members = [p for p in folder.iterdir() if p.is_file() and p.suffix.lower() == extension]
if not members:
_fail(f'missing physical dependency: {directory}/*{extension}')
paths.extend(members)
if not any(p.suffix.lower() == '.cfg' for p in paths) or not any(p.suffix.lower() == '.prp' for p in paths):
_fail('missing library cfg/prp dependency')
# The LMC stores the database locations as NUL-terminated ASCII strings.
# Reject absent references before launching LM (it may otherwise rebuild).
references = re.findall(rb'(?:PartsDBLibs|CellDBLibs)[\\/][^\x00\r\n]+?\.(?:pdb|cel)(?=\x00)', library.read_bytes(), re.I)
included = {p.relative_to(root).as_posix().casefold() for p in paths}
for raw in references:
try:
name = raw.decode('utf-8').replace('\\', '/')
except UnicodeError:
_fail('unreadable physical dependency reference')
if name.casefold() not in included:
_fail(f'missing physical dependency: {name}')
manifest = {}
for path in sorted(paths, key=lambda p: p.relative_to(root).as_posix()):
if path.is_symlink() or getattr(path.lstat(), 'st_file_attributes', 0) & 0x400:
_fail('library dependency cannot be a reparse point')
before = path.stat()
digest = _hash(path)
after = path.stat()
if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
_fail('source library changed while fingerprinting')
manifest[path.relative_to(root).as_posix()] = {'sha256': digest, 'size': after.st_size,
'mtime_ns': after.st_mtime_ns}
return manifest
def _fingerprint(manifest):
return hashlib.sha256(_json_bytes(manifest)).hexdigest()
def _content_fingerprint(manifest):
# LM normally touches the copied cfg timestamp while opening. Source proof
# and prelaunch copy proof include timestamps; post-open proof binds bytes.
return _fingerprint({name: {key: value for key, value in row.items() if key != 'mtime_ns'}
for name, row in manifest.items()})
def _clone_library(library, root, manifest):
destination = root / 'library'
destination.mkdir()
for name in manifest:
target = destination / name
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(library.parent / name, target)
clone = destination / library.name
if _library_manifest(clone) != manifest or _library_manifest(library) != manifest:
_fail('source library changed or clone dependency proof failed')
return clone
def _validated_cells(rows):
if not isinstance(rows, list) or not rows:
_fail('part has no authoritative associated cells')
cells = []
names = {}
for row in rows:
if not isinstance(row, dict) or not isinstance(row.get('partition'), str) or not row['partition'] or not isinstance(row.get('name'), str) or not row['name']:
_fail('invalid associated cell record')
cell = CellChoice(row['partition'], row['name'])
if cell.name in names:
_fail(f'ambiguous or duplicate associated cell: {cell.name}')
names[cell.name] = cell.partition
cells.append(cell)
return tuple(cells)
def _catalog_from_evidence(evidence, library, part, partition, fingerprint, path):
if (evidence.get('schema') != 1 or evidence.get('library_path') != str(library)
or evidence.get('part_number') != part or evidence.get('requested_partition') != partition
or evidence.get('source_fingerprint') != fingerprint or not evidence.get('source_unchanged')):
_fail('catalog evidence binding is invalid')
result = evidence['result']
if not result.get('verified') or not result.get('quit_verified') or result.get('part_number') != part or not result.get('part_partition'):
_fail('catalog worker did not verify the requested part')
_require_cleanup(result.get('cleanup'))
if partition is not None and result['part_partition'] != partition:
_fail('catalog partition binding changed')
return CellCatalog(library, result['part_partition'], part, _validated_cells(result['cells']), fingerprint, path)
def _require_cleanup(cleanup):
if not isinstance(cleanup, dict) or cleanup.get('errors') or not cleanup.get('desktop_handle_closed') or not cleanup.get('desktop_confirmation', {}).get('released'):
_fail('catalog private desktop cleanup was not proven')
if not cleanup.get('processes'):
_fail('catalog owned process cleanup is missing')
for process in cleanup['processes']:
if process.get('errors') or process.get('job_active_processes') != 0 or not process.get('process_handle_closed') or not process.get('job_handle_closed') or process.get('unconfirmed_descendant_handles', 0):
_fail('catalog owned Job process cleanup was not proven')
def _dispose_clone(root):
target = root / 'library'
# Resolve and verify the exact owned path before recursive removal.
if target.is_symlink() or target.is_junction() or target.resolve() != root.resolve() / 'library':
_fail('catalog clone cleanup path ownership changed')
if target.exists():
shutil.rmtree(target)
_write_json(root / 'clone-cleanup.json', {'path': str(target), 'removed': not target.exists()})
def read_library_cell_catalog(library_path: Path, part_number: str, evidence_root: Path, *, partition: str | None = None) -> CellCatalog:
library = Path(library_path).resolve()
if not isinstance(part_number, str) or not part_number.strip() or (partition is not None and not partition):
_fail('part number and optional partition must be nonempty')
evidence_root = Path(evidence_root).resolve()
if evidence_root == library.parent or library.parent in evidence_root.parents:
_fail('catalog evidence must be outside the source library')
manifest = _library_manifest(library)
fingerprint = _fingerprint(manifest)
key = hashlib.sha256(_json_bytes([str(library), fingerprint, part_number, partition])).hexdigest()
cache_path = evidence_root / 'cache' / (key + '.json')
if cache_path.is_file():
try:
cache = json.loads(cache_path.read_text(encoding='utf-8'))
path = evidence_root / cache['evidence']
path.resolve().relative_to(evidence_root)
if _hash(path) != cache['sha256']:
raise ValueError('evidence digest changed')
value = _catalog_from_evidence(json.loads(path.read_text(encoding='utf-8')), library, part_number, partition, fingerprint, path)
except (ValueError, KeyError, OSError, TypeError):
pass # Re-read through an owned clone; never return damaged proof.
else:
if _library_manifest(library) != manifest:
_fail('source library changed during cache validation')
return value
root = evidence_root / 'reads' / uuid.uuid4().hex
root.mkdir(parents=True)
evidence_path = root / 'catalog.json'
reader_started = False
try:
clone = _clone_library(library, root, manifest)
_write_json(root / 'source-before.json', manifest)
reader_started = True
try:
result = _run_isolated_reader(clone, part_number, partition, root)
finally:
after = _library_manifest(library)
_write_json(root / 'source-after.json', after)
_write_json(root / 'source-hashes.json', {'before': fingerprint, 'after': _fingerprint(after), 'unchanged': after == manifest})
if after != manifest:
_fail('source library changed during catalog read')
if result.get('library') != str(clone):
_fail('catalog worker library identity differs from owned clone')
evidence = {'schema': 1, 'library_path': str(library), 'part_number': part_number,
'requested_partition': partition, 'source_fingerprint': fingerprint,
'source_unchanged': True, 'source_manifest': manifest, 'result': result}
value = _catalog_from_evidence(evidence, library, part_number, partition, fingerprint, evidence_path)
_dispose_clone(root)
_write_json(evidence_path, evidence)
_write_json(cache_path, {'evidence': evidence_path.relative_to(evidence_root).as_posix(), 'sha256': _hash(evidence_path)})
return value
except Exception as error:
_write_json(root / 'failure.json', {'error': str(error)})
cleanup_path = root / 'desktop-cleanup.json'
if not reader_started:
_dispose_clone(root)
elif cleanup_path.is_file():
_require_cleanup(json.loads(cleanup_path.read_text(encoding='utf-8')))
_dispose_clone(root)
raise
def project_library_path(project: Path) -> Path:
project = Path(project).resolve()
try:
data = project.read_bytes()
text = data.decode('utf-8-sig')
except UnicodeError:
text = data.decode('mbcs' if os.name == 'nt' else 'cp1252')
rows = [line for line in text.splitlines() if re.match(r'^\s*KEY\s+CentralLibrary(?:\s|$)', line, re.I)]
if len(rows) != 1:
_fail('project must define exactly one KEY CentralLibrary')
match = re.fullmatch(r'\s*KEY\s+CentralLibrary\s+"([^"\x00]+)"\s*', rows[0], re.I)
if match is None or not match[1].strip():
_fail('project KEY CentralLibrary must contain one quoted path')
path = Path(match[1].replace('\\', os.sep))
return (path if path.is_absolute() else project.parent / path).resolve()
def read_project_cell_choices(project_paths: tuple[Path, ...], part_number: str, evidence_root: Path) -> tuple[str, ...]:
if not project_paths:
_fail('no project libraries are available for verification')
choices = None
for library in dict.fromkeys(project_library_path(project) for project in project_paths):
catalog = read_library_cell_catalog(library, part_number, evidence_root)
names = {cell.name for cell in _validated_cells([{'partition': c.partition, 'name': c.name} for c in catalog.cells])}
choices = names if choices is None else choices & names
if not choices:
_fail('project libraries have no common associated cell')
return tuple(sorted(choices))
def _worker_command(request):
if getattr(sys, 'frozen', False):
return (sys.executable, '--cell-catalog-worker', str(request))
return (sys.executable, '-m', 'dx_productivity.trial_task_center.cell_catalog_worker', str(request))
def _library_manager_executable():
# Registered COM executable is the installed version; never start via COM
# activation, which could reuse a user-owned Library Manager session.
import winreg
command = None
for view in (winreg.KEY_WOW64_32KEY, winreg.KEY_WOW64_64KEY):
try:
with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, 'LibraryManager.Application\\CLSID', 0, winreg.KEY_READ | view) as key:
clsid = winreg.QueryValue(key, None)
with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, f'CLSID\\{clsid}\\LocalServer32', 0, winreg.KEY_READ | view) as key:
command = winreg.QueryValue(key, None).strip()
break
except OSError:
continue
if command is None:
_fail('installed Library Manager registration is unavailable')
match = re.match(r'^"([^"]+\.exe)"', command, re.I) or re.match(r'^(.+?\.exe)(?:\s|$)', command, re.I)
if match is None or not Path(match[1]).is_file():
_fail('installed Library Manager executable is unavailable')
return Path(match[1]).resolve()
def _existing_library_manager_pids():
"""Toolhelp enumerates image names without attaching to COM or user windows."""
import ctypes
from ctypes import wintypes
class Entry(ctypes.Structure):
_fields_ = [('dwSize', wintypes.DWORD), ('cntUsage', wintypes.DWORD), ('th32ProcessID', wintypes.DWORD),
('th32DefaultHeapID', ctypes.c_size_t), ('th32ModuleID', wintypes.DWORD),
('cntThreads', wintypes.DWORD), ('th32ParentProcessID', wintypes.DWORD),
('pcPriClassBase', wintypes.LONG), ('dwFlags', wintypes.DWORD),
('szExeFile', wintypes.WCHAR * 260)]
kernel = ctypes.WinDLL('kernel32', use_last_error=True)
kernel.CreateToolhelp32Snapshot.argtypes = [wintypes.DWORD, wintypes.DWORD]
kernel.CreateToolhelp32Snapshot.restype = wintypes.HANDLE
kernel.Process32FirstW.argtypes = kernel.Process32NextW.argtypes = [wintypes.HANDLE, ctypes.POINTER(Entry)]
kernel.CloseHandle.argtypes = [wintypes.HANDLE]
handle = kernel.CreateToolhelp32Snapshot(2, 0)
if handle == ctypes.c_void_p(-1).value:
raise ctypes.WinError(ctypes.get_last_error())
try:
entry = Entry()
entry.dwSize = ctypes.sizeof(entry)
pids = []
available = kernel.Process32FirstW(handle, ctypes.byref(entry))
if not available:
raise ctypes.WinError(ctypes.get_last_error())
while available:
if entry.szExeFile.casefold() == 'librarymanager.exe':
pids.append(entry.th32ProcessID)
available = kernel.Process32NextW(handle, ctypes.byref(entry))
if ctypes.get_last_error() != 18: # ERROR_NO_MORE_FILES
raise ctypes.WinError(ctypes.get_last_error())
return pids
finally:
kernel.CloseHandle(handle)
def _require_no_existing_manager():
if _existing_library_manager_pids():
_fail('existing unowned Library Manager prevents an isolated catalog read')
@contextmanager
def _catalog_launch_lock():
import win32event
mutex = win32event.CreateMutex(None, False, 'Local\\DxPartReplace-CellCatalog-LibraryManager-v1')
acquired = False
try:
result = win32event.WaitForSingleObject(mutex, 120_000)
if result not in (0, 0x80):
_fail('isolated catalog launch lock timed out')
acquired = True
yield
finally:
if acquired:
win32event.ReleaseMutex(mutex)
mutex.Close()
def _run_isolated_reader(clone, part, partition, root):
with _catalog_launch_lock():
_require_no_existing_manager()
return _run_owned_reader(clone, part, partition, root)
def _run_owned_reader(clone, part, partition, root):
from .isolated_desktop import PrivateDesktop
from .legacy_paths import _AliasPool, _fits, _short_path
exe = _library_manager_executable()
desktop = PrivateDesktop('dx-cell-' + uuid.uuid4().hex, enabled=True)
aliases = _AliasPool()
report_path = root / 'worker-result.json'
clone_fingerprint = _content_fingerprint(_library_manifest(clone))
try:
access = clone
if not _fits(clone.parent):
short = _short_path(clone.parent)
access = (Path(short) if short and _fits(short) else aliases.alias(clone.parent)) / clone.name
if access.resolve(strict=True) != clone:
_fail('cloned library access path does not match owned clone')
with desktop:
environment = dict(os.environ, SDD_HOME=str(exe.parents[3]))
# Keep LM's working directory outside the library, as in the
# validated probe; its title may otherwise show only a basename.
manager = desktop.start_process((str(exe), str(access)), cwd=root, env=environment)
request_path = root / 'worker-request.json'
_write_json(request_path, {'desktop': desktop.name, 'pid': manager.pid, 'library': str(clone),
'part_number': part, 'partition': partition, 'report': str(report_path),
'clone_content_fingerprint': clone_fingerprint, 'library_access': str(access)})
if not getattr(sys, 'frozen', False):
source_root = str(Path(__file__).resolve().parents[2])
environment['PYTHONPATH'] = source_root + os.pathsep + environment.get('PYTHONPATH', '')
with (root / 'stdout.txt').open('wb') as stdout, (root / 'stderr.txt').open('wb') as stderr:
process = desktop.start_process(_worker_command(request_path), cwd=root, env=environment,
stdout=stdout, stderr=stderr)
code = process.wait(timeout=90)
if code != 0:
detail = json.loads(report_path.read_text(encoding='utf-8')) if report_path.is_file() else {}
_fail('isolated catalog worker failed: ' + str(detail.get('error', code)))
result = json.loads(report_path.read_text(encoding='utf-8'))
finally:
_write_json(root / 'desktop-cleanup.json', desktop.cleanup_record)
alias_errors = aliases.close()
_write_json(root / 'alias-cleanup.json', {'errors': [str(error) for error in alias_errors]})
if alias_errors:
_fail('catalog access alias cleanup failed')
cleanup = desktop.cleanup_record
_require_cleanup(cleanup)
return result | {'cleanup': cleanup}
@@ -0,0 +1,176 @@
"""Hidden Library Manager reader; always launched on its owned private desktop."""
from __future__ import annotations
import json
import os
from pathlib import Path
import sys
import time
import traceback
from .cell_catalog import _content_fingerprint, _fail, _library_manifest, _validated_cells, _write_json
def _current_desktop():
from .cad_identity import current_desktop_name
return current_desktop_name()
def _windows():
import win32gui
import win32process
windows = []
def collect(handle, _):
children = []
if win32gui.GetClassName(handle) == '#32770':
win32gui.EnumChildWindows(handle, lambda child, unused: children.append(win32gui.GetWindowText(child)[:512])
if win32gui.GetWindowText(child) and len(children) < 20 else None, None)
windows.append({'handle': handle, 'pid': win32process.GetWindowThreadProcessId(handle)[1],
'title': win32gui.GetWindowText(handle), 'class': win32gui.GetClassName(handle),
'title_length': len(win32gui.GetWindowText(handle)), 'dialog_text': children})
win32gui.EnumWindows(collect, None)
return windows
def _verify_owned_window(request, windows):
if not request['desktop'].startswith('dx-cell-') or _current_desktop() != request['desktop']:
_fail('catalog worker is not on its owned private desktop')
owned = [window for window in windows if window['pid'] == request['pid']]
if any(window['class'] == '#32770' for window in owned):
_fail('Library Manager opened a migration or rebuild dialog')
matches = []
for window in owned:
if not window['class'].startswith('Afx:') or not window['title'].startswith('Library Manager: '):
continue
expected = 'Library Manager: ' + request['library']
# Installed LM truncates its native caption at 159 characters. This
# identifies only the owned main window; COM FullName must still match
# the entire canonical clone path before any association read or Quit.
if len(window['title']) == 159 and len(expected) > 159 and os.path.normcase(expected).startswith(os.path.normcase(window['title'])):
matches.append(window)
continue
try:
title_path = Path(window['title'][len('Library Manager: '):])
if not title_path.is_absolute():
title_path = Path(request['library']).parent / title_path
if title_path.resolve(strict=True) == Path(request['library']).resolve(strict=True):
matches.append(window)
except OSError:
continue
if len(matches) != 1:
return False
return True
def _verify_app(app, request):
if not _verify_owned_window(request, _windows()):
_fail('owned Library Manager PID/title identity was lost')
library = app.ActiveLibrary
if library is None or Path(str(library.FullName)).resolve(strict=True) != Path(request['library']).resolve(strict=True):
_fail('Library Manager ActiveLibrary differs from owned clone')
return library
def _physical(root, directory, name, suffix):
names = [path.stem for path in (root / directory).iterdir() if path.is_file() and path.suffix.lower() == suffix]
if sum(stem.casefold() == name.casefold() for stem in names) != 1:
_fail(f'missing or ambiguous physical dependency: {directory}/{name}{suffix}')
def _read_associations(library, part_number, selected_partition, root):
cells = library.Partitions(3)
cell_partitions = []
for index in range(1, int(cells.Count) + 1):
name = str(cells.Item(index).Name)
_physical(root, 'CellDBLibs', name, '.cel')
cell_partitions.append(name)
parts = library.Partitions(1)
found = []
for index in range(1, int(parts.Count) + 1):
partition = parts.Item(index)
name = str(partition.Name)
_physical(root, 'PartsDBLibs', name, '.pdb')
if selected_partition is not None and name != selected_partition:
continue
for position in range(1, int(partition.Count) + 1):
part = partition.Item(position)
if str(part.Name) != part_number:
continue
associated = part.AssociatedCells
rows = []
for cell_index in range(1, int(associated.Count) + 1):
cell = associated.Item(cell_index)
row = {'name': str(cell.Name), 'partition': str(cell.PartitionName)}
if row['partition'] not in cell_partitions:
_fail('associated cell partition has no physical dependency')
rows.append(row)
found.append({'part_partition': name, 'cells': rows})
if len(found) != 1:
_fail('part number is missing or ambiguous across library partitions')
_validated_cells(found[0]['cells'])
return found[0] | {'part_number': part_number, 'cell_partitions': cell_partitions,
'part_partition_count': int(parts.Count)}
def _verify_clone_content(clone, expected):
if _content_fingerprint(_library_manifest(clone)) != expected:
_fail('clone dependency content changed during library read')
def run(request_path: Path) -> int:
request = json.loads(Path(request_path).read_text(encoding='utf-8'))
report = {'verified': False, 'phase': 'startup', 'window_snapshots': []}
app = None
initialized = False
try:
if not request['desktop'].startswith('dx-cell-') or _current_desktop() != request['desktop']:
_fail('catalog worker desktop identity mismatch')
import pythoncom
import win32com.client
pythoncom.CoInitialize()
initialized = True
deadline = time.monotonic() + 50
while time.monotonic() < deadline:
windows = [window for window in _windows() if window['pid'] == request['pid']]
if not report['window_snapshots'] or report['window_snapshots'][-1] != windows:
report['window_snapshots'] = (report['window_snapshots'] + [windows])[-10:]
if _verify_owned_window(request, windows):
try:
candidate = win32com.client.GetActiveObject('LibraryManager.Application')
except pythoncom.com_error as error:
report['last_com_error'] = str(error)
time.sleep(.1)
continue
library = _verify_app(candidate, request)
app = candidate
break
time.sleep(.1)
else:
_fail('owned cloned library startup timed out')
clone = Path(request['library'])
_verify_clone_content(clone, request['clone_content_fingerprint'])
_verify_app(app, request)
report['phase'] = 'associations'
result = _read_associations(library, request['part_number'], request['partition'], clone.parent)
_verify_app(app, request)
_verify_clone_content(clone, request['clone_content_fingerprint'])
report.update(result, library=str(clone), desktop=request['desktop'], pid=request['pid'], verified=True, phase='complete')
except Exception as error:
report.update(error=str(error), traceback=traceback.format_exc())
finally:
if app is not None:
try:
_verify_app(app, request)
app.Quit()
report['quit_verified'] = True
except Exception as error:
report.update(verified=False, error='owned Library Manager close failed: ' + str(error))
if initialized:
app = None
pythoncom.CoUninitialize()
_write_json(Path(request['report']), report)
return 0 if report.get('verified') and report.get('quit_verified') else 1
if __name__ == '__main__':
raise SystemExit(run(Path(sys.argv[1])))
+239
View File
@@ -0,0 +1,239 @@
from pathlib import Path
from types import SimpleNamespace
import json
import os
import pytest
from dx_productivity.trial_task_center import cell_catalog as catalog
from dx_productivity.trial_task_center import cell_catalog_worker as worker
@pytest.fixture
def library(tmp_path):
root = tmp_path / 'source'
root.mkdir()
files = {'lib.lmc': b'PartsDBLibs\\RES.pdb\0CellDBLibs\\RES.cel\0',
'lib.cfg': b'config', 'CentLib.prp': b'properties',
'upgrade.bin': b'upgrade', 'CLibv38.upd': b'',
'PartsDBLibs/RES.pdb': b'parts', 'CellDBLibs/RES.cel': b'cells'}
for name, data in files.items():
path = root / name
path.parent.mkdir(exist_ok=True)
path.write_bytes(data)
return root / 'lib.lmc'
def proof(clone, part, partition, root):
return {'verified': True, 'library': str(clone), 'part_number': part,
'part_partition': partition or 'RES',
'cells': [{'partition': 'RES', 'name': 'RESC1005N_0402'}], 'quit_verified': True,
'cleanup': {'errors': [], 'desktop_handle_closed': True,
'desktop_confirmation': {'released': True},
'processes': [{'errors': [], 'job_active_processes': 0,
'process_handle_closed': True, 'job_handle_closed': True}]}}
@pytest.fixture
def reader(monkeypatch):
calls = []
def run(clone, part, partition, root):
calls.append(clone)
source = clone.parents[4] / 'source'
# Inspect the clone before its required disposal, not after return.
for path in source.rglob('*'):
if path.is_file():
copied = clone.parent / path.relative_to(source)
assert copied.read_bytes() == path.read_bytes()
assert copied.stat().st_mtime_ns == path.stat().st_mtime_ns
return proof(clone, part, partition, root)
monkeypatch.setattr(catalog, '_run_isolated_reader', run)
return calls
def test_complete_clone_preserves_metadata_and_cache_rechecks_source(library, tmp_path, reader):
root = tmp_path / 'evidence'
first = catalog.read_library_cell_catalog(library, 'PN', root)
clone = reader[0]
assert first.cells == (catalog.CellChoice('RES', 'RESC1005N_0402'),)
assert first.library_path == library.resolve()
assert first.evidence_path.is_file()
assert not clone.parent.exists()
assert catalog.read_library_cell_catalog(library, 'PN', root) == first
assert len(reader) == 1
(library.parent / 'CellDBLibs/RES.cel').write_bytes(b'changed')
changed = catalog.read_library_cell_catalog(library, 'PN', root)
assert changed.source_fingerprint != first.source_fingerprint
assert len(reader) == 2
def test_missing_physical_dependency_fails_before_process(library, tmp_path, reader):
(library.parent / 'CellDBLibs/RES.cel').unlink()
with pytest.raises(ValueError, match='dependency'):
catalog.read_library_cell_catalog(library, 'PN', tmp_path / 'out')
assert not reader
def test_source_mutation_during_worker_cannot_publish_cache(library, tmp_path, monkeypatch):
def mutate(clone, part, partition, root):
(library.parent / 'CentLib.prp').write_bytes(b'changed')
return proof(clone, part, partition, root)
monkeypatch.setattr(catalog, '_run_isolated_reader', mutate)
with pytest.raises(ValueError, match='changed'):
catalog.read_library_cell_catalog(library, 'PN', tmp_path / 'out')
assert not list((tmp_path / 'out').glob('cache/*.json'))
def test_tampered_cache_evidence_is_rejected(library, tmp_path, reader):
first = catalog.read_library_cell_catalog(library, 'PN', tmp_path / 'out')
first.evidence_path.write_text('{}')
second = catalog.read_library_cell_catalog(library, 'PN', tmp_path / 'out')
assert len(reader) == 2
assert second.evidence_path != first.evidence_path
@pytest.mark.parametrize('cells', [[], [{'partition':'A','name':'same'}, {'partition':'B','name':'same'}]])
def test_zero_or_ambiguous_cells_are_not_authoritative(library, tmp_path, monkeypatch, cells):
def run(clone, part, partition, root):
return dict(proof(clone, part, partition, root), cells=cells)
monkeypatch.setattr(catalog, '_run_isolated_reader', run)
with pytest.raises(ValueError, match='associated|ambiguous'):
catalog.read_library_cell_catalog(library, 'PN', tmp_path / 'out')
class Collection:
def __init__(self, items):
self.items = items
self.Count = len(items)
def Item(self, index):
assert type(index) is int, 'COM string lookup silently returns None'
return self.items[index - 1]
def fake_library(parts):
return SimpleNamespace(Partitions=lambda kind: Collection(parts if kind == 1 else [SimpleNamespace(Name='RES')]))
def part_partition(name, parts):
collection = Collection(parts)
collection.Name = name
return collection
def part(name, cells=None):
return SimpleNamespace(Name=name, AssociatedCells=Collection(cells or [SimpleNamespace(Name='CELL', PartitionName='RES')]))
def test_numeric_enumeration_matches_exact_part_name_and_rejects_duplicate_partitions(library):
lib = fake_library([part_partition('RES', [part('PN-prefix'), part('PN')])])
assert worker._read_associations(lib, 'PN', None, library.parent)['part_partition'] == 'RES'
lib = fake_library([part_partition('RES', [part('PN')]), part_partition('OTHER', [part('PN')])])
(library.parent / 'PartsDBLibs/OTHER.pdb').write_bytes(b'other')
with pytest.raises(ValueError, match='ambiguous'):
worker._read_associations(lib, 'PN', None, library.parent)
assert worker._read_associations(lib, 'PN', 'RES', library.parent)['cells'][0]['name'] == 'CELL'
def test_com_partition_requires_exact_physical_database(library):
(library.parent / 'PartsDBLibs/RES.pdb').rename(library.parent / 'PartsDBLibs/RES-other.pdb')
with pytest.raises(ValueError, match='dependency'):
worker._read_associations(fake_library([part_partition('RES', [part('PN')])]), 'PN', None, library.parent)
@pytest.mark.parametrize('text', ['', 'KEY CentralLibrary "a.lmc"\nKEY CentralLibrary "b.lmc"', 'KEY CentralLibrary ""', 'KEY CentralLibrary broken value'])
def test_project_library_config_is_strict(tmp_path, text):
project = tmp_path / 'a.prj'
project.write_text(text)
with pytest.raises(ValueError, match='CentralLibrary'):
catalog.project_library_path(project)
def test_project_relative_library_and_candidate_intersection(tmp_path, monkeypatch):
projects = []
for index in range(2):
project = tmp_path / f'{index}.prj'
project.write_text(f'KEY CentralLibrary "lib{index}/lib.lmc"')
projects.append(project)
assert catalog.project_library_path(projects[0]) == (tmp_path / 'lib0/lib.lmc').resolve()
def read(path, pn, root):
names = ('CELL', 'OTHER') if path.parent.name == 'lib0' else ('CELL',)
return catalog.CellCatalog(path, 'RES', pn, tuple(catalog.CellChoice('RES', n) for n in names), 'fingerprint', root)
monkeypatch.setattr(catalog, 'read_library_cell_catalog', read)
assert catalog.read_project_cell_choices(tuple(projects), 'PN', tmp_path) == ('CELL',)
def test_hidden_worker_dispatch_and_frozen_command(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import application
request = tmp_path / 'request.json'
monkeypatch.setattr(worker, 'run', lambda path: 17 if path == request else 2)
assert application.main(['--cell-catalog-worker', str(request)]) == 17
monkeypatch.setattr(catalog.sys, 'frozen', True, raising=False)
assert catalog._worker_command(request) == (catalog.sys.executable, '--cell-catalog-worker', str(request))
def test_unowned_or_dialog_window_rejects_before_com_read(monkeypatch, tmp_path):
request = {'desktop': 'dx-cell-test', 'pid': 123, 'library': str(tmp_path/'lib.lmc')}
monkeypatch.setattr(worker, '_current_desktop', lambda: 'Default')
with pytest.raises(ValueError, match='desktop'):
worker._verify_owned_window(request, [])
monkeypatch.setattr(worker, '_current_desktop', lambda: 'dx-cell-test')
with pytest.raises(ValueError, match='dialog'):
worker._verify_owned_window(request, [{'pid':123,'handle':1,'class':'#32770','title':'Migration'}])
def test_existing_library_manager_blocks_owned_launch(monkeypatch, tmp_path):
monkeypatch.setattr(catalog, '_existing_library_manager_pids', lambda: [777])
with pytest.raises(ValueError, match='existing.*Library Manager'):
catalog._require_no_existing_manager()
def test_unproven_cleanup_is_not_cached(library, tmp_path, monkeypatch):
def run(clone, part, partition, root):
result = proof(clone, part, partition, root)
result['cleanup']['processes'][0]['job_active_processes'] = 1
return result
monkeypatch.setattr(catalog, '_run_isolated_reader', run)
with pytest.raises(ValueError, match='cleanup'):
catalog.read_library_cell_catalog(library, 'PN', tmp_path / 'out')
def test_missing_com_cell_partition_dependency_blocks_partial_associations(library):
lib = SimpleNamespace(Partitions=lambda kind: Collection(
[part_partition('RES', [part('PN')])] if kind == 1 else
[SimpleNamespace(Name='RES'), SimpleNamespace(Name='MISSING')]))
with pytest.raises(ValueError, match='dependency'):
worker._read_associations(lib, 'PN', None, library.parent)
def test_owned_title_can_use_library_basename_for_library_working_directory(library, monkeypatch):
request = {'desktop':'dx-cell-test', 'pid':123, 'library':str(library)}
monkeypatch.setattr(worker, '_current_desktop', lambda: 'dx-cell-test')
windows = [{'pid':123, 'handle':1, 'class':'Afx:main', 'title':'Library Manager: lib.lmc'}]
assert worker._verify_owned_window(request, windows)
windows[0]['title'] = 'Library Manager: other.lmc'
assert not worker._verify_owned_window(request, windows)
def test_clone_allows_normal_cfg_timestamp_touch_but_rejects_content_migration(library):
expected = catalog._content_fingerprint(catalog._library_manifest(library))
cfg = library.with_suffix('.cfg')
info = cfg.stat()
os.utime(cfg, ns=(info.st_atime_ns, info.st_mtime_ns + 1_000_000_000))
worker._verify_clone_content(library, expected)
(library.parent / 'CellDBLibs/RES.cel').write_bytes(b'migrated')
with pytest.raises(ValueError, match='content'):
worker._verify_clone_content(library, expected)
def test_owned_title_truncation_still_requires_exact_com_library(library, monkeypatch):
request = {'desktop':'dx-cell-test', 'pid':123, 'library':str(library)}
monkeypatch.setattr(worker, '_current_desktop', lambda: 'dx-cell-test')
title = ('Library Manager: ' + str(library))[:159]
windows = [{'pid':123, 'handle':1, 'class':'Afx:main', 'title':title}]
monkeypatch.setattr(worker, '_windows', lambda: windows)
assert worker._verify_owned_window(request, windows)
other = library.with_suffix('.cfg')
with pytest.raises(ValueError, match='differs'):
worker._verify_app(SimpleNamespace(ActiveLibrary=SimpleNamespace(FullName=str(other))), request)
expected = SimpleNamespace(FullName=str(library))
assert worker._verify_app(SimpleNamespace(ActiveLibrary=expected), request) is expected