Compare commits

..
19 changed files with 861 additions and 106 deletions

No files matched your search

+8
View File
@@ -193,6 +193,14 @@ Windows 版本判断以 Build 为准:`22000` 及以上归为 Win11,`10240–
GUI 中状态为 `绿色 / Ready` 的条目不能勾选、也不会进入批量队列。
### PCB 读写确认
桌面普通校验默认在读写确认弹窗无人应答 3 秒后核验占用。可在高级设置取消勾选「无人应答时自动核验 PCB 读写占用」,本次启动的后续批次便会在无人应答时跳过该项。手动选择继续也会核验占用。
命令行使用 `--batch-lmc` 时,加 `--auto-confirm-pcb-open` 可对已识别的读写确认执行同样的核验。带此参数的无界面运行发现该弹窗后立即开始检查。版本选择和 ICDB 维护分别使用各自的入口。
程序核对当前工程、LMC、布局和共享数据库。出现身份不符、实际占用、无法绑定的地址记录、绝对或不唯一的 iCDBDir,以及需要维护的库时,报告会记录具体原因。双击表格备注可查看并复制全文。
### 批量状态桥(只读、默认启用)
`tools/status_bridge/bin/CbbStatusBridge32.exe` 是与 Mentor EE 7.9 x86/MFC ABI
@@ -0,0 +1,13 @@
# 工单 #19 审查后续验证
## 合入与发布
PR #18 的目标为 main,PR #20 叠在 PR #18 的分支上。计划先合入 #18,再将 #20 的变更合入 main。发版前在 main 核对两轮改动和测试证据,从最终提交构建新测试版。现有 beta.5 标签对应提交 `3efeaed`。其中不含 PR #20 的目录扫描、读写确认和完整备注改动。
## 占用验证
- 在 Windows 上保留实际文件探测,分别验证共享数据库由独占句柄持有和释放后的选择。另用存在地址记录的工作目录覆盖原生只读检查的调度、正反回执解析和再次探测。该用例替换 Mentor 回执来源。
- 在隔离工程 1GPHY_RTL8211F 上,以之前捕获的项目地址记录调用实际 Mentor Project Backup。原生结果为 `NOT_IN_USE`、`repair_required=true`、`inspection_only=true`、`repair_requested=false`,退出码 0。程序拒绝自动继续。工程地址、工程数据库和共享符号数据库的哈希保持一致,原生检查进程已退出。原始回执 SHA-256 为 `22812c4423bc06fedce4eb9c89ee17e1fe10452fde76aff02ae0380a4505d1d6`。
- 批次回归核对前项保持 SKIPPED,释放复核成功后实际调度同库下一项。工单原先的 5 个工程、364 项生产库及 Win10/SMB 仍待现场复验。
最终全量 Python 测试 2,526 项通过,用时 366.39 秒,退出码 0。编译和差异检查通过。本轮未复现审查机的文件探测挂起。
+1 -1
View File
@@ -3,7 +3,7 @@ requires = ["setuptools>=84.1.0"]
build-backend = "setuptools.build_meta"
[project]
name = "cbb-refresh-verify"
version = "0.2.4b4"
version = "0.2.4b5"
requires-python = ">=3.12,<3.13"
dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<0.7", "Pillow>=13.0.0,<14"]
+1 -1
View File
@@ -1 +1 @@
__version__ = "0.2.4b4"
__version__ = "0.2.4b5"
+4 -1
View File
@@ -143,6 +143,8 @@ def main(argv: Sequence[str] | None = None) -> int:
parser.add_argument('--collect-failure-logs', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--batch-lmc', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--block', action='append', default=[], help=argparse.SUPPRESS)
parser.add_argument('--auto-confirm-pcb-open', action='store_true',
help='With --batch-lmc, continue through the known PCB prompt after checking resource access')
parser.add_argument('--limit', type=_positive_int, help='Maximum requested CBB names for --batch-lmc (default: all)')
parser.add_argument('--libspec', default='', help=argparse.SUPPRESS)
parser.add_argument('--dms-login-config', default='', help=argparse.SUPPRESS)
@@ -203,7 +205,8 @@ def main(argv: Sequence[str] | None = None) -> int:
mentor_bin=args.mentor_bin, logging_context=context,
mapped_drive=lease.drive,
mapped_remote_root=lease.remote_root,
native_lm_verify=native_lm_verify_enabled())
native_lm_verify=native_lm_verify_enabled(),
auto_confirm_pcb_open=args.auto_confirm_pcb_open)
for name in names]
def retain_mapping(reason):
lease.retain_for_recovery()
+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.
+54 -2
View File
@@ -43,7 +43,9 @@ def _cancel_target(snapshot):
from .post_repair_consent import exact_prompt
from .dialog_rules import pcb_version_choice
if exact_prompt(snapshot):
return 'read_write_access', next(c for c in snapshot.controls if c.control_id == 7)
no = next((c for c in snapshot.controls if c.class_name == 'Button'
and c.control_id == 7 and c.enabled), None)
return ('read_write_access', no) if no is not None else None
text = ' '.join(' '.join(c.name for c in snapshot.controls
if c.class_name == 'Static').split())
buttons = [c for c in snapshot.controls if c.class_name == 'Button']
@@ -99,6 +101,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 +226,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 +239,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 +269,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 +406,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)
+98 -36
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,10 @@ def resource_guard(job, allowed_pids):
class OpenController:
def __init__(self, job):
def __init__(self, job, *, auto_confirm=False, require_complete_proof=False):
self.job = job
self.auto_confirm = auto_confirm
self.require_complete_proof = require_complete_proof or auto_confirm
self.choice = None
self.original = self.owner = None
self.sent = False
@@ -120,14 +157,21 @@ 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'])
show(self.choice)
self.choice = OpenChoice(self.job['block_name'], self.job['lmc_file'],
auto_confirm=self.auto_confirm)
if show is not None:
show(self.choice)
elif self.auto_confirm:
self.choice.choose('continue', origin='headless_opt_in')
else:
raise ValueError('PCB_OPEN_CONFIRMATION_REQUIRED')
if (owner != self.owner or snapshot.hwnd != self.original.hwnd
or _prompt_identity(snapshot) != _prompt_identity(self.original)):
raise ValueError('PCB_OPEN_IDENTITY_CHANGED')
@@ -137,36 +181,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.require_complete_proof
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.require_complete_proof:
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,
+157 -27
View File
@@ -11,11 +11,11 @@ import json
from cbb_refresh_verify.operation_queue import BatchTaskContext, QueueCancelled, TaskHandoff
from PySide6.QtCore import QObject, QThreadPool, Signal, Qt, QTimer
from PySide6.QtGui import QColor, QIcon
from PySide6.QtGui import QColor, QIcon, QTextCursor
from PySide6.QtWidgets import (QWidget, QLineEdit, QPushButton, QFormLayout,
QTextEdit, QFileDialog, QHBoxLayout, QLabel, QSpinBox, QMessageBox, QToolButton,
QTableWidget, QTableWidgetItem, QHeaderView, QCheckBox, QVBoxLayout, QProgressBar, QComboBox,
QTabBar, QStackedWidget, QSizePolicy)
QTabBar, QStackedWidget, QSizePolicy, QDialog, QDialogButtonBox, QPlainTextEdit)
from PySide6.QtWidgets import QStyle
@@ -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
@@ -176,6 +176,9 @@ class MainWindow(QWidget):
self.native_lm_verify_check.setChecked(native_lm_verify_enabled())
self.native_lm_verify_check.setToolTip(
'仅在 Win10 兼容测试时启用;默认仍使用已验证的 ReusableCircuit 直接流程。')
self.auto_confirm_pcb_open_check = QCheckBox('无人应答时自动核验 PCB 读写占用')
self.auto_confirm_pcb_open_check.setChecked(True)
self.auto_confirm_pcb_open_check.setToolTip('普通校验中,3 秒后检查占用,确认可写后继续。关闭后默认跳过本项。')
self.advanced_toggle = QToolButton(); self.advanced_toggle.setText('高级设置')
self.advanced_toggle.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_TitleBarUnshadeButton))
self.advanced_toggle.setCheckable(True); self.advanced_toggle.setChecked(False)
@@ -185,10 +188,12 @@ class MainWindow(QWidget):
advanced_layout.addRow('DMS 登录配置', self.dms_edit)
advanced_layout.addRow('Mentor bin', self.mentor_bin_edit)
advanced_layout.addRow('触发方式', self.native_lm_verify_check)
advanced_layout.addRow('读写确认', self.auto_confirm_pcb_open_check)
self.advanced_panel.setVisible(False)
self.advanced_toggle.toggled.connect(self.advanced_panel.setVisible)
self.cbb_table = QTableWidget(0, 4)
self.cbb_table.setHorizontalHeaderLabels(['CBB 名称', '分区', '状态', '备注'])
self.cbb_table.setHorizontalHeaderLabels(['CBB 名称', '分区', '状态', '备注(双击查看)'])
self.cbb_table.cellDoubleClicked.connect(self._show_result_detail)
self.cbb_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
self.cbb_table.horizontalHeader().setSectionResizeMode(3, QHeaderView.Stretch)
for column in (1, 2):
@@ -349,6 +354,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
@@ -541,7 +547,7 @@ class MainWindow(QWidget):
current_library = _path_key(self.mentor_lmc_path or self.lmc_edit.text()) if self.lmc_edit.text().strip() else None
notice = ('上次操作结果待复查,执行前将重新检查占用。'
if self._management_library_unsafe(current_library) else '')
notice = '旧表已失效,请重新读取中心库。' if self._stale_table else notice
notice = '当前显示上次读取结果(已失效)· 请重新读取中心库。' if self._stale_table else notice
self.library_notice.setText(notice)
self.library_notice.setVisible(bool(notice))
for widget in (self.lmc_edit, self.browse_button, self.load_button,
@@ -1035,7 +1041,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 +1260,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 +1289,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 +1311,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 +1335,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 +1433,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 +1484,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)))
@@ -1725,6 +1817,8 @@ class MainWindow(QWidget):
requests = ([request for request in request_snapshot if request.block_name in names] if request_snapshot is not None
else [replace(self._request(name), maintenance=maintenance, auto_repair=False) for name in names])
if not requests: return
auto_confirm = self.auto_confirm_pcb_open_check.isChecked()
requests = [replace(request, auto_confirm_pcb_open=auto_confirm) for request in requests]
library = requests[0].lmc_file
if any(job.active and job.kind == 'verify' and job.requests == tuple(requests)
and _path_key(job.context.library) == _path_key(library) for job in self._jobs.values()): return
@@ -1751,7 +1845,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),
req,
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 +1995,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)
@@ -1944,6 +2044,36 @@ class MainWindow(QWidget):
self.cbb_table.item(row, 3).setToolTip(detail)
if self.logging_context: self.logging_context.logger.info('cbb_progress %s', line)
def _show_result_detail(self, row, column):
if column != 3:
return
item = self.cbb_table.item(row, column)
name = self.cbb_table.item(row, 0)
if item is None or name is None or not item.toolTip():
return
dialog = QDialog(self)
dialog.setAttribute(Qt.WA_DeleteOnClose)
dialog.setWindowTitle(f'{name.text()} 结果详情')
dialog.resize(660, 380)
layout = QVBoxLayout(dialog)
text = QPlainTextEdit(dialog)
text.setReadOnly(True)
text.setPlainText(item.toolTip())
text.moveCursor(QTextCursor.Start)
layout.addWidget(text)
buttons = QDialogButtonBox(QDialogButtonBox.Close, dialog)
copy = buttons.addButton('复制全文', QDialogButtonBox.ActionRole)
def copy_detail():
from PySide6.QtWidgets import QApplication
QApplication.clipboard().setText(text.toPlainText())
copy.clicked.connect(copy_detail)
buttons.rejected.connect(dialog.close)
layout.addWidget(buttons)
dialog.show()
def _mark_row_ready(self, row):
"""Color authoritative READY rows while retaining management selection."""
name_item = self.cbb_table.item(row, 0)
+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)
+10 -2
View File
@@ -83,6 +83,9 @@ class VerifyRequest:
maintenance: bool = False
post_repair_proof: object | None = field(default=None, repr=False, compare=False)
diagnostic_only: bool = False
# Explicit True/False selects ordinary Verify's complete access proof.
# None preserves the manual confirmation policy for other callers.
auto_confirm_pcb_open: bool | None = None
@dataclass(frozen=True)
@@ -1205,14 +1208,18 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
diagnostic_closing = True
from .dialog_supervisor import DialogPollResult
dialog_result = DialogPollResult(activity=False)
if (version_prompt is not None and consent is None and dialog_agent is not None
if ((version_prompt is not None or request.auto_confirm_pcb_open)
and consent is None and dialog_agent is not None
and not request.diagnostic_only and not request.native_lm_verify
and not request.maintenance and not request.interactive_input
and dialog_result.error_code == 'DATABASE_RECOVERY_REQUIRED'
and dialog_result.snapshot is not None):
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 is True,
require_complete_proof=request.auto_confirm_pcb_open is not None)
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 +1277,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)
+6 -4
View File
@@ -60,11 +60,13 @@ def test_supervisor_acknowledged_failed_open_can_close_empty_shell_with_address(
@pytest.mark.parametrize('aliased', [False, True])
def test_late_release_is_rechecked_before_later_same_library_item(tmp_path, monkeypatch, aliased):
@pytest.mark.parametrize('first_status', ['FAIL', 'SKIPPED'])
def test_late_release_is_rechecked_before_later_same_library_item(tmp_path, monkeypatch, aliased, first_status):
library = tmp_path/'lib.lmc'
calls, checks = [], []
failed = verify_runner.VerifyResult('FAIL', stderr='bad database', safe_to_continue=False,
evidence_path=tmp_path/'result.json', error_category='MENTOR_DATABASE_LOAD_FAILED')
failed = verify_runner.VerifyResult(first_status, stderr='native operation declined', safe_to_continue=False,
evidence_path=tmp_path/'result.json',
error_category='PCB_OPEN_SKIPPED' if first_status == 'SKIPPED' else 'MENTOR_DATABASE_LOAD_FAILED')
def verify(request):
calls.append(request.block_name)
return failed if request.block_name == 'Bad' else verify_runner.VerifyResult('PASS')
@@ -78,7 +80,7 @@ def test_late_release_is_rechecked_before_later_same_library_item(tmp_path, monk
results = verify_runner.run_batch([verify_runner.VerifyRequest(library, n, tmp_path)
for n in ('Bad','Good')], verifier=verify)
assert calls == ['Bad','Good']
assert [r.status for r in results] == ['FAIL','PASS']
assert [r.status for r in results] == [first_status,'PASS']
assert results[0].safe_to_continue
+208
View File
@@ -112,3 +112,211 @@ 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()
from cbb_refresh_verify import native_repair
address = work/'database/cdbsvr/sAddress.adr'
address.parent.mkdir()
address.write_text('recorded address')
verdict = 'NOT_IN_USE'
inspected = []
def inspect(target, root, **kwargs):
assert kwargs['inspection_only'] is True
assert target.project == project and target.database == address.parent.parent
inspected.append(target.database)
output = (f'Loading project file [{project}].\nChecking if project is in use.\n'
+ ("Project is not in use. Full iCDB Project Backup's functionality is available.\n"
"Backup information loaded correctly." if verdict == 'NOT_IN_USE' else 'Project is in use.'))
return dict(status=verdict, repair_required=False, inspection_only=True,
repair_requested=False, native_pid=100, native_exit_code=0,
native_identity=dict(pid=100, created_handle=1, image='iCDBProjectBackup.exe',
owner_sid='test', session_id=1),
release={'native_exited': True}, project=str(project),
database=str(target.database), output=output)
monkeypatch.setattr(native_repair, 'run_native_repair', inspect)
unoccupied, _ = run('address-checked-unoccupied', 6)
assert not unoccupied.error_code and inspected == [address.parent.parent]
verdict = 'IN_USE'
occupied, _ = run('address-checked-occupied', 7)
assert occupied.error_code == 'PCB_OPEN_SKIPPED' and 'PCB_OPEN_DATABASE_IN_USE' in occupied.detail
assert inspected == [address.parent.parent]*2
assert address.read_text() == 'recorded address'
address.unlink()
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'
def test_headless_opt_in_checks_resources_without_presenting_dialog(tmp_path, monkeypatch):
import json
from cbb_refresh_verify import pcb_open_consent as consent
monkeypatch.setattr(consent, 'validate_owner', lambda *_: {'target': 'bound'})
checked = []
def guard(_, __, *, require_complete_proof):
checked.append(require_complete_proof)
return nullcontext()
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)
actions = []
def perform(_, action, phase):
actions.append(action['target']['control_id'])
return SimpleNamespace(error_code='', accepted_controls=tuple(actions), detail='', channel='win32_button_click')
result = controller.handle(snapshot(), (snapshot(),), target_pid=20, launcher_pid=10, worker_pid=5,
show=None, perform=perform)
assert not result.error_code
assert checked == [True] and actions == [6]
receipt = json.loads((tmp_path/'pcb-open-user-choice.json').read_text(encoding='utf-8'))
assert receipt['decision_origin'] == 'headless_opt_in'
+14
View File
@@ -166,3 +166,17 @@ def test_retained_mapping_logs_context_and_confirmed_release_guidance(batch_cli,
assert 'Z:' in notice and r'\\server\share' in notice
assert '释放残留会话' in notice and '确认' in notice
assert 'net use' not in notice.lower()
def test_batch_cli_can_enable_verified_pcb_open(batch_cli, monkeypatch):
app, runner, _, _, _ = batch_cli
received = []
def run(requests, **kwargs):
received.extend(request.auto_confirm_pcb_open for request in requests)
return [VerifyResult('PASS') for _ in requests]
monkeypatch.setattr(runner, 'run_batch', run)
assert app.main(['--batch-lmc', 'lib.lmc', '--block', 'One']) == 0
assert app.main(['--batch-lmc', 'lib.lmc', '--block', 'One', '--auto-confirm-pcb-open']) == 0
assert received == [False, True]
+47
View File
@@ -290,3 +290,50 @@ def test_large_catalog_local_filter_and_selection_remain_responsive(qtbot, tmp_p
print(f'catalog rows={size} load={loaded:.3f}s local_actions={elapsed:.3f}s')
assert elapsed < 2.0
assert window.selected_records() == ()
def test_double_click_shows_complete_skipped_reason(qtbot, tmp_path, monkeypatch):
from PySide6.QtWidgets import QApplication, QDialog, QPlainTextEdit, QPushButton
window = load_window(qtbot, tmp_path, monkeypatch)
window.show()
reason = ('PCB_OPEN_SKIPPED: 检查未通过\n' +
'\n'.join(f'共享数据库占用记录 {index}' for index in range(30)) +
'\n完整路径 <library>/SymbolLibs/icdb.dat')
window._progress({'block': 'Beta', 'stage': 'SKIPPED', 'detail': reason})
row = window._row_by_name['Beta']
item = window.cbb_table.item(row, 3)
window.cbb_table.scrollToItem(item)
position = window.cbb_table.visualItemRect(item).center()
viewport = window.cbb_table.viewport()
assert viewport.rect().contains(position)
qtbot.mouseClick(viewport, Qt.LeftButton, pos=position)
qtbot.mouseDClick(viewport, Qt.LeftButton, pos=position)
dialogs = [dialog for dialog in window.findChildren(QDialog)
if dialog.isVisible() and '结果详情' in dialog.windowTitle()]
assert len(dialogs) == 1
dialog = dialogs[0]
text = dialog.findChild(QPlainTextEdit)
assert text.isReadOnly()
assert text.toPlainText() == reason
copy, = [button for button in dialog.findChildren(QPushButton) if button.text() == '复制全文']
qtbot.mouseClick(copy, Qt.LeftButton)
assert QApplication.clipboard().text() == reason
dialog.close()
@pytest.mark.parametrize('enabled', [False, True])
def test_pcb_open_option_is_bound_only_to_ordinary_verify(qtbot, tmp_path, monkeypatch, enabled):
requests = []
def verify(request):
requests.append(request)
return VerifyResult('SKIPPED')
window = load_window(qtbot, tmp_path, monkeypatch, verifier=verify)
window.auto_confirm_pcb_open_check.setChecked(enabled)
assert window._request('Beta').auto_confirm_pcb_open is None
window._run(['Beta'])
qtbot.waitUntil(lambda: not window.busy)
assert len(requests) == 1
assert requests[0].auto_confirm_pcb_open is enabled