Compare commits

..
Author SHA1 Message Date
阿白叔 86837155ea fix: preserve catalog state and verify PCB write access 2026-11-20 23:24:47 +08:00
11 changed files with 651 additions and 92 deletions

No files matched your search

+29 -22
View File
@@ -172,12 +172,13 @@ class BatchCheckpoint:
)
return cls(records)
def append(self, path: Path, record: BatchStatusRecord) -> None:
checkpoint = Path(path)
checkpoint.parent.mkdir(parents=True, exist_ok=True)
with checkpoint.open("a", encoding="utf-8", newline="\n") as handle:
handle.write(json.dumps(record.to_json(), ensure_ascii=False, separators=(",", ":")) + "\n")
handle.flush()
def append(self, path: Path | None, record: BatchStatusRecord) -> None:
if path is not None:
checkpoint = Path(path)
checkpoint.parent.mkdir(parents=True, exist_ok=True)
with checkpoint.open("a", encoding="utf-8", newline="\n") as handle:
handle.write(json.dumps(record.to_json(), ensure_ascii=False, separators=(",", ":")) + "\n")
handle.flush()
self.records[record.block_name] = record
@@ -200,16 +201,20 @@ class BatchStatusSession:
self.rotate_every = max(1, int(rotate_every))
self.restart_count = 0
def scan(self, names: Iterable[str], lmc_file: Path, checkpoint_path: Path,
def scan(self, names: Iterable[str], lmc_file: Path, checkpoint_path: Path | None,
*, block_type: str = "RULP", resume: bool = False) -> list[BatchStatusRecord]:
fingerprint = fingerprint_library(Path(lmc_file))
if resume:
checkpoint = BatchCheckpoint.load(checkpoint_path)
else:
checkpoint = BatchCheckpoint()
checkpoint_file = Path(checkpoint_path)
checkpoint_file.parent.mkdir(parents=True, exist_ok=True)
checkpoint_file.write_text('', encoding='utf-8')
from .operation_queue import check_active
check_active()
fingerprint = fingerprint_library(Path(lmc_file)).sha256 if checkpoint_path is not None else ''
checkpoint = BatchCheckpoint()
if checkpoint_path is not None:
if resume:
checkpoint = BatchCheckpoint.load(checkpoint_path)
else:
checkpoint_file = Path(checkpoint_path)
checkpoint_file.parent.mkdir(parents=True, exist_ok=True)
checkpoint_file.write_text('', encoding='utf-8')
results: list[BatchStatusRecord] = []
names = tuple(str(name) for name in names)
server = self.bridge if all(callable(getattr(self.bridge, method, None))
@@ -219,9 +224,10 @@ class BatchStatusSession:
try:
queried = 0
for index, name in enumerate(names):
check_active()
previous = checkpoint.get(name)
if (previous and previous.status in {'READY', 'PENDING'}
and previous.fingerprint == fingerprint.sha256 and previous.block_type == block_type):
and previous.fingerprint == fingerprint and previous.block_type == block_type):
results.append(previous)
continue
try:
@@ -232,12 +238,12 @@ class BatchStatusSession:
record = BatchStatusRecord(
block_name=name, status=result.status, source=result.source,
raw_status=result.raw_status, detail=result.detail,
fingerprint=fingerprint.sha256, timestamp=_now(),
fingerprint=fingerprint, timestamp=_now(),
block_type=block_type,
)
except BridgeUnavailable as error:
record = BatchStatusRecord(block_name=name, status="UNAVAILABLE",
detail=str(error), fingerprint=fingerprint.sha256,
detail=str(error), fingerprint=fingerprint,
timestamp=_now(), block_type=block_type)
except BridgeResponseError as error:
message = str(error)
@@ -252,7 +258,7 @@ class BatchStatusSession:
else "UNAVAILABLE" if unavailable
else "MALFORMED" if malformed else "ERROR")
record = BatchStatusRecord(block_name=name, status=status, detail=message,
fingerprint=fingerprint.sha256, timestamp=_now(), block_type=block_type)
fingerprint=fingerprint, timestamp=_now(), block_type=block_type)
if server is not None and status != "UNAVAILABLE":
try:
server.restart()
@@ -260,12 +266,13 @@ class BatchStatusSession:
pass
except Exception as error: # bridge failures isolate one CBB
record = BatchStatusRecord(block_name=name, status="ERROR", detail=str(error),
fingerprint=fingerprint.sha256, timestamp=_now(), block_type=block_type)
fingerprint=fingerprint, timestamp=_now(), block_type=block_type)
if server is not None:
try:
server.restart()
except BridgeUnavailable:
pass
check_active()
checkpoint.append(checkpoint_path, record)
results.append(record)
if record.status == "UNAVAILABLE" and index + 1 < len(names):
@@ -276,7 +283,7 @@ class BatchStatusSession:
for remaining in names[index + 1:]:
unavailable_record = BatchStatusRecord(
block_name=remaining, status=record.status, detail=record.detail,
fingerprint=fingerprint.sha256, timestamp=_now(),
fingerprint=fingerprint, timestamp=_now(),
block_type=block_type,
)
checkpoint.append(checkpoint_path, unavailable_record)
@@ -291,7 +298,7 @@ class BatchStatusSession:
return results
def authoritative_status_map(names: Iterable[str], lmc_file: Path, checkpoint_path: Path,
def authoritative_status_map(names: Iterable[str], lmc_file: Path, checkpoint_path: Path | None = None,
*, bridge_path: Path | None = None,
timeout_seconds: float = 10.0) -> dict[str, str]:
"""Return only bridge-backed statuses for an optional UI integration.
+51 -1
View File
@@ -99,6 +99,42 @@ def _database_log_declined(root, pcb_pid):
return False
def _read_write_declined(job, root, pcb_pid):
from .dialog_models import WindowSnapshot
from .session_record import IDENTITY_KEYS
choice_path = root/'pcb-open-user-choice.json'
dialogs_path = root/'dialogs.jsonl'
try:
if (choice_path.stat().st_size > 1024*1024 or dialogs_path.stat().st_size > 1024*1024
or not job.get('operation_id') or (root/'save.log').exists()):
return False
choice = json.loads(choice_path.read_text(encoding='utf-8'))
binding = {key: job[key] for key in ('operation_id', 'desktop', 'project', 'pcb')}
if (any(choice.get(key) != value for key, value in binding.items())
or choice.get('library') != job['lmc_file'] or choice.get('choice') not in ('skip', 'cancel')):
return False
owner = choice['owner']['target']
if (owner.get('pid') != pcb_pid or not owner.get('owner_sid')
or any(owner.get(key) is None for key in IDENTITY_KEYS)):
return False
original = choice['snapshot']
snapshot = WindowSnapshot.from_record(original)
target = _cancel_target(snapshot)
if snapshot.pid != pcb_pid or target is None or target[0] != 'read_write_access':
return False
expected = 'PCB_OPEN_SKIPPED' if choice['choice'] == 'skip' else 'USER_CANCELLED'
for line in dialogs_path.read_text(encoding='utf-8').splitlines():
record = json.loads(line)
if (record.get('action') == 'user_confirmed_pcb_open' and record.get('accepted_control') == [7]
and record.get('error_code') == expected
and all(record.get(key) == value for key, value in original.items())):
return owner
except (OSError, ValueError, TypeError, KeyError, AttributeError):
pass
return False
def cancelled_prewrite_startup(job, pcb_pid=None):
"""Positive ordinary pre-document cancellation proof; absence of Save is insufficient."""
from .session_record import IDENTITY_KEYS, read_session_record
@@ -188,6 +224,7 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
declined_hwnd = None
declined_kind = None
cancelled_open = _database_log_declined(root, pcb_pid)
decline_owner = None
dismissed_tips = set()
close_handle = None
close_identity = None
@@ -200,8 +237,19 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
or residual_sessions._handle_identity(close_handle) != close_identity
or win32process.GetWindowThreadProcessId(hwnd)[1] != pcb_pid):
raise ValueError('STARTUP_ACTION_UNCONFIRMED')
if decline_owner:
actual = {'pid': pcb_pid, **close_identity,
**residual_sessions._force_ownership(close_handle, pcb_pid)}
if any(actual.get(key) != value for key, value in decline_owner.items()):
raise ValueError('STARTUP_ACTION_UNCONFIRMED: 原进程身份变化')
win32gui.PostMessage(hwnd, message, 0, 0)
while True:
# PCB can dismiss the prompt before the supervisor records its action.
if not cancelled_open:
decline_owner = _read_write_declined(job, root, pcb_pid)
if decline_owner:
cancelled_open = True
result['cancelled_prompt'] = 'read_write_access'
records = [r for r in _process_details('ExpeditionPCB.exe') if r[0] == pcb_pid]
if not records:
if (close_handle is not None
@@ -219,6 +267,8 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
result['release'] = {'pcb_exited': True, 'launcher_exited': launcher_exited,
'addresses': addresses,
'safe_to_continue': launcher_exited and (cancelled_open or not addresses)}
if addresses:
result['release']['resource_release_confirmed'] = False
if result['release']['safe_to_continue']:
result['status'] = 'CLOSED'
result.pop('detail', None)
@@ -354,7 +404,7 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
close_identity = residual_sessions._handle_identity(close_handle)
if Path(close_identity['image']).name.casefold() != 'expeditionpcb.exe':
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
if cancelled_diagnostic or cancelled_prewrite:
if cancelled_diagnostic or cancelled_prewrite or decline_owner:
cleanup_post(main[0],win32con.WM_CLOSE)
else:
win32gui.PostMessage(main[0], win32con.WM_CLOSE, 0, 0)
+12 -5
View File
@@ -245,13 +245,17 @@ class NativeManagementAdapter:
if hasattr(worker, 'bind_session'):
worker.bind_session(job)
from contextlib import nullcontext
from .operation_queue import commit_worker_start, native_channel
from .operation_queue import commit_worker_start, native_channel, task_stop
# Only admitted native waiting outlives the UI's metadata deadline.
channel = native_channel(read_only=True) if job.get('worker_role') == 'catalog_readonly' else nullcontext()
read_only = job.get('worker_role') == 'catalog_readonly'
channel = native_channel(read_only=True) if read_only else nullcontext()
stop = task_stop(self.stop) if read_only else self.stop
cancelled = False
with channel:
commit_worker_start(worker, job)
while worker.poll() is None and time.monotonic() < deadline:
if self.stop is not None and self.stop.is_set():
if stop is not None and stop.is_set():
cancelled = True
Path(job['cancel_signal']).touch()
break
time.sleep(.1)
@@ -268,8 +272,9 @@ class NativeManagementAdapter:
if self.session_progress is not None else None)
if add_job:
(evidence/'cancel-native-add.signal').touch()
reason = 'CANCELLED' if cancelled else 'TIMEOUT'
return {'success': False, 'safe_to_continue': False,
'detail': f'TIMEOUT: 原生调用尚未返回,保留私有桌面 {desktop},请检查 {evidence}'}
'detail': f'{reason}: 原生调用尚未返回,保留私有桌面 {desktop},请检查 {evidence}'}
try:
result = json.loads((evidence/'result.json').read_text(encoding='utf-8'))
if not isinstance(result.get('safe_to_continue'), bool):
@@ -1117,7 +1122,7 @@ def _catalog_com(job, root):
if name != job['desktop'] or not name.startswith('CbbManagement_'):
raise RuntimeError('拒绝在非本次私有桌面读取原生目录。')
if _process_details('LibraryManager.exe'):
raise RuntimeError('已有 Library Manager 运行,请关闭后重试。')
raise RuntimeError('LIBRARY_MANAGER_BUSY: 已有 Library Manager 运行,请关闭后重试。')
except Exception as error:
error.safe_to_continue = True
raise
@@ -1217,6 +1222,8 @@ def _catalog_com(job, root):
for i in range(1, int(parts.Count) + 1):
partition = parts.Item(i)
for j in range(1, int(partition.Count) + 1):
if job.get('worker_role') == 'catalog_readonly':
_require_management_continuation(job, root)
item = partition.Item(j)
block_name, partition_name = str(item.Name), str(item.PartitionName)
validate_name(block_name)
+91 -35
View File
@@ -1,6 +1,7 @@
"""Explicit user answers to the owned PCB's exact read/write question."""
"""Bound authorization for the owned PCB's exact read/write question."""
from contextlib import contextmanager, ExitStack
from pathlib import Path
from pathlib import Path, PureWindowsPath
import re
from threading import Lock
import time
@@ -15,8 +16,9 @@ def _prompt_identity(snapshot):
class OpenChoice:
def __init__(self, block, library):
def __init__(self, block, library, *, auto_confirm=False):
self.block, self.library = block, library
self.auto_confirm = auto_confirm
self.decision = None
self.decision_origin = None
self._lock = Lock()
@@ -26,8 +28,8 @@ class OpenChoice:
raise ValueError('无效的打开工程选择')
with self._lock:
if self.decision is None:
self.decision = decision
self.decision_origin = origin
self.decision = decision
def validate_owner(job, target_pid, launcher_pid, worker_pid):
@@ -47,14 +49,14 @@ def validate_owner(job, target_pid, launcher_pid, worker_pid):
@contextmanager
def resource_guard(job, allowed_pids):
def resource_guard(job, allowed_pids, *, require_complete_proof=False):
import hashlib
from .file_probe import hold_release_files
from .maintenance_entry import maintenance_project_files
from .native_repair import RepairTarget, run_native_repair
from .native_occupancy import confirmed_inspection
from .session_record import IDENTITY_KEYS
from .operation_queue import task_stop
from .operation_queue import check_active, task_stop
from .management import _write_json
from .owner_probe import query_process_snapshot
from .library_lock import _owner_is_blocking
@@ -72,15 +74,43 @@ def resource_guard(job, allowed_pids):
for row in query_process_snapshot():
if row['pid'] not in allowed_pids and _owner_is_blocking(row, library, roots):
raise ValueError(f'目标还有其他会话,PID={row["pid"]};未确认读写打开。')
check_active()
check()
stop = task_stop(None)
with ExitStack() as stack:
files = stack.enter_context(hold_release_files(library, roots, stop=stop))
inspections = []
if require_complete_proof:
from .backup_recovery import _project_text
references = re.findall(r'^KEY ProjectFile "([^"]+)"', _project_text(pcb), re.M)
if len(references) != 1 or (pcb.parent/references[0]).resolve() != project.resolve():
raise ValueError(f'PCB_OPEN_PROJECT_CHANGED: PCB 未唯一关联当前工程:{pcb}')
required_files = {library.resolve(), (pcb.parent/'Layout/LayoutDB.lyt').resolve()}
for config in configs:
text = _project_text(config)
references = re.findall(r'^KEY iCDBDir\b.*$', text, re.M)
if not references and config != project:
continue
reference = re.fullmatch(r'KEY iCDBDir "([^"]+)"\s*', references[0]) if len(references) == 1 else None
if reference is None or PureWindowsPath(reference[1]).anchor:
raise ValueError(f'PCB_OPEN_DATABASE_UNCONFIRMED: iCDBDir 必须唯一且为相对路径:{config}')
database = (config.parent/reference[1]).resolve()
if not database.is_relative_to(project.parent.resolve()):
raise ValueError(f'PCB_OPEN_DATABASE_UNCONFIRMED: iCDBDir 越出工程:{database}')
required_files.add(database/'icdb.dat')
shared = library.parent/'SymbolLibs/__ReusableBlocksSymb'
if shared.exists():
required_files.add((shared/'icdb.dat').resolve())
missing = required_files - {Path(path).resolve() for path in files['exclusive_files']}
if missing:
raise ValueError('PCB_OPEN_DATABASE_UNCONFIRMED: 缺少文件占用证明:'
+ '、'.join(str(path) for path in sorted(missing)))
if files['addresses']:
targets = files['inspection_targets']
if any(Path(item['project']).resolve() not in {p.resolve() for p in configs} for item in targets):
raise ValueError('PCB_OPEN_DATABASE_UNCONFIRMED: 地址未绑定实际工程配置,需人工核对')
for item in targets:
if Path(item['project']).resolve() not in {p.resolve() for p in configs}:
raise ValueError(f"PCB_OPEN_DATABASE_UNCONFIRMED: 地址未绑定实际工程配置:{item['database']}")
stack.close() # Native inspection must access the DB; repeat exact proof afterwards.
for index, item in enumerate(targets):
target = RepairTarget(Path(item['project']), Path(item['database']))
@@ -88,11 +118,15 @@ def resource_guard(job, allowed_pids):
result = run_native_repair(target, evidence, mentor_bin=job.get('mentor_bin'),
timeout_seconds=min(45, float(job.get('timeout', 45))), inspection_only=True, stop=stop)
identity = result.get('native_identity') or {}
if (not confirmed_inspection(target, result) or result['status'] != 'NOT_IN_USE'
if (not confirmed_inspection(target, result)
or identity.get('pid') != result.get('native_pid')
or any(identity.get(key) is None for key in IDENTITY_KEYS)
or not identity.get('image') or not identity.get('owner_sid')):
raise ValueError('PCB_OPEN_DATABASE_UNCONFIRMED: 原生检查未确认当前数据库未占用')
raise ValueError(f'PCB_OPEN_DATABASE_UNCONFIRMED: 原生占用检查无法确认:{target.database}')
if result['status'] == 'IN_USE':
raise ValueError(f'PCB_OPEN_DATABASE_IN_USE: 原生检查确认数据库占用:{target.database}')
if require_complete_proof and result['repair_required']:
raise ValueError(f'PCB_OPEN_DATABASE_UNCONFIRMED: 原生检查提示需要维护:{target.database}')
inspections.append(result)
current = stack.enter_context(hold_release_files(library, roots, stop=stop))
if any(current[key] != files[key] for key in (
@@ -101,6 +135,7 @@ def resource_guard(job, allowed_pids):
if binding() != original_binding:
raise ValueError('PCB_OPEN_PROJECT_CHANGED: 原生检查期间工程引用变化')
check()
check_active()
_write_json(Path(job['root'])/'pcb-open-resource-proof.json', {
'operation_id': job.get('operation_id'), 'library': str(library),
'project': str(project), 'pcb': str(pcb), 'binding': original_binding,
@@ -110,8 +145,9 @@ def resource_guard(job, allowed_pids):
class OpenController:
def __init__(self, job):
def __init__(self, job, *, auto_confirm=False):
self.job = job
self.auto_confirm = auto_confirm
self.choice = None
self.original = self.owner = None
self.sent = False
@@ -120,13 +156,15 @@ class OpenController:
def handle(self, snapshot, snapshots, *, target_pid, launcher_pid, worker_pid, show, perform):
from .dialog_supervisor import DialogPollResult
from .management import _write_json
from .operation_queue import QueueCancelled, check_active
try:
if not exact_prompt(snapshot) or snapshot.pid != target_pid or len(snapshots) != 1:
raise ValueError('PCB_OPEN_PROMPT_CHANGED')
owner = validate_owner(self.job, target_pid, launcher_pid, worker_pid)
if self.choice is None:
self.owner, self.original = owner, snapshot
self.choice = OpenChoice(self.job['block_name'], self.job['lmc_file'])
self.choice = OpenChoice(self.job['block_name'], self.job['lmc_file'],
auto_confirm=self.auto_confirm)
show(self.choice)
if (owner != self.owner or snapshot.hwnd != self.original.hwnd
or _prompt_identity(snapshot) != _prompt_identity(self.original)):
@@ -137,36 +175,54 @@ class OpenController:
raise ValueError('PCB_OPEN_ANSWER_NOT_COMPLETED')
if self.choice.decision is None:
return DialogPollResult(activity=True, observed_snapshots=tuple(snapshots))
control = 6 if self.choice.decision == 'continue' else 7
action = {'action': 'user_confirmed_pcb_open', 'channels': ['win32_button_click'],
'target': {'control_id': control}, 'desktop': self.job['desktop'],
'pid': target_pid, 'owner': owner, 'choice': self.choice.decision}
action['decision_origin'] = self.choice.decision_origin
def send():
_write_json(Path(self.job['root'])/'pcb-open-user-choice.json', dict(
choice=self.choice.decision, decision_origin=self.choice.decision_origin,
project=self.job['project'], pcb=self.job['pcb'],
library=self.job['lmc_file'], owner=owner, snapshot=snapshot.to_record()))
self.sent, self.sent_at = True, time.monotonic()
return perform(snapshot, action, snapshot.phase)
if control == 6:
decision = self.choice.decision
origin = self.choice.decision_origin
skipped_detail = ('超时默认跳过本项。' if origin == 'timeout_default' else '用户跳过本项。')
if decision == 'continue':
allowed = {target_pid, launcher_pid, worker_pid, self.job.get('supervisor_pid')}
with resource_guard(self.job, allowed):
pass
# Deliberate TOCTOU tradeoff: release probes before Yes so Mentor
# can acquire the files without a sharing violation; recheck identity.
try:
guard = (resource_guard(self.job, allowed, require_complete_proof=True) if self.auto_confirm
else resource_guard(self.job, allowed))
with guard:
pass
# Mentor needs the handles released before Yes. Recheck the
# owner here and the actual window in the private agent.
check_active()
except QueueCancelled:
decision, skipped_detail = 'cancel', '校验已取消。'
except Exception as error:
if not self.auto_confirm:
raise
decision, skipped_detail = 'skip', str(error)
if validate_owner(self.job, target_pid, launcher_pid, worker_pid) != owner:
raise ValueError('PCB_OPEN_IDENTITY_CHANGED')
result = send()
else:
result = send()
if decision == 'continue':
try:
check_active()
except QueueCancelled:
decision, skipped_detail = 'cancel', '校验已取消。'
control = 6 if decision == 'continue' else 7
action = {'action': 'user_confirmed_pcb_open', 'channels': ['win32_button_click'],
'target': {'control_id': control}, 'desktop': self.job['desktop'],
'pid': target_pid, 'owner': owner, 'choice': decision, 'decision_origin': origin}
_write_json(Path(self.job['root'])/'pcb-open-user-choice.json', dict(
choice=decision, decision_origin=origin, detail=skipped_detail if control == 7 else '',
operation_id=self.job.get('operation_id'), desktop=self.job['desktop'],
project=self.job['project'], pcb=self.job['pcb'],
library=self.job['lmc_file'], owner=owner, snapshot=snapshot.to_record()))
if control == 6:
try:
check_active()
except QueueCancelled:
return DialogPollResult(error_code='USER_CANCELLED', detail='校验已取消。',
snapshot=snapshot, observed_snapshots=tuple(snapshots))
self.sent, self.sent_at = True, time.monotonic()
result = perform(snapshot, action, snapshot.phase)
error = result.error_code
if not error and result.accepted_controls != (control,):
error = 'PCB_OPEN_ANSWER_FAILED'
if not error and control == 7:
error = 'PCB_OPEN_SKIPPED' if self.choice.decision == 'skip' else 'USER_CANCELLED'
skipped_detail = ('超时默认跳过本项。' if self.choice.decision_origin == 'timeout_default'
else '用户跳过本项。')
error = 'PCB_OPEN_SKIPPED' if decision == 'skip' else 'USER_CANCELLED'
return DialogPollResult(activity=True, action_sent=True, snapshot=snapshot,
error_code=error, detail=result.detail or (skipped_detail if control == 7 else ''),
accepted_controls=result.accepted_controls, channel=result.channel,
+116 -23
View File
@@ -123,6 +123,7 @@ class MainWindow(QWidget):
self._dialogs = []
self._current_job = None
self._stale_table = False
self._table_library_path = None
self._read_counts = (None, None, None)
self._diagnostic_evidence = {}
self.pool = QThreadPool(self); self.pool.setMaxThreadCount(8)
@@ -154,8 +155,7 @@ class MainWindow(QWidget):
self.busy = False; self.loaded_path = None; self.stop = Event(); self.ready_names = set()
self._row_by_name = {}
self._records_by_name = {}
self.status_refresher = status_refresher or (lambda names, path: authoritative_status_map(
names, path, self.data_root / 'status-refresh.jsonl'))
self.status_refresher = status_refresher or authoritative_status_map
self.skipped_names = set(); self.skip_reasons = {}
self._global_icdb_run = False
self._icdb_completed = 0
@@ -349,6 +349,7 @@ class MainWindow(QWidget):
self._update()
def _invalidate(self):
self._cancel_catalog_read()
if self._current_job is not None and self._current_job.kind == 'read':
self._current_job.context.close(timeout_seconds=0)
self._view_revision += 1
@@ -1035,7 +1036,8 @@ class MainWindow(QWidget):
if isinstance(error, TaskHandoff) and job.lease is not None:
self._retain_path_lease(job.lease)
if not self._job_current(job): return
if isinstance(error, QueueCancelled): self._display_error(error)
if isinstance(error, QueueCancelled):
self._display_error('已取消读取中心库。' if job.kind == 'read' else error)
else: self._failed(error)
self.worker.signals.failed.connect(failed)
self.worker.signals.finished.connect(lambda: (self._lifecycle_workers.discard(worker), self._finish_job(job)))
@@ -1253,10 +1255,17 @@ class MainWindow(QWidget):
self._bind_summary_action(summary, action, recover)
summary.show(); self._update()
def _cancel_catalog_read(self):
for job in self._jobs.values():
if job.kind == 'catalog':
job.context.cancel()
self.native_queue.wake()
def load_library(self):
if self._closing or not self.lmc_edit.text(): return
if (self._current_job is not None and self._current_job.kind == 'read'
and self._current_job.active and self._current_job.revision == self._view_revision): return
self._cancel_catalog_read()
self._view_revision += 1
self._diagnostic_evidence.clear()
self._stale_table = bool(self._records_by_name)
@@ -1275,6 +1284,7 @@ class MainWindow(QWidget):
self._release_library_lease()
self.loaded_path = None
path = self.lmc_edit.text()
preserve = self._table_library_path == path and self._read_counts[1] is not None
self.status_label.setText('正在读取中心库…')
def read():
import pythoncom
@@ -1296,9 +1306,6 @@ class MainWindow(QWidget):
recovery_view = False
result = self.reader(mentor_path)
job.context.check_active()
if not result.error:
self._publish_check_statuses(mentor_path,
{record.name: record.status for record in result.records}, lease)
if self.logging_context:
statuses = Counter(record.status for record in result.records)
unknown = [record.name for record in result.records if record.status in {'UNKNOWN', 'UNAVAILABLE'}]
@@ -1323,15 +1330,24 @@ class MainWindow(QWidget):
if path != self.lmc_edit.text() or job.revision != self._view_revision:
self._close_path_lease(lease)
return
if result.error:
if result.error or (job.active and job.context.stop.is_set()):
self._close_path_lease(lease)
self.status_label.setText(result.error); return
self.status_label.setText(result.error or '已取消读取中心库。')
return
self.library_lease = lease
self.mentor_lmc_path = mentor_path
if preserve and self.catalog_reader is not None and not result.catalog_verified:
self._start_catalog(job, result, lease, mentor_path, loaded)
return
if result.catalog_verified or self.catalog_reader is None:
self._publish_check_statuses(mentor_path,
{record.name: record.status for record in result.records
if record.catalog_source != 'directory_only'}, lease)
self._stale_table = False
self._table_library_path = path
self._read_counts = (result.directory_count, result.native_count,
result.missing_project_count if result.missing_project_count is not None else len(skip_reasons))
self._maintenance_recovery_view = recovery_view
self.mentor_lmc_path = mentor_path
self.loaded_path = path
try:
if self._settings_enabled:
@@ -1412,18 +1428,41 @@ class MainWindow(QWidget):
job = SimpleNamespace(context=context, kind='catalog', revision=read_job.revision,
lease=lease, requests=(), records={}, active=True, keep_session=False)
self._jobs[context.operation_id] = job
def reconcile():
catalog = self.catalog_reader(Path(library), self.data_root/'catalog'/context.operation_id)
root = self.data_root/'catalog'/context.operation_id
checkpoint = root/'status-refresh.pending.jsonl' if self.status_refresher is authoritative_status_map else None
started = time.monotonic()
def phase(stage, detail):
if self.logging_context:
self.logging_context.logger.info('%s library=%s elapsed_ms=%d detail=%s', stage,
library, int((time.monotonic()-started)*1000), detail)
try:
self.signals.event.emit((read_job.revision, read_job, {
'stage': stage, 'detail': detail, 'library': str(library),
'catalog_id': context.operation_id,
}))
except RuntimeError:
pass # A closed Qt receiver cannot change the scan outcome.
def reconcile(evidence):
phase('catalog_start', '正在读取 Mentor 原生目录…')
catalog = self.catalog_reader(Path(library), evidence)
if _path_key(catalog.library) != _path_key(library) or not catalog.safe_to_continue or catalog.flow != 1:
raise ValueError('CATALOG_UNCONFIRMED: 原生目录身份或退出未确认。')
native = {entry.name: entry for entry in catalog.entries if entry.partition == 'Logical-Physical'}
directories = {record.name: record for record in initial.records}
names = tuple(sorted(native.keys() | directories.keys()))
try:
context.check_active()
phase('catalog_status', f'正在核对 {len(native)} 项原生状态…')
if checkpoint is None:
statuses = self.status_refresher(tuple(native), Path(library))
except Exception:
statuses = {name:'UNAVAILABLE' for name in native}
self._publish_check_statuses(library, statuses, lease)
else:
statuses = self.status_refresher(tuple(native), Path(library), checkpoint)
if native and (not native.keys() <= statuses.keys()
or any(statuses[name] == 'UNAVAILABLE' for name in native)
or not any(statuses[name] in {'READY', 'PENDING'} for name in native)):
raise ValueError('原生状态读取未确认,请重新读取中心库。')
context.check_active()
records, reasons = [], {}
for name in names:
source = ('both' if name in native and name in directories else
@@ -1440,15 +1479,63 @@ class MainWindow(QWidget):
result = LibraryReadResult(tuple(records), directory_count=len(directories), native_count=len(native),
missing_project_count=sum(name in native for name in reasons), catalog_verified=True)
return result, reasons, lease, library, False
# Full-library status and preflight follow native catalog IO; ten seconds
# is not enough even on a local 364-entry library. Keep one bounded task.
worker = ServiceWorker(lambda:self.native_queue.run(reconcile, context=context, timeout_seconds=120, skip_unavailable=True))
def attempt(evidence):
return self.native_queue.run(lambda: reconcile(evidence), context=context,
timeout_seconds=120, skip_unavailable=True)
def scan():
from cbb_refresh_verify.native_management import NativeOperationError
from cbb_refresh_verify.owner_probe import query_owners
try:
return attempt(root)
except NativeOperationError as error:
if not error.safe_to_continue or not str(error).startswith('LIBRARY_MANAGER_BUSY:'):
raise
phase('catalog_waiting', 'Library Manager 正在使用,退出后将自动重试读取。')
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
context.check_active()
owners = query_owners(('LibraryManager.exe',), timeout_seconds=2)
context.check_active()
if not owners:
return attempt(root/'retry')
context.stop.wait(1)
context.check_active()
raise
self.status_label.setText('正在读取 Mentor 原生目录…')
worker = ServiceWorker(scan)
self._lifecycle_workers.add(worker)
def completed(payload):
if self._job_current(read_job): deliver(payload)
def failed(error):
if self._job_current(read_job):
self.status_label.setText(f'目录已显示;原生目录未确认:{error}')
from cbb_refresh_verify.native_management import NativeOperationError
if isinstance(error, TaskHandoff) or (isinstance(error, NativeOperationError)
and not error.safe_to_continue):
self._retain_path_lease(lease)
if not self._job_current(read_job):
return
cancelled = context.stop.is_set() or isinstance(error, QueueCancelled)
detail = '已取消读取中心库。' if cancelled else f'原生目录未确认,请重新读取:{error}'
phase('catalog_cancelled' if cancelled else 'catalog_failed', detail)
self.status_label.setText(detail)
def completed(payload):
if not self._job_current(read_job):
return
if context.stop.is_set():
failed(QueueCancelled('读取已取消'))
return
try:
if checkpoint is not None:
checkpoint.replace(self.data_root/'status-refresh.jsonl')
except OSError as error:
failed(error)
return
deliver(payload)
phase('catalog_done', f'已读取 {len(payload[0].records)} 项。')
worker.signals.succeeded.connect(completed)
worker.signals.failed.connect(failed)
worker.signals.finished.connect(lambda:(self._lifecycle_workers.discard(worker),self._finish_job(job)))
@@ -1751,7 +1838,8 @@ class MainWindow(QWidget):
def action():
from cbb_refresh_verify.verify_runner import read_library_flag_if_available, run_verify
verify = self.verifier or (lambda req: run_verify(
req, progress=lambda e: self._emit_job(job, 'event', e),
replace(req, auto_confirm_pcb_open=not maintenance),
progress=lambda e: self._emit_job(job, 'event', e),
flag_reader=read_library_flag_if_available,
version_prompt=lambda choice: self._emit_job(job, 'version_choice', choice), stop=job.context.stop))
def verifier(req):
@@ -1900,6 +1988,11 @@ class MainWindow(QWidget):
from shiboken6 import isValid
if not isValid(self) or not isValid(self.cbb_table):
return
if event.get('stage') in {'catalog_start', 'catalog_status', 'catalog_waiting'}:
catalog_job = self._jobs.get(event.get('catalog_id'))
if catalog_job is None or catalog_job.context.stop.is_set():
return
self.status_label.setText(event['detail'])
if event.get('stage') == 'waiting_native_slot':
self.status_label.setText(event.get('detail', '已排队,等待执行'))
self._queue_waiting(event)
+7 -5
View File
@@ -8,17 +8,19 @@ class PcbOpenDialog(QMessageBox):
self.choice = choice
self.setWindowTitle('确认打开 PCB 工程')
self.setIcon(QMessageBox.Question)
advice = ('程序将检查工程和共享库占用,再决定是否继续。' if choice.auto_confirm else
'请确认没有其他用户打开此工程,再选择继续以读写权限打开。')
self.setText(f'CBB:{choice.block}\n中心库:{choice.library}\n\n'
'PCB 提示上次可能未正常关闭,或工程仍被其他用户打开。\n'
'请确认没有其他用户打开此工程,再选择继续以读写权限打开。')
self.continue_button = self.addButton('确认无人使用,继续打开', QMessageBox.ActionRole)
'PCB 提示上次可能未正常关闭,或工程仍被其他用户打开。\n'
+ advice)
self.continue_button = self.addButton(
'检查占用后继续' if choice.auto_confirm else '确认无人使用,继续打开', QMessageBox.ActionRole)
self.skip_button = self.addButton('跳过本项', QMessageBox.ActionRole)
self.cancel_button = self.addButton('取消本批次', QMessageBox.RejectRole)
self.setDefaultButton(self.skip_button)
self.setEscapeButton(self.cancel_button)
self.setModal(True)
self.buttonClicked.connect(lambda b: choice.choose('continue' if b is self.continue_button else
'skip' if b is self.skip_button else 'cancel',
origin=self.property('selectionOrigin') or 'user'))
self.finished.connect(lambda _: choice.choose('cancel'))
arm_default(self, self.skip_button)
arm_default(self, self.continue_button if choice.auto_confirm else self.skip_button)
+4 -1
View File
@@ -83,6 +83,7 @@ class VerifyRequest:
maintenance: bool = False
post_repair_proof: object | None = field(default=None, repr=False, compare=False)
diagnostic_only: bool = False
auto_confirm_pcb_open: bool = False
@dataclass(frozen=True)
@@ -1212,7 +1213,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
from .pcb_open_consent import OpenController, exact_prompt
if exact_prompt(dialog_result.snapshot):
if open_controller is None:
open_controller = OpenController(job)
open_controller = OpenController(job, auto_confirm=(
request.auto_confirm_pcb_open and not request.maintenance))
dialog_result = open_controller.handle(dialog_result.snapshot, dialog_result.observed_snapshots,
target_pid=target_pid, launcher_pid=launcher_pid, worker_pid=process.pid,
show=version_prompt, perform=dialog_supervisor.backend.perform)
@@ -1270,6 +1272,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
'CANCELLED' if dialog_result.error_code == 'USER_CANCELLED' else
'SKIPPED' if dialog_result.error_code == 'PCB_OPEN_SKIPPED' else 'FAIL',
stderr=f'{dialog_result.error_code}: {dialog_result.detail}',
error_category='PCB_OPEN_SKIPPED' if dialog_result.error_code == 'PCB_OPEN_SKIPPED' else '',
error_stage=phase.value,
safe_to_continue=False,
))
+53
View File
@@ -371,3 +371,56 @@ def test_only_exact_empty_zero_area_childless_ie_infrastructure_is_benign(tmp_pa
entry = result['benign_auxiliary_windows'][0]
assert entry['class'] == 'Internet Explorer_Hidden' and entry['rect'] == [0, 0, 0, 0]
assert entry['children'] == []
@pytest.mark.parametrize('receipt', ['matching', 'late', 'different_operation', 'different_identity'])
def test_supervisor_no_lets_own_empty_pcb_close_with_address_remaining(tmp_path, monkeypatch, receipt):
import win32con
job, records, messages, _, visible = read_write_fixture(tmp_path, monkeypatch)
job['operation_id'] = 'verify-owned'
address = tmp_path/'database/cdbsvr/sAddress.adr'
address.parent.mkdir(parents=True)
address.write_text('existing address')
snapshot = failed_session._startup_snapshot(200, 12).to_record()
from cbb_refresh_verify import residual_sessions
monkeypatch.setattr(residual_sessions, '_force_ownership', lambda *_: {
'owner_sid': 'S-1-5-21-test', 'session_id': 1})
owner = {'pid': 12, 'owner_sid': 'S-1-5-21-test', 'session_id': 1,
'image': records[0][1], 'created_handle': 'reused' if receipt == 'different_identity' else 'original'}
(tmp_path/'pcb-open-user-choice.json').write_text(json.dumps(dict(
operation_id='another-operation' if receipt == 'different_operation' else job['operation_id'],
desktop=job['desktop'], project=job['project'], pcb=job['pcb'],
library=job['lmc_file'], choice='skip', snapshot=snapshot, owner={'target': owner})))
visible.remove(200)
def record_acknowledgement():
(tmp_path/'dialogs.jsonl').write_text(json.dumps(dict(
snapshot, action='user_confirmed_pcb_open', error_code='PCB_OPEN_SKIPPED',
accepted_control=[7]))+'\n')
if receipt == 'late':
from types import SimpleNamespace
elapsed = 0.0
def advance(seconds):
nonlocal elapsed
elapsed += seconds
if elapsed < 0.3:
record_acknowledgement()
monkeypatch.setattr(failed_session, 'time',
SimpleNamespace(monotonic=lambda: elapsed, sleep=advance))
else:
record_acknowledgement()
result = failed_session.close_failed_startup(
job, 12, timeout_seconds=0 if receipt == 'different_operation' else 1)
if receipt in {'different_operation', 'different_identity'}:
assert result['status'] == 'RETAINED' and records and not messages
return
assert result['status'] == 'CLOSED'
assert result['cancelled_prompt'] == 'read_write_access'
assert result['release']['addresses'] == [str(address)]
assert result['release']['resource_release_confirmed'] is False
assert messages == [(100, win32con.WM_CLOSE)]
assert not records and address.is_file()
+99
View File
@@ -649,3 +649,102 @@ def test_recovery_retry_rejects_old_external_progress_and_choice(qtbot,tmp_path,
assert choice.decision=='cancel'
finally:
release.set(); qtbot.waitUntil(lambda:not dialog.busy)
@pytest.mark.parametrize('cancel', [True, False])
def test_uncommitted_catalog_refresh_preserves_last_full_result(qtbot, tmp_path, monkeypatch, cancel):
from cbb_refresh_verify.management import Catalog, CatalogEntry
from cbb_refresh_verify.ui import main_window as ui
reading, release = Event(), Event()
calls = []
snapshot = tmp_path/'status-refresh.jsonl'
def read_status(names, path, checkpoint_path=None):
calls.append(names)
if checkpoint_path is not None:
checkpoint_path.parent.mkdir(parents=True, exist_ok=True)
checkpoint_path.write_text('full scan' if len(calls) == 1 else 'partial scan', encoding='utf-8')
if len(calls) == 2:
reading.set()
release.wait(5)
return {name: 'READY' for name in names}
monkeypatch.setattr(ui, 'authoritative_status_map', read_status)
window = window_for(qtbot, tmp_path, monkeypatch,
reader=lambda _: LibraryReadResult((CbbRecord('A', 'LP'),), directory_count=1),
catalog_reader=lambda path, _: Catalog(path, 1, (CatalogEntry('A', 'Logical-Physical'),)))
try:
load(window, qtbot)
qtbot.waitUntil(lambda: window.ready_names == {'A'})
reports = []
monkeypatch.setattr(window, '_publish_check_statuses',
lambda library, statuses, lease: reports.append(dict(statuses)))
original_replace = Path.replace
def replace_file(path, target):
if target == snapshot:
raise PermissionError('snapshot is held')
return original_replace(path, target)
if not cancel:
monkeypatch.setattr(Path, 'replace', replace_file)
window.load_button.click()
qtbot.waitUntil(reading.is_set)
assert window.ready_names == {'A'}
assert not window.batch_button.isEnabled()
assert snapshot.read_text(encoding='utf-8') == 'full scan'
if cancel:
window.stop_button.click()
release.set()
qtbot.waitUntil(lambda: not any(job.kind == 'catalog' for job in window._jobs.values()))
assert ('已取消读取' if cancel else 'snapshot is held') in window.status_label.text()
assert reports == []
assert window.ready_names == {'A'}
assert snapshot.read_text(encoding='utf-8') == 'full scan'
window.status_refresher(('A',), Path('a.lmc'))
assert snapshot.read_text(encoding='utf-8') == 'full scan'
finally:
release.set()
window.pool.waitForDone(6000)
@pytest.mark.parametrize('cancelled', [False, True])
def test_external_catalog_owner_wait_retries_once_or_cancels(qtbot, tmp_path, monkeypatch, cancelled):
from cbb_refresh_verify.management import Catalog, CatalogEntry
from cbb_refresh_verify.native_management import NativeOperationError
probing, released = Event(), Event()
calls = []
def read_catalog(path, evidence):
calls.append(evidence)
if len(calls) == 1:
raise NativeOperationError('LIBRARY_MANAGER_BUSY: 已有 Library Manager 运行。', safe_to_continue=True)
return Catalog(path, 1, (CatalogEntry('A', 'Logical-Physical'),))
def owners(*args, **kwargs):
probing.set()
return [] if released.is_set() else [{'pid': 123}]
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', owners)
window = window_for(qtbot, tmp_path, monkeypatch,
reader=lambda _: LibraryReadResult((CbbRecord('A', 'LP'),), directory_count=1),
catalog_reader=read_catalog, status_refresher=lambda names, _: {name: 'READY' for name in names})
try:
load(window, qtbot)
qtbot.waitUntil(probing.is_set)
assert not window.native_queue.active
if cancelled:
window.stop_button.click()
released.set()
qtbot.waitUntil(lambda: not any(job.kind == 'catalog' for job in window._jobs.values()), timeout=4000)
assert len(calls) == (1 if cancelled else 2)
if cancelled:
assert '已取消读取' in window.status_label.text()
else:
assert calls[0] != calls[1]
assert window.ready_names == {'A'}
finally:
released.set()
window.pool.waitForDone(6000)
+40
View File
@@ -238,3 +238,43 @@ def test_catalog_native_wait_outlives_metadata_deadline(tmp_path, transport, mon
(evidence/'finish').touch()
finisher.join(6)
context.close(timeout_seconds=6)
@pytest.mark.parametrize('switch', [False, True])
def test_stop_reaches_active_catalog_adapter(qtbot, tmp_path, monkeypatch, transport, switch):
from types import SimpleNamespace
from cbb_refresh_verify.native_management import NativeManagementAdapter
Transport, workers = transport
original = Transport.__init__
def hold_until_signalled(self, command, *args, **kwargs):
Path(command[-1]).with_name('hold-handler').touch()
original(self, command, *args, **kwargs)
monkeypatch.setattr(Transport, '__init__', hold_until_signalled)
library = tmp_path/'library.lmc'
library.write_bytes(b'isolated')
adapter = NativeManagementAdapter(worker_factory=Transport)
window = window_for(qtbot, tmp_path/'ui', monkeypatch, catalog_reader=adapter.catalog)
mapping_calls = []
window.path_lease_factory = lambda path: SimpleNamespace(mentor_path=path, display_path=path,
drive='', remote_root='', close=lambda: mapping_calls.append('close'),
retain_for_recovery=lambda: mapping_calls.append('retain'))
load(window, qtbot, str(library))
qtbot.waitUntil(lambda: bool(workers) and workers[0].path.with_name('handler-entered').exists())
worker = workers[0]
try:
if switch:
window.lmc_edit.setText(str(tmp_path/'different.lmc'))
else:
window.stop_button.click()
qtbot.waitUntil(lambda: worker.path.with_name('cancel-management.signal').exists(), timeout=3000)
qtbot.waitUntil(lambda: bool(mapping_calls), timeout=3000)
assert mapping_calls[0] == 'retain'
if not switch:
qtbot.waitUntil(lambda: '已取消读取中心库' in window.status_label.text(), timeout=3000)
assert not window.native_queue.active
assert worker.poll() is None
finally:
worker.path.with_name('finish').touch()
qtbot.waitUntil(lambda: worker.poll() is not None, timeout=5000)
+149
View File
@@ -112,3 +112,152 @@ def test_readwrite_choice_rejects_replaced_native_button(tmp_path,monkeypatch):
changed=replace(original,controls=tuple(replace(c,handle=c.handle+1) if c.control_id==6 else c
for c in original.controls))
assert controller.handle(changed,(changed,),**kwargs).error_code=='DATABASE_RECOVERY_REQUIRED'
@pytest.mark.parametrize('origin', ['user', 'timeout_default'])
@pytest.mark.parametrize('guard_error, control, code', [
(None, 6, ''),
(OSError('共享数据库被占用:SymbolLibs/icdb.dat'), 7, 'PCB_OPEN_SKIPPED'),
(TimeoutError('原生检查超时'), 7, 'PCB_OPEN_SKIPPED'),
])
def test_normal_readwrite_uses_same_resource_check(tmp_path, monkeypatch, origin, guard_error, control, code):
from contextlib import contextmanager
import json
from cbb_refresh_verify import pcb_open_consent as consent
monkeypatch.setattr(consent, 'validate_owner', lambda *_: {'target': 'owned'})
events = []
@contextmanager
def guard(*_, require_complete_proof=False):
assert require_complete_proof
events.append('probe')
if guard_error is not None:
raise guard_error
yield
events.append('released_probe_handles')
monkeypatch.setattr(consent, 'resource_guard', guard)
controller = consent.OpenController(dict(root=str(tmp_path), block_name='A', lmc_file='lib.lmc',
project='A.prj', pcb='A.pcb', desktop='CbbVerify_test'), auto_confirm=True)
shown = []
def perform(_, action, phase):
clicked = action['target']['control_id']
events.append(clicked)
return SimpleNamespace(accepted_controls=(clicked,), error_code='', detail='', channel='win32_button_click')
kwargs = dict(target_pid=20, launcher_pid=10, worker_pid=5, show=shown.append, perform=perform)
controller.handle(snapshot(), (snapshot(),), **kwargs)
assert not events
shown[0].choose('continue', origin=origin)
result = controller.handle(snapshot(), (snapshot(),), **kwargs)
assert result.error_code == code
assert events == (['probe', 'released_probe_handles', control] if guard_error is None else ['probe', control])
if guard_error is not None:
assert str(guard_error) in result.detail
record = json.loads((tmp_path/'pcb-open-user-choice.json').read_text(encoding='utf-8'))
assert record['decision_origin'] == origin
assert record['choice'] == ('continue' if control == 6 else 'skip')
controller.handle(snapshot(), (snapshot(),), **kwargs)
assert events.count(control) == 1
def test_unattended_ordinary_dialog_defaults_to_checking_resources(qtbot):
from cbb_refresh_verify.pcb_open_consent import OpenChoice
from cbb_refresh_verify.ui.pcb_open_dialog import PcbOpenDialog
choice = OpenChoice('A', 'lib.lmc', auto_confirm=True)
dialog = PcbOpenDialog(choice)
qtbot.addWidget(dialog)
assert dialog.defaultButton() is dialog.continue_button
dialog.skip_button.click()
assert choice.decision == 'skip'
assert choice.decision_origin == 'user'
def test_unattended_readwrite_checks_actual_shared_database_handle(tmp_path, monkeypatch):
import win32con
import win32file
from cbb_refresh_verify import pcb_open_consent as consent
from cbb_refresh_verify import owner_probe
library = tmp_path/'lib.lmc'
work = tmp_path/'ReusableBlocksLP/A/Work'
project, pcb = work/'A.prj', work/'PCB/A.pcb'
shared = tmp_path/'SymbolLibs/__ReusableBlocksSymb/icdb.dat'
for path in (library, work/'database/icdb.dat', pcb.parent/'Layout/LayoutDB.lyt', shared):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(b'fixture')
project.write_text('KEY PCBDesignPath "PCB/A.pcb"\nKEY iCDBDir "database"\n')
pcb.write_text('KEY ProjectFile "../A.prj"\n')
owner = {'target': 'bound'}
monkeypatch.setattr(consent, 'validate_owner', lambda *_: owner)
monkeypatch.setattr(owner_probe, 'query_process_snapshot', lambda: [])
def run(attempt, expected_control):
evidence = tmp_path/attempt
evidence.mkdir()
controller = consent.OpenController(dict(root=str(evidence), block_name='A', lmc_file=str(library),
project=str(project), pcb=str(pcb), desktop='CbbVerify_test'), auto_confirm=True)
shown, actions = [], []
def perform(_, action, phase):
actions.append(action['target']['control_id'])
if expected_control == 6:
handle = win32file.CreateFile(str(shared), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, 0, None)
handle.Close()
return SimpleNamespace(error_code='', accepted_controls=tuple(actions), detail='', channel='win32_button_click')
options = dict(target_pid=20, launcher_pid=10, worker_pid=5, show=shown.append, perform=perform)
controller.handle(snapshot(), (snapshot(),), **options)
shown[0].choose('continue', origin='timeout_default')
result = controller.handle(snapshot(), (snapshot(),), **options)
assert actions == [expected_control], result.detail
return result, evidence
held = win32file.CreateFile(str(shared), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, 0, None)
try:
skipped, evidence = run('occupied', 7)
assert skipped.error_code == 'PCB_OPEN_SKIPPED'
assert str(shared) in skipped.detail
assert not (evidence/'pcb-open-resource-proof.json').exists()
finally:
held.Close()
resumed, evidence = run('released', 6)
assert not resumed.error_code
assert (evidence/'pcb-open-resource-proof.json').is_file()
project.write_text('KEY PCBDesignPath "PCB/A.pcb"\nKEY iCDBDir "../../../outside"\n')
unbound, _ = run('wrong-project-database', 7)
assert 'iCDBDir' in unbound.detail
def test_stop_during_receipt_never_sends_native_yes(tmp_path, monkeypatch):
from cbb_refresh_verify import management
from cbb_refresh_verify import pcb_open_consent as consent
from cbb_refresh_verify.operation_queue import QueueCancelled
stopped = False
original = management._write_json
def write_choice(path, value):
nonlocal stopped
original(path, value)
stopped = True
def check_active():
if stopped:
raise QueueCancelled('cancelled')
monkeypatch.setattr(management, '_write_json', write_choice)
monkeypatch.setattr('cbb_refresh_verify.operation_queue.check_active', check_active)
monkeypatch.setattr(consent, 'validate_owner', lambda *_: {'target': 'bound'})
monkeypatch.setattr(consent, 'resource_guard', lambda *_, **__: nullcontext())
controller = consent.OpenController(dict(root=str(tmp_path), block_name='A', lmc_file='lib.lmc',
project='A.prj', pcb='A.pcb', desktop='CbbVerify_test'), auto_confirm=True)
shown = []
options = dict(target_pid=20, launcher_pid=10, worker_pid=5, show=shown.append,
perform=lambda *_: pytest.fail('sent during cancellation'))
controller.handle(snapshot(), (snapshot(),), **options)
shown[0].choose('continue')
assert controller.handle(snapshot(), (snapshot(),), **options).error_code == 'USER_CANCELLED'