Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e293a9b03c | ||
|
|
3b4323405a | ||
|
|
48f38d1bdd | ||
|
|
3223889dc7 | ||
|
|
f4f5e939eb | ||
|
|
8e0f78979a | ||
|
|
4fb978ee21 | ||
|
|
31a93cd313 | ||
|
|
6d2b6de027 | ||
|
|
47c2cfecc6 | ||
|
|
7c239e123b | ||
|
|
2d6acc1180 | ||
|
|
86837155ea | ||
|
|
3efeaed656 |
No files matched your search
@@ -193,6 +193,14 @@ Windows 版本判断以 Build 为准:`22000` 及以上归为 Win11,`10240–
|
|||||||
|
|
||||||
GUI 中状态为 `绿色 / Ready` 的条目不能勾选、也不会进入批量队列。
|
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
|
`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,5 +1,6 @@
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import os
|
import os
|
||||||
|
from shutil import copyfile
|
||||||
import struct
|
import struct
|
||||||
project_root = Path(SPECPATH).parent
|
project_root = Path(SPECPATH).parent
|
||||||
assets_root = project_root / 'src' / 'cbb_refresh_verify' / 'assets'
|
assets_root = project_root / 'src' / 'cbb_refresh_verify' / 'assets'
|
||||||
@@ -42,3 +43,4 @@ pyz = PYZ(a.pure)
|
|||||||
exe = EXE(pyz, a.scripts, [], exclude_binaries=True, name='CbbRefreshVerify', console=False,
|
exe = EXE(pyz, a.scripts, [], exclude_binaries=True, name='CbbRefreshVerify', console=False,
|
||||||
icon=str(assets_root / 'cbb_refresh_verify.ico'))
|
icon=str(assets_root / 'cbb_refresh_verify.ico'))
|
||||||
coll = COLLECT(exe, a.binaries, a.zipfiles, a.datas, name='CbbRefreshVerify-Background')
|
coll = COLLECT(exe, a.binaries, a.zipfiles, a.datas, name='CbbRefreshVerify-Background')
|
||||||
|
copyfile(project_root / 'packaging' / '使用说明.txt', Path(coll.name) / '使用说明.txt')
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
CBB 刷新校验使用说明
|
||||||
|
|
||||||
|
将 ZIP 完整解压到可写文件夹,保留 CbbRefreshVerify.exe 和 _internal,
|
||||||
|
双击 CbbRefreshVerify.exe。目标电脑需要安装 Mentor EE 7.9.5,
|
||||||
|
并能访问中心库及其依赖。写入或恢复前请手动保留可用备份。
|
||||||
|
|
||||||
|
在「检验」页选择 .lmc 文件并点击「读取 CBB」。目录预览先出现,
|
||||||
|
READY 和待验证状态会随后由 Mentor 核对。确认中心库和目标工程后
|
||||||
|
开始校验。校验会保存工程,经 Mentor 确认为 READY 才显示通过。
|
||||||
|
|
||||||
|
点击「取消当前任务并停止队列」后,程序等待原生操作安全退出。
|
||||||
|
重新提交同库任务时,若仍在收尾,界面会显示等待原因。可通过
|
||||||
|
「释放残留会话」核对占用的库、工程和进程,查看历史操作记录。
|
||||||
|
|
||||||
|
应用默认把日志、批次报告和证据保存在程序旁的 data 目录下。
|
||||||
|
可在「检验」页点「打开日志目录」。使用命令行时,可指定数据目录。
|
||||||
|
data\logs\application.log 包含启动和任务状态,data\reports 包含批次结果。
|
||||||
|
|
||||||
|
PowerShell 批次示例(在 CbbRefreshVerify.exe 所在目录中运行)
|
||||||
|
|
||||||
|
$run = Start-Process .\CbbRefreshVerify.exe -ArgumentList '--batch-lmc', '"D:\测试库\mentor_lib.lmc"', '--block', 'CBB_01', '--data-root', '"D:\CBB日志"' -RedirectStandardError .\batch-error.txt -PassThru -Wait
|
||||||
|
$run.ExitCode
|
||||||
|
|
||||||
|
--block 可重复指定工程。--auto-confirm-pcb-open 允许命令行在核验
|
||||||
|
资源可写后继续处理已识别的 PCB 读写确认。退出码 0 表示所选项全部
|
||||||
|
通过,1 表示输入或启动失败,2 表示批次有未通过项或命令参数错误。
|
||||||
|
启动或输入错误写入重定向的 batch-error.txt。
|
||||||
+1
-1
@@ -3,7 +3,7 @@ requires = ["setuptools>=84.1.0"]
|
|||||||
build-backend = "setuptools.build_meta"
|
build-backend = "setuptools.build_meta"
|
||||||
[project]
|
[project]
|
||||||
name = "cbb-refresh-verify"
|
name = "cbb-refresh-verify"
|
||||||
version = "0.2.4b4"
|
version = "0.2.4b6"
|
||||||
requires-python = ">=3.12,<3.13"
|
requires-python = ">=3.12,<3.13"
|
||||||
dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<0.7", "Pillow>=13.0.0,<14"]
|
dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<0.7", "Pillow>=13.0.0,<14"]
|
||||||
|
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
__version__ = "0.2.4b4"
|
__version__ = "0.2.4b6"
|
||||||
@@ -3,6 +3,7 @@ import argparse, os, sys
|
|||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Sequence
|
from typing import Sequence
|
||||||
|
from .network_path import NetworkPathError
|
||||||
from .runtime_logging import configure
|
from .runtime_logging import configure
|
||||||
|
|
||||||
|
|
||||||
@@ -62,6 +63,29 @@ def resolve_data_root(cli_value: Path | None) -> Path:
|
|||||||
local = os.environ.get("LOCALAPPDATA")
|
local = os.environ.get("LOCALAPPDATA")
|
||||||
return (Path(local) / "CbbRefreshVerify" if local else Path.home() / "AppData" / "Local" / "CbbRefreshVerify").resolve()
|
return (Path(local) / "CbbRefreshVerify" if local else Path.home() / "AppData" / "Local" / "CbbRefreshVerify").resolve()
|
||||||
|
|
||||||
|
def _report_entry_error(message: str, *, command_line: bool) -> int:
|
||||||
|
if not command_line:
|
||||||
|
import win32api
|
||||||
|
import win32con
|
||||||
|
win32api.MessageBox(None, message, 'CBB 刷新校验启动失败', win32con.MB_ICONERROR)
|
||||||
|
elif sys.stderr is not None:
|
||||||
|
print(message, file=sys.stderr, flush=True)
|
||||||
|
elif os.name == 'nt':
|
||||||
|
# PyInstaller's windowed executable leaves sys.stderr unset even
|
||||||
|
# when the caller supplied a redirected Windows stderr handle.
|
||||||
|
import pywintypes
|
||||||
|
import win32api
|
||||||
|
import win32console
|
||||||
|
import win32file
|
||||||
|
try:
|
||||||
|
handle = win32api.GetStdHandle(win32console.STD_ERROR_HANDLE)
|
||||||
|
if handle:
|
||||||
|
win32file.WriteFile(handle, (message + '\n').encode('utf-8'))
|
||||||
|
except pywintypes.error:
|
||||||
|
pass
|
||||||
|
return 1
|
||||||
|
|
||||||
|
|
||||||
def _positive_int(value):
|
def _positive_int(value):
|
||||||
try:
|
try:
|
||||||
number = int(value)
|
number = int(value)
|
||||||
@@ -143,6 +167,8 @@ def main(argv: Sequence[str] | None = None) -> int:
|
|||||||
parser.add_argument('--collect-failure-logs', type=Path, help=argparse.SUPPRESS)
|
parser.add_argument('--collect-failure-logs', type=Path, help=argparse.SUPPRESS)
|
||||||
parser.add_argument('--batch-lmc', 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('--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('--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('--libspec', default='', help=argparse.SUPPRESS)
|
||||||
parser.add_argument('--dms-login-config', default='', help=argparse.SUPPRESS)
|
parser.add_argument('--dms-login-config', default='', help=argparse.SUPPRESS)
|
||||||
@@ -169,14 +195,24 @@ def main(argv: Sequence[str] | None = None) -> int:
|
|||||||
return dialog_agent_main(args.dialog_agent)
|
return dialog_agent_main(args.dialog_agent)
|
||||||
if args.verify_worker:
|
if args.verify_worker:
|
||||||
return _native_worker_entry('verify', args.verify_worker)
|
return _native_worker_entry('verify', args.verify_worker)
|
||||||
context = configure(resolve_data_root(args.data_root)); logger = context.logger; logger.info("application_start")
|
command_line = bool(args.batch_lmc or args.smoke_test)
|
||||||
|
data_root = args.data_root
|
||||||
|
try:
|
||||||
|
data_root = resolve_data_root(data_root)
|
||||||
|
context = configure(data_root)
|
||||||
|
except (OSError, ValueError, RuntimeError):
|
||||||
|
location = data_root if data_root is not None else '默认数据目录'
|
||||||
|
return _report_entry_error(f'DATA_ROOT_UNWRITABLE: 无法写入数据目录 {location}。'
|
||||||
|
'请指定可写的 --data-root。', command_line=command_line)
|
||||||
|
logger = context.logger
|
||||||
|
logger.info("application_start")
|
||||||
try:
|
try:
|
||||||
if args.batch_lmc:
|
if args.batch_lmc:
|
||||||
from .verify_runner import (VerifyRequest, native_lm_verify_enabled,
|
from .verify_runner import (VerifyRequest, native_lm_verify_enabled,
|
||||||
run_batch, write_batch_report, failure_report_path)
|
run_batch, write_batch_report, failure_report_path)
|
||||||
from .library_reader import read_library_fast
|
from .library_reader import read_library_fast
|
||||||
from .batch_status import authoritative_status_map
|
from .batch_status import authoritative_status_map
|
||||||
from .network_path import LibraryPathLease, select_library_file
|
from .network_path import LibraryPathLease, select_library_file, validate_library_file
|
||||||
with LibraryPathLease.acquire(args.batch_lmc) as lease:
|
with LibraryPathLease.acquire(args.batch_lmc) as lease:
|
||||||
mentor_path = select_library_file(lease.mentor_path)
|
mentor_path = select_library_file(lease.mentor_path)
|
||||||
logger.info(
|
logger.info(
|
||||||
@@ -184,15 +220,18 @@ def main(argv: Sequence[str] | None = None) -> int:
|
|||||||
lease.display_path, mentor_path, lease.drive or '-',
|
lease.display_path, mentor_path, lease.drive or '-',
|
||||||
lease.remote_root or '-', lease.created)
|
lease.remote_root or '-', lease.created)
|
||||||
names = list(args.block)
|
names = list(args.block)
|
||||||
if not names:
|
if names:
|
||||||
|
validate_library_file(mentor_path)
|
||||||
|
else:
|
||||||
library = read_library_fast(
|
library = read_library_fast(
|
||||||
mentor_path,
|
mentor_path,
|
||||||
status_reader=lambda path, names: authoritative_status_map(
|
status_reader=lambda path, names: authoritative_status_map(
|
||||||
names, path, context.root/'status-scan.jsonl'),
|
names, path, context.root/'status-scan.jsonl'),
|
||||||
)
|
)
|
||||||
if library.error: raise RuntimeError(library.error)
|
if library.error: raise NetworkPathError(library.error)
|
||||||
names = [record.name for record in library.records if record.status != 'READY']
|
names = [record.name for record in library.records if record.status != 'READY']
|
||||||
if not names: raise RuntimeError('中心库未读取到需要校验的 CBB')
|
if not names:
|
||||||
|
raise NetworkPathError('INPUT_NO_BLOCKS: 中心库未读取到需要校验的 CBB。')
|
||||||
total = len(names)
|
total = len(names)
|
||||||
if args.limit is not None:
|
if args.limit is not None:
|
||||||
names = names[:args.limit]
|
names = names[:args.limit]
|
||||||
@@ -203,7 +242,8 @@ def main(argv: Sequence[str] | None = None) -> int:
|
|||||||
mentor_bin=args.mentor_bin, logging_context=context,
|
mentor_bin=args.mentor_bin, logging_context=context,
|
||||||
mapped_drive=lease.drive,
|
mapped_drive=lease.drive,
|
||||||
mapped_remote_root=lease.remote_root,
|
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]
|
for name in names]
|
||||||
def retain_mapping(reason):
|
def retain_mapping(reason):
|
||||||
lease.retain_for_recovery()
|
lease.retain_for_recovery()
|
||||||
@@ -214,10 +254,27 @@ def main(argv: Sequence[str] | None = None) -> int:
|
|||||||
lease.drive or '-', lease.remote_root or '-', lease.display_path,
|
lease.drive or '-', lease.remote_root or '-', lease.display_path,
|
||||||
mentor_path, reason)
|
mentor_path, reason)
|
||||||
try:
|
try:
|
||||||
from threading import Event
|
from .operation_queue import BatchTaskContext, NativeQueue, request_library_keys
|
||||||
stop = Event()
|
from .session_record import discover_sessions, handoff_session
|
||||||
with batch_stop_signals(stop):
|
|
||||||
results = run_batch(requests, stop=stop)
|
aliases = tuple(request_library_keys(requests[0]))
|
||||||
|
task = BatchTaskContext(str(mentor_path), aliases=aliases,
|
||||||
|
targets=tuple(names), native_policy='external')
|
||||||
|
queue = NativeQueue()
|
||||||
|
with batch_stop_signals(task.stop):
|
||||||
|
for old_session in discover_sessions(context.root):
|
||||||
|
if old_session.get('status') != 'ACTIVE':
|
||||||
|
continue
|
||||||
|
old_request = VerifyRequest(Path(old_session['library']), names[0], context.root)
|
||||||
|
if request_library_keys(old_request).intersection(aliases):
|
||||||
|
handoff_session(old_session['path'], evidence_root=context.root, observe_only=True)
|
||||||
|
|
||||||
|
def admit(_request, action):
|
||||||
|
return queue.run(action, stop=task.stop, context=task,
|
||||||
|
wait_for_release_seconds=120,
|
||||||
|
waiting=lambda: logger.info('batch_waiting_for_session_release library=%s', mentor_path))
|
||||||
|
|
||||||
|
results = run_batch(requests, stop=task.stop, context=task, item_executor=admit)
|
||||||
except Exception:
|
except Exception:
|
||||||
retain_mapping('batch_exception')
|
retain_mapping('batch_exception')
|
||||||
raise
|
raise
|
||||||
@@ -245,6 +302,12 @@ def main(argv: Sequence[str] | None = None) -> int:
|
|||||||
logger.info('gui_smoke_window_created title=%s', window.windowTitle())
|
logger.info('gui_smoke_window_created title=%s', window.windowTitle())
|
||||||
QTimer.singleShot(250, app.quit)
|
QTimer.singleShot(250, app.quit)
|
||||||
code = int(app.exec()); logger.info("application_clean_shutdown exit_code=%s", code); return code
|
code = int(app.exec()); logger.info("application_clean_shutdown exit_code=%s", code); return code
|
||||||
except Exception: logger.exception("application_startup_failure"); return 1
|
except NetworkPathError as error:
|
||||||
|
logger.warning('application_input_failure %s', error)
|
||||||
|
return _report_entry_error(str(error), command_line=command_line)
|
||||||
|
except Exception:
|
||||||
|
logger.exception('application_startup_failure')
|
||||||
|
return _report_entry_error(f'APPLICATION_STARTUP_FAILED: 无法完成启动或批次,请查看日志目录 {context.root}。',
|
||||||
|
command_line=command_line)
|
||||||
finally:
|
finally:
|
||||||
for handler in logger.handlers: handler.flush()
|
for handler in logger.handlers: handler.flush()
|
||||||
@@ -172,12 +172,13 @@ class BatchCheckpoint:
|
|||||||
)
|
)
|
||||||
return cls(records)
|
return cls(records)
|
||||||
|
|
||||||
def append(self, path: Path, record: BatchStatusRecord) -> None:
|
def append(self, path: Path | None, record: BatchStatusRecord) -> None:
|
||||||
checkpoint = Path(path)
|
if path is not None:
|
||||||
checkpoint.parent.mkdir(parents=True, exist_ok=True)
|
checkpoint = Path(path)
|
||||||
with checkpoint.open("a", encoding="utf-8", newline="\n") as handle:
|
checkpoint.parent.mkdir(parents=True, exist_ok=True)
|
||||||
handle.write(json.dumps(record.to_json(), ensure_ascii=False, separators=(",", ":")) + "\n")
|
with checkpoint.open("a", encoding="utf-8", newline="\n") as handle:
|
||||||
handle.flush()
|
handle.write(json.dumps(record.to_json(), ensure_ascii=False, separators=(",", ":")) + "\n")
|
||||||
|
handle.flush()
|
||||||
self.records[record.block_name] = record
|
self.records[record.block_name] = record
|
||||||
|
|
||||||
|
|
||||||
@@ -200,16 +201,20 @@ class BatchStatusSession:
|
|||||||
self.rotate_every = max(1, int(rotate_every))
|
self.rotate_every = max(1, int(rotate_every))
|
||||||
self.restart_count = 0
|
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]:
|
*, block_type: str = "RULP", resume: bool = False, progress=None) -> list[BatchStatusRecord]:
|
||||||
fingerprint = fingerprint_library(Path(lmc_file))
|
from .operation_queue import check_active
|
||||||
if resume:
|
|
||||||
checkpoint = BatchCheckpoint.load(checkpoint_path)
|
check_active()
|
||||||
else:
|
fingerprint = fingerprint_library(Path(lmc_file)).sha256 if checkpoint_path is not None else ''
|
||||||
checkpoint = BatchCheckpoint()
|
checkpoint = BatchCheckpoint()
|
||||||
checkpoint_file = Path(checkpoint_path)
|
if checkpoint_path is not None:
|
||||||
checkpoint_file.parent.mkdir(parents=True, exist_ok=True)
|
if resume:
|
||||||
checkpoint_file.write_text('', encoding='utf-8')
|
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] = []
|
results: list[BatchStatusRecord] = []
|
||||||
names = tuple(str(name) for name in names)
|
names = tuple(str(name) for name in names)
|
||||||
server = self.bridge if all(callable(getattr(self.bridge, method, None))
|
server = self.bridge if all(callable(getattr(self.bridge, method, None))
|
||||||
@@ -219,10 +224,13 @@ class BatchStatusSession:
|
|||||||
try:
|
try:
|
||||||
queried = 0
|
queried = 0
|
||||||
for index, name in enumerate(names):
|
for index, name in enumerate(names):
|
||||||
|
check_active()
|
||||||
previous = checkpoint.get(name)
|
previous = checkpoint.get(name)
|
||||||
if (previous and previous.status in {'READY', 'PENDING'}
|
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)
|
results.append(previous)
|
||||||
|
if progress is not None:
|
||||||
|
progress(len(results), len(names))
|
||||||
continue
|
continue
|
||||||
try:
|
try:
|
||||||
result: BridgeResult = self.bridge.query(
|
result: BridgeResult = self.bridge.query(
|
||||||
@@ -232,12 +240,12 @@ class BatchStatusSession:
|
|||||||
record = BatchStatusRecord(
|
record = BatchStatusRecord(
|
||||||
block_name=name, status=result.status, source=result.source,
|
block_name=name, status=result.status, source=result.source,
|
||||||
raw_status=result.raw_status, detail=result.detail,
|
raw_status=result.raw_status, detail=result.detail,
|
||||||
fingerprint=fingerprint.sha256, timestamp=_now(),
|
fingerprint=fingerprint, timestamp=_now(),
|
||||||
block_type=block_type,
|
block_type=block_type,
|
||||||
)
|
)
|
||||||
except BridgeUnavailable as error:
|
except BridgeUnavailable as error:
|
||||||
record = BatchStatusRecord(block_name=name, status="UNAVAILABLE",
|
record = BatchStatusRecord(block_name=name, status="UNAVAILABLE",
|
||||||
detail=str(error), fingerprint=fingerprint.sha256,
|
detail=str(error), fingerprint=fingerprint,
|
||||||
timestamp=_now(), block_type=block_type)
|
timestamp=_now(), block_type=block_type)
|
||||||
except BridgeResponseError as error:
|
except BridgeResponseError as error:
|
||||||
message = str(error)
|
message = str(error)
|
||||||
@@ -252,7 +260,7 @@ class BatchStatusSession:
|
|||||||
else "UNAVAILABLE" if unavailable
|
else "UNAVAILABLE" if unavailable
|
||||||
else "MALFORMED" if malformed else "ERROR")
|
else "MALFORMED" if malformed else "ERROR")
|
||||||
record = BatchStatusRecord(block_name=name, status=status, detail=message,
|
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":
|
if server is not None and status != "UNAVAILABLE":
|
||||||
try:
|
try:
|
||||||
server.restart()
|
server.restart()
|
||||||
@@ -260,14 +268,17 @@ class BatchStatusSession:
|
|||||||
pass
|
pass
|
||||||
except Exception as error: # bridge failures isolate one CBB
|
except Exception as error: # bridge failures isolate one CBB
|
||||||
record = BatchStatusRecord(block_name=name, status="ERROR", detail=str(error),
|
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:
|
if server is not None:
|
||||||
try:
|
try:
|
||||||
server.restart()
|
server.restart()
|
||||||
except BridgeUnavailable:
|
except BridgeUnavailable:
|
||||||
pass
|
pass
|
||||||
|
check_active()
|
||||||
checkpoint.append(checkpoint_path, record)
|
checkpoint.append(checkpoint_path, record)
|
||||||
results.append(record)
|
results.append(record)
|
||||||
|
if progress is not None:
|
||||||
|
progress(len(results), len(names))
|
||||||
if record.status == "UNAVAILABLE" and index + 1 < len(names):
|
if record.status == "UNAVAILABLE" and index + 1 < len(names):
|
||||||
# Startup/protocol failures cannot be repaired by retrying
|
# Startup/protocol failures cannot be repaired by retrying
|
||||||
# the same request contract for every CBB.
|
# the same request contract for every CBB.
|
||||||
@@ -276,11 +287,13 @@ class BatchStatusSession:
|
|||||||
for remaining in names[index + 1:]:
|
for remaining in names[index + 1:]:
|
||||||
unavailable_record = BatchStatusRecord(
|
unavailable_record = BatchStatusRecord(
|
||||||
block_name=remaining, status=record.status, detail=record.detail,
|
block_name=remaining, status=record.status, detail=record.detail,
|
||||||
fingerprint=fingerprint.sha256, timestamp=_now(),
|
fingerprint=fingerprint, timestamp=_now(),
|
||||||
block_type=block_type,
|
block_type=block_type,
|
||||||
)
|
)
|
||||||
checkpoint.append(checkpoint_path, unavailable_record)
|
checkpoint.append(checkpoint_path, unavailable_record)
|
||||||
results.append(unavailable_record)
|
results.append(unavailable_record)
|
||||||
|
if progress is not None:
|
||||||
|
progress(len(results), len(names))
|
||||||
break
|
break
|
||||||
queried += 1
|
queried += 1
|
||||||
if server is not None and queried % self.rotate_every == 0 and name != names[-1]:
|
if server is not None and queried % self.rotate_every == 0 and name != names[-1]:
|
||||||
@@ -291,9 +304,9 @@ class BatchStatusSession:
|
|||||||
return results
|
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,
|
*, bridge_path: Path | None = None,
|
||||||
timeout_seconds: float = 10.0) -> dict[str, str]:
|
timeout_seconds: float = 10.0, progress=None) -> dict[str, str]:
|
||||||
"""Return only bridge-backed statuses for an optional UI integration.
|
"""Return only bridge-backed statuses for an optional UI integration.
|
||||||
|
|
||||||
Production always queries fresh statuses, including after native writes;
|
Production always queries fresh statuses, including after native writes;
|
||||||
@@ -306,7 +319,7 @@ def authoritative_status_map(names: Iterable[str], lmc_file: Path, checkpoint_pa
|
|||||||
names = tuple(str(name) for name in names)
|
names = tuple(str(name) for name in names)
|
||||||
try:
|
try:
|
||||||
records = BatchStatusSession(bridge, timeout_seconds=timeout_seconds).scan(
|
records = BatchStatusSession(bridge, timeout_seconds=timeout_seconds).scan(
|
||||||
names, lmc_file, checkpoint_path, resume=False)
|
names, lmc_file, checkpoint_path, resume=False, progress=progress)
|
||||||
return {record.block_name: record.status for record in records}
|
return {record.block_name: record.status for record in records}
|
||||||
except BridgeUnavailable:
|
except BridgeUnavailable:
|
||||||
return {name: "UNAVAILABLE" for name in names}
|
return {name: "UNAVAILABLE" for name in names}
|
||||||
|
|||||||
@@ -512,8 +512,9 @@ class DesktopWorker:
|
|||||||
def bind_session(self, job):
|
def bind_session(self, job):
|
||||||
from .session_record import register_worker_session
|
from .session_record import register_worker_session
|
||||||
from .library_lock import duplicate_worker_lease
|
from .library_lock import duplicate_worker_lease
|
||||||
lease = (None if job.get('inspection_only') is True else
|
read_only = (job.get('inspection_only') is True or
|
||||||
duplicate_worker_lease(job['library'], self.handle))
|
(job.get('operation') == 'catalog' and job.get('worker_role') == 'catalog_readonly'))
|
||||||
|
lease = None if read_only else duplicate_worker_lease(job['library'], self.handle)
|
||||||
register_worker_session(self, {**job, 'worker_lease_handle': lease})
|
register_worker_session(self, {**job, 'worker_lease_handle': lease})
|
||||||
|
|
||||||
def native_write_pending(self):
|
def native_write_pending(self):
|
||||||
|
|||||||
@@ -43,7 +43,9 @@ def _cancel_target(snapshot):
|
|||||||
from .post_repair_consent import exact_prompt
|
from .post_repair_consent import exact_prompt
|
||||||
from .dialog_rules import pcb_version_choice
|
from .dialog_rules import pcb_version_choice
|
||||||
if exact_prompt(snapshot):
|
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
|
text = ' '.join(' '.join(c.name for c in snapshot.controls
|
||||||
if c.class_name == 'Static').split())
|
if c.class_name == 'Static').split())
|
||||||
buttons = [c for c in snapshot.controls if c.class_name == 'Button']
|
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
|
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):
|
def cancelled_prewrite_startup(job, pcb_pid=None):
|
||||||
"""Positive ordinary pre-document cancellation proof; absence of Save is insufficient."""
|
"""Positive ordinary pre-document cancellation proof; absence of Save is insufficient."""
|
||||||
from .session_record import IDENTITY_KEYS, read_session_record
|
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_hwnd = None
|
||||||
declined_kind = None
|
declined_kind = None
|
||||||
cancelled_open = _database_log_declined(root, pcb_pid)
|
cancelled_open = _database_log_declined(root, pcb_pid)
|
||||||
|
decline_owner = None
|
||||||
dismissed_tips = set()
|
dismissed_tips = set()
|
||||||
close_handle = None
|
close_handle = None
|
||||||
close_identity = 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 residual_sessions._handle_identity(close_handle) != close_identity
|
||||||
or win32process.GetWindowThreadProcessId(hwnd)[1] != pcb_pid):
|
or win32process.GetWindowThreadProcessId(hwnd)[1] != pcb_pid):
|
||||||
raise ValueError('STARTUP_ACTION_UNCONFIRMED')
|
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)
|
win32gui.PostMessage(hwnd, message, 0, 0)
|
||||||
while True:
|
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]
|
records = [r for r in _process_details('ExpeditionPCB.exe') if r[0] == pcb_pid]
|
||||||
if not records:
|
if not records:
|
||||||
if (close_handle is not None
|
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,
|
result['release'] = {'pcb_exited': True, 'launcher_exited': launcher_exited,
|
||||||
'addresses': addresses,
|
'addresses': addresses,
|
||||||
'safe_to_continue': launcher_exited and (cancelled_open or not 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']:
|
if result['release']['safe_to_continue']:
|
||||||
result['status'] = 'CLOSED'
|
result['status'] = 'CLOSED'
|
||||||
result.pop('detail', None)
|
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)
|
close_identity = residual_sessions._handle_identity(close_handle)
|
||||||
if Path(close_identity['image']).name.casefold() != 'expeditionpcb.exe':
|
if Path(close_identity['image']).name.casefold() != 'expeditionpcb.exe':
|
||||||
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
|
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)
|
cleanup_post(main[0],win32con.WM_CLOSE)
|
||||||
else:
|
else:
|
||||||
win32gui.PostMessage(main[0], win32con.WM_CLOSE, 0, 0)
|
win32gui.PostMessage(main[0], win32con.WM_CLOSE, 0, 0)
|
||||||
|
|||||||
@@ -77,10 +77,15 @@ def _snapshot(library, roots):
|
|||||||
raise ValueError('目标库身份缺失')
|
raise ValueError('目标库身份缺失')
|
||||||
addresses = sorted(path for path in entries if path.name.casefold() == 'saddress.adr')
|
addresses = sorted(path for path in entries if path.name.casefold() == 'saddress.adr')
|
||||||
targets, signatures = [], {}
|
targets, signatures = [], {}
|
||||||
|
from .icdb_ownership import shared_symbol_database
|
||||||
|
shared = shared_symbol_database(library)
|
||||||
for address in addresses:
|
for address in addresses:
|
||||||
data = address.read_bytes()
|
data = address.read_bytes()
|
||||||
signatures[str(address)] = hashlib.sha256(data).hexdigest()
|
signatures[str(address)] = hashlib.sha256(data).hexdigest()
|
||||||
database = address.parent.parent
|
database = address.parent.parent
|
||||||
|
if address == shared/'cdbsvr/sAddress.adr' and shared/'icdb.dat' in native:
|
||||||
|
targets.append({'scope': 'shared_symbols', 'database': str(shared), 'address': str(address)})
|
||||||
|
continue
|
||||||
matches = []
|
matches = []
|
||||||
for project in database.parent.glob('*.prj'):
|
for project in database.parent.glob('*.prj'):
|
||||||
if project not in entries or project.stat().st_size > 1024*1024:
|
if project not in entries or project.stat().st_size > 1024*1024:
|
||||||
|
|||||||
@@ -8,18 +8,22 @@ def session_resource_scope(job):
|
|||||||
project, pcb = job.get('project'), job.get('pcb')
|
project, pcb = job.get('project'), job.get('pcb')
|
||||||
projects = [str(Path(project))] if project else []
|
projects = [str(Path(project))] if project else []
|
||||||
databases = [str(Path(p).parent/'database') for p in (project, pcb) if p]
|
databases = [str(Path(p).parent/'database') for p in (project, pcb) if p]
|
||||||
shared = library.parent/'SymbolLibs/__ReusableBlocksSymb'
|
shared = shared_symbol_database(library)
|
||||||
return {'scope_state': 'DECLARED' if project else 'RECHECK_REQUIRED',
|
return {'scope_state': 'DECLARED' if project else 'RECHECK_REQUIRED',
|
||||||
'library': str(library), 'operation_id': job.get('operation_id'),
|
'library': str(library), 'operation_id': job.get('operation_id'),
|
||||||
'block_name': job.get('block'), 'projects': projects,
|
'block_name': job.get('block'), 'projects': projects,
|
||||||
'databases': list(dict.fromkeys(databases)), 'shared_dependencies': [str(shared)]}
|
'databases': list(dict.fromkeys(databases)), 'shared_dependencies': [str(shared)]}
|
||||||
|
|
||||||
|
|
||||||
|
def shared_symbol_database(library):
|
||||||
|
return Path(library).parent/'SymbolLibs/__ReusableBlocksSymb'
|
||||||
|
|
||||||
|
|
||||||
def database_directories(lmc_file, project, pcb):
|
def database_directories(lmc_file, project, pcb):
|
||||||
return tuple(dict.fromkeys((
|
return tuple(dict.fromkeys((
|
||||||
Path(project).parent/'database',
|
Path(project).parent/'database',
|
||||||
Path(pcb).parent/'database',
|
Path(pcb).parent/'database',
|
||||||
Path(lmc_file).parent/'SymbolLibs/__ReusableBlocksSymb',
|
shared_symbol_database(lmc_file),
|
||||||
)))
|
)))
|
||||||
|
|
||||||
|
|
||||||
@@ -37,6 +41,9 @@ def inspect_release_addresses(snapshot, *, stop=None):
|
|||||||
from .library_lock import LibraryBusy
|
from .library_lock import LibraryBusy
|
||||||
results = []
|
results = []
|
||||||
for item in snapshot['inspection_targets']:
|
for item in snapshot['inspection_targets']:
|
||||||
|
if item.get('scope') == 'shared_symbols':
|
||||||
|
raise LibraryBusy('SHARED_ICDB_INSPECTION_UNAVAILABLE: 共享符号库地址需要原生核对:'
|
||||||
|
+ item['address'])
|
||||||
target = RepairTarget(Path(item['project']), Path(item['database']))
|
target = RepairTarget(Path(item['project']), Path(item['database']))
|
||||||
root = Path(tempfile.mkdtemp(prefix='cbb-release-inspection-'))
|
root = Path(tempfile.mkdtemp(prefix='cbb-release-inspection-'))
|
||||||
result = run_native_repair(target, root, inspection_only=True, stop=stop)
|
result = run_native_repair(target, root, inspection_only=True, stop=stop)
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import logging
|
|||||||
import json
|
import json
|
||||||
from collections import Counter, defaultdict
|
from collections import Counter, defaultdict
|
||||||
from .models import CbbRecord, LibraryReadResult
|
from .models import CbbRecord, LibraryReadResult
|
||||||
from .network_path import absolute_preserving_drive
|
from .network_path import absolute_preserving_drive, validate_library_file
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
CACHE_SCHEMA_VERSION = 2
|
CACHE_SCHEMA_VERSION = 2
|
||||||
@@ -206,15 +206,7 @@ def read_library_fast(path: Path, *, status_reader=None):
|
|||||||
"""Discover directories; this does not validate native format/registration."""
|
"""Discover directories; this does not validate native format/registration."""
|
||||||
try:
|
try:
|
||||||
path = Path(path)
|
path = Path(path)
|
||||||
if path.suffix.casefold() != '.lmc':
|
validate_library_file(path)
|
||||||
return LibraryReadResult((), 'INPUT_SUFFIX: 请选择 .lmc 中心库文件。')
|
|
||||||
if not path.is_file():
|
|
||||||
return LibraryReadResult((), f'INPUT_MISSING: 中心库不存在或不是文件: {path}')
|
|
||||||
with path.open('rb') as stream:
|
|
||||||
if not stream.read(1):
|
|
||||||
return LibraryReadResult((), 'INPUT_EMPTY: 中心库文件为空。')
|
|
||||||
if any(lock.is_dir() for lock in (path.with_suffix('.lock'), path.with_name('.'+path.stem+'.cbb-upload.lock'))):
|
|
||||||
return LibraryReadResult((), 'INPUT_LOCK_DIRECTORY: 中心库锁路径是目录。')
|
|
||||||
folder = path.parent/'ReusableBlocksLP'
|
folder = path.parent/'ReusableBlocksLP'
|
||||||
if folder.exists() and not folder.is_dir():
|
if folder.exists() and not folder.is_dir():
|
||||||
return LibraryReadResult((), f'INPUT_DIRECTORY: ReusableBlocksLP 不是目录: {folder}')
|
return LibraryReadResult((), f'INPUT_DIRECTORY: ReusableBlocksLP 不是目录: {folder}')
|
||||||
|
|||||||
@@ -0,0 +1,171 @@
|
|||||||
|
"""Preserve one generated PCB Cell Library after a bound integration failure."""
|
||||||
|
from contextlib import contextmanager, ExitStack
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import stat
|
||||||
|
|
||||||
|
|
||||||
|
def _cache_paths(pcb):
|
||||||
|
cache = Path(pcb).parent/'Work/Layout_Temp'
|
||||||
|
return cache, cache/'JobPrefsDB.jpf'
|
||||||
|
|
||||||
|
|
||||||
|
def _cache_identity(cache):
|
||||||
|
metadata = cache.lstat()
|
||||||
|
if not stat.S_ISDIR(metadata.st_mode) or metadata.st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
|
||||||
|
raise ValueError('本地 Cell Library 不是普通目录')
|
||||||
|
if cache.resolve(strict=True) != cache:
|
||||||
|
raise ValueError('本地 Cell Library 路径含链接')
|
||||||
|
return {'device': metadata.st_dev, 'file_id': metadata.st_ino,
|
||||||
|
'created_ns': metadata.st_ctime_ns}
|
||||||
|
|
||||||
|
|
||||||
|
def _digest(path):
|
||||||
|
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def capture_binding_change(job, config, emit):
|
||||||
|
"""Keep the exact changed pcb.prj and the pre-launch generated directory identity."""
|
||||||
|
from .management import _write_json
|
||||||
|
|
||||||
|
cache, preferences = _cache_paths(job['pcb'])
|
||||||
|
if not preferences.is_file():
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
record = {key: str(job[key]) for key in ('operation_id', 'project', 'pcb', 'lmc_file', 'block_name')}
|
||||||
|
record.update(config=str(config), config_sha256=_digest(config), original_cache=_cache_identity(cache))
|
||||||
|
_write_json(Path(job['root'])/'local-cell-library-binding.json', record)
|
||||||
|
except (OSError, ValueError, KeyError) as error:
|
||||||
|
emit(stage='local_cell_library_binding_unavailable', detail=str(error))
|
||||||
|
|
||||||
|
|
||||||
|
def _explicit_cache_error(text, preferences):
|
||||||
|
native = str(text).replace('/', '\\').casefold()
|
||||||
|
path = str(preferences).replace('/', '\\').casefold()
|
||||||
|
return ('could not load job preferences db' in native and 'unable to create local cell library' in native
|
||||||
|
and re.search(re.escape(path) + r'(?![\w.\\/])', native) is not None)
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def _hold_primary_files(proof, cache, required):
|
||||||
|
"""Keep the proven databases protected while moving the generated directory."""
|
||||||
|
import win32con
|
||||||
|
import win32file
|
||||||
|
|
||||||
|
paths = {Path(p) for p in proof['exclusive_files'] if not Path(p).is_relative_to(cache)}
|
||||||
|
if not required <= paths:
|
||||||
|
raise ValueError('缺少主要工程文件占用证明')
|
||||||
|
with ExitStack() as stack:
|
||||||
|
for path in sorted(paths):
|
||||||
|
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
|
||||||
|
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
|
||||||
|
stack.callback(handle.Close)
|
||||||
|
for name, digest in proof['signatures'].items():
|
||||||
|
path = Path(name)
|
||||||
|
if not path.is_relative_to(cache):
|
||||||
|
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, win32con.FILE_SHARE_READ, None,
|
||||||
|
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
|
||||||
|
stack.callback(handle.Close)
|
||||||
|
if _digest(path) != digest:
|
||||||
|
raise ValueError('会话地址或工程绑定已变化')
|
||||||
|
yield
|
||||||
|
|
||||||
|
|
||||||
|
def preserve_failed_cache(request, result, *, stop=None):
|
||||||
|
"""After clean exit, preserve generated files and return one retry's receipt."""
|
||||||
|
if not result.safe_to_continue or not result.evidence_path or (stop is not None and stop.is_set()):
|
||||||
|
return None
|
||||||
|
import pywintypes
|
||||||
|
from .backup_recovery import _project_text
|
||||||
|
from .library_lock import _prove_library_released
|
||||||
|
from .management import _write_json
|
||||||
|
from .mentor_adapter import _CENTRAL_LIBRARY_KEY
|
||||||
|
from .operation_queue import QueueCancelled, check_active, local_commit
|
||||||
|
from .scoped_manifest import scan_tree
|
||||||
|
from .verify_runner import preflight
|
||||||
|
|
||||||
|
root = Path(result.evidence_path).parent
|
||||||
|
receipt_path = root/'local-cell-library-retry.json'
|
||||||
|
binding_path = root/'local-cell-library-binding.json'
|
||||||
|
if not binding_path.is_file() or receipt_path.exists():
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
job = json.loads((root/'request.json').read_text(encoding='utf-8'))
|
||||||
|
binding = json.loads(binding_path.read_text(encoding='utf-8'))
|
||||||
|
project, pcb = preflight(request)
|
||||||
|
if (binding.get('operation_id') != job.get('operation_id') or not job.get('operation_id')
|
||||||
|
or binding.get('block_name') != request.block_name
|
||||||
|
or any(not binding.get(key) or Path(binding[key]).resolve() != Path(path).resolve()
|
||||||
|
for key, path in [('lmc_file', request.lmc_file), ('project', project), ('pcb', pcb)])):
|
||||||
|
return None
|
||||||
|
cache, preferences = _cache_paths(pcb)
|
||||||
|
config = pcb.with_name('pcb.prj')
|
||||||
|
if not _explicit_cache_error(result.stderr, preferences):
|
||||||
|
return None
|
||||||
|
events = [json.loads(line) for line in (root/'events.jsonl').read_text(encoding='utf-8').splitlines()]
|
||||||
|
stages = {event.get('stage') for event in events}
|
||||||
|
identity_bound = any(event.get('stage') == 'identity_verified'
|
||||||
|
and Path(event.get('project') or '.').resolve() == project.resolve()
|
||||||
|
and Path(event.get('document') or '.').name.casefold() == pcb.name.casefold()
|
||||||
|
for event in events)
|
||||||
|
if (not identity_bound
|
||||||
|
or not any(event.get('stage') == 'central_library_path' and event.get('status') == 'UPDATED'
|
||||||
|
and Path(event.get('path') or '.').resolve() == config.resolve()
|
||||||
|
and Path(event.get('target') or '.').resolve() == Path(request.lmc_file).resolve()
|
||||||
|
for event in events)
|
||||||
|
or stages.intersection({'save_start', 'save_helper', 'save_progress', 'saved_and_closed'})
|
||||||
|
or (root/'save.log').exists()
|
||||||
|
or not any(event.get('stage') == 'integration_error'
|
||||||
|
and _explicit_cache_error(event.get('detail'), preferences) for event in events)):
|
||||||
|
return None
|
||||||
|
|
||||||
|
def validate_binding():
|
||||||
|
if (config.resolve(strict=True) != config or config != Path(binding['config'])
|
||||||
|
or _digest(config) != binding['config_sha256'] or _cache_identity(cache) != binding['original_cache']):
|
||||||
|
raise ValueError('PCB 项目绑定或生成目录身份已变化')
|
||||||
|
references = _CENTRAL_LIBRARY_KEY.findall(_project_text(config))
|
||||||
|
if not references or any((config.parent/target).resolve() != Path(request.lmc_file).resolve()
|
||||||
|
for _, target, _ in references):
|
||||||
|
raise ValueError('PCB 项目未绑定当前中心库')
|
||||||
|
members = scan_tree(cache, check=check_active)
|
||||||
|
if not all(path in members and stat.S_ISREG(members[path].st_mode)
|
||||||
|
for path in (preferences, cache/'CellDB.cel')):
|
||||||
|
raise ValueError('未确认 Mentor 生成的本地 Cell Library 文件')
|
||||||
|
|
||||||
|
validate_binding()
|
||||||
|
with _prove_library_released(request.lmc_file, block_name=request.block_name, stop=stop) as proof:
|
||||||
|
if proof.get('data_recovery_required') is True or proof.get('blocked_resources'):
|
||||||
|
raise ValueError('数据库资源仍待确认')
|
||||||
|
# Windows cannot rename this directory while an exclusive handle to
|
||||||
|
# its generated LayoutDB is held. The current library lease stays held.
|
||||||
|
validate_binding()
|
||||||
|
|
||||||
|
preserved = project.parent.parent/('Layout_Temp.before-rebuild-' + root.name)
|
||||||
|
if os.path.lexists(preserved):
|
||||||
|
return None
|
||||||
|
receipt = {'kind': 'LOCAL_CELL_LIBRARY_RETRY', 'status': 'PRESERVE_REQUESTED',
|
||||||
|
'original_operation_id': binding['operation_id'],
|
||||||
|
'initial_evidence': str(result.evidence_path), 'cache': str(cache),
|
||||||
|
'preserved_name': preserved.name, 'preserved_path': str(preserved)}
|
||||||
|
_write_json(receipt_path, receipt)
|
||||||
|
required = {Path(request.lmc_file).resolve(), (pcb.parent/'Layout/LayoutDB.lyt').resolve()}
|
||||||
|
with _hold_primary_files(proof, cache, required), local_commit():
|
||||||
|
if stop is not None and stop.is_set():
|
||||||
|
return None
|
||||||
|
validate_binding()
|
||||||
|
cache.rename(preserved)
|
||||||
|
receipt['status'] = 'PRESERVED'
|
||||||
|
_write_json(receipt_path, receipt)
|
||||||
|
return receipt
|
||||||
|
except QueueCancelled:
|
||||||
|
raise
|
||||||
|
except (OSError, ValueError, KeyError, TypeError, RuntimeError, pywintypes.error) as error:
|
||||||
|
try:
|
||||||
|
_write_json(root/'local-cell-library-retry-unavailable.json', {
|
||||||
|
'initial_evidence': str(result.evidence_path), 'detail': str(error)})
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
return None
|
||||||
@@ -709,8 +709,11 @@ def execute_job(job, emit):
|
|||||||
else:
|
else:
|
||||||
from .maintenance_entry import maintenance_project_files
|
from .maintenance_entry import maintenance_project_files
|
||||||
for index, config in enumerate(maintenance_project_files(job['project'], job['pcb'])):
|
for index, config in enumerate(maintenance_project_files(job['project'], job['pcb'])):
|
||||||
ensure_project_central_library(config, job['lmc_file'],
|
changed = ensure_project_central_library(config, job['lmc_file'],
|
||||||
evidence_dir=Path(root)/'diagnostics'/f'project-{index}', emit=emit)
|
evidence_dir=Path(root)/'diagnostics'/f'project-{index}', emit=emit)
|
||||||
|
if changed and prewrite_eligible and config == Path(job['pcb']).with_name('pcb.prj'):
|
||||||
|
from .local_cell_library import capture_binding_change
|
||||||
|
capture_binding_change(job, config, emit)
|
||||||
if prewrite_eligible:
|
if prewrite_eligible:
|
||||||
from .diagnostic_open import snapshot_diagnostic_logs
|
from .diagnostic_open import snapshot_diagnostic_logs
|
||||||
from .session_record import process_identity
|
from .session_record import process_identity
|
||||||
|
|||||||
@@ -24,9 +24,10 @@ _retained_workers = []
|
|||||||
|
|
||||||
|
|
||||||
class NativeOperationError(RuntimeError):
|
class NativeOperationError(RuntimeError):
|
||||||
def __init__(self, detail, *, safe_to_continue):
|
def __init__(self, detail, *, safe_to_continue, blocking_manager_pids=()):
|
||||||
super().__init__(detail)
|
super().__init__(detail)
|
||||||
self.safe_to_continue = safe_to_continue
|
self.safe_to_continue = safe_to_continue
|
||||||
|
self.blocking_manager_pids = tuple(blocking_manager_pids)
|
||||||
# Coordinator-owned Create/Add/conflict/update/remove/backup-reimport evidence:
|
# Coordinator-owned Create/Add/conflict/update/remove/backup-reimport evidence:
|
||||||
# diagnostics/issue2-native-crud-20261103/engine-e2e/cycle-result.json
|
# diagnostics/issue2-native-crud-20261103/engine-e2e/cycle-result.json
|
||||||
_PRODUCTION_ADD_VALIDATED = True
|
_PRODUCTION_ADD_VALIDATED = True
|
||||||
@@ -245,13 +246,17 @@ class NativeManagementAdapter:
|
|||||||
if hasattr(worker, 'bind_session'):
|
if hasattr(worker, 'bind_session'):
|
||||||
worker.bind_session(job)
|
worker.bind_session(job)
|
||||||
from contextlib import nullcontext
|
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.
|
# 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:
|
with channel:
|
||||||
commit_worker_start(worker, job)
|
commit_worker_start(worker, job)
|
||||||
while worker.poll() is None and time.monotonic() < deadline:
|
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()
|
Path(job['cancel_signal']).touch()
|
||||||
break
|
break
|
||||||
time.sleep(.1)
|
time.sleep(.1)
|
||||||
@@ -268,8 +273,9 @@ class NativeManagementAdapter:
|
|||||||
if self.session_progress is not None else None)
|
if self.session_progress is not None else None)
|
||||||
if add_job:
|
if add_job:
|
||||||
(evidence/'cancel-native-add.signal').touch()
|
(evidence/'cancel-native-add.signal').touch()
|
||||||
|
reason = 'CANCELLED' if cancelled else 'TIMEOUT'
|
||||||
return {'success': False, 'safe_to_continue': False,
|
return {'success': False, 'safe_to_continue': False,
|
||||||
'detail': f'TIMEOUT: 原生调用尚未返回,保留私有桌面 {desktop},请检查 {evidence}'}
|
'detail': f'{reason}: 原生调用尚未返回,保留私有桌面 {desktop},请检查 {evidence}'}
|
||||||
try:
|
try:
|
||||||
result = json.loads((evidence/'result.json').read_text(encoding='utf-8'))
|
result = json.loads((evidence/'result.json').read_text(encoding='utf-8'))
|
||||||
if not isinstance(result.get('safe_to_continue'), bool):
|
if not isinstance(result.get('safe_to_continue'), bool):
|
||||||
@@ -281,15 +287,20 @@ class NativeManagementAdapter:
|
|||||||
finally:
|
finally:
|
||||||
worker.close()
|
worker.close()
|
||||||
|
|
||||||
def catalog(self, library, evidence):
|
def catalog(self, library, evidence, *, include_engineering_identity=True):
|
||||||
result = self._worker({'operation': 'catalog', 'worker_role': 'catalog_readonly',
|
result = self._worker({'operation': 'catalog', 'worker_role': 'catalog_readonly',
|
||||||
'library': str(absolute_preserving_drive(library))}, evidence)
|
'library': str(absolute_preserving_drive(library)),
|
||||||
|
'include_engineering_identity': include_engineering_identity}, evidence)
|
||||||
if not result.get('success') or not result.get('safe_to_continue'):
|
if not result.get('success') or not result.get('safe_to_continue'):
|
||||||
raise NativeOperationError(result.get('detail', '原生目录复读未确认,禁止文件夹回退。'),
|
raise NativeOperationError(result.get('detail', '原生目录复读未确认,禁止文件夹回退。'),
|
||||||
safe_to_continue=result.get('safe_to_continue') is True)
|
safe_to_continue=result.get('safe_to_continue') is True,
|
||||||
|
blocking_manager_pids=result.get('blocking_manager_pids', ()))
|
||||||
return Catalog(Path(result['library']), int(result['flow']),
|
return Catalog(Path(result['library']), int(result['flow']),
|
||||||
tuple(CatalogEntry(**entry) for entry in result['entries']), result['safe_to_continue'])
|
tuple(CatalogEntry(**entry) for entry in result['entries']), result['safe_to_continue'])
|
||||||
|
|
||||||
|
def catalog_registrations(self, library, evidence):
|
||||||
|
return self.catalog(library, evidence, include_engineering_identity=False)
|
||||||
|
|
||||||
def remove(self, request, evidence):
|
def remove(self, request, evidence):
|
||||||
caps = self.capabilities()
|
caps = self.capabilities()
|
||||||
if not caps['remove'].supported:
|
if not caps['remove'].supported:
|
||||||
@@ -1082,6 +1093,77 @@ def _wait_native_exit(pids, timeout=10):
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def _catalog_shared_dependencies(library):
|
||||||
|
from .icdb_ownership import shared_symbol_database
|
||||||
|
database = shared_symbol_database(library) / 'icdb.dat'
|
||||||
|
try:
|
||||||
|
info = database.stat()
|
||||||
|
except FileNotFoundError:
|
||||||
|
return set()
|
||||||
|
return {(info.st_dev, info.st_ino, database.resolve())}
|
||||||
|
|
||||||
|
|
||||||
|
def _probe_catalog_files(library):
|
||||||
|
import pywintypes, win32con, win32file
|
||||||
|
from contextlib import ExitStack
|
||||||
|
|
||||||
|
with ExitStack() as handles:
|
||||||
|
paths = (library, *(path for _, _, path in _catalog_shared_dependencies(library)))
|
||||||
|
for path in paths:
|
||||||
|
try:
|
||||||
|
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
|
||||||
|
win32con.OPEN_EXISTING, 0, None)
|
||||||
|
except (OSError, pywintypes.error) as error:
|
||||||
|
raise OSError(f'{path}:{error}') from error
|
||||||
|
handles.callback(handle.Close)
|
||||||
|
|
||||||
|
|
||||||
|
def _open_catalog_manager_library(pid):
|
||||||
|
from .residual_sessions import _process_windows, _window_error
|
||||||
|
|
||||||
|
windows = _process_windows({pid})
|
||||||
|
if _window_error(windows, pid):
|
||||||
|
return None
|
||||||
|
paths = set()
|
||||||
|
for window in windows[pid]:
|
||||||
|
title = window['title']
|
||||||
|
if title.startswith('Library Manager: '):
|
||||||
|
path = Path(title.removeprefix('Library Manager: ').strip())
|
||||||
|
if path.is_absolute() and path.suffix.casefold() == '.lmc':
|
||||||
|
paths.add(path)
|
||||||
|
return next(iter(paths)) if len(paths) == 1 else None
|
||||||
|
|
||||||
|
|
||||||
|
def _check_catalog_owners(library, processes):
|
||||||
|
"""A foreign LM is compatible only with a disjoint library and free target resources."""
|
||||||
|
library = Path(library).resolve()
|
||||||
|
manager_pids = [pid for pid, *_ in processes]
|
||||||
|
target_dependencies = _catalog_shared_dependencies(library)
|
||||||
|
for pid in manager_pids:
|
||||||
|
try:
|
||||||
|
current = _open_catalog_manager_library(pid)
|
||||||
|
if current is None:
|
||||||
|
detail = '无法确认已运行的 Library Manager 对应哪个库'
|
||||||
|
else:
|
||||||
|
other = current.resolve(strict=True)
|
||||||
|
if library.samefile(other):
|
||||||
|
detail = '当前库已在另一个 Library Manager 中打开'
|
||||||
|
elif any(left[2] == right[2] or (left[1] and left[:2] == right[:2])
|
||||||
|
for left in target_dependencies for right in _catalog_shared_dependencies(other)):
|
||||||
|
detail = '另一个 Library Manager 正在使用相同的共享符号库'
|
||||||
|
else:
|
||||||
|
continue
|
||||||
|
except (OSError, ValueError) as error:
|
||||||
|
detail = f'无法确认另一中心库的资源范围:{error}'
|
||||||
|
raise NativeOperationError(f'LIBRARY_MANAGER_BUSY: PID {pid} · {detail}。',
|
||||||
|
safe_to_continue=True, blocking_manager_pids=(pid,))
|
||||||
|
try:
|
||||||
|
_probe_catalog_files(library)
|
||||||
|
except OSError as error:
|
||||||
|
raise NativeOperationError(f'LIBRARY_MANAGER_BUSY: PID {manager_pids} · 当前库资源占用未确认:{error}',
|
||||||
|
safe_to_continue=True, blocking_manager_pids=manager_pids) from error
|
||||||
|
|
||||||
|
|
||||||
def _catalog_native(job, root):
|
def _catalog_native(job, root):
|
||||||
import gc, pythoncom
|
import gc, pythoncom
|
||||||
from .com_runtime import initialize_com, uninitialize_com
|
from .com_runtime import initialize_com, uninitialize_com
|
||||||
@@ -1097,7 +1179,8 @@ def _catalog_native(job, root):
|
|||||||
uninitialize_com(initialized)
|
uninitialize_com(initialized)
|
||||||
# A failed COM activation can have created an unaccounted server. An empty
|
# A failed COM activation can have created an unaccounted server. An empty
|
||||||
# PID list is missing release evidence, not proof that nothing was launched.
|
# PID list is missing release evidence, not proof that nothing was launched.
|
||||||
result['safe_to_continue'] = bool(result.get('native_pids')) and _wait_native_exit(result['native_pids'])
|
result['safe_to_continue'] = bool(result.get('no_new_manager') or (
|
||||||
|
result.get('native_pids') and _wait_native_exit(result['native_pids'])))
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
@@ -1116,8 +1199,16 @@ def _catalog_com(job, root):
|
|||||||
desktop, name = _current_desktop()
|
desktop, name = _current_desktop()
|
||||||
if name != job['desktop'] or not name.startswith('CbbManagement_'):
|
if name != job['desktop'] or not name.startswith('CbbManagement_'):
|
||||||
raise RuntimeError('拒绝在非本次私有桌面读取原生目录。')
|
raise RuntimeError('拒绝在非本次私有桌面读取原生目录。')
|
||||||
if _process_details('LibraryManager.exe'):
|
previous_managers = _process_details('LibraryManager.exe')
|
||||||
raise RuntimeError('已有 Library Manager 运行,请关闭后重试。')
|
if previous_managers:
|
||||||
|
if job.get('worker_role') != 'catalog_readonly' or job.get('include_engineering_identity', True):
|
||||||
|
raise RuntimeError('LIBRARY_MANAGER_BUSY: 已有 Library Manager 运行,请关闭后重试。')
|
||||||
|
expected = Path(job['mentor_home'])/'lm/win32/bin/LibraryManager.exe'
|
||||||
|
if hash_file(expected) != _BINARY_PROOF['lm/win32/bin/LibraryManager.exe']:
|
||||||
|
pids = sorted(pid for pid, *_ in previous_managers)
|
||||||
|
raise NativeOperationError(f'LIBRARY_MANAGER_BUSY: PID {pids} · 当前安装尚未验证并行目录读取。',
|
||||||
|
safe_to_continue=True, blocking_manager_pids=pids)
|
||||||
|
_check_catalog_owners(job['library'], previous_managers)
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
error.safe_to_continue = True
|
error.safe_to_continue = True
|
||||||
raise
|
raise
|
||||||
@@ -1173,16 +1264,26 @@ def _catalog_com(job, root):
|
|||||||
# Keep the launch pending until its exact native identity is recorded.
|
# Keep the launch pending until its exact native identity is recorded.
|
||||||
app = dispatch_native(job, lambda: win32com.client.DispatchEx('LibraryManager.Application'),
|
app = dispatch_native(job, lambda: win32com.client.DispatchEx('LibraryManager.Application'),
|
||||||
asynchronous=True)
|
asynchronous=True)
|
||||||
app.Visible = True
|
|
||||||
processes = _process_details('LibraryManager.exe')
|
processes = _process_details('LibraryManager.exe')
|
||||||
owned_pids.update(int(p[0]) for p in processes)
|
previous_pids = {pid for pid, *_ in previous_managers}
|
||||||
from .session_record import update_worker_state
|
new_processes = [process for process in processes if process[0] not in previous_pids]
|
||||||
update_worker_state(job, 'POSTCALL', identities=[('native', pid) for pid in owned_pids])
|
if not new_processes and previous_pids and {p[0] for p in processes} == previous_pids:
|
||||||
if len(owned_pids) != 1:
|
# DispatchEx reused an existing instance. Drop this proxy without invoking any method.
|
||||||
|
result.update(no_new_manager=True, blocking_manager_pids=sorted(previous_pids))
|
||||||
|
raise RuntimeError(f'LIBRARY_MANAGER_BUSY: 当前 COM 注册复用了已有 Library Manager,PID {sorted(previous_pids)}。')
|
||||||
|
if len(new_processes) != 1:
|
||||||
raise RuntimeError('无法唯一确认本次 Library Manager 进程。')
|
raise RuntimeError('无法唯一确认本次 Library Manager 进程。')
|
||||||
|
pid, executable, *_ = new_processes[0]
|
||||||
expected_binary = Path(job['mentor_home'])/'lm/win32/bin/LibraryManager.exe'
|
expected_binary = Path(job['mentor_home'])/'lm/win32/bin/LibraryManager.exe'
|
||||||
if Path(processes[0][1]).resolve() != expected_binary.resolve():
|
if Path(executable).resolve() != expected_binary.resolve():
|
||||||
raise RuntimeError('COM 注册指向不同的 Library Manager 安装,拒绝打开中心库。')
|
raise RuntimeError('COM 注册指向不同的 Library Manager 安装,拒绝打开中心库。')
|
||||||
|
if job.get('session_record_path') or previous_pids:
|
||||||
|
desktop_pids = {win32process.GetWindowThreadProcessId(hwnd)[1] for hwnd in desktop.EnumDesktopWindows()}
|
||||||
|
if pid not in desktop_pids:
|
||||||
|
raise RuntimeError('无法确认新 Library Manager 位于本次私有桌面。')
|
||||||
|
owned_pids.add(pid)
|
||||||
|
update_worker_state(job, 'POSTCALL', identities=[('native', pid)])
|
||||||
|
app.Visible = True
|
||||||
watcher = threading.Thread(target=observe_dialogs, daemon=True)
|
watcher = threading.Thread(target=observe_dialogs, daemon=True)
|
||||||
watcher.start()
|
watcher.start()
|
||||||
if job['operation'] in ('probe_create_add', 'probe_create'):
|
if job['operation'] in ('probe_create_add', 'probe_create'):
|
||||||
@@ -1217,17 +1318,20 @@ def _catalog_com(job, root):
|
|||||||
for i in range(1, int(parts.Count) + 1):
|
for i in range(1, int(parts.Count) + 1):
|
||||||
partition = parts.Item(i)
|
partition = parts.Item(i)
|
||||||
for j in range(1, int(partition.Count) + 1):
|
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)
|
item = partition.Item(j)
|
||||||
block_name, partition_name = str(item.Name), str(item.PartitionName)
|
block_name, partition_name = str(item.Name), str(item.PartitionName)
|
||||||
validate_name(block_name)
|
validate_name(block_name)
|
||||||
identity = {}
|
identity = {}
|
||||||
work = Path(job['library']).parent/'ReusableBlocksLP'/block_name/'Work'
|
if job.get('include_engineering_identity', True):
|
||||||
projects = list(work.glob('*.prj'))
|
work = Path(job['library']).parent/'ReusableBlocksLP'/block_name/'Work'
|
||||||
if len(projects) == 1:
|
projects = list(work.glob('*.prj'))
|
||||||
try:
|
if len(projects) == 1:
|
||||||
identity = engineering_identity(projects[0])
|
try:
|
||||||
except (ValueError, OSError):
|
identity = engineering_identity(projects[0])
|
||||||
pass
|
except (ValueError, OSError):
|
||||||
|
pass
|
||||||
entries.append(asdict(CatalogEntry(block_name, partition_name, identity)))
|
entries.append(asdict(CatalogEntry(block_name, partition_name, identity)))
|
||||||
item = None
|
item = None
|
||||||
partition = None
|
partition = None
|
||||||
@@ -1255,7 +1359,7 @@ def _catalog_com(job, root):
|
|||||||
result['close_detail'] = str(error)
|
result['close_detail'] = str(error)
|
||||||
result['close_exception'] = _exception_details(error)
|
result['close_exception'] = _exception_details(error)
|
||||||
library = None
|
library = None
|
||||||
if app is not None and not job.get('_native_add_pending'):
|
if app is not None and owned_pids and not job.get('_native_add_pending'):
|
||||||
try:
|
try:
|
||||||
dispatch_native(job, lambda: app.Quit(), phase='CLOSING')
|
dispatch_native(job, lambda: app.Quit(), phase='CLOSING')
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
@@ -1374,6 +1478,8 @@ def management_worker_main(request_path, *, catalog_readonly=False):
|
|||||||
except Exception as error:
|
except Exception as error:
|
||||||
if getattr(error, 'safe_to_continue', None) is True:
|
if getattr(error, 'safe_to_continue', None) is True:
|
||||||
result['safe_to_continue'] = True
|
result['safe_to_continue'] = True
|
||||||
|
if getattr(error, 'blocking_manager_pids', ()):
|
||||||
|
result['blocking_manager_pids'] = list(error.blocking_manager_pids)
|
||||||
result['detail'] = str(error)
|
result['detail'] = str(error)
|
||||||
result['exception'] = _exception_details(error)
|
result['exception'] = _exception_details(error)
|
||||||
finally:
|
finally:
|
||||||
|
|||||||
@@ -183,22 +183,41 @@ def _normalize_input_path(path) -> str:
|
|||||||
def select_library_file(path) -> Path:
|
def select_library_file(path) -> Path:
|
||||||
"""Return a concrete LMC, accepting a directory with exactly one LMC."""
|
"""Return a concrete LMC, accepting a directory with exactly one LMC."""
|
||||||
candidate = Path(path)
|
candidate = Path(path)
|
||||||
if candidate.is_file():
|
try:
|
||||||
if candidate.suffix.casefold() != ".lmc":
|
if candidate.is_file():
|
||||||
raise NetworkPathError(f"中心库文件必须是 .lmc: {candidate}")
|
if candidate.suffix.casefold() != ".lmc":
|
||||||
return candidate
|
raise NetworkPathError(f"INPUT_SUFFIX: 中心库文件必须是 .lmc: {candidate}")
|
||||||
if candidate.is_dir():
|
return candidate
|
||||||
files = sorted(
|
if candidate.is_dir():
|
||||||
(item for item in candidate.iterdir()
|
files = [item for item in candidate.iterdir()
|
||||||
if item.is_file() and item.suffix.casefold() == ".lmc"),
|
if item.suffix.casefold() == ".lmc" and item.is_file()]
|
||||||
key=lambda item: item.name.casefold(),
|
if len(files) != 1:
|
||||||
)
|
raise NetworkPathError(
|
||||||
if len(files) != 1:
|
f"INPUT_DIRECTORY: 中心库目录必须包含唯一的 .lmc 文件,当前找到 {len(files)} 个: {candidate}"
|
||||||
raise NetworkPathError(
|
)
|
||||||
f"中心库目录必须包含唯一的 .lmc 文件,当前找到 {len(files)} 个: {candidate}"
|
return files[0]
|
||||||
)
|
except PermissionError as error:
|
||||||
return files[0]
|
raise NetworkPathError(f"INPUT_PERMISSION: 无权读取中心库: {candidate}") from error
|
||||||
raise NetworkPathError(f"中心库路径不存在或不可访问: {candidate}")
|
raise NetworkPathError(f"INPUT_MISSING: 中心库路径不存在或不可访问: {candidate}")
|
||||||
|
|
||||||
|
|
||||||
|
def validate_library_file(path: Path) -> None:
|
||||||
|
"""Reject invalid LMC inputs before a directory scan or native dispatch."""
|
||||||
|
if path.suffix.casefold() != '.lmc':
|
||||||
|
raise NetworkPathError(f'INPUT_SUFFIX: 请选择 .lmc 中心库文件: {path}')
|
||||||
|
try:
|
||||||
|
if not path.is_file():
|
||||||
|
raise NetworkPathError(f'INPUT_MISSING: 中心库不存在或不是文件: {path}')
|
||||||
|
with path.open('rb') as stream:
|
||||||
|
if not stream.read(1):
|
||||||
|
raise NetworkPathError(f'INPUT_EMPTY: 中心库文件为空: {path}')
|
||||||
|
if any(lock.is_dir() for lock in
|
||||||
|
(path.with_suffix('.lock'), path.with_name('.' + path.stem + '.cbb-upload.lock'))):
|
||||||
|
raise NetworkPathError(f'INPUT_LOCK_DIRECTORY: 中心库锁路径是目录: {path}')
|
||||||
|
except FileNotFoundError as error:
|
||||||
|
raise NetworkPathError(f'INPUT_MISSING: 中心库不存在: {path}') from error
|
||||||
|
except PermissionError as error:
|
||||||
|
raise NetworkPathError(f'INPUT_PERMISSION: 无权读取中心库: {path}') from error
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
|
|||||||
@@ -13,10 +13,18 @@ class QueueCancelled(RuntimeError):
|
|||||||
|
|
||||||
class QueueUnavailable(RuntimeError):
|
class QueueUnavailable(RuntimeError):
|
||||||
"""Admission failed before action dispatch; this task created no native session."""
|
"""Admission failed before action dispatch; this task created no native session."""
|
||||||
def __init__(self, library):
|
def __init__(self, library, sessions=(), *, timed_out=False):
|
||||||
self.library = str(library)
|
self.library = str(library)
|
||||||
super().__init__('NATIVE_SESSION_PENDING: '+self.library+
|
self.sessions = tuple(sessions)
|
||||||
' 的已登记会话仍在运行或初始化,当前项未启动。')
|
self.timed_out = timed_out
|
||||||
|
details = []
|
||||||
|
for session in self.sessions:
|
||||||
|
block = session.get('block') or '当前库'
|
||||||
|
resources = '、'.join(map(str, session.get('blocked_resources') or ()))
|
||||||
|
details.append(' / '.join(filter(None, (block, session.get('operation_id'),
|
||||||
|
resources, session.get('path')))))
|
||||||
|
message = f'NATIVE_SESSION_PENDING: {self.library} 的已登记会话待释放,当前项未启动。'
|
||||||
|
super().__init__(message + (' ' + ';'.join(details) if details else ''))
|
||||||
|
|
||||||
|
|
||||||
class TaskHandoff(QueueCancelled):
|
class TaskHandoff(QueueCancelled):
|
||||||
@@ -417,8 +425,10 @@ class NativeQueue:
|
|||||||
for context in contexts)
|
for context in contexts)
|
||||||
|
|
||||||
def run(self, action, *, stop=None, waiting=None, ready=lambda: True, wait_state=None,
|
def run(self, action, *, stop=None, waiting=None, ready=lambda: True, wait_state=None,
|
||||||
context=None, timeout_seconds=10, skip_unavailable=False):
|
context=None, timeout_seconds=10, skip_unavailable=False, wait_for_release_seconds=None):
|
||||||
|
release_deadline = None
|
||||||
def available_now():
|
def available_now():
|
||||||
|
nonlocal release_deadline
|
||||||
if not ready():
|
if not ready():
|
||||||
return False
|
return False
|
||||||
if context is None:
|
if context is None:
|
||||||
@@ -426,8 +436,15 @@ class NativeQueue:
|
|||||||
from .session_record import _live_library_available
|
from .session_record import _live_library_available
|
||||||
for path in (context.library, *context.aliases):
|
for path in (context.library, *context.aliases):
|
||||||
if not _live_library_available(path):
|
if not _live_library_available(path):
|
||||||
if skip_unavailable:
|
if skip_unavailable and wait_for_release_seconds is None:
|
||||||
raise QueueUnavailable(path)
|
raise QueueUnavailable(path)
|
||||||
|
if wait_for_release_seconds is not None:
|
||||||
|
now = time.monotonic()
|
||||||
|
if release_deadline is None:
|
||||||
|
release_deadline = now + wait_for_release_seconds
|
||||||
|
if now >= release_deadline:
|
||||||
|
from .session_record import retained_session_states
|
||||||
|
raise QueueUnavailable(path, retained_session_states(path), timed_out=True)
|
||||||
return False
|
return False
|
||||||
return True
|
return True
|
||||||
ticket = [object(), False]
|
ticket = [object(), False]
|
||||||
|
|||||||
@@ -61,7 +61,12 @@ def owner_probe_main(job):
|
|||||||
import pythoncom
|
import pythoncom
|
||||||
import win32com.client
|
import win32com.client
|
||||||
job = Path(job)
|
job = Path(job)
|
||||||
request = json.loads(job.read_text('utf-8'))
|
try:
|
||||||
|
request = json.loads(job.read_text('utf-8'))
|
||||||
|
except (OSError, ValueError):
|
||||||
|
return 1
|
||||||
|
if not isinstance(request, dict):
|
||||||
|
return 1
|
||||||
full_snapshot = request == {'snapshot_version': 1} and type(request.get('snapshot_version')) is int
|
full_snapshot = request == {'snapshot_version': 1} and type(request.get('snapshot_version')) is int
|
||||||
names = request.get('names')
|
names = request.get('names')
|
||||||
if not full_snapshot:
|
if not full_snapshot:
|
||||||
@@ -84,5 +89,8 @@ def owner_probe_main(job):
|
|||||||
response = {'snapshot_version': 1} if full_snapshot else {'names': names}
|
response = {'snapshot_version': 1} if full_snapshot else {'names': names}
|
||||||
job.with_name('result.json').write_text(json.dumps({**response, 'owners': rows}), encoding='utf-8')
|
job.with_name('result.json').write_text(json.dumps({**response, 'owners': rows}), encoding='utf-8')
|
||||||
return 0
|
return 0
|
||||||
|
except OSError:
|
||||||
|
# The supervisor may remove its temporary request while this helper exits.
|
||||||
|
return 1
|
||||||
finally:
|
finally:
|
||||||
pythoncom.CoUninitialize()
|
pythoncom.CoUninitialize()
|
||||||
@@ -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 contextlib import contextmanager, ExitStack
|
||||||
from pathlib import Path
|
from pathlib import Path, PureWindowsPath
|
||||||
|
import re
|
||||||
from threading import Lock
|
from threading import Lock
|
||||||
import time
|
import time
|
||||||
|
|
||||||
@@ -15,8 +16,9 @@ def _prompt_identity(snapshot):
|
|||||||
|
|
||||||
|
|
||||||
class OpenChoice:
|
class OpenChoice:
|
||||||
def __init__(self, block, library):
|
def __init__(self, block, library, *, auto_confirm=False):
|
||||||
self.block, self.library = block, library
|
self.block, self.library = block, library
|
||||||
|
self.auto_confirm = auto_confirm
|
||||||
self.decision = None
|
self.decision = None
|
||||||
self.decision_origin = None
|
self.decision_origin = None
|
||||||
self._lock = Lock()
|
self._lock = Lock()
|
||||||
@@ -26,8 +28,8 @@ class OpenChoice:
|
|||||||
raise ValueError('无效的打开工程选择')
|
raise ValueError('无效的打开工程选择')
|
||||||
with self._lock:
|
with self._lock:
|
||||||
if self.decision is None:
|
if self.decision is None:
|
||||||
self.decision = decision
|
|
||||||
self.decision_origin = origin
|
self.decision_origin = origin
|
||||||
|
self.decision = decision
|
||||||
|
|
||||||
|
|
||||||
def validate_owner(job, target_pid, launcher_pid, worker_pid):
|
def validate_owner(job, target_pid, launcher_pid, worker_pid):
|
||||||
@@ -47,14 +49,15 @@ def validate_owner(job, target_pid, launcher_pid, worker_pid):
|
|||||||
|
|
||||||
|
|
||||||
@contextmanager
|
@contextmanager
|
||||||
def resource_guard(job, allowed_pids):
|
def resource_guard(job, allowed_pids, *, require_complete_proof=False):
|
||||||
import hashlib
|
import hashlib
|
||||||
from .file_probe import hold_release_files
|
from .file_probe import hold_release_files
|
||||||
|
from .icdb_ownership import shared_symbol_database
|
||||||
from .maintenance_entry import maintenance_project_files
|
from .maintenance_entry import maintenance_project_files
|
||||||
from .native_repair import RepairTarget, run_native_repair
|
from .native_repair import RepairTarget, run_native_repair
|
||||||
from .native_occupancy import confirmed_inspection
|
from .native_occupancy import confirmed_inspection
|
||||||
from .session_record import IDENTITY_KEYS
|
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 .management import _write_json
|
||||||
from .owner_probe import query_process_snapshot
|
from .owner_probe import query_process_snapshot
|
||||||
from .library_lock import _owner_is_blocking
|
from .library_lock import _owner_is_blocking
|
||||||
@@ -72,15 +75,59 @@ def resource_guard(job, allowed_pids):
|
|||||||
for row in query_process_snapshot():
|
for row in query_process_snapshot():
|
||||||
if row['pid'] not in allowed_pids and _owner_is_blocking(row, library, roots):
|
if row['pid'] not in allowed_pids and _owner_is_blocking(row, library, roots):
|
||||||
raise ValueError(f'目标还有其他会话,PID={row["pid"]};未确认读写打开。')
|
raise ValueError(f'目标还有其他会话,PID={row["pid"]};未确认读写打开。')
|
||||||
|
check_active()
|
||||||
check()
|
check()
|
||||||
stop = task_stop(None)
|
stop = task_stop(None)
|
||||||
with ExitStack() as stack:
|
with ExitStack() as stack:
|
||||||
files = stack.enter_context(hold_release_files(library, roots, stop=stop))
|
files = stack.enter_context(hold_release_files(library, roots, stop=stop))
|
||||||
inspections = []
|
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 = shared_symbol_database(library)
|
||||||
|
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']:
|
if files['addresses']:
|
||||||
targets = files['inspection_targets']
|
targets = files['inspection_targets']
|
||||||
if any(Path(item['project']).resolve() not in {p.resolve() for p in configs} for item in targets):
|
for item in targets:
|
||||||
raise ValueError('PCB_OPEN_DATABASE_UNCONFIRMED: 地址未绑定实际工程配置,需人工核对')
|
if item.get('scope') == 'shared_symbols':
|
||||||
|
address = Path(item['address'])
|
||||||
|
shared = shared_symbol_database(library).resolve()
|
||||||
|
if (Path(item['database']).resolve() != shared
|
||||||
|
or address.resolve() != shared/'cdbsvr/sAddress.adr'
|
||||||
|
or str(address) not in files['binding_files']
|
||||||
|
or shared/'icdb.dat' not in {Path(p).resolve() for p in files['exclusive_files']}):
|
||||||
|
raise ValueError(f'SHARED_ICDB_BINDING_UNCONFIRMED: {address}')
|
||||||
|
_write_json(Path(job['root'])/'pcb-open-resource-denied.json', {
|
||||||
|
'status': 'SHARED_ICDB_INSPECTION_UNAVAILABLE',
|
||||||
|
'operation_id': job.get('operation_id'), 'library': str(library),
|
||||||
|
'database': str(shared), 'address': str(address),
|
||||||
|
'address_sha256': files['signatures'][str(address)],
|
||||||
|
'exclusive_file_observed': True,
|
||||||
|
})
|
||||||
|
raise ValueError('SHARED_ICDB_INSPECTION_UNAVAILABLE: 共享符号库地址需要原生核对:'+str(address))
|
||||||
|
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.
|
stack.close() # Native inspection must access the DB; repeat exact proof afterwards.
|
||||||
for index, item in enumerate(targets):
|
for index, item in enumerate(targets):
|
||||||
target = RepairTarget(Path(item['project']), Path(item['database']))
|
target = RepairTarget(Path(item['project']), Path(item['database']))
|
||||||
@@ -88,11 +135,15 @@ def resource_guard(job, allowed_pids):
|
|||||||
result = run_native_repair(target, evidence, mentor_bin=job.get('mentor_bin'),
|
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)
|
timeout_seconds=min(45, float(job.get('timeout', 45))), inspection_only=True, stop=stop)
|
||||||
identity = result.get('native_identity') or {}
|
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 identity.get('pid') != result.get('native_pid')
|
||||||
or any(identity.get(key) is None for key in IDENTITY_KEYS)
|
or any(identity.get(key) is None for key in IDENTITY_KEYS)
|
||||||
or not identity.get('image') or not identity.get('owner_sid')):
|
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)
|
inspections.append(result)
|
||||||
current = stack.enter_context(hold_release_files(library, roots, stop=stop))
|
current = stack.enter_context(hold_release_files(library, roots, stop=stop))
|
||||||
if any(current[key] != files[key] for key in (
|
if any(current[key] != files[key] for key in (
|
||||||
@@ -101,6 +152,7 @@ def resource_guard(job, allowed_pids):
|
|||||||
if binding() != original_binding:
|
if binding() != original_binding:
|
||||||
raise ValueError('PCB_OPEN_PROJECT_CHANGED: 原生检查期间工程引用变化')
|
raise ValueError('PCB_OPEN_PROJECT_CHANGED: 原生检查期间工程引用变化')
|
||||||
check()
|
check()
|
||||||
|
check_active()
|
||||||
_write_json(Path(job['root'])/'pcb-open-resource-proof.json', {
|
_write_json(Path(job['root'])/'pcb-open-resource-proof.json', {
|
||||||
'operation_id': job.get('operation_id'), 'library': str(library),
|
'operation_id': job.get('operation_id'), 'library': str(library),
|
||||||
'project': str(project), 'pcb': str(pcb), 'binding': original_binding,
|
'project': str(project), 'pcb': str(pcb), 'binding': original_binding,
|
||||||
@@ -110,8 +162,10 @@ def resource_guard(job, allowed_pids):
|
|||||||
|
|
||||||
|
|
||||||
class OpenController:
|
class OpenController:
|
||||||
def __init__(self, job):
|
def __init__(self, job, *, auto_confirm=False, require_complete_proof=False):
|
||||||
self.job = job
|
self.job = job
|
||||||
|
self.auto_confirm = auto_confirm
|
||||||
|
self.require_complete_proof = require_complete_proof or auto_confirm
|
||||||
self.choice = None
|
self.choice = None
|
||||||
self.original = self.owner = None
|
self.original = self.owner = None
|
||||||
self.sent = False
|
self.sent = False
|
||||||
@@ -120,14 +174,21 @@ class OpenController:
|
|||||||
def handle(self, snapshot, snapshots, *, target_pid, launcher_pid, worker_pid, show, perform):
|
def handle(self, snapshot, snapshots, *, target_pid, launcher_pid, worker_pid, show, perform):
|
||||||
from .dialog_supervisor import DialogPollResult
|
from .dialog_supervisor import DialogPollResult
|
||||||
from .management import _write_json
|
from .management import _write_json
|
||||||
|
from .operation_queue import QueueCancelled, check_active
|
||||||
try:
|
try:
|
||||||
if not exact_prompt(snapshot) or snapshot.pid != target_pid or len(snapshots) != 1:
|
if not exact_prompt(snapshot) or snapshot.pid != target_pid or len(snapshots) != 1:
|
||||||
raise ValueError('PCB_OPEN_PROMPT_CHANGED')
|
raise ValueError('PCB_OPEN_PROMPT_CHANGED')
|
||||||
owner = validate_owner(self.job, target_pid, launcher_pid, worker_pid)
|
owner = validate_owner(self.job, target_pid, launcher_pid, worker_pid)
|
||||||
if self.choice is None:
|
if self.choice is None:
|
||||||
self.owner, self.original = owner, snapshot
|
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'],
|
||||||
show(self.choice)
|
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
|
if (owner != self.owner or snapshot.hwnd != self.original.hwnd
|
||||||
or _prompt_identity(snapshot) != _prompt_identity(self.original)):
|
or _prompt_identity(snapshot) != _prompt_identity(self.original)):
|
||||||
raise ValueError('PCB_OPEN_IDENTITY_CHANGED')
|
raise ValueError('PCB_OPEN_IDENTITY_CHANGED')
|
||||||
@@ -137,36 +198,54 @@ class OpenController:
|
|||||||
raise ValueError('PCB_OPEN_ANSWER_NOT_COMPLETED')
|
raise ValueError('PCB_OPEN_ANSWER_NOT_COMPLETED')
|
||||||
if self.choice.decision is None:
|
if self.choice.decision is None:
|
||||||
return DialogPollResult(activity=True, observed_snapshots=tuple(snapshots))
|
return DialogPollResult(activity=True, observed_snapshots=tuple(snapshots))
|
||||||
control = 6 if self.choice.decision == 'continue' else 7
|
decision = self.choice.decision
|
||||||
action = {'action': 'user_confirmed_pcb_open', 'channels': ['win32_button_click'],
|
origin = self.choice.decision_origin
|
||||||
'target': {'control_id': control}, 'desktop': self.job['desktop'],
|
skipped_detail = ('超时默认跳过本项。' if origin == 'timeout_default' else '用户跳过本项。')
|
||||||
'pid': target_pid, 'owner': owner, 'choice': self.choice.decision}
|
if decision == 'continue':
|
||||||
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:
|
|
||||||
allowed = {target_pid, launcher_pid, worker_pid, self.job.get('supervisor_pid')}
|
allowed = {target_pid, launcher_pid, worker_pid, self.job.get('supervisor_pid')}
|
||||||
with resource_guard(self.job, allowed):
|
try:
|
||||||
pass
|
guard = (resource_guard(self.job, allowed, require_complete_proof=True) if self.require_complete_proof
|
||||||
# Deliberate TOCTOU tradeoff: release probes before Yes so Mentor
|
else resource_guard(self.job, allowed))
|
||||||
# can acquire the files without a sharing violation; recheck identity.
|
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:
|
if validate_owner(self.job, target_pid, launcher_pid, worker_pid) != owner:
|
||||||
raise ValueError('PCB_OPEN_IDENTITY_CHANGED')
|
raise ValueError('PCB_OPEN_IDENTITY_CHANGED')
|
||||||
result = send()
|
if decision == 'continue':
|
||||||
else:
|
try:
|
||||||
result = send()
|
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
|
error = result.error_code
|
||||||
if not error and result.accepted_controls != (control,):
|
if not error and result.accepted_controls != (control,):
|
||||||
error = 'PCB_OPEN_ANSWER_FAILED'
|
error = 'PCB_OPEN_ANSWER_FAILED'
|
||||||
if not error and control == 7:
|
if not error and control == 7:
|
||||||
error = 'PCB_OPEN_SKIPPED' if self.choice.decision == 'skip' else 'USER_CANCELLED'
|
error = 'PCB_OPEN_SKIPPED' if decision == 'skip' else 'USER_CANCELLED'
|
||||||
skipped_detail = ('超时默认跳过本项。' if self.choice.decision_origin == 'timeout_default'
|
|
||||||
else '用户跳过本项。')
|
|
||||||
return DialogPollResult(activity=True, action_sent=True, snapshot=snapshot,
|
return DialogPollResult(activity=True, action_sent=True, snapshot=snapshot,
|
||||||
error_code=error, detail=result.detail or (skipped_detail if control == 7 else ''),
|
error_code=error, detail=result.detail or (skipped_detail if control == 7 else ''),
|
||||||
accepted_controls=result.accepted_controls, channel=result.channel,
|
accepted_controls=result.accepted_controls, channel=result.channel,
|
||||||
|
|||||||
@@ -612,7 +612,7 @@ def _cancelled_diagnostic_record(row):
|
|||||||
or not same(job['cancel_signal'], session['cancel_signal'])
|
or not same(job['cancel_signal'], session['cancel_signal'])
|
||||||
or Path(job['cancel_signal']).parent != root or not Path(job['cancel_signal']).is_file()
|
or Path(job['cancel_signal']).parent != root or not Path(job['cancel_signal']).is_file()
|
||||||
or result.get('status') != 'CANCELLED' or result.get('error_stage') != 'PCB_STARTING'
|
or result.get('status') != 'CANCELLED' or result.get('error_stage') != 'PCB_STARTING'
|
||||||
or result.get('write_outcome', {}).get('save_state') != 'UNKNOWN'
|
or (result.get('write_outcome') or {}).get('save_state') != 'UNKNOWN'
|
||||||
or state.get('phase') != 'UNCONFIRMED' or (root/'save.log').exists()):
|
or state.get('phase') != 'UNCONFIRMED' or (root/'save.log').exists()):
|
||||||
continue
|
continue
|
||||||
native = [p for p in identities if p.get('role') == 'native' and p['pid'] == row['pid']]
|
native = [p for p in identities if p.get('role') == 'native' and p['pid'] == row['pid']]
|
||||||
@@ -818,6 +818,58 @@ def resume_cancelled_startup(path, *, stop=None):
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _recorded_process_exited(identity):
|
||||||
|
import pywintypes
|
||||||
|
import win32con
|
||||||
|
import win32event
|
||||||
|
|
||||||
|
try:
|
||||||
|
with _process_handle(identity['pid']) as handle:
|
||||||
|
if win32event.WaitForSingleObject(handle, 0) == win32con.WAIT_OBJECT_0:
|
||||||
|
return True
|
||||||
|
return _handle_identity(handle)['created_handle'] != identity['created_handle']
|
||||||
|
except pywintypes.error as error:
|
||||||
|
return error.winerror == 87
|
||||||
|
|
||||||
|
|
||||||
|
def orphaned_catalog_session(path):
|
||||||
|
from .session_record import IDENTITY_KEYS, MAX_BYTES, read_session_record
|
||||||
|
import stat
|
||||||
|
|
||||||
|
path = Path(path)
|
||||||
|
try:
|
||||||
|
session = read_session_record(path, evidence_root=path.parent)
|
||||||
|
if (session.get('operation') != 'catalog' or session.get('worker_role') != 'catalog_readonly'
|
||||||
|
or not str(session.get('desktop', '')).startswith('CbbManagement_')):
|
||||||
|
return False
|
||||||
|
request = path.with_name('request.json')
|
||||||
|
if request.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
|
||||||
|
return False
|
||||||
|
with request.open('rb') as stream:
|
||||||
|
data = stream.read(MAX_BYTES + 1)
|
||||||
|
if len(data) > MAX_BYTES:
|
||||||
|
return False
|
||||||
|
job = json.loads(data)
|
||||||
|
if (any(job.get(key) != session.get(key) for key in
|
||||||
|
('operation_id', 'operation', 'library', 'desktop', 'worker_role'))
|
||||||
|
or Path(job['session_record_path']).resolve() != path.resolve()):
|
||||||
|
return False
|
||||||
|
identity = job['supervisor_identity']
|
||||||
|
if (not isinstance(identity, dict) or any(identity.get(key) is None for key in IDENTITY_KEYS)
|
||||||
|
or type(identity['pid']) is not int or identity['pid'] <= 0
|
||||||
|
or identity['pid'] != job.get('supervisor_pid')):
|
||||||
|
return False
|
||||||
|
if session.get('supervisor_identity') != identity:
|
||||||
|
if session.get('supervisor_identity') is not None:
|
||||||
|
return False
|
||||||
|
lost = read_session_record(path.with_name('supervisor-lost.json'), evidence_root=path.parent)
|
||||||
|
if lost.get('operation_id') != session['operation_id'] or lost.get('phase') != 'SUPERVISOR_LOST':
|
||||||
|
return False
|
||||||
|
return _recorded_process_exited(identity)
|
||||||
|
except (OSError, ValueError, TypeError, KeyError, AttributeError):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def finish_owned_idle_session(path, *, stop=None):
|
def finish_owned_idle_session(path, *, stop=None):
|
||||||
"""One normal close for a registered, settled, empty client; never a server."""
|
"""One normal close for a registered, settled, empty client; never a server."""
|
||||||
from contextlib import ExitStack
|
from contextlib import ExitStack
|
||||||
@@ -840,17 +892,37 @@ def finish_owned_idle_session(path, *, stop=None):
|
|||||||
with item.open('rb') as stream: data = stream.read(1024*1024+1)
|
with item.open('rb') as stream: data = stream.read(1024*1024+1)
|
||||||
if len(data) > 1024*1024: raise ValueError('OWNED_CLEANUP_RECORD_TOO_LARGE')
|
if len(data) > 1024*1024: raise ValueError('OWNED_CLEANUP_RECORD_TOO_LARGE')
|
||||||
return json.loads(data)
|
return json.loads(data)
|
||||||
job, result = read('request.json'), read('result.json')
|
job = read('request.json')
|
||||||
if not isinstance(job, dict) or not isinstance(result, dict): return False
|
if not isinstance(job, dict): return False
|
||||||
if (any(job.get(k) != session.get(k) for k in ('operation_id','operation','library','desktop','block'))
|
if (any(job.get(k) != session.get(k) for k in ('operation_id','operation','library','desktop','block'))
|
||||||
or Path(job.get('session_record_path','')).resolve() != path.resolve()
|
or Path(job.get('session_record_path','')).resolve() != path.resolve()): return False
|
||||||
or result.get('safe_to_continue') is not False): return False
|
|
||||||
operation, desktop = job['operation'], job['desktop']
|
operation, desktop = job['operation'], job['desktop']
|
||||||
|
|
||||||
|
def read_result():
|
||||||
|
try:
|
||||||
|
return read('result.json')
|
||||||
|
except FileNotFoundError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
result = read_result()
|
||||||
|
if result is None:
|
||||||
|
if (state.get('phase') not in ('PRECALL', 'POSTCALL', 'RELEASE_CHECK', 'FINISHED', 'UNCONFIRMED')
|
||||||
|
or not orphaned_catalog_session(path)):
|
||||||
|
return False
|
||||||
|
elif not isinstance(result, dict) or result.get('safe_to_continue') is not False:
|
||||||
|
return False
|
||||||
|
cancelled_before_write = None
|
||||||
if operation == 'verify':
|
if operation == 'verify':
|
||||||
|
if result is None:
|
||||||
|
return False
|
||||||
facts = result.get('write_outcome') or {}
|
facts = result.get('write_outcome') or {}
|
||||||
failed_open = (result.get('error_stage') == 'PCB_STARTING'
|
failed_open = (result.get('error_stage') == 'PCB_STARTING'
|
||||||
and result.get('error_category') in ('MENTOR_DATABASE_LOAD_FAILED','ICDB_REPAIR_REQUIRED')
|
and result.get('error_category') in ('MENTOR_DATABASE_LOAD_FAILED','ICDB_REPAIR_REQUIRED')
|
||||||
and not path.with_name('save.log').exists())
|
and not path.with_name('save.log').exists())
|
||||||
|
if (result.get('status') == 'CANCELLED' and result.get('error_stage') == 'PCB_STARTING'
|
||||||
|
and state.get('phase') == 'UNCONFIRMED'):
|
||||||
|
from .failed_session import cancelled_prewrite_startup
|
||||||
|
cancelled_before_write = cancelled_prewrite_startup(job)
|
||||||
saved_closed = (isinstance(facts, dict) and facts.get('interrupted') is False
|
saved_closed = (isinstance(facts, dict) and facts.get('interrupted') is False
|
||||||
and all(facts.get(k) == v for k,v in (
|
and all(facts.get(k) == v for k,v in (
|
||||||
('save_state','COMMITTED'),('close_state','CLOSED'),('helper_state','EXITED'))))
|
('save_state','COMMITTED'),('close_state','CLOSED'),('helper_state','EXITED'))))
|
||||||
@@ -859,7 +931,8 @@ def finish_owned_idle_session(path, *, stop=None):
|
|||||||
or result.get('block_name') != job['block']
|
or result.get('block_name') != job['block']
|
||||||
or Path(result.get('evidence_path','')).resolve() != path.with_name('result.json').resolve()
|
or Path(result.get('evidence_path','')).resolve() != path.with_name('result.json').resolve()
|
||||||
or Path(job.get('root','')).resolve() != path.parent.resolve()
|
or Path(job.get('root','')).resolve() != path.parent.resolve()
|
||||||
or job.get('lmc_file') != job['library'] or not (failed_open or saved_closed)): return False
|
or job.get('lmc_file') != job['library']
|
||||||
|
or not (failed_open or saved_closed or cancelled_before_write is not None)): return False
|
||||||
client_name = 'expeditionpcb.exe'
|
client_name = 'expeditionpcb.exe'
|
||||||
elif operation == 'catalog' and job.get('worker_role') == 'catalog_readonly' and desktop.startswith('CbbManagement_'):
|
elif operation == 'catalog' and job.get('worker_role') == 'catalog_readonly' and desktop.startswith('CbbManagement_'):
|
||||||
client_name = 'librarymanager.exe'
|
client_name = 'librarymanager.exe'
|
||||||
@@ -895,28 +968,70 @@ def finish_owned_idle_session(path, *, stop=None):
|
|||||||
for c in w.get('children',[])) for w in windows)):
|
for c in w.get('children',[])) for w in windows)):
|
||||||
return None
|
return None
|
||||||
return close_target(client_name, windows, incomplete=_window_error(snapshot,client['pid']))[0]
|
return close_target(client_name, windows, incomplete=_window_error(snapshot,client['pid']))[0]
|
||||||
|
def load_failure_button():
|
||||||
|
from .failed_session import _startup_snapshot, _cancel_target
|
||||||
|
snapshot = _process_windows({client['pid']}, include_hidden_documents=True)
|
||||||
|
windows = snapshot.get(client['pid'], [])
|
||||||
|
if (_window_error(snapshot, client['pid']) or not windows
|
||||||
|
or any(w.get('desktop') != desktop for w in windows)):
|
||||||
|
return None
|
||||||
|
modals = [w for w in windows if w['class'] == '#32770']
|
||||||
|
if len(modals) != 1:
|
||||||
|
return None
|
||||||
|
with _window_desktop(desktop):
|
||||||
|
observed = _startup_snapshot(modals[0]['hwnd'], client['pid'])
|
||||||
|
target = _cancel_target(observed)
|
||||||
|
if target is None or target[0] != 'database_load_log':
|
||||||
|
return None
|
||||||
|
return observed, target[1].handle
|
||||||
|
|
||||||
if not same_client(): return False
|
if not same_client(): return False
|
||||||
|
if (cancelled_before_write is not None
|
||||||
|
and cancelled_prewrite_startup(job, client['pid']) != cancelled_before_write):
|
||||||
|
return False
|
||||||
target = empty_target()
|
target = empty_target()
|
||||||
if target is None or stop is not None and stop.is_set(): return False
|
failure = load_failure_button() if target is None and cancelled_before_write is not None else None
|
||||||
|
if (target is None and failure is None) or stop is not None and stop.is_set(): return False
|
||||||
check_active()
|
check_active()
|
||||||
current, _, _ = _session(path, path.parent)
|
current, _, _ = _session(path, path.parent)
|
||||||
if current != session: return False
|
if current != session: return False
|
||||||
claim = dict(operation_id=session['operation_id'],pid=client['pid'],identity=client,
|
claim = dict(operation_id=session['operation_id'],pid=client['pid'],identity=client,
|
||||||
status='REQUESTED',hwnd=target['hwnd'],desktop=desktop)
|
status='REQUESTED',hwnd=target['hwnd'] if target is not None else failure[1],
|
||||||
|
desktop=desktop)
|
||||||
write_session_record(path, {**session,'owned_idle_cleanup':claim})
|
write_session_record(path, {**session,'owned_idle_cleanup':claim})
|
||||||
# Re-read after durable I/O; never act on a window that gained a document.
|
# Re-read after durable I/O; never act on a window that gained a document.
|
||||||
latest, latest_state, latest_identities = _session(path, path.parent)
|
latest, latest_state, latest_identities = _session(path, path.parent)
|
||||||
if (latest_state != state or latest_identities != identities
|
if (latest_state != state or latest_identities != identities
|
||||||
or latest.get('owned_idle_cleanup') != claim
|
or latest.get('owned_idle_cleanup') != claim
|
||||||
or any(latest.get(k) != v for k,v in session.items() if k != 'recorded_at')
|
or any(latest.get(k) != v for k,v in session.items() if k != 'recorded_at')
|
||||||
or not same_client() or empty_target() != target or read('request.json') != job
|
or not same_client() or read('request.json') != job
|
||||||
or read('result.json') != result or stop is not None and stop.is_set()): return False
|
or (empty_target() != target if failure is None else load_failure_button() != failure)
|
||||||
|
or (cancelled_before_write is not None
|
||||||
|
and cancelled_prewrite_startup(job, client['pid']) != cancelled_before_write)
|
||||||
|
or read_result() != result or result is None and not orphaned_catalog_session(path)
|
||||||
|
or stop is not None and stop.is_set()): return False
|
||||||
with native_phase(read_only=True):
|
with native_phase(read_only=True):
|
||||||
_post_window_message(target,target['hwnd'],client['pid'],win32con.WM_CLOSE)
|
if failure is not None:
|
||||||
deadline = time.monotonic()+3
|
_post_window_message({'desktop': desktop}, failure[1], client['pid'], win32con.BM_CLICK)
|
||||||
while time.monotonic() < deadline:
|
deadline = time.monotonic() + 5
|
||||||
if win32event.WaitForSingleObject(handle,100) == win32con.WAIT_OBJECT_0: break
|
while time.monotonic() < deadline and same_client():
|
||||||
if stop is not None and stop.is_set(): break
|
if stop is not None and stop.is_set():
|
||||||
|
break
|
||||||
|
target = empty_target()
|
||||||
|
if target is not None:
|
||||||
|
break
|
||||||
|
time.sleep(.1)
|
||||||
|
if (target is not None and (not same_client() or empty_target() != target
|
||||||
|
or cancelled_prewrite_startup(job, client['pid']) != cancelled_before_write)):
|
||||||
|
target = None
|
||||||
|
if target is not None and (stop is None or not stop.is_set()):
|
||||||
|
_post_window_message(target, target['hwnd'], client['pid'], win32con.WM_CLOSE)
|
||||||
|
deadline = time.monotonic() + 3
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
if win32event.WaitForSingleObject(handle, 100) == win32con.WAIT_OBJECT_0:
|
||||||
|
break
|
||||||
|
if stop is not None and stop.is_set():
|
||||||
|
break
|
||||||
exited = win32event.WaitForSingleObject(handle,0) == win32con.WAIT_OBJECT_0
|
exited = win32event.WaitForSingleObject(handle,0) == win32con.WAIT_OBJECT_0
|
||||||
write_session_record(path.with_name('owned-idle-cleanup-result.json'),dict(
|
write_session_record(path.with_name('owned-idle-cleanup-result.json'),dict(
|
||||||
operation_id=session['operation_id'],library=session['library'],
|
operation_id=session['operation_id'],library=session['library'],
|
||||||
|
|||||||
@@ -164,6 +164,8 @@ def register_worker_session(worker, job):
|
|||||||
'lease_state': 'ACTIVE', 'resource_scope': session_resource_scope(job),
|
'lease_state': 'ACTIVE', 'resource_scope': session_resource_scope(job),
|
||||||
'worker_protection': protection, 'task_operation_id': context.operation_id if context else None,
|
'worker_protection': protection, 'task_operation_id': context.operation_id if context else None,
|
||||||
'blocked_resources': [], 'data_recovery_required': None})
|
'blocked_resources': [], 'data_recovery_required': None})
|
||||||
|
if protection == 'catalog_readonly' and job.get('supervisor_identity'):
|
||||||
|
record['supervisor_identity'] = job['supervisor_identity']
|
||||||
if job.get('start_gate_protocol') == 'event-v1':
|
if job.get('start_gate_protocol') == 'event-v1':
|
||||||
import win32api, win32con, win32event
|
import win32api, win32con, win32event
|
||||||
event = win32event.CreateEvent(None, True, False, None)
|
event = win32event.CreateEvent(None, True, False, None)
|
||||||
@@ -315,7 +317,7 @@ def _result(status, detail='', *, session=None, state=None, proof=None):
|
|||||||
(session or {}).get('data_recovery_required'))}
|
(session or {}).get('data_recovery_required'))}
|
||||||
|
|
||||||
|
|
||||||
def _reconcile(path, root, handles, stack, *, release=True):
|
def _reconcile(path, root, handles, stack, *, release=True, stop=None):
|
||||||
import pywintypes, win32api, win32con, win32event
|
import pywintypes, win32api, win32con, win32event
|
||||||
from .residual_sessions import _handle_identity, _force_ownership
|
from .residual_sessions import _handle_identity, _force_ownership
|
||||||
session, state, processes = _session(path, root)
|
session, state, processes = _session(path, root)
|
||||||
@@ -353,11 +355,12 @@ def _reconcile(path, root, handles, stack, *, release=True):
|
|||||||
if active:
|
if active:
|
||||||
return _result('ACTIVE', '原生调用尚未确认返回', session=session, state=state)
|
return _result('ACTIVE', '原生调用尚未确认返回', session=session, state=state)
|
||||||
if not release:
|
if not release:
|
||||||
return _result('UNCONFIRMED', '记录中的进程已退出,需确认库占用已释放', session=session, state=state)
|
return {**_result('UNCONFIRMED', '记录中的进程已退出,需确认库占用已释放',
|
||||||
|
session=session, state=state), 'processes_exited': True}
|
||||||
from .library_lock import release_retained_library
|
from .library_lock import release_retained_library
|
||||||
try:
|
try:
|
||||||
proof = release_retained_library(session['library'], Path(path).parent/'release-proof',
|
proof = release_retained_library(session['library'], Path(path).parent/'release-proof',
|
||||||
block_name=session.get('block'))
|
block_name=session.get('block'), **({'stop': stop} if stop is not None else {}))
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
return _result('UNCONFIRMED', str(error), session=session, state=state)
|
return _result('UNCONFIRMED', str(error), session=session, state=state)
|
||||||
if proof.get('status') != 'RELEASE_CONFIRMED':
|
if proof.get('status') != 'RELEASE_CONFIRMED':
|
||||||
@@ -367,10 +370,10 @@ def _reconcile(path, root, handles, stack, *, release=True):
|
|||||||
return _result('RELEASED', session=session, state=state, proof=proof)
|
return _result('RELEASED', session=session, state=state, proof=proof)
|
||||||
|
|
||||||
|
|
||||||
def reconcile_session_record(path, *, evidence_root):
|
def reconcile_session_record(path, *, evidence_root, stop=None):
|
||||||
with ExitStack() as stack:
|
with ExitStack() as stack:
|
||||||
try:
|
try:
|
||||||
return _reconcile(Path(path), Path(evidence_root), {}, stack)
|
return _reconcile(Path(path), Path(evidence_root), {}, stack, stop=stop)
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
return _result('UNCONFIRMED', str(error))
|
return _result('UNCONFIRMED', str(error))
|
||||||
|
|
||||||
@@ -510,6 +513,26 @@ def handoff_session(path, *, evidence_root, process=None, progress=None, stop=No
|
|||||||
thread.start()
|
thread.start()
|
||||||
|
|
||||||
|
|
||||||
|
def _completed_read_only_catalog(path, session, observed):
|
||||||
|
if (session.get('operation') != 'catalog' or session.get('worker_role') != 'catalog_readonly'
|
||||||
|
or observed.get('phase') != 'FINISHED' or observed.get('processes_exited') is not True):
|
||||||
|
return False
|
||||||
|
# A final worker receipt and fresh exit facts retire the read-only journal
|
||||||
|
# from recovery discovery. The original files remain available as evidence.
|
||||||
|
result_path = path.with_name('result.json')
|
||||||
|
try:
|
||||||
|
if result_path.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
|
||||||
|
return False
|
||||||
|
with result_path.open('rb') as stream:
|
||||||
|
data = stream.read(MAX_BYTES + 1)
|
||||||
|
if len(data) > MAX_BYTES:
|
||||||
|
return False
|
||||||
|
result = json.loads(data)
|
||||||
|
return isinstance(result, dict) and result.get('safe_to_continue') is True
|
||||||
|
except (OSError, ValueError):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def discover_sessions(evidence_root, *, library=None):
|
def discover_sessions(evidence_root, *, library=None):
|
||||||
"""Only our bounded journals are inputs; never execute a stored command."""
|
"""Only our bounded journals are inputs; never execute a stored command."""
|
||||||
root = Path(evidence_root)
|
root = Path(evidence_root)
|
||||||
@@ -550,6 +573,8 @@ def discover_sessions(evidence_root, *, library=None):
|
|||||||
if library is not None and _library_key(value.get('library', '')) != _library_key(library):
|
if library is not None and _library_key(value.get('library', '')) != _library_key(library):
|
||||||
continue
|
continue
|
||||||
observed = inspect_session_record(path, evidence_root=root)
|
observed = inspect_session_record(path, evidence_root=root)
|
||||||
|
if _completed_read_only_catalog(path, value, observed):
|
||||||
|
continue
|
||||||
value = {**value, **observed, 'library': value.get('library'),
|
value = {**value, **observed, 'library': value.get('library'),
|
||||||
'block': value.get('block'), 'operation_id': value['operation_id'], 'path': str(path)}
|
'block': value.get('block'), 'operation_id': value['operation_id'], 'path': str(path)}
|
||||||
except (OSError, ValueError):
|
except (OSError, ValueError):
|
||||||
|
|||||||
@@ -5,17 +5,18 @@ import ntpath
|
|||||||
import time
|
import time
|
||||||
from collections import Counter
|
from collections import Counter
|
||||||
from dataclasses import replace
|
from dataclasses import replace
|
||||||
|
from datetime import datetime
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
import json
|
import json
|
||||||
|
|
||||||
from cbb_refresh_verify.operation_queue import BatchTaskContext, QueueCancelled, TaskHandoff
|
from cbb_refresh_verify.operation_queue import BatchTaskContext, QueueCancelled, TaskHandoff
|
||||||
|
|
||||||
from PySide6.QtCore import QObject, QThreadPool, Signal, Qt, QTimer
|
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,
|
from PySide6.QtWidgets import (QWidget, QLineEdit, QPushButton, QFormLayout,
|
||||||
QTextEdit, QFileDialog, QHBoxLayout, QLabel, QSpinBox, QMessageBox, QToolButton,
|
QTextEdit, QFileDialog, QHBoxLayout, QLabel, QSpinBox, QMessageBox, QToolButton,
|
||||||
QTableWidget, QTableWidgetItem, QHeaderView, QCheckBox, QVBoxLayout, QProgressBar, QComboBox,
|
QTableWidget, QTableWidgetItem, QHeaderView, QCheckBox, QVBoxLayout, QProgressBar, QComboBox,
|
||||||
QTabBar, QStackedWidget, QSizePolicy)
|
QTabBar, QStackedWidget, QSizePolicy, QDialog, QDialogButtonBox, QPlainTextEdit)
|
||||||
from PySide6.QtWidgets import QStyle
|
from PySide6.QtWidgets import QStyle
|
||||||
|
|
||||||
|
|
||||||
@@ -76,6 +77,8 @@ STATUS_LABELS = {
|
|||||||
'MALFORMED': '状态桥协议错误',
|
'MALFORMED': '状态桥协议错误',
|
||||||
'CRASHED': '状态桥崩溃',
|
'CRASHED': '状态桥崩溃',
|
||||||
}
|
}
|
||||||
|
CATALOG_MANAGER_WAIT_SECONDS = 120
|
||||||
|
VERIFY_RELEASE_WAIT_SECONDS = 120
|
||||||
|
|
||||||
def application_icon_path():
|
def application_icon_path():
|
||||||
return Path(__file__).resolve().parents[1] / 'assets' / 'cbb_refresh_verify.ico'
|
return Path(__file__).resolve().parents[1] / 'assets' / 'cbb_refresh_verify.ico'
|
||||||
@@ -117,12 +120,16 @@ class MainWindow(QWidget):
|
|||||||
self.native_backup_timer.timeout.connect(self._poll_native_backup)
|
self.native_backup_timer.timeout.connect(self._poll_native_backup)
|
||||||
self._injected_reader = reader is not None
|
self._injected_reader = reader is not None
|
||||||
self.reader = reader or read_library_fast
|
self.reader = reader or read_library_fast
|
||||||
self.catalog_reader = catalog_reader or (None if reader is not None else getattr(self.management_adapter,'catalog',None))
|
self.catalog_reader = catalog_reader or (None if reader is not None else getattr(
|
||||||
|
self.management_adapter, 'catalog_registrations', getattr(self.management_adapter, 'catalog', None)))
|
||||||
self._view_revision = 0
|
self._view_revision = 0
|
||||||
self._jobs = {}
|
self._jobs = {}
|
||||||
self._dialogs = []
|
self._dialogs = []
|
||||||
self._current_job = None
|
self._current_job = None
|
||||||
self._stale_table = False
|
self._stale_table = False
|
||||||
|
self._table_library_path = None
|
||||||
|
self._catalog_snapshot_time = ''
|
||||||
|
self._catalog_retry = False
|
||||||
self._read_counts = (None, None, None)
|
self._read_counts = (None, None, None)
|
||||||
self._diagnostic_evidence = {}
|
self._diagnostic_evidence = {}
|
||||||
self.pool = QThreadPool(self); self.pool.setMaxThreadCount(8)
|
self.pool = QThreadPool(self); self.pool.setMaxThreadCount(8)
|
||||||
@@ -154,8 +161,7 @@ class MainWindow(QWidget):
|
|||||||
self.busy = False; self.loaded_path = None; self.stop = Event(); self.ready_names = set()
|
self.busy = False; self.loaded_path = None; self.stop = Event(); self.ready_names = set()
|
||||||
self._row_by_name = {}
|
self._row_by_name = {}
|
||||||
self._records_by_name = {}
|
self._records_by_name = {}
|
||||||
self.status_refresher = status_refresher or (lambda names, path: authoritative_status_map(
|
self.status_refresher = status_refresher or authoritative_status_map
|
||||||
names, path, self.data_root / 'status-refresh.jsonl'))
|
|
||||||
self.skipped_names = set(); self.skip_reasons = {}
|
self.skipped_names = set(); self.skip_reasons = {}
|
||||||
self._global_icdb_run = False
|
self._global_icdb_run = False
|
||||||
self._icdb_completed = 0
|
self._icdb_completed = 0
|
||||||
@@ -176,6 +182,9 @@ class MainWindow(QWidget):
|
|||||||
self.native_lm_verify_check.setChecked(native_lm_verify_enabled())
|
self.native_lm_verify_check.setChecked(native_lm_verify_enabled())
|
||||||
self.native_lm_verify_check.setToolTip(
|
self.native_lm_verify_check.setToolTip(
|
||||||
'仅在 Win10 兼容测试时启用;默认仍使用已验证的 ReusableCircuit 直接流程。')
|
'仅在 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 = QToolButton(); self.advanced_toggle.setText('高级设置')
|
||||||
self.advanced_toggle.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_TitleBarUnshadeButton))
|
self.advanced_toggle.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_TitleBarUnshadeButton))
|
||||||
self.advanced_toggle.setCheckable(True); self.advanced_toggle.setChecked(False)
|
self.advanced_toggle.setCheckable(True); self.advanced_toggle.setChecked(False)
|
||||||
@@ -185,10 +194,12 @@ class MainWindow(QWidget):
|
|||||||
advanced_layout.addRow('DMS 登录配置', self.dms_edit)
|
advanced_layout.addRow('DMS 登录配置', self.dms_edit)
|
||||||
advanced_layout.addRow('Mentor bin', self.mentor_bin_edit)
|
advanced_layout.addRow('Mentor bin', self.mentor_bin_edit)
|
||||||
advanced_layout.addRow('触发方式', self.native_lm_verify_check)
|
advanced_layout.addRow('触发方式', self.native_lm_verify_check)
|
||||||
|
advanced_layout.addRow('读写确认', self.auto_confirm_pcb_open_check)
|
||||||
self.advanced_panel.setVisible(False)
|
self.advanced_panel.setVisible(False)
|
||||||
self.advanced_toggle.toggled.connect(self.advanced_panel.setVisible)
|
self.advanced_toggle.toggled.connect(self.advanced_panel.setVisible)
|
||||||
self.cbb_table = QTableWidget(0, 4)
|
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(0, QHeaderView.Stretch)
|
||||||
self.cbb_table.horizontalHeader().setSectionResizeMode(3, QHeaderView.Stretch)
|
self.cbb_table.horizontalHeader().setSectionResizeMode(3, QHeaderView.Stretch)
|
||||||
for column in (1, 2):
|
for column in (1, 2):
|
||||||
@@ -212,6 +223,9 @@ class MainWindow(QWidget):
|
|||||||
self.status_filter.currentIndexChanged.connect(self._apply_filters)
|
self.status_filter.currentIndexChanged.connect(self._apply_filters)
|
||||||
self.timeout_spin = QSpinBox(); self.timeout_spin.setRange(30, 1800); self.timeout_spin.setValue(DEFAULT_TIMEOUT_SECONDS); self.timeout_spin.setSuffix(' 秒 / 无进展')
|
self.timeout_spin = QSpinBox(); self.timeout_spin.setRange(30, 1800); self.timeout_spin.setValue(DEFAULT_TIMEOUT_SECONDS); self.timeout_spin.setSuffix(' 秒 / 无进展')
|
||||||
self.load_button = QPushButton('读取 CBB'); self.load_button.clicked.connect(self.load_library)
|
self.load_button = QPushButton('读取 CBB'); self.load_button.clicked.connect(self.load_library)
|
||||||
|
self.catalog_status_button = QPushButton('刷新已登记项状态')
|
||||||
|
self.catalog_status_button.clicked.connect(self._refresh_registered_catalog)
|
||||||
|
self.catalog_status_button.hide()
|
||||||
self.browse_button = QPushButton('选择'); self.browse_button.clicked.connect(self.choose_library)
|
self.browse_button = QPushButton('选择'); self.browse_button.clicked.connect(self.choose_library)
|
||||||
self.selected_batch_button = QPushButton('批量校验已选'); self.selected_batch_button.clicked.connect(self.verify_selected)
|
self.selected_batch_button = QPushButton('批量校验已选'); self.selected_batch_button.clicked.connect(self.verify_selected)
|
||||||
self.batch_button = QPushButton('校验可见非 READY'); self.batch_button.clicked.connect(self.verify_all)
|
self.batch_button = QPushButton('校验可见非 READY'); self.batch_button.clicked.connect(self.verify_all)
|
||||||
@@ -250,7 +264,7 @@ class MainWindow(QWidget):
|
|||||||
self.output.setMaximumHeight(180)
|
self.output.setMaximumHeight(180)
|
||||||
layout = QVBoxLayout(self)
|
layout = QVBoxLayout(self)
|
||||||
row = QHBoxLayout(); row.addWidget(QLabel('中心库')); row.addWidget(self.lmc_edit)
|
row = QHBoxLayout(); row.addWidget(QLabel('中心库')); row.addWidget(self.lmc_edit)
|
||||||
row.addWidget(self.browse_button); row.addWidget(self.load_button)
|
row.addWidget(self.browse_button); row.addWidget(self.load_button); row.addWidget(self.catalog_status_button)
|
||||||
layout.addLayout(row)
|
layout.addLayout(row)
|
||||||
self.library_notice = QLabel()
|
self.library_notice = QLabel()
|
||||||
self.library_notice.setWordWrap(True)
|
self.library_notice.setWordWrap(True)
|
||||||
@@ -349,6 +363,7 @@ class MainWindow(QWidget):
|
|||||||
self._update()
|
self._update()
|
||||||
|
|
||||||
def _invalidate(self):
|
def _invalidate(self):
|
||||||
|
self._cancel_catalog_read()
|
||||||
if self._current_job is not None and self._current_job.kind == 'read':
|
if self._current_job is not None and self._current_job.kind == 'read':
|
||||||
self._current_job.context.close(timeout_seconds=0)
|
self._current_job.context.close(timeout_seconds=0)
|
||||||
self._view_revision += 1
|
self._view_revision += 1
|
||||||
@@ -356,6 +371,7 @@ class MainWindow(QWidget):
|
|||||||
self._reimport_offers = ()
|
self._reimport_offers = ()
|
||||||
self._diagnostic_evidence.clear()
|
self._diagnostic_evidence.clear()
|
||||||
self._resume_batch = None
|
self._resume_batch = None
|
||||||
|
self._catalog_retry = False
|
||||||
self._stale_table = bool(self._records_by_name)
|
self._stale_table = bool(self._records_by_name)
|
||||||
self._release_library_lease()
|
self._release_library_lease()
|
||||||
self.loaded_path = None
|
self.loaded_path = None
|
||||||
@@ -541,7 +557,17 @@ class MainWindow(QWidget):
|
|||||||
current_library = _path_key(self.mentor_lmc_path or self.lmc_edit.text()) if self.lmc_edit.text().strip() else None
|
current_library = _path_key(self.mentor_lmc_path or self.lmc_edit.text()) if self.lmc_edit.text().strip() else None
|
||||||
notice = ('上次操作结果待复查,执行前将重新检查占用。'
|
notice = ('上次操作结果待复查,执行前将重新检查占用。'
|
||||||
if self._management_library_unsafe(current_library) else '')
|
if self._management_library_unsafe(current_library) else '')
|
||||||
notice = '旧表已失效,请重新读取中心库。' if self._stale_table else notice
|
if self._stale_table:
|
||||||
|
if self._catalog_snapshot_time:
|
||||||
|
when = self._catalog_snapshot_time
|
||||||
|
notice = f'显示上次完整清单({when},待刷新)· {self._table_library_path}'
|
||||||
|
else:
|
||||||
|
notice = '当前显示上次读取结果(已失效)· 请重新读取中心库。'
|
||||||
|
self.catalog_status_button.setVisible(
|
||||||
|
self._catalog_retry and not self._closing and self._table_library_path == self.lmc_edit.text()
|
||||||
|
and self._read_counts[1] is not None and self.mentor_lmc_path is not None)
|
||||||
|
self.catalog_status_button.setEnabled(not self.busy)
|
||||||
|
self.load_button.setText('重试读取' if self._catalog_retry else '读取 CBB')
|
||||||
self.library_notice.setText(notice)
|
self.library_notice.setText(notice)
|
||||||
self.library_notice.setVisible(bool(notice))
|
self.library_notice.setVisible(bool(notice))
|
||||||
for widget in (self.lmc_edit, self.browse_button, self.load_button,
|
for widget in (self.lmc_edit, self.browse_button, self.load_button,
|
||||||
@@ -579,6 +605,7 @@ class MainWindow(QWidget):
|
|||||||
def _show_unfinished_management(self):
|
def _show_unfinished_management(self):
|
||||||
from cbb_refresh_verify.management import unfinished_operations
|
from cbb_refresh_verify.management import unfinished_operations
|
||||||
from cbb_refresh_verify.session_record import discover_sessions, handoff_session
|
from cbb_refresh_verify.session_record import discover_sessions, handoff_session
|
||||||
|
from cbb_refresh_verify.residual_sessions import orphaned_catalog_session
|
||||||
root = self.data_root
|
root = self.data_root
|
||||||
revision, owner = self._view_revision, self._current_job
|
revision, owner = self._view_revision, self._current_job
|
||||||
context = BatchTaskContext(str(root))
|
context = BatchTaskContext(str(root))
|
||||||
@@ -592,8 +619,9 @@ class MainWindow(QWidget):
|
|||||||
sessions = discover_sessions(root)
|
sessions = discover_sessions(root)
|
||||||
for session in sessions:
|
for session in sessions:
|
||||||
if session['status'] == 'ACTIVE':
|
if session['status'] == 'ACTIVE':
|
||||||
|
recover_catalog = orphaned_catalog_session(session['path'])
|
||||||
handoff_session(session['path'], evidence_root=root,
|
handoff_session(session['path'], evidence_root=root,
|
||||||
observe_only=True,
|
observe_only=not recover_catalog,
|
||||||
progress=lambda value: notify({'stage': 'session_observation', **value}))
|
progress=lambda value: notify({'stage': 'session_observation', **value}))
|
||||||
return unfinished, sessions
|
return unfinished, sessions
|
||||||
worker = ServiceWorker(lambda:context.run(inspect))
|
worker = ServiceWorker(lambda:context.run(inspect))
|
||||||
@@ -1035,13 +1063,14 @@ class MainWindow(QWidget):
|
|||||||
if isinstance(error, TaskHandoff) and job.lease is not None:
|
if isinstance(error, TaskHandoff) and job.lease is not None:
|
||||||
self._retain_path_lease(job.lease)
|
self._retain_path_lease(job.lease)
|
||||||
if not self._job_current(job): return
|
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)
|
else: self._failed(error)
|
||||||
self.worker.signals.failed.connect(failed)
|
self.worker.signals.failed.connect(failed)
|
||||||
self.worker.signals.finished.connect(lambda: (self._lifecycle_workers.discard(worker), self._finish_job(job)))
|
self.worker.signals.finished.connect(lambda: (self._lifecycle_workers.discard(worker), self._finish_job(job)))
|
||||||
self.pool.start(self.worker)
|
self.pool.start(self.worker)
|
||||||
|
|
||||||
def _queued_action(self, action, *, label='', library=None, job=None):
|
def _queued_action(self, action, *, label='', library=None, job=None, wait_for_release=False):
|
||||||
from cbb_refresh_verify.session_record import library_available, library_wait_reason
|
from cbb_refresh_verify.session_record import library_available, library_wait_reason
|
||||||
if library is None:
|
if library is None:
|
||||||
from PySide6.QtCore import QThread
|
from PySide6.QtCore import QThread
|
||||||
@@ -1060,6 +1089,7 @@ class MainWindow(QWidget):
|
|||||||
emit(event)
|
emit(event)
|
||||||
return action()
|
return action()
|
||||||
return lambda: self.native_queue.run(execute, stop=stop, context=job.context if job else None, skip_unavailable=True,
|
return lambda: self.native_queue.run(execute, stop=stop, context=job.context if job else None, skip_unavailable=True,
|
||||||
|
wait_for_release_seconds=VERIFY_RELEASE_WAIT_SECONDS if wait_for_release else None,
|
||||||
wait_state=lambda: library_wait_reason(library),
|
wait_state=lambda: library_wait_reason(library),
|
||||||
waiting=lambda: emit({'stage': 'waiting_native_slot',
|
waiting=lambda: emit({'stage': 'waiting_native_slot',
|
||||||
'library': str(library), 'retained': not library_available(library),
|
'library': str(library), 'retained': not library_available(library),
|
||||||
@@ -1253,12 +1283,22 @@ class MainWindow(QWidget):
|
|||||||
self._bind_summary_action(summary, action, recover)
|
self._bind_summary_action(summary, action, recover)
|
||||||
summary.show(); self._update()
|
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):
|
def load_library(self):
|
||||||
if self._closing or not self.lmc_edit.text(): return
|
if self._closing or not self.lmc_edit.text(): return
|
||||||
if (self._current_job is not None and self._current_job.kind == 'read'
|
if any(job.kind in ('read', 'catalog') and job.active
|
||||||
and self._current_job.active and self._current_job.revision == self._view_revision): return
|
and not job.context.stop.is_set() and job.revision == self._view_revision
|
||||||
|
for job in self._jobs.values()):
|
||||||
|
return
|
||||||
|
self._cancel_catalog_read()
|
||||||
self._view_revision += 1
|
self._view_revision += 1
|
||||||
self._diagnostic_evidence.clear()
|
self._diagnostic_evidence.clear()
|
||||||
|
self._catalog_retry = False
|
||||||
self._stale_table = bool(self._records_by_name)
|
self._stale_table = bool(self._records_by_name)
|
||||||
job = self._new_job('read', library=self.lmc_edit.text())
|
job = self._new_job('read', library=self.lmc_edit.text())
|
||||||
job.lease = None
|
job.lease = None
|
||||||
@@ -1275,6 +1315,7 @@ class MainWindow(QWidget):
|
|||||||
self._release_library_lease()
|
self._release_library_lease()
|
||||||
self.loaded_path = None
|
self.loaded_path = None
|
||||||
path = self.lmc_edit.text()
|
path = self.lmc_edit.text()
|
||||||
|
preserve = self._read_counts[1] is not None
|
||||||
self.status_label.setText('正在读取中心库…')
|
self.status_label.setText('正在读取中心库…')
|
||||||
def read():
|
def read():
|
||||||
import pythoncom
|
import pythoncom
|
||||||
@@ -1296,9 +1337,6 @@ class MainWindow(QWidget):
|
|||||||
recovery_view = False
|
recovery_view = False
|
||||||
result = self.reader(mentor_path)
|
result = self.reader(mentor_path)
|
||||||
job.context.check_active()
|
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:
|
if self.logging_context:
|
||||||
statuses = Counter(record.status for record in result.records)
|
statuses = Counter(record.status for record in result.records)
|
||||||
unknown = [record.name for record in result.records if record.status in {'UNKNOWN', 'UNAVAILABLE'}]
|
unknown = [record.name for record in result.records if record.status in {'UNKNOWN', 'UNAVAILABLE'}]
|
||||||
@@ -1307,8 +1345,9 @@ class MainWindow(QWidget):
|
|||||||
len(result.records), int((time.monotonic() - started) * 1000),
|
len(result.records), int((time.monotonic() - started) * 1000),
|
||||||
dict(statuses), unknown[:20])
|
dict(statuses), unknown[:20])
|
||||||
skip_reasons = {}
|
skip_reasons = {}
|
||||||
if not result.error:
|
if not result.error and (self.catalog_reader is None or result.catalog_verified):
|
||||||
for record in result.records:
|
for record in result.records:
|
||||||
|
job.context.check_active()
|
||||||
reason = preflight_skip_reason(mentor_path, record.name)
|
reason = preflight_skip_reason(mentor_path, record.name)
|
||||||
if reason:
|
if reason:
|
||||||
skip_reasons[record.name] = reason
|
skip_reasons[record.name] = reason
|
||||||
@@ -1323,16 +1362,27 @@ class MainWindow(QWidget):
|
|||||||
if path != self.lmc_edit.text() or job.revision != self._view_revision:
|
if path != self.lmc_edit.text() or job.revision != self._view_revision:
|
||||||
self._close_path_lease(lease)
|
self._close_path_lease(lease)
|
||||||
return
|
return
|
||||||
if result.error:
|
if result.error or (job.active and job.context.stop.is_set()):
|
||||||
self._close_path_lease(lease)
|
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.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)
|
||||||
|
preview = self.catalog_reader is not None and not result.catalog_verified
|
||||||
self._stale_table = False
|
self._stale_table = False
|
||||||
|
self._table_library_path = path
|
||||||
|
self._catalog_snapshot_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') if result.catalog_verified else ''
|
||||||
self._read_counts = (result.directory_count, result.native_count,
|
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))
|
result.missing_project_count if result.missing_project_count is not None else len(skip_reasons))
|
||||||
self._maintenance_recovery_view = recovery_view
|
self._maintenance_recovery_view = recovery_view
|
||||||
self.mentor_lmc_path = mentor_path
|
self.loaded_path = path if not preview or self._injected_reader else None
|
||||||
self.loaded_path = path
|
|
||||||
try:
|
try:
|
||||||
if self._settings_enabled:
|
if self._settings_enabled:
|
||||||
self.data_root.mkdir(parents=True, exist_ok=True)
|
self.data_root.mkdir(parents=True, exist_ok=True)
|
||||||
@@ -1401,7 +1451,7 @@ class MainWindow(QWidget):
|
|||||||
self.status_label.setText('协调阻止恢复视图:仅按目录显示工程,状态未确认(UNKNOWN),不代表损坏。'
|
self.status_label.setText('协调阻止恢复视图:仅按目录显示工程,状态未确认(UNKNOWN),不代表损坏。'
|
||||||
'仅可明确执行 ICDB 维护或释放检查,其他写入与原生状态读取已禁用。')
|
'仅可明确执行 ICDB 维护或释放检查,其他写入与原生状态读取已禁用。')
|
||||||
self._apply_filters()
|
self._apply_filters()
|
||||||
if self.catalog_reader is not None and not result.catalog_verified:
|
if preview:
|
||||||
self._start_catalog(job, result, lease, mentor_path, loaded)
|
self._start_catalog(job, result, lease, mentor_path, loaded)
|
||||||
self._start(read, loaded, queued=False, job=job, metadata_only=True,
|
self._start(read, loaded, queued=False, job=job, metadata_only=True,
|
||||||
stale=lambda payload: self._close_path_lease(payload[2]))
|
stale=lambda payload: self._close_path_lease(payload[2]))
|
||||||
@@ -1412,20 +1462,54 @@ class MainWindow(QWidget):
|
|||||||
job = SimpleNamespace(context=context, kind='catalog', revision=read_job.revision,
|
job = SimpleNamespace(context=context, kind='catalog', revision=read_job.revision,
|
||||||
lease=lease, requests=(), records={}, active=True, keep_session=False)
|
lease=lease, requests=(), records={}, active=True, keep_session=False)
|
||||||
self._jobs[context.operation_id] = job
|
self._jobs[context.operation_id] = job
|
||||||
def reconcile():
|
root = self.data_root/'catalog'/context.operation_id
|
||||||
catalog = self.catalog_reader(Path(library), 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:
|
if _path_key(catalog.library) != _path_key(library) or not catalog.safe_to_continue or catalog.flow != 1:
|
||||||
raise ValueError('CATALOG_UNCONFIRMED: 原生目录身份或退出未确认。')
|
raise ValueError('CATALOG_UNCONFIRMED: 原生目录身份或退出未确认。')
|
||||||
native = {entry.name: entry for entry in catalog.entries if entry.partition == 'Logical-Physical'}
|
native = {entry.name: entry for entry in catalog.entries if entry.partition == 'Logical-Physical'}
|
||||||
directories = {record.name: record for record in initial.records}
|
directories = {record.name: record for record in initial.records}
|
||||||
names = tuple(sorted(native.keys() | directories.keys()))
|
names = tuple(sorted(native.keys() | directories.keys()))
|
||||||
try:
|
context.check_active()
|
||||||
|
phase('catalog_status', f'已核对 0/{len(native)} 项原生状态…')
|
||||||
|
if checkpoint is None:
|
||||||
statuses = self.status_refresher(tuple(native), Path(library))
|
statuses = self.status_refresher(tuple(native), Path(library))
|
||||||
except Exception:
|
else:
|
||||||
statuses = {name:'UNAVAILABLE' for name in native}
|
from cbb_refresh_verify.operation_queue import note_metadata_progress
|
||||||
self._publish_check_statuses(library, statuses, lease)
|
last_notice = 0.0
|
||||||
|
|
||||||
|
def report_progress(done, total):
|
||||||
|
nonlocal last_notice
|
||||||
|
note_metadata_progress()
|
||||||
|
now = time.monotonic()
|
||||||
|
if done == total or now - last_notice >= .2:
|
||||||
|
last_notice = now
|
||||||
|
phase('catalog_status', f'已核对 {done}/{total} 项原生状态…')
|
||||||
|
|
||||||
|
statuses = self.status_refresher(tuple(native), Path(library), checkpoint, progress=report_progress)
|
||||||
|
if any(statuses.get(name) not in {'READY', 'PENDING'} for name in native):
|
||||||
|
raise ValueError('原生状态读取未确认,请重新读取中心库。')
|
||||||
|
context.check_active()
|
||||||
|
phase('catalog_reconcile', '正在合并目录和状态…')
|
||||||
records, reasons = [], {}
|
records, reasons = [], {}
|
||||||
for name in names:
|
for name in names:
|
||||||
|
context.check_active()
|
||||||
source = ('both' if name in native and name in directories else
|
source = ('both' if name in native and name in directories else
|
||||||
'native_only' if name in native else 'directory_only')
|
'native_only' if name in native else 'directory_only')
|
||||||
reason = ('CATALOG_NOT_REGISTERED: 仅发现目录,原生目录未登记。' if name not in native else
|
reason = ('CATALOG_NOT_REGISTERED: 仅发现目录,原生目录未登记。' if name not in native else
|
||||||
@@ -1440,20 +1524,98 @@ class MainWindow(QWidget):
|
|||||||
result = LibraryReadResult(tuple(records), directory_count=len(directories), native_count=len(native),
|
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)
|
missing_project_count=sum(name in native for name in reasons), catalog_verified=True)
|
||||||
return result, reasons, lease, library, False
|
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.
|
def attempt(evidence):
|
||||||
worker = ServiceWorker(lambda:self.native_queue.run(reconcile, context=context, timeout_seconds=120, skip_unavailable=True))
|
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', f'{error} 等待释放后自动重试读取。')
|
||||||
|
deadline = time.monotonic() + CATALOG_MANAGER_WAIT_SECONDS
|
||||||
|
blockers = set(error.blocking_manager_pids)
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
context.check_active()
|
||||||
|
try:
|
||||||
|
owners = query_owners(('LibraryManager.exe',),
|
||||||
|
timeout_seconds=min(2, max(.1, deadline - time.monotonic())))
|
||||||
|
except (OSError, RuntimeError):
|
||||||
|
context.stop.wait(1)
|
||||||
|
continue
|
||||||
|
context.check_active()
|
||||||
|
if not owners or blockers and blockers.isdisjoint(owner['pid'] for owner in 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)
|
self._lifecycle_workers.add(worker)
|
||||||
def completed(payload):
|
|
||||||
if self._job_current(read_job): deliver(payload)
|
|
||||||
def failed(error):
|
def failed(error):
|
||||||
if self._job_current(read_job):
|
from cbb_refresh_verify.native_management import NativeOperationError
|
||||||
self.status_label.setText(f'目录已显示;原生目录未确认:{error}')
|
|
||||||
|
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._catalog_retry = True
|
||||||
|
self._stale_table = bool(self._records_by_name) and bool(self._catalog_snapshot_time)
|
||||||
|
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.succeeded.connect(completed)
|
||||||
worker.signals.failed.connect(failed)
|
worker.signals.failed.connect(failed)
|
||||||
worker.signals.finished.connect(lambda:(self._lifecycle_workers.discard(worker),self._finish_job(job)))
|
worker.signals.finished.connect(lambda:(self._lifecycle_workers.discard(worker),self._finish_job(job)))
|
||||||
self.pool.start(worker)
|
self.pool.start(worker)
|
||||||
|
|
||||||
|
def _refresh_registered_catalog(self):
|
||||||
|
if (self.busy or not self._catalog_retry or self.mentor_lmc_path is None
|
||||||
|
or self._table_library_path != self.lmc_edit.text() or self._read_counts[1] is None):
|
||||||
|
return
|
||||||
|
library, lease = self.mentor_lmc_path, self.library_lease
|
||||||
|
names = tuple(name for name, record in self._records_by_name.items()
|
||||||
|
if record.catalog_source in {'both', 'native_only'})
|
||||||
|
if not names:
|
||||||
|
self.status_label.setText('上次清单中没有已登记项。')
|
||||||
|
return
|
||||||
|
job = self._new_job('status', library=library, targets=names, lease=lease)
|
||||||
|
self.status_label.setText('正在刷新上次登记项的原生状态…')
|
||||||
|
|
||||||
|
def refreshed(statuses):
|
||||||
|
if any(statuses.get(name) not in {'READY', 'PENDING'} for name in names):
|
||||||
|
self.status_label.setText('原生状态未确认,保留上次读取结果。')
|
||||||
|
return
|
||||||
|
self._apply_refreshed_records((names, statuses, None, ''))
|
||||||
|
self.status_label.setText(f'已刷新 {len(names)} 项原生状态,目录仍待重新读取。')
|
||||||
|
|
||||||
|
self._start(lambda: self.status_refresher(names, Path(library)), refreshed, job=job)
|
||||||
|
|
||||||
def _execution_status_reader(self, operation_id, lease):
|
def _execution_status_reader(self, operation_id, lease):
|
||||||
"""Recheck registration once per submission and status at each admission."""
|
"""Recheck registration once per submission and status at each admission."""
|
||||||
catalog_reader, status_reader = self.catalog_reader, self.status_refresher
|
catalog_reader, status_reader = self.catalog_reader, self.status_refresher
|
||||||
@@ -1725,6 +1887,8 @@ class MainWindow(QWidget):
|
|||||||
requests = ([request for request in request_snapshot if request.block_name in names] if request_snapshot is not None
|
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])
|
else [replace(self._request(name), maintenance=maintenance, auto_repair=False) for name in names])
|
||||||
if not requests: return
|
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
|
library = requests[0].lmc_file
|
||||||
if any(job.active and job.kind == 'verify' and job.requests == tuple(requests)
|
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
|
and _path_key(job.context.library) == _path_key(library) for job in self._jobs.values()): return
|
||||||
@@ -1751,7 +1915,8 @@ class MainWindow(QWidget):
|
|||||||
def action():
|
def action():
|
||||||
from cbb_refresh_verify.verify_runner import read_library_flag_if_available, run_verify
|
from cbb_refresh_verify.verify_runner import read_library_flag_if_available, run_verify
|
||||||
verify = self.verifier or (lambda req: 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,
|
flag_reader=read_library_flag_if_available,
|
||||||
version_prompt=lambda choice: self._emit_job(job, 'version_choice', choice), stop=job.context.stop))
|
version_prompt=lambda choice: self._emit_job(job, 'version_choice', choice), stop=job.context.stop))
|
||||||
def verifier(req):
|
def verifier(req):
|
||||||
@@ -1772,7 +1937,8 @@ class MainWindow(QWidget):
|
|||||||
self._emit_job(job, 'event', {'block': req.block_name, 'stage': 'icdb_check_start'})
|
self._emit_job(job, 'event', {'block': req.block_name, 'stage': 'icdb_check_start'})
|
||||||
return verify(req)
|
return verify(req)
|
||||||
results = run_batch(requests, verifier=verifier, stop=job.context.stop, context=job.context,
|
results = run_batch(requests, verifier=verifier, stop=job.context.stop, context=job.context,
|
||||||
item_executor=lambda req, action: self._queued_action(action, library=req.lmc_file, job=job)(),
|
item_executor=lambda req, action: self._queued_action(
|
||||||
|
action, library=req.lmc_file, job=job, wait_for_release=True)(),
|
||||||
progress=lambda name, result: self._emit_job(job, 'event', {'block': name, 'stage': result.status,
|
progress=lambda name, result: self._emit_job(job, 'event', {'block': name, 'stage': result.status,
|
||||||
'error_category': result.error_category, 'evidence': str(result.evidence_path or ''),
|
'error_category': result.error_category, 'evidence': str(result.evidence_path or ''),
|
||||||
'detail': result.stderr or result.stdout}))
|
'detail': result.stderr or result.stdout}))
|
||||||
@@ -1785,7 +1951,11 @@ class MainWindow(QWidget):
|
|||||||
write_maintenance_report(requests, results, report, ())
|
write_maintenance_report(requests, results, report, ())
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
self._emit_job(job, 'event', {'stage': 'report_failed', 'detail': str(error)})
|
self._emit_job(job, 'event', {'stage': 'report_failed', 'detail': str(error)})
|
||||||
affected = [req.block_name for req, result in zip(requests, results) if result.status != 'SKIPPED']
|
# A proven pre-write cancel can be submitted again. The next
|
||||||
|
# admission still rereads the catalog, status and occupancy.
|
||||||
|
affected = [req.block_name for req, result in zip(requests, results)
|
||||||
|
if result.status != 'SKIPPED'
|
||||||
|
and not (result.status == 'CANCELLED' and result.cancelled_before_write)]
|
||||||
safe = all(result.safe_to_continue for result in results)
|
safe = all(result.safe_to_continue for result in results)
|
||||||
self._emit_job(job, 'batch_ready', (results, report))
|
self._emit_job(job, 'batch_ready', (results, report))
|
||||||
refresh = None
|
refresh = None
|
||||||
@@ -1900,6 +2070,11 @@ class MainWindow(QWidget):
|
|||||||
from shiboken6 import isValid
|
from shiboken6 import isValid
|
||||||
if not isValid(self) or not isValid(self.cbb_table):
|
if not isValid(self) or not isValid(self.cbb_table):
|
||||||
return
|
return
|
||||||
|
if event.get('stage') in {'catalog_start', 'catalog_status', 'catalog_waiting', 'catalog_reconcile'}:
|
||||||
|
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':
|
if event.get('stage') == 'waiting_native_slot':
|
||||||
self.status_label.setText(event.get('detail', '已排队,等待执行'))
|
self.status_label.setText(event.get('detail', '已排队,等待执行'))
|
||||||
self._queue_waiting(event)
|
self._queue_waiting(event)
|
||||||
@@ -1944,6 +2119,36 @@ class MainWindow(QWidget):
|
|||||||
self.cbb_table.item(row, 3).setToolTip(detail)
|
self.cbb_table.item(row, 3).setToolTip(detail)
|
||||||
if self.logging_context: self.logging_context.logger.info('cbb_progress %s', line)
|
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):
|
def _mark_row_ready(self, row):
|
||||||
"""Color authoritative READY rows while retaining management selection."""
|
"""Color authoritative READY rows while retaining management selection."""
|
||||||
name_item = self.cbb_table.item(row, 0)
|
name_item = self.cbb_table.item(row, 0)
|
||||||
@@ -2001,12 +2206,12 @@ class MainWindow(QWidget):
|
|||||||
if len(outcome) <= 2:
|
if len(outcome) <= 2:
|
||||||
return
|
return
|
||||||
results, _, affected, refresh = outcome
|
results, _, affected, refresh = outcome
|
||||||
if refresh is None:
|
if refresh is not None:
|
||||||
|
self._apply_refreshed_records(refresh)
|
||||||
|
elif affected:
|
||||||
reason = ('状态尚未复核,请重新读取。' if all(r.safe_to_continue for r in results)
|
reason = ('状态尚未复核,请重新读取。' if all(r.safe_to_continue for r in results)
|
||||||
else '会话或数据库安全未确认;暂缓原生状态复核,请确认释放后重新读取。')
|
else '会话或数据库安全未确认;暂缓原生状态复核,请确认释放后重新读取。')
|
||||||
self._defer_status_refresh(affected, reason)
|
self._defer_status_refresh(affected, reason)
|
||||||
else:
|
|
||||||
self._apply_refreshed_records(refresh)
|
|
||||||
from shiboken6 import isValid
|
from shiboken6 import isValid
|
||||||
summary = getattr(self, 'summary', None)
|
summary = getattr(self, 'summary', None)
|
||||||
self.status_label.setText(summary.text().replace('\n', ' ') if summary is not None and isValid(summary)
|
self.status_label.setText(summary.text().replace('\n', ' ') if summary is not None and isValid(summary)
|
||||||
|
|||||||
@@ -8,17 +8,19 @@ class PcbOpenDialog(QMessageBox):
|
|||||||
self.choice = choice
|
self.choice = choice
|
||||||
self.setWindowTitle('确认打开 PCB 工程')
|
self.setWindowTitle('确认打开 PCB 工程')
|
||||||
self.setIcon(QMessageBox.Question)
|
self.setIcon(QMessageBox.Question)
|
||||||
|
advice = ('程序将检查工程和共享库占用,再决定是否继续。' if choice.auto_confirm else
|
||||||
|
'请确认没有其他用户打开此工程,再选择继续以读写权限打开。')
|
||||||
self.setText(f'CBB:{choice.block}\n中心库:{choice.library}\n\n'
|
self.setText(f'CBB:{choice.block}\n中心库:{choice.library}\n\n'
|
||||||
'PCB 提示上次可能未正常关闭,或工程仍被其他用户打开。\n'
|
'PCB 提示上次可能未正常关闭,或工程仍被其他用户打开。\n'
|
||||||
'请确认没有其他用户打开此工程,再选择继续以读写权限打开。')
|
+ advice)
|
||||||
self.continue_button = self.addButton('确认无人使用,继续打开', QMessageBox.ActionRole)
|
self.continue_button = self.addButton(
|
||||||
|
'检查占用后继续' if choice.auto_confirm else '确认无人使用,继续打开', QMessageBox.ActionRole)
|
||||||
self.skip_button = self.addButton('跳过本项', QMessageBox.ActionRole)
|
self.skip_button = self.addButton('跳过本项', QMessageBox.ActionRole)
|
||||||
self.cancel_button = self.addButton('取消本批次', QMessageBox.RejectRole)
|
self.cancel_button = self.addButton('取消本批次', QMessageBox.RejectRole)
|
||||||
self.setDefaultButton(self.skip_button)
|
|
||||||
self.setEscapeButton(self.cancel_button)
|
self.setEscapeButton(self.cancel_button)
|
||||||
self.setModal(True)
|
self.setModal(True)
|
||||||
self.buttonClicked.connect(lambda b: choice.choose('continue' if b is self.continue_button else
|
self.buttonClicked.connect(lambda b: choice.choose('continue' if b is self.continue_button else
|
||||||
'skip' if b is self.skip_button else 'cancel',
|
'skip' if b is self.skip_button else 'cancel',
|
||||||
origin=self.property('selectionOrigin') or 'user'))
|
origin=self.property('selectionOrigin') or 'user'))
|
||||||
self.finished.connect(lambda _: choice.choose('cancel'))
|
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,7 +4,7 @@ from threading import Event
|
|||||||
|
|
||||||
from PySide6.QtCore import QThreadPool, Signal, Qt
|
from PySide6.QtCore import QThreadPool, Signal, Qt
|
||||||
from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, QPushButton,
|
from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, QPushButton,
|
||||||
QTableWidget, QTableWidgetItem, QHeaderView, QMessageBox)
|
QTableWidget, QTableWidgetItem, QHeaderView, QMessageBox, QToolButton)
|
||||||
|
|
||||||
from .workers import ServiceWorker
|
from .workers import ServiceWorker
|
||||||
from .timed_prompt import arm_default
|
from .timed_prompt import arm_default
|
||||||
@@ -36,8 +36,15 @@ class ResidualReleaseDialog(QDialog):
|
|||||||
self.message = QLabel('正在检查当前库关联的会话…')
|
self.message = QLabel('正在检查当前库关联的会话…')
|
||||||
self.message.setWordWrap(True)
|
self.message.setWordWrap(True)
|
||||||
layout.addWidget(self.message)
|
layout.addWidget(self.message)
|
||||||
|
self.runtime_toggle = QToolButton()
|
||||||
|
self.runtime_toggle.setCheckable(True)
|
||||||
|
self.runtime_toggle.hide()
|
||||||
|
layout.addWidget(self.runtime_toggle)
|
||||||
self.runtime_label = QLabel()
|
self.runtime_label = QLabel()
|
||||||
self.runtime_label.setWordWrap(True)
|
self.runtime_label.setWordWrap(True)
|
||||||
|
self.runtime_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
|
||||||
|
self.runtime_label.hide()
|
||||||
|
self.runtime_toggle.toggled.connect(self.runtime_label.setVisible)
|
||||||
layout.addWidget(self.runtime_label)
|
layout.addWidget(self.runtime_label)
|
||||||
self.table = QTableWidget(0, 8)
|
self.table = QTableWidget(0, 8)
|
||||||
self.table.setHorizontalHeaderLabels(['工程', '程序', 'PID', '状态', '窗口位置', '程序路径', '确认范围', '执行结果'])
|
self.table.setHorizontalHeaderLabels(['工程', '程序', 'PID', '状态', '窗口位置', '程序路径', '确认范围', '执行结果'])
|
||||||
@@ -58,7 +65,7 @@ class ResidualReleaseDialog(QDialog):
|
|||||||
for button in (self.refresh_button, self.confirm_button, self.details_button, self.prompt_button,
|
for button in (self.refresh_button, self.confirm_button, self.details_button, self.prompt_button,
|
||||||
self.cancel_native_button, self.force_button, self.close_button): buttons.addWidget(button)
|
self.cancel_native_button, self.force_button, self.close_button): buttons.addWidget(button)
|
||||||
layout.addLayout(buttons)
|
layout.addLayout(buttons)
|
||||||
self.refresh_button.clicked.connect(self.refresh)
|
self.refresh_button.clicked.connect(lambda: self.refresh(reconcile=True))
|
||||||
self.confirm_button.clicked.connect(self.confirm_release)
|
self.confirm_button.clicked.connect(self.confirm_release)
|
||||||
self.close_button.clicked.connect(self.close)
|
self.close_button.clicked.connect(self.close)
|
||||||
self.prompt_button.clicked.connect(self.answer_prompt)
|
self.prompt_button.clicked.connect(self.answer_prompt)
|
||||||
@@ -207,7 +214,7 @@ class ResidualReleaseDialog(QDialog):
|
|||||||
self._start(lambda: answer_save_question(session, code),
|
self._start(lambda: answer_save_question(session, code),
|
||||||
lambda _: setattr(self, '_refresh_after', True))
|
lambda _: setattr(self, '_refresh_after', True))
|
||||||
|
|
||||||
def refresh(self):
|
def refresh(self, *, reconcile=False):
|
||||||
if self.busy: return
|
if self.busy: return
|
||||||
from cbb_refresh_verify.library_lock import inspect_residual_sessions
|
from cbb_refresh_verify.library_lock import inspect_residual_sessions
|
||||||
self.plan = None
|
self.plan = None
|
||||||
@@ -226,19 +233,51 @@ class ResidualReleaseDialog(QDialog):
|
|||||||
text += '确认后将复查库占用状态。'
|
text += '确认后将复查库占用状态。'
|
||||||
self.message.setText(text)
|
self.message.setText(text)
|
||||||
states = {'ACTIVE': '进行中', 'UNCONFIRMED': '待核对', 'IDENTITY_CHANGED': '待核对'}
|
states = {'ACTIVE': '进行中', 'UNCONFIRMED': '待核对', 'IDENTITY_CHANGED': '待核对'}
|
||||||
self.runtime_label.setText('\n'.join(
|
history = plan.get('runtime_sessions', [])
|
||||||
f'{states.get(row["status"], "待核对")} · {row.get("block") or "当前库"} · '
|
lines = []
|
||||||
f'{row.get("detail") or "操作状态需重新核对"}' for row in plan.get('runtime_sessions', [])))
|
for row in history:
|
||||||
|
pids = ', '.join(str(p['pid']) for p in row.get('processes', []) if 'pid' in p)
|
||||||
|
scope = row.get('resource_scope') or {}
|
||||||
|
resources = row.get('blocked_resources') or scope.get('shared_dependencies') or ()
|
||||||
|
detail = row.get('detail') or '操作状态需重新核对'
|
||||||
|
operation = {'catalog': '读取中心库', 'verify': '校验', 'repair': 'ICDB 维护'}.get(
|
||||||
|
row.get('operation'), row.get('operation') or '原生操作')
|
||||||
|
identity = ' · '.join(filter(None, (operation, row.get('recorded_at'),
|
||||||
|
f'PID {pids}' if pids else row.get('operation_id'))))
|
||||||
|
lines.append(f'{states.get(row["status"], "待核对")} · {row.get("block") or "当前库"} · {identity}\n'
|
||||||
|
+ ' · '.join((detail, *map(str, resources))))
|
||||||
|
self.runtime_label.setText('\n\n'.join(lines))
|
||||||
|
self.runtime_toggle.setText(f'会话记录({len(history)})')
|
||||||
|
self.runtime_toggle.setVisible(bool(history))
|
||||||
|
self.runtime_label.setVisible(bool(history) and self.runtime_toggle.isChecked())
|
||||||
|
|
||||||
def inspect():
|
def inspect():
|
||||||
from cbb_refresh_verify.network_path import select_library_file
|
from cbb_refresh_verify.network_path import select_library_file
|
||||||
from cbb_refresh_verify.session_record import discover_sessions, retained_session_states
|
from cbb_refresh_verify.session_record import (
|
||||||
|
discover_sessions, reconcile_session_record, record_session_release, retained_session_states)
|
||||||
library = self.library if self.library.suffix.casefold() == '.lmc' else select_library_file(self.library)
|
library = self.library if self.library.suffix.casefold() == '.lmc' else select_library_file(self.library)
|
||||||
plan = inspect_residual_sessions(library)
|
plan = inspect_residual_sessions(library)
|
||||||
states = {row['path']: row for row in retained_session_states(library)}
|
evidence_root = self.evidence_dir.parent
|
||||||
states.update({str(Path(row['path']).absolute()).casefold(): row for row in
|
cached = {row.get('operation_id') or row['path']: row for row in retained_session_states(library)}
|
||||||
discover_sessions(self.evidence_dir.parent, library=library)})
|
discovered = {row.get('operation_id') or row['path']: row for row in
|
||||||
return {**plan, 'runtime_sessions': list(states.values())}
|
discover_sessions(evidence_root, library=library)}
|
||||||
self._start(inspect, ready, metadata_only=True)
|
for key, row in discovered.items():
|
||||||
|
cached[key] = row
|
||||||
|
if reconcile:
|
||||||
|
for key, row in discovered.items():
|
||||||
|
if row.get('processes_exited') is not True:
|
||||||
|
continue
|
||||||
|
result = reconcile_session_record(row['path'], evidence_root=evidence_root, stop=self.stop)
|
||||||
|
if result['status'] == 'RELEASED' and result.get('release_proof'):
|
||||||
|
receipts = record_session_release(result['release_proof'], [row])
|
||||||
|
if not receipts:
|
||||||
|
cached.pop(key, None)
|
||||||
|
else:
|
||||||
|
cached[key] = {**row, 'detail': '\n'.join(receipts)}
|
||||||
|
else:
|
||||||
|
cached[key] = {**row, **result}
|
||||||
|
return {**plan, 'runtime_sessions': list(cached.values())}
|
||||||
|
self._start(inspect, ready, metadata_only=not reconcile)
|
||||||
|
|
||||||
def force_release(self):
|
def force_release(self):
|
||||||
if self.busy or not self.plan or not self.plan['sessions']: return
|
if self.busy or not self.plan or not self.plan['sessions']: return
|
||||||
|
|||||||
@@ -83,6 +83,9 @@ class VerifyRequest:
|
|||||||
maintenance: bool = False
|
maintenance: bool = False
|
||||||
post_repair_proof: object | None = field(default=None, repr=False, compare=False)
|
post_repair_proof: object | None = field(default=None, repr=False, compare=False)
|
||||||
diagnostic_only: bool = 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)
|
@dataclass(frozen=True)
|
||||||
@@ -105,6 +108,7 @@ class VerifyResult:
|
|||||||
release_proof: dict | None = None
|
release_proof: dict | None = None
|
||||||
write_outcome: dict | None = None
|
write_outcome: dict | None = None
|
||||||
session_record_path: Path | None = None
|
session_record_path: Path | None = None
|
||||||
|
cancelled_before_write: bool = False
|
||||||
|
|
||||||
|
|
||||||
def resolve_importer(mentor_bin: str | None = None) -> Path:
|
def resolve_importer(mentor_bin: str | None = None) -> Path:
|
||||||
@@ -670,8 +674,34 @@ def _run_verify_task(request, *, progress=None, flag_reader=None, process_runner
|
|||||||
request, progress=progress, flag_reader=flag_reader,
|
request, progress=progress, flag_reader=flag_reader,
|
||||||
process_runner=process_runner, port_check=port_check,
|
process_runner=process_runner, port_check=port_check,
|
||||||
dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt, stop=stop)
|
dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt, stop=stop)
|
||||||
|
local_retry = None
|
||||||
|
if (library_lock is not None and result.error_category == 'MENTOR_LOCAL_CELL_LIBRARY'
|
||||||
|
and not request.diagnostic_only and not request.auto_repair and not request.native_lm_verify
|
||||||
|
and not request.interactive_input and request.post_repair_proof is None):
|
||||||
|
from .local_cell_library import preserve_failed_cache
|
||||||
|
release_confirmed = result.safe_to_continue
|
||||||
|
local_retry = preserve_failed_cache(request, result, stop=stop)
|
||||||
|
if local_retry is not None:
|
||||||
|
initial_seconds = result.timings_seconds.get('total', 0.0)
|
||||||
|
original_evidence = result.evidence_path
|
||||||
|
_notify_progress(progress, {'stage': 'local_cell_library_retry', 'block': request.block_name,
|
||||||
|
'detail': '已保留旧本地 Cell Library,重新打开一次让 Mentor 重建。'})
|
||||||
|
check_active()
|
||||||
|
release_confirmed = False
|
||||||
|
result = _run_verify_serialized(request, progress=progress, flag_reader=flag_reader,
|
||||||
|
process_runner=process_runner, port_check=port_check,
|
||||||
|
dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt, stop=stop)
|
||||||
|
local_retry.update(status='REBUILT_AND_VERIFIED' if result.status == 'PASS' else 'REVERIFY_FAILED',
|
||||||
|
retry_evidence=str(result.evidence_path or ''))
|
||||||
|
_write_optional_evidence(original_evidence.with_name('local-cell-library-retry.json'), local_retry)
|
||||||
|
retry_seconds = result.timings_seconds.get('total', 0.0)
|
||||||
|
result = replace(result, recovery_attempts=(*result.recovery_attempts, local_retry),
|
||||||
|
timings_seconds={**result.timings_seconds, 'initial_verify': initial_seconds,
|
||||||
|
'local_cell_library_retry': retry_seconds, 'total': initial_seconds + retry_seconds})
|
||||||
|
if result.evidence_path:
|
||||||
|
_write_optional_evidence(result.evidence_path, {'block_name': request.block_name, **asdict(result)})
|
||||||
facts = result.write_outcome or {}
|
facts = result.write_outcome or {}
|
||||||
if (not request.diagnostic_only and not request.auto_repair and request.post_repair_proof is None
|
if (local_retry is None and not request.diagnostic_only and not request.auto_repair and request.post_repair_proof is None
|
||||||
and result.status == 'FAIL' and result.safe_to_continue and result.evidence_path
|
and result.status == 'FAIL' and result.safe_to_continue and result.evidence_path
|
||||||
and result.library_flag == 'NOT_GREEN' and result.error_stage == 'library_flag'
|
and result.library_flag == 'NOT_GREEN' and result.error_stage == 'library_flag'
|
||||||
and result.error_category == 'MENTOR_VERIFY_NOT_COMMITTED'
|
and result.error_category == 'MENTOR_VERIFY_NOT_COMMITTED'
|
||||||
@@ -1124,8 +1154,10 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
|||||||
from .failed_session import cancelled_prewrite_startup
|
from .failed_session import cancelled_prewrite_startup
|
||||||
_stop_worker(process, wait_for_native_write=False if request.diagnostic_only else
|
_stop_worker(process, wait_for_native_write=False if request.diagnostic_only else
|
||||||
lambda:cancelled_prewrite_startup(job,target_pid) is None)
|
lambda:cancelled_prewrite_startup(job,target_pid) is None)
|
||||||
|
prewrite = cancelled_prewrite_startup(job, target_pid) is not None
|
||||||
return finish(VerifyResult('CANCELLED', stderr='已取消当前校验。',
|
return finish(VerifyResult('CANCELLED', stderr='已取消当前校验。',
|
||||||
safe_to_continue=False, error_stage=phase.value))
|
safe_to_continue=False, error_stage=phase.value,
|
||||||
|
cancelled_before_write=prewrite))
|
||||||
if events.exists():
|
if events.exists():
|
||||||
with events.open(encoding='utf-8') as stream:
|
with events.open(encoding='utf-8') as stream:
|
||||||
stream.seek(offset)
|
stream.seek(offset)
|
||||||
@@ -1205,14 +1237,18 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
|||||||
diagnostic_closing = True
|
diagnostic_closing = True
|
||||||
from .dialog_supervisor import DialogPollResult
|
from .dialog_supervisor import DialogPollResult
|
||||||
dialog_result = DialogPollResult(activity=False)
|
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.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.error_code == 'DATABASE_RECOVERY_REQUIRED'
|
||||||
and dialog_result.snapshot is not None):
|
and dialog_result.snapshot is not None):
|
||||||
from .pcb_open_consent import OpenController, exact_prompt
|
from .pcb_open_consent import OpenController, exact_prompt
|
||||||
if exact_prompt(dialog_result.snapshot):
|
if exact_prompt(dialog_result.snapshot):
|
||||||
if open_controller is None:
|
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,
|
dialog_result = open_controller.handle(dialog_result.snapshot, dialog_result.observed_snapshots,
|
||||||
target_pid=target_pid, launcher_pid=launcher_pid, worker_pid=process.pid,
|
target_pid=target_pid, launcher_pid=launcher_pid, worker_pid=process.pid,
|
||||||
show=version_prompt, perform=dialog_supervisor.backend.perform)
|
show=version_prompt, perform=dialog_supervisor.backend.perform)
|
||||||
@@ -1270,6 +1306,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
|||||||
'CANCELLED' if dialog_result.error_code == 'USER_CANCELLED' else
|
'CANCELLED' if dialog_result.error_code == 'USER_CANCELLED' else
|
||||||
'SKIPPED' if dialog_result.error_code == 'PCB_OPEN_SKIPPED' else 'FAIL',
|
'SKIPPED' if dialog_result.error_code == 'PCB_OPEN_SKIPPED' else 'FAIL',
|
||||||
stderr=f'{dialog_result.error_code}: {dialog_result.detail}',
|
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,
|
error_stage=phase.value,
|
||||||
safe_to_continue=False,
|
safe_to_continue=False,
|
||||||
))
|
))
|
||||||
@@ -1517,6 +1554,7 @@ def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=Non
|
|||||||
results = []
|
results = []
|
||||||
queue_stop = False
|
queue_stop = False
|
||||||
retained_libraries = {}
|
retained_libraries = {}
|
||||||
|
timed_out_admissions = {}
|
||||||
for request in requests:
|
for request in requests:
|
||||||
from .operation_queue import request_library_keys
|
from .operation_queue import request_library_keys
|
||||||
library_keys = request_library_keys(request, context)
|
library_keys = request_library_keys(request, context)
|
||||||
@@ -1538,6 +1576,8 @@ def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=Non
|
|||||||
previous, index = retained_libraries[next(iter(library_keys.intersection(retained_libraries)))]
|
previous, index = retained_libraries[next(iter(library_keys.intersection(retained_libraries)))]
|
||||||
result = VerifyResult('SKIPPED', error_category='PREVIOUS_SESSION_UNRELEASED',
|
result = VerifyResult('SKIPPED', error_category='PREVIOUS_SESSION_UNRELEASED',
|
||||||
error_stage='admission', stderr=f'前项 {getattr(previous, "block_name", previous)} 的同库会话尚未释放,当前项未启动。')
|
error_stage='admission', stderr=f'前项 {getattr(previous, "block_name", previous)} 的同库会话尚未释放,当前项未启动。')
|
||||||
|
elif library_keys.intersection(timed_out_admissions):
|
||||||
|
result = timed_out_admissions[next(iter(library_keys.intersection(timed_out_admissions)))]
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
def execute():
|
def execute():
|
||||||
@@ -1551,10 +1591,14 @@ def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=Non
|
|||||||
from .operation_queue import QueueCancelled, QueueUnavailable, TaskHandoff
|
from .operation_queue import QueueCancelled, QueueUnavailable, TaskHandoff
|
||||||
# An unexpected exception cannot establish database safety.
|
# An unexpected exception cannot establish database safety.
|
||||||
result = (VerifyResult('SKIPPED', stderr=str(error), error_category='NATIVE_SESSION_PENDING',
|
result = (VerifyResult('SKIPPED', stderr=str(error), error_category='NATIVE_SESSION_PENDING',
|
||||||
error_stage='admission') if isinstance(error, QueueUnavailable) else
|
error_stage='admission', evidence_path=next(
|
||||||
|
(Path(row['path']) for row in error.sessions if row.get('path')), None))
|
||||||
|
if isinstance(error, QueueUnavailable) else
|
||||||
_handoff_verify_result(error) if isinstance(error, TaskHandoff) else
|
_handoff_verify_result(error) if isinstance(error, TaskHandoff) else
|
||||||
VerifyResult('CANCELLED' if isinstance(error, QueueCancelled) else 'FAIL',
|
VerifyResult('CANCELLED' if isinstance(error, QueueCancelled) else 'FAIL',
|
||||||
stderr=str(error), safe_to_continue=isinstance(error, QueueCancelled)))
|
stderr=str(error), safe_to_continue=isinstance(error, QueueCancelled)))
|
||||||
|
if isinstance(error, QueueUnavailable) and error.timed_out:
|
||||||
|
timed_out_admissions.update(dict.fromkeys(library_keys, result))
|
||||||
results.append(result)
|
results.append(result)
|
||||||
# Never start another writer after an unconfirmed native shutdown.
|
# Never start another writer after an unconfirmed native shutdown.
|
||||||
if not result.safe_to_continue:
|
if not result.safe_to_continue:
|
||||||
|
|||||||
@@ -0,0 +1,118 @@
|
|||||||
|
"""Verify the Windows desktop and CLI input paths in a candidate package."""
|
||||||
|
|
||||||
|
from contextlib import contextmanager
|
||||||
|
import json
|
||||||
|
import locale
|
||||||
|
from pathlib import Path
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
import ntsecuritycon
|
||||||
|
import pywintypes
|
||||||
|
import win32api
|
||||||
|
import win32con
|
||||||
|
import win32gui
|
||||||
|
import win32process
|
||||||
|
import win32security
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def deny_access(path, rights):
|
||||||
|
dacl_info = win32security.DACL_SECURITY_INFORMATION
|
||||||
|
original = win32security.GetFileSecurity(str(path), dacl_info)
|
||||||
|
sid, _, _ = win32security.LookupAccountName(None, win32api.GetUserName())
|
||||||
|
acl = win32security.ACL()
|
||||||
|
acl.AddAccessDeniedAce(win32security.ACL_REVISION, rights, sid)
|
||||||
|
acl.AddAccessAllowedAce(win32security.ACL_REVISION, win32con.GENERIC_ALL, sid)
|
||||||
|
restricted = win32security.SECURITY_DESCRIPTOR()
|
||||||
|
restricted.SetSecurityDescriptorDacl(True, acl, False)
|
||||||
|
win32security.SetFileSecurity(str(path), dacl_info, restricted)
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
win32security.SetFileSecurity(str(path), dacl_info, original)
|
||||||
|
|
||||||
|
|
||||||
|
def cli(exe, library, data_root, expected):
|
||||||
|
result = subprocess.run(
|
||||||
|
[str(exe), '--batch-lmc', str(library), '--block', 'Fixture', '--data-root', str(data_root)],
|
||||||
|
capture_output=True, timeout=15, creationflags=subprocess.CREATE_NO_WINDOW,
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
detail = result.stderr.decode('utf-8')
|
||||||
|
except UnicodeDecodeError:
|
||||||
|
detail = result.stderr.decode(locale.getencoding())
|
||||||
|
assert result.returncode == 1 and expected in detail, (result.returncode, detail)
|
||||||
|
assert 'Traceback' not in detail and not (data_root / 'reports').exists()
|
||||||
|
return {'exit_code': result.returncode, 'message': detail.strip()}
|
||||||
|
|
||||||
|
|
||||||
|
def startup_dialog(exe, data_root):
|
||||||
|
from cbb_refresh_verify.desktop_worker import DesktopWorker
|
||||||
|
|
||||||
|
worker = DesktopWorker([str(exe), '--data-root', str(data_root)], 'CbbInputSmoke_' + uuid4().hex[:8])
|
||||||
|
try:
|
||||||
|
deadline = time.monotonic() + 15
|
||||||
|
while worker.poll() is None and time.monotonic() < deadline:
|
||||||
|
try:
|
||||||
|
windows = worker.desktop.EnumDesktopWindows()
|
||||||
|
except pywintypes.error as error:
|
||||||
|
if error.winerror != 0:
|
||||||
|
raise
|
||||||
|
windows = ()
|
||||||
|
for hwnd in windows:
|
||||||
|
if win32process.GetWindowThreadProcessId(hwnd)[1] != worker.pid or not win32gui.IsWindowVisible(hwnd):
|
||||||
|
continue
|
||||||
|
title = win32gui.GetWindowText(hwnd)
|
||||||
|
assert title == 'CBB 刷新校验启动失败', title
|
||||||
|
if win32gui.GetClassName(hwnd) != '#32770':
|
||||||
|
continue
|
||||||
|
children = []
|
||||||
|
win32gui.EnumChildWindows(hwnd, lambda child, _: children.append(child) or True, None)
|
||||||
|
button = next((child for child in children if win32gui.GetClassName(child) == 'Button'), None)
|
||||||
|
if button is None:
|
||||||
|
continue
|
||||||
|
texts = [win32gui.GetWindowText(child) for child in children]
|
||||||
|
message = next((text for text in texts if 'DATA_ROOT_UNWRITABLE' in text), '')
|
||||||
|
assert str(data_root) in message and '无法写入数据目录' in message, texts
|
||||||
|
win32gui.PostMessage(button, win32con.BM_CLICK, 0, 0)
|
||||||
|
code = worker.wait(5)
|
||||||
|
assert code == 1
|
||||||
|
return {'exit_code': code, 'title': title, 'message': message}
|
||||||
|
time.sleep(0.1)
|
||||||
|
raise AssertionError(f'Startup dialog did not appear, exit={worker.poll()}')
|
||||||
|
finally:
|
||||||
|
if worker.poll() is None:
|
||||||
|
win32process.TerminateProcess(worker.handle, 1)
|
||||||
|
worker.wait(5)
|
||||||
|
worker.close()
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
workspace, executable, evidence_dir = (Path(arg).resolve() for arg in sys.argv[1:])
|
||||||
|
sys.path.insert(0, str(workspace / 'src'))
|
||||||
|
evidence_dir.mkdir(parents=True, exist_ok=False)
|
||||||
|
assert (executable.parent / '使用说明.txt').read_bytes() == (workspace / 'packaging' / '使用说明.txt').read_bytes()
|
||||||
|
empty_library = evidence_dir / 'empty.lmc'
|
||||||
|
empty_library.touch()
|
||||||
|
unreadable_library = evidence_dir / 'unreadable.lmc'
|
||||||
|
unreadable_library.write_bytes(b'fixture')
|
||||||
|
data_root = evidence_dir / 'data'
|
||||||
|
data_root.mkdir()
|
||||||
|
blocked_root = evidence_dir / 'readonly'
|
||||||
|
blocked_root.mkdir()
|
||||||
|
results = {'guide': 'matched', 'empty_lmc': cli(executable, empty_library, data_root, 'INPUT_EMPTY')}
|
||||||
|
with deny_access(unreadable_library, ntsecuritycon.FILE_READ_DATA):
|
||||||
|
results['unreadable_lmc'] = cli(executable, unreadable_library, data_root, 'INPUT_PERMISSION')
|
||||||
|
with deny_access(blocked_root, ntsecuritycon.FILE_ADD_FILE | ntsecuritycon.FILE_ADD_SUBDIRECTORY):
|
||||||
|
results['cli_data_root'] = cli(executable, empty_library, blocked_root, 'DATA_ROOT_UNWRITABLE')
|
||||||
|
results['gui_data_root'] = startup_dialog(executable, blocked_root)
|
||||||
|
summary = json.dumps(results, ensure_ascii=False, indent=2)
|
||||||
|
(evidence_dir / 'result.json').write_text(summary + '\n', encoding='utf-8')
|
||||||
|
print(summary)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
@@ -1,13 +1,97 @@
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('filename, contents, code', [
|
||||||
|
('empty.lmc', b'', 'INPUT_EMPTY'),
|
||||||
|
('missing.lmc', None, 'INPUT_MISSING'),
|
||||||
|
('library.txt', b'library', 'INPUT_SUFFIX'),
|
||||||
|
])
|
||||||
|
def test_explicit_cli_block_validates_lmc_before_dispatch(tmp_path, monkeypatch, capsys, filename, contents, code):
|
||||||
|
from cbb_refresh_verify import application, verify_runner
|
||||||
|
|
||||||
|
path = tmp_path / filename
|
||||||
|
if contents is not None:
|
||||||
|
path.write_bytes(contents)
|
||||||
|
monkeypatch.setattr(verify_runner, 'run_batch', lambda *a, **kw: pytest.fail('invalid input dispatched'))
|
||||||
|
|
||||||
|
assert application.main(['--batch-lmc', str(path), '--block', 'A',
|
||||||
|
'--data-root', str(tmp_path / 'data')]) == 1
|
||||||
|
assert code in capsys.readouterr().err
|
||||||
|
|
||||||
|
|
||||||
|
def test_explicit_cli_block_reports_unreadable_lmc(tmp_path, monkeypatch, capsys):
|
||||||
|
from cbb_refresh_verify import application, verify_runner
|
||||||
|
|
||||||
|
path = tmp_path / 'library.lmc'
|
||||||
|
path.write_bytes(b'library')
|
||||||
|
original_open = Path.open
|
||||||
|
|
||||||
|
def open_path(candidate, *args, **kwargs):
|
||||||
|
if candidate == path:
|
||||||
|
raise PermissionError('denied')
|
||||||
|
return original_open(candidate, *args, **kwargs)
|
||||||
|
|
||||||
|
monkeypatch.setattr(Path, 'open', open_path)
|
||||||
|
monkeypatch.setattr(verify_runner, 'run_batch', lambda *a, **kw: pytest.fail('unreadable input dispatched'))
|
||||||
|
assert application.main(['--batch-lmc', str(path), '--block', 'A',
|
||||||
|
'--data-root', str(tmp_path / 'data')]) == 1
|
||||||
|
assert 'INPUT_PERMISSION' in capsys.readouterr().err
|
||||||
|
|
||||||
|
|
||||||
|
def test_cli_unwritable_data_root_returns_input_exit_code(tmp_path, capsys):
|
||||||
|
from cbb_refresh_verify import application
|
||||||
|
|
||||||
|
path = tmp_path / 'data'
|
||||||
|
path.touch()
|
||||||
|
assert application.main(['--batch-lmc', str(tmp_path / 'library.lmc'), '--data-root', str(path)]) == 1
|
||||||
|
error = capsys.readouterr().err
|
||||||
|
assert 'DATA_ROOT_UNWRITABLE' in error and str(path) in error
|
||||||
|
assert 'Traceback' not in error
|
||||||
|
|
||||||
|
|
||||||
|
def test_windowed_cli_can_write_to_redirected_windows_stderr(tmp_path):
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
|
||||||
|
path = tmp_path / 'data'
|
||||||
|
path.touch()
|
||||||
|
command = (
|
||||||
|
'import sys; from cbb_refresh_verify.application import main; '
|
||||||
|
'sys.stderr = None; raise SystemExit(main(sys.argv[1:]))'
|
||||||
|
)
|
||||||
|
result = subprocess.run([sys.executable, '-X', 'utf8', '-c', command,
|
||||||
|
'--batch-lmc', str(tmp_path / 'library.lmc'), '--data-root', str(path)],
|
||||||
|
capture_output=True, encoding='utf-8', timeout=15,
|
||||||
|
creationflags=subprocess.CREATE_NO_WINDOW)
|
||||||
|
assert result.returncode == 1
|
||||||
|
assert 'DATA_ROOT_UNWRITABLE' in result.stderr and str(path) in result.stderr
|
||||||
|
|
||||||
|
|
||||||
|
def test_desktop_unwritable_data_root_shows_chinese_startup_error(tmp_path, monkeypatch):
|
||||||
|
import win32api
|
||||||
|
from cbb_refresh_verify import application
|
||||||
|
|
||||||
|
path = tmp_path / 'data'
|
||||||
|
path.touch()
|
||||||
|
messages = []
|
||||||
|
monkeypatch.setattr(win32api, 'MessageBox', lambda parent, detail, title, flags: messages.append((title, detail)))
|
||||||
|
|
||||||
|
assert application.main(['--data-root', str(path)]) == 1
|
||||||
|
assert len(messages) == 1
|
||||||
|
assert '启动失败' in messages[0][0]
|
||||||
|
assert '无法写入数据目录' in messages[0][1] and str(path) in messages[0][1]
|
||||||
|
|
||||||
|
|
||||||
def test_cli_signal_requests_cooperative_batch_stop(tmp_path, monkeypatch):
|
def test_cli_signal_requests_cooperative_batch_stop(tmp_path, monkeypatch):
|
||||||
import signal
|
import signal
|
||||||
from cbb_refresh_verify import application, verify_runner
|
from cbb_refresh_verify import application, verify_runner
|
||||||
library = tmp_path/'center.lmc'
|
library = tmp_path/'center.lmc'
|
||||||
library.touch()
|
library.write_bytes(b'library')
|
||||||
old = signal.getsignal(signal.SIGINT)
|
old = signal.getsignal(signal.SIGINT)
|
||||||
def run(requests, *, stop):
|
def run(requests, *, stop, context, item_executor):
|
||||||
|
assert context.stop is stop and callable(item_executor)
|
||||||
signal.getsignal(signal.SIGINT)(signal.SIGINT, None)
|
signal.getsignal(signal.SIGINT)(signal.SIGINT, None)
|
||||||
assert stop.is_set()
|
assert stop.is_set()
|
||||||
return [verify_runner.VerifyResult('CANCELLED')]
|
return [verify_runner.VerifyResult('CANCELLED')]
|
||||||
@@ -65,6 +149,7 @@ def test_batch_cli_acquires_unc_lease_before_directory_scan(tmp_path, monkeypatc
|
|||||||
monkeypatch.setattr(application, 'configure', lambda *_args: type('C', (), {
|
monkeypatch.setattr(application, 'configure', lambda *_args: type('C', (), {
|
||||||
'root': tmp_path,
|
'root': tmp_path,
|
||||||
'logger': type('L', (), {'info': lambda *a, **k: None,
|
'logger': type('L', (), {'info': lambda *a, **k: None,
|
||||||
|
'warning': lambda *a, **k: None,
|
||||||
'exception': lambda *a, **k: None,
|
'exception': lambda *a, **k: None,
|
||||||
'handlers': ()})(),
|
'handlers': ()})(),
|
||||||
})())
|
})())
|
||||||
|
|||||||
@@ -182,6 +182,7 @@ def test_broken_management_progress_sink_does_not_abort_completed_items(tmp_path
|
|||||||
|
|
||||||
def test_verify_ui_busy_admission_reports_each_skip_and_remains_usable(qtbot, tmp_path, monkeypatch):
|
def test_verify_ui_busy_admission_reports_each_skip_and_remains_usable(qtbot, tmp_path, monkeypatch):
|
||||||
from test_ui_filters import load_window
|
from test_ui_filters import load_window
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.ui.main_window.VERIFY_RELEASE_WAIT_SECONDS', .1)
|
||||||
window = load_window(qtbot, tmp_path, monkeypatch,
|
window = load_window(qtbot, tmp_path, monkeypatch,
|
||||||
verifier=lambda req: pytest.fail('live observer must prevent native launch'))
|
verifier=lambda req: pytest.fail('live observer must prevent native launch'))
|
||||||
library = window.mentor_lmc_path or window.loaded_path
|
library = window.mentor_lmc_path or window.loaded_path
|
||||||
|
|||||||
@@ -166,6 +166,7 @@ def test_cli_unsafe_batch_preserves_created_drive(tmp_path, monkeypatch):
|
|||||||
from cbb_refresh_verify import application
|
from cbb_refresh_verify import application
|
||||||
backend = FakeWNet()
|
backend = FakeWNet()
|
||||||
lease = LibraryPathLease.acquire(r'\\server\share\lib.lmc', backend=backend)
|
lease = LibraryPathLease.acquire(r'\\server\share\lib.lmc', backend=backend)
|
||||||
|
(tmp_path/'lib.lmc').write_bytes(b'library')
|
||||||
monkeypatch.setattr(LibraryPathLease, 'acquire', lambda path: lease)
|
monkeypatch.setattr(LibraryPathLease, 'acquire', lambda path: lease)
|
||||||
monkeypatch.setattr('cbb_refresh_verify.network_path.select_library_file', lambda path: tmp_path/'lib.lmc')
|
monkeypatch.setattr('cbb_refresh_verify.network_path.select_library_file', lambda path: tmp_path/'lib.lmc')
|
||||||
monkeypatch.setattr('cbb_refresh_verify.verify_runner.run_batch', lambda requests, **kw: [VerifyResult('FAIL', safe_to_continue=False)])
|
monkeypatch.setattr('cbb_refresh_verify.verify_runner.run_batch', lambda requests, **kw: [VerifyResult('FAIL', safe_to_continue=False)])
|
||||||
|
|||||||
@@ -371,3 +371,56 @@ def test_only_exact_empty_zero_area_childless_ie_infrastructure_is_benign(tmp_pa
|
|||||||
entry = result['benign_auxiliary_windows'][0]
|
entry = result['benign_auxiliary_windows'][0]
|
||||||
assert entry['class'] == 'Internet Explorer_Hidden' and entry['rect'] == [0, 0, 0, 0]
|
assert entry['class'] == 'Internet Explorer_Hidden' and entry['rect'] == [0, 0, 0, 0]
|
||||||
assert entry['children'] == []
|
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()
|
||||||
@@ -649,3 +649,102 @@ def test_recovery_retry_rejects_old_external_progress_and_choice(qtbot,tmp_path,
|
|||||||
assert choice.decision=='cancel'
|
assert choice.decision=='cancel'
|
||||||
finally:
|
finally:
|
||||||
release.set(); qtbot.waitUntil(lambda:not dialog.busy)
|
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, *, progress=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)
|
||||||
@@ -238,3 +238,43 @@ def test_catalog_native_wait_outlives_metadata_deadline(tmp_path, transport, mon
|
|||||||
(evidence/'finish').touch()
|
(evidence/'finish').touch()
|
||||||
finisher.join(6)
|
finisher.join(6)
|
||||||
context.close(timeout_seconds=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)
|
||||||
@@ -60,11 +60,13 @@ def test_supervisor_acknowledged_failed_open_can_close_empty_shell_with_address(
|
|||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize('aliased', [False, True])
|
@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'
|
library = tmp_path/'lib.lmc'
|
||||||
calls, checks = [], []
|
calls, checks = [], []
|
||||||
failed = verify_runner.VerifyResult('FAIL', stderr='bad database', safe_to_continue=False,
|
failed = verify_runner.VerifyResult(first_status, stderr='native operation declined', safe_to_continue=False,
|
||||||
evidence_path=tmp_path/'result.json', error_category='MENTOR_DATABASE_LOAD_FAILED')
|
evidence_path=tmp_path/'result.json',
|
||||||
|
error_category='PCB_OPEN_SKIPPED' if first_status == 'SKIPPED' else 'MENTOR_DATABASE_LOAD_FAILED')
|
||||||
def verify(request):
|
def verify(request):
|
||||||
calls.append(request.block_name)
|
calls.append(request.block_name)
|
||||||
return failed if request.block_name == 'Bad' else verify_runner.VerifyResult('PASS')
|
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)
|
results = verify_runner.run_batch([verify_runner.VerifyRequest(library, n, tmp_path)
|
||||||
for n in ('Bad','Good')], verifier=verify)
|
for n in ('Bad','Good')], verifier=verify)
|
||||||
assert calls == ['Bad','Good']
|
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
|
assert results[0].safe_to_continue
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,250 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from cbb_refresh_verify import native_management as native
|
||||||
|
from cbb_refresh_verify.batch_status import BatchStatusSession
|
||||||
|
from cbb_refresh_verify.status_bridge import BridgeResult
|
||||||
|
|
||||||
|
|
||||||
|
def test_status_scan_delivers_progress_after_each_record(tmp_path):
|
||||||
|
snapshots = []
|
||||||
|
bridge = SimpleNamespace(query=lambda *args, **kwargs: BridgeResult("READY", "test"))
|
||||||
|
lmc = tmp_path / 'library.lmc'
|
||||||
|
lmc.write_bytes(b'library')
|
||||||
|
checkpoint = tmp_path / 'pending.jsonl'
|
||||||
|
|
||||||
|
def progress(completed, total):
|
||||||
|
snapshots.append((completed, total, len(checkpoint.read_text('utf-8').splitlines())))
|
||||||
|
|
||||||
|
results = BatchStatusSession(bridge).scan(['A', 'B'], lmc, checkpoint, progress=progress)
|
||||||
|
assert [record.status for record in results] == ['READY', 'READY']
|
||||||
|
assert snapshots == [(1, 2, 1), (2, 2, 2)]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('include_identity', [False, True])
|
||||||
|
def test_catalog_registration_only_skips_project_identities(tmp_path, monkeypatch, include_identity):
|
||||||
|
import win32com.client
|
||||||
|
from cbb_refresh_verify import mentor_adapter
|
||||||
|
|
||||||
|
lmc = tmp_path / 'lib.lmc'
|
||||||
|
lmc.touch()
|
||||||
|
project = tmp_path / 'ReusableBlocksLP/A/Work/A.prj'
|
||||||
|
project.parent.mkdir(parents=True)
|
||||||
|
project.touch()
|
||||||
|
hashed = []
|
||||||
|
monkeypatch.setattr(native, 'engineering_identity', lambda p: hashed.append(p) or {'identity': True})
|
||||||
|
|
||||||
|
partition = SimpleNamespace(Count=1,
|
||||||
|
Item=lambda _: SimpleNamespace(Name='A', PartitionName='Logical-Physical'))
|
||||||
|
library = SimpleNamespace(FullName=str(lmc), FlowType=1, Close=lambda: None,
|
||||||
|
Partitions=lambda _: SimpleNamespace(Count=1, Item=lambda _: partition))
|
||||||
|
app = SimpleNamespace(OpenLibrary=lambda _: library, Quit=lambda: None)
|
||||||
|
exe = tmp_path / 'lm/win32/bin/LibraryManager.exe'
|
||||||
|
no_owners = iter([[], [(123, str(exe), '', 0)]])
|
||||||
|
monkeypatch.setattr(mentor_adapter, '_process_details', lambda _: next(no_owners))
|
||||||
|
monkeypatch.setattr(native, '_current_desktop',
|
||||||
|
lambda: (SimpleNamespace(EnumDesktopWindows=lambda: []), 'CbbManagement_test'))
|
||||||
|
monkeypatch.setattr(win32com.client, 'DispatchEx', lambda _: app)
|
||||||
|
result = native._catalog_com({'operation': 'catalog', 'worker_role': 'catalog_readonly',
|
||||||
|
'include_engineering_identity': include_identity, 'library': str(lmc),
|
||||||
|
'desktop': 'CbbManagement_test', 'mentor_home': str(tmp_path), 'supervisor_pid': __import__('os').getpid()}, tmp_path)
|
||||||
|
assert result['success']
|
||||||
|
assert hashed == ([project] if include_identity else [])
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('scope', ['foreign', 'same', 'shared', 'unknown', 'switched', 'occupied'])
|
||||||
|
def test_catalog_distinguishes_foreign_and_conflicting_manager(tmp_path, monkeypatch, scope):
|
||||||
|
target = tmp_path/'target'/'lib.lmc'
|
||||||
|
outside = tmp_path/'outside'/'lib.lmc'
|
||||||
|
for lmc in (target, outside):
|
||||||
|
lmc.parent.mkdir()
|
||||||
|
lmc.touch()
|
||||||
|
if scope == 'shared':
|
||||||
|
from cbb_refresh_verify.icdb_ownership import shared_symbol_database
|
||||||
|
first = shared_symbol_database(target)/'icdb.dat'
|
||||||
|
second = shared_symbol_database(outside)/'icdb.dat'
|
||||||
|
first.parent.mkdir(parents=True)
|
||||||
|
second.parent.mkdir(parents=True)
|
||||||
|
first.touch()
|
||||||
|
second.hardlink_to(first)
|
||||||
|
lk = target if scope == 'same' else outside
|
||||||
|
actual = None if scope == 'unknown' else target if scope == 'switched' else lk
|
||||||
|
monkeypatch.setattr(native, '_open_catalog_manager_library', lambda _: actual, raising=False)
|
||||||
|
owners = [(123, 'LibraryManager.exe', '' if scope == 'unknown' else f'LibraryManager.exe "{lk}"', 0)]
|
||||||
|
if scope == 'occupied':
|
||||||
|
def held(library):
|
||||||
|
raise OSError('shared database handle is occupied')
|
||||||
|
monkeypatch.setattr(native, '_probe_catalog_files', held)
|
||||||
|
if scope == 'foreign':
|
||||||
|
native._check_catalog_owners(target, owners)
|
||||||
|
else:
|
||||||
|
with pytest.raises(RuntimeError, match='LIBRARY_MANAGER_BUSY.*123'):
|
||||||
|
native._check_catalog_owners(target, owners)
|
||||||
|
|
||||||
|
|
||||||
|
def test_catalog_rejects_reused_foreign_com_proxy_without_mutating_it(tmp_path, monkeypatch):
|
||||||
|
import win32com.client
|
||||||
|
from cbb_refresh_verify import mentor_adapter
|
||||||
|
|
||||||
|
target = tmp_path/'target'/'lib.lmc'
|
||||||
|
other = tmp_path/'other'/'lib.lmc'
|
||||||
|
for lmc in (target, other):
|
||||||
|
lmc.parent.mkdir()
|
||||||
|
lmc.touch()
|
||||||
|
exe = tmp_path/'lm/win32/bin/LibraryManager.exe'
|
||||||
|
exe.parent.mkdir(parents=True)
|
||||||
|
exe.write_bytes(b'library manager')
|
||||||
|
monkeypatch.setitem(native._BINARY_PROOF, 'lm/win32/bin/LibraryManager.exe', native.hash_file(exe))
|
||||||
|
before = [(123, 'LibraryManager.exe', f'LibraryManager.exe "{other}"', 0)]
|
||||||
|
monkeypatch.setattr(mentor_adapter, '_process_details', lambda _: before)
|
||||||
|
monkeypatch.setattr(native, '_open_catalog_manager_library', lambda _: other, raising=False)
|
||||||
|
monkeypatch.setattr(native, '_current_desktop',
|
||||||
|
lambda: (SimpleNamespace(EnumDesktopWindows=lambda: []), 'CbbManagement_test'))
|
||||||
|
|
||||||
|
class Foreign:
|
||||||
|
def __setattr__(self, key, value):
|
||||||
|
pytest.fail(f'changed foreign LM property {key}')
|
||||||
|
def OpenLibrary(self, *_):
|
||||||
|
pytest.fail('opened target from a foreign LM')
|
||||||
|
def Quit(self):
|
||||||
|
pytest.fail('quit foreign LM')
|
||||||
|
|
||||||
|
monkeypatch.setattr(win32com.client, 'DispatchEx', lambda _: Foreign())
|
||||||
|
result = native._catalog_com({'operation': 'catalog', 'worker_role': 'catalog_readonly',
|
||||||
|
'include_engineering_identity': False, 'library': str(target),
|
||||||
|
'desktop': 'CbbManagement_test', 'mentor_home': str(tmp_path), 'supervisor_pid': __import__('os').getpid()}, tmp_path)
|
||||||
|
assert not result['success']
|
||||||
|
assert result['native_pids'] == []
|
||||||
|
assert result['no_new_manager'] is True
|
||||||
|
assert 'LIBRARY_MANAGER_BUSY' in result['detail']
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def test_catalog_progress_and_pending_preview_are_visible(qtbot, tmp_path, monkeypatch):
|
||||||
|
from threading import Event
|
||||||
|
from cbb_refresh_verify.management import Catalog, CatalogEntry
|
||||||
|
from cbb_refresh_verify.ui import main_window as ui
|
||||||
|
from test_issue15_ui_integration import load
|
||||||
|
|
||||||
|
checked, finish = Event(), Event()
|
||||||
|
library = tmp_path/'lib.lmc'
|
||||||
|
library.write_bytes(b'test catalog')
|
||||||
|
for name in ('A', 'B'):
|
||||||
|
(tmp_path/'ReusableBlocksLP'/name).mkdir(parents=True)
|
||||||
|
|
||||||
|
def status(names, path, checkpoint=None, *, progress=None):
|
||||||
|
if progress is not None:
|
||||||
|
progress(1, len(names))
|
||||||
|
checked.set()
|
||||||
|
assert finish.wait(5)
|
||||||
|
checkpoint.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
checkpoint.write_text('complete', encoding='utf-8')
|
||||||
|
return {name: 'READY' for name in names}
|
||||||
|
|
||||||
|
monkeypatch.setattr(ui, 'authoritative_status_map', status)
|
||||||
|
monkeypatch.setattr(ui, 'preflight_skip_reason', lambda *_: None)
|
||||||
|
window = ui.MainWindow(data_root=tmp_path/'data', catalog_reader=lambda path, _: Catalog(
|
||||||
|
path, 1, tuple(CatalogEntry(name, 'Logical-Physical') for name in ('A', 'B'))))
|
||||||
|
qtbot.addWidget(window)
|
||||||
|
window.show()
|
||||||
|
try:
|
||||||
|
load(window, qtbot, str(library))
|
||||||
|
qtbot.waitUntil(checked.is_set)
|
||||||
|
qtbot.waitUntil(lambda: '已核对 1/2' in window.status_label.text(), timeout=1000)
|
||||||
|
assert window.ready_names == set()
|
||||||
|
assert not window.icdb_repair_button.isEnabled()
|
||||||
|
assert not window.backup_restore_button.isEnabled()
|
||||||
|
assert not (tmp_path/'data'/'status-refresh.jsonl').exists()
|
||||||
|
finish.set()
|
||||||
|
qtbot.waitUntil(lambda: window.ready_names == {'A', 'B'})
|
||||||
|
finally:
|
||||||
|
finish.set()
|
||||||
|
window.pool.waitForDone(6000)
|
||||||
|
|
||||||
|
|
||||||
|
def test_timed_out_catalog_can_refresh_already_registered_status_only(qtbot, tmp_path, monkeypatch):
|
||||||
|
from cbb_refresh_verify.management import Catalog, CatalogEntry
|
||||||
|
from cbb_refresh_verify.models import CbbRecord, LibraryReadResult
|
||||||
|
from cbb_refresh_verify.ui import main_window as ui
|
||||||
|
from test_issue15_ui_integration import load, window_for
|
||||||
|
|
||||||
|
calls = []
|
||||||
|
still_active = []
|
||||||
|
|
||||||
|
def catalog(library, _):
|
||||||
|
calls.append(library)
|
||||||
|
if len(calls) > 1:
|
||||||
|
raise native.NativeOperationError('LIBRARY_MANAGER_BUSY: PID 123', safe_to_continue=True,
|
||||||
|
blocking_manager_pids=(123,))
|
||||||
|
return Catalog(library, 1, (CatalogEntry('A', 'Logical-Physical'),))
|
||||||
|
|
||||||
|
monkeypatch.setattr(ui, 'CATALOG_MANAGER_WAIT_SECONDS', 0, raising=False)
|
||||||
|
window = window_for(qtbot, tmp_path, monkeypatch,
|
||||||
|
reader=lambda _: LibraryReadResult((CbbRecord('A', 'LP'), CbbRecord('Ghost', 'LP')), directory_count=2),
|
||||||
|
catalog_reader=catalog, status_refresher=lambda names, _: (
|
||||||
|
still_active.append(tuple(names)) or {name: ('READY' if len(calls) == 1 else 'PENDING') for name in names}))
|
||||||
|
try:
|
||||||
|
load(window, qtbot)
|
||||||
|
qtbot.waitUntil(lambda: window.ready_names == {'A'})
|
||||||
|
window.load_button.click()
|
||||||
|
qtbot.waitUntil(lambda: window.load_button.text() == '重试读取')
|
||||||
|
assert window.ready_names == {'A'}
|
||||||
|
assert not window.batch_button.isEnabled()
|
||||||
|
window.catalog_status_button.click()
|
||||||
|
qtbot.waitUntil(lambda: window._records_by_name['A'].status == 'PENDING')
|
||||||
|
assert window._records_by_name['Ghost'].status == 'UNKNOWN'
|
||||||
|
assert not window.batch_button.isEnabled()
|
||||||
|
assert len(calls) == 2 and still_active == [('A',), ('A',)]
|
||||||
|
assert window.loaded_path is None
|
||||||
|
finally:
|
||||||
|
window.pool.waitForDone(6000)
|
||||||
|
|
||||||
|
|
||||||
|
def test_catalog_switch_retains_complete_snapshot_and_ignores_duplicate_reads(qtbot, tmp_path, monkeypatch):
|
||||||
|
from threading import Event
|
||||||
|
from cbb_refresh_verify.management import Catalog, CatalogEntry
|
||||||
|
from cbb_refresh_verify.ui import main_window as ui
|
||||||
|
from test_issue15_ui_integration import load
|
||||||
|
|
||||||
|
paths = {name: tmp_path/name/'lib.lmc' for name in ('A', 'B')}
|
||||||
|
for name, library in paths.items():
|
||||||
|
(library.parent/'ReusableBlocksLP'/name).mkdir(parents=True)
|
||||||
|
library.write_bytes(b'catalog')
|
||||||
|
reading, allow_return = Event(), Event()
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def catalog(path, _):
|
||||||
|
calls.append(path.parent.name)
|
||||||
|
if path == paths['B']:
|
||||||
|
reading.set()
|
||||||
|
assert allow_return.wait(5)
|
||||||
|
return Catalog(path, 1, (CatalogEntry(path.parent.name, 'Logical-Physical'),))
|
||||||
|
|
||||||
|
def statuses(names, path, checkpoint=None, *, progress=None):
|
||||||
|
checkpoint.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
checkpoint.write_text(path.parent.name, encoding='utf-8')
|
||||||
|
return {name: 'READY' for name in names}
|
||||||
|
|
||||||
|
monkeypatch.setattr(ui, 'authoritative_status_map', statuses)
|
||||||
|
monkeypatch.setattr(ui, 'preflight_skip_reason', lambda *_: None)
|
||||||
|
window = ui.MainWindow(data_root=tmp_path/'data', catalog_reader=catalog)
|
||||||
|
qtbot.addWidget(window)
|
||||||
|
window.show()
|
||||||
|
try:
|
||||||
|
load(window, qtbot, str(paths['A']))
|
||||||
|
qtbot.waitUntil(lambda: window.ready_names == {'A'})
|
||||||
|
load(window, qtbot, str(paths['B']))
|
||||||
|
qtbot.waitUntil(reading.is_set)
|
||||||
|
window.load_button.click()
|
||||||
|
assert window.ready_names == {'A'}
|
||||||
|
assert str(paths['A']) in window.library_notice.text()
|
||||||
|
assert not window.batch_button.isEnabled()
|
||||||
|
allow_return.set()
|
||||||
|
qtbot.waitUntil(lambda: window.ready_names == {'B'})
|
||||||
|
assert calls == ['A', 'B']
|
||||||
|
assert (tmp_path/'data/status-refresh.jsonl').read_text('utf-8') == 'B'
|
||||||
|
finally:
|
||||||
|
allow_return.set()
|
||||||
|
window.pool.waitForDone(6000)
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
from contextlib import contextmanager
|
||||||
|
import json
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from cbb_refresh_verify import verify_runner
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('scenario', ['retry', 'pending', 'no-binding-change', 'still-occupied',
|
||||||
|
'before-save-only', 'other-engineering-error'])
|
||||||
|
def test_local_cell_library_failure_retries_once_only_after_bound_release(tmp_path, monkeypatch, scenario):
|
||||||
|
from cbb_refresh_verify import library_lock
|
||||||
|
|
||||||
|
library = tmp_path / 'lib.lmc'
|
||||||
|
library.write_bytes(b'isolated library')
|
||||||
|
work = tmp_path / 'ReusableBlocksLP/A/Work'
|
||||||
|
project = work / 'A.prj'
|
||||||
|
pcb = work / 'PCB/A.pcb'
|
||||||
|
config = pcb.with_name('pcb.prj')
|
||||||
|
layout = pcb.parent / 'Layout/LayoutDB.lyt'
|
||||||
|
cache = pcb.parent / 'Work/Layout_Temp'
|
||||||
|
prefs = cache / 'JobPrefsDB.jpf'
|
||||||
|
for path in (layout, prefs, work / 'database/icdb.dat'):
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
path.write_bytes(b'original-' + path.name.encode('ascii'))
|
||||||
|
project.write_text('KEY PCBDesignPath "PCB/A.pcb"\nKEY iCDBDir "database"\n', encoding='utf-8')
|
||||||
|
pcb.write_text('KEY ProjectFile "../A.prj"\n', encoding='utf-8')
|
||||||
|
config.write_text('KEY CentralLibrary "../../../../lib.lmc"\n', encoding='utf-8')
|
||||||
|
(cache / 'CellDB.cel').write_bytes(b'old generated cell library')
|
||||||
|
first, second = tmp_path / 'first', tmp_path / 'second'
|
||||||
|
first.mkdir()
|
||||||
|
second.mkdir()
|
||||||
|
original = first / 'result.json'
|
||||||
|
original.write_text('{"status":"FAIL"}', encoding='utf-8')
|
||||||
|
new_evidence = second / 'result.json'
|
||||||
|
new_evidence.touch()
|
||||||
|
error = (f'Project Integration error: ERROR: Could not load Job Preferences DB [{prefs}] | '
|
||||||
|
'ERROR: Unable to create local Cell Library.')
|
||||||
|
if scenario == 'other-engineering-error':
|
||||||
|
error = 'Project Integration error: generic failure'
|
||||||
|
events = [
|
||||||
|
{'stage': 'central_library_path', 'status': 'MATCH' if scenario == 'no-binding-change' else 'UPDATED',
|
||||||
|
'path': str(config), 'target': str(library)},
|
||||||
|
{'stage': 'identity_verified', 'project': str(project), 'document': pcb.name},
|
||||||
|
{'stage': 'integration_error', 'detail': error},
|
||||||
|
]
|
||||||
|
if scenario == 'before-save-only':
|
||||||
|
events.append({'stage': 'save_start'})
|
||||||
|
(first / 'events.jsonl').write_text(''.join(json.dumps(e) + '\n' for e in events), encoding='utf-8')
|
||||||
|
job = dict(lmc_file=str(library), block_name='A', project=str(project), pcb=str(pcb),
|
||||||
|
operation_id='fixture-operation', root=str(first))
|
||||||
|
(first / 'request.json').write_text(json.dumps(job), encoding='utf-8')
|
||||||
|
if scenario != 'no-binding-change':
|
||||||
|
from cbb_refresh_verify.local_cell_library import capture_binding_change
|
||||||
|
capture_binding_change(job, config, lambda **_: None)
|
||||||
|
initial = verify_runner.VerifyResult('FAIL', stderr=error,
|
||||||
|
error_category=verify_runner.classify_failure_category(error), evidence_path=original,
|
||||||
|
safe_to_continue=True, timings_seconds={'total': 2.0})
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def prove(library_path, *, block_name, **_):
|
||||||
|
assert library_path == library and block_name == 'A'
|
||||||
|
if scenario == 'still-occupied':
|
||||||
|
raise library_lock.LibraryBusy('Occupied fixture')
|
||||||
|
yield {'blocked_resources': [], 'exclusive_files': [str(library), str(layout)], 'signatures': {}}
|
||||||
|
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def verify(request, **_):
|
||||||
|
calls.append(request.block_name)
|
||||||
|
if len(calls) == 1:
|
||||||
|
return initial
|
||||||
|
assert not cache.exists()
|
||||||
|
cache.mkdir()
|
||||||
|
prefs.write_bytes(b'rebuilt by Mentor')
|
||||||
|
if scenario == 'pending':
|
||||||
|
return verify_runner.VerifyResult('FAIL', error_stage='library_flag',
|
||||||
|
error_category='MENTOR_VERIFY_NOT_COMMITTED', library_flag='NOT_GREEN',
|
||||||
|
safe_to_continue=True, evidence_path=new_evidence,
|
||||||
|
write_outcome=dict(save_state='COMMITTED',close_state='CLOSED',helper_state='EXITED',
|
||||||
|
resource_state='RELEASED',interrupted=False))
|
||||||
|
return verify_runner.VerifyResult('PASS', library_flag='GREEN', evidence_path=new_evidence,
|
||||||
|
safe_to_continue=True, timings_seconds={'total': 3.0})
|
||||||
|
|
||||||
|
monkeypatch.setattr(library_lock, '_prove_library_released', prove)
|
||||||
|
monkeypatch.setattr(library_lock, 'recheck_previous_release', lambda *_, **__: None)
|
||||||
|
monkeypatch.setattr(verify_runner, '_run_verify_serialized', verify)
|
||||||
|
result = verify_runner._run_verify_task(verify_runner.VerifyRequest(library, 'A', tmp_path))
|
||||||
|
assert original.read_text(encoding='utf-8') == '{"status":"FAIL"}'
|
||||||
|
assert layout.read_bytes() == b'original-LayoutDB.lyt'
|
||||||
|
if scenario in {'retry', 'pending'}:
|
||||||
|
assert calls == ['A', 'A']
|
||||||
|
receipt = json.loads((first / 'local-cell-library-retry.json').read_text(encoding='utf-8'))
|
||||||
|
assert prefs.read_bytes() == b'rebuilt by Mentor'
|
||||||
|
assert result.status == ('PASS' if scenario == 'retry' else 'FAIL')
|
||||||
|
assert receipt['initial_evidence'] == str(original)
|
||||||
|
assert receipt['retry_evidence'] == str(new_evidence)
|
||||||
|
assert (work.parent / receipt['preserved_name'] / 'JobPrefsDB.jpf').read_bytes() == b'original-JobPrefsDB.jpf'
|
||||||
|
else:
|
||||||
|
assert calls == ['A']
|
||||||
|
assert prefs.read_bytes() == b'original-JobPrefsDB.jpf'
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
"""Regression checks for read-only admission and cancel/retry handoff."""
|
||||||
|
from pathlib import Path
|
||||||
|
from threading import Event
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from cbb_refresh_verify import desktop_worker, library_lock, session_record
|
||||||
|
from cbb_refresh_verify.operation_queue import BatchTaskContext, NativeQueue, QueueUnavailable
|
||||||
|
|
||||||
|
|
||||||
|
def test_read_only_catalog_registers_without_reusing_retained_writer_lease(monkeypatch):
|
||||||
|
registrations = []
|
||||||
|
monkeypatch.setattr(library_lock, 'duplicate_worker_lease', lambda *a:
|
||||||
|
pytest.fail('read-only catalog must not duplicate a writer lease'))
|
||||||
|
monkeypatch.setattr(session_record, 'register_worker_session', lambda worker, job:
|
||||||
|
registrations.append(job))
|
||||||
|
worker = type('Worker', (), {'handle': object()})()
|
||||||
|
desktop_worker.DesktopWorker.bind_session(worker, dict(
|
||||||
|
operation='catalog', worker_role='catalog_readonly', library='target.lmc'))
|
||||||
|
assert registrations[0]['worker_lease_handle'] is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_waiting_rerun_yields_queue_to_independent_library(monkeypatch):
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
|
||||||
|
released, waiting = Event(), Event()
|
||||||
|
queue = NativeQueue()
|
||||||
|
monkeypatch.setattr(session_record, '_live_library_available',
|
||||||
|
lambda library: library != 'target.lmc' or released.is_set())
|
||||||
|
with ThreadPoolExecutor(1) as pool:
|
||||||
|
result = pool.submit(queue.run, lambda: 'target admitted',
|
||||||
|
context=BatchTaskContext('target.lmc'),
|
||||||
|
waiting=waiting.set, wait_for_release_seconds=2)
|
||||||
|
assert waiting.wait(1)
|
||||||
|
assert queue.run(lambda: 'independent admitted',
|
||||||
|
context=BatchTaskContext('other.lmc')) == 'independent admitted'
|
||||||
|
released.set()
|
||||||
|
queue.wake()
|
||||||
|
assert result.result(1) == 'target admitted'
|
||||||
|
|
||||||
|
|
||||||
|
def test_unreleased_retry_expires_before_action_starts(monkeypatch):
|
||||||
|
monkeypatch.setattr(session_record, '_live_library_available', lambda _: False)
|
||||||
|
monkeypatch.setattr(session_record, 'retained_session_states', lambda _: [
|
||||||
|
{'operation_id': 'cancelled-operation', 'block': 'OldBlock', 'path': 'original/session.json',
|
||||||
|
'blocked_resources': ['shared/icdb.dat']}])
|
||||||
|
with pytest.raises(QueueUnavailable) as caught:
|
||||||
|
NativeQueue().run(lambda: pytest.fail('unsafe native admission'),
|
||||||
|
context=BatchTaskContext('target.lmc'), wait_for_release_seconds=.02)
|
||||||
|
assert 'OldBlock' in str(caught.value)
|
||||||
|
assert 'shared/icdb.dat' in str(caught.value)
|
||||||
|
assert caught.value.sessions[0]['path'] == 'original/session.json'
|
||||||
|
|
||||||
|
|
||||||
|
def test_catalog_recovery_only_adopts_an_exact_exited_supervisor(tmp_path, monkeypatch):
|
||||||
|
import json
|
||||||
|
from cbb_refresh_verify import residual_sessions
|
||||||
|
|
||||||
|
path = tmp_path/'session.json'
|
||||||
|
library = tmp_path/'library.lmc'
|
||||||
|
identity = dict(pid=55, image='original.exe', created_handle='created', owner_sid='owner', session_id=1)
|
||||||
|
record = dict(operation_id='catalog-crash', operation='catalog', worker_role='catalog_readonly',
|
||||||
|
desktop='CbbManagement_recovery', library=str(library), block=None,
|
||||||
|
supervisor_identity=identity)
|
||||||
|
session_record.write_session_record(path, record)
|
||||||
|
job = dict(record, supervisor_pid=55, session_record_path=str(path))
|
||||||
|
(tmp_path/'request.json').write_text(json.dumps(job), encoding='utf-8')
|
||||||
|
monkeypatch.setattr(residual_sessions, '_recorded_process_exited', lambda found: found == identity)
|
||||||
|
assert residual_sessions.orphaned_catalog_session(path)
|
||||||
|
job['supervisor_identity'] = {**identity, 'pid': 56}
|
||||||
|
(tmp_path/'request.json').write_text(json.dumps(job), encoding='utf-8')
|
||||||
|
assert not residual_sessions.orphaned_catalog_session(path)
|
||||||
|
|
||||||
|
|
||||||
|
def test_idle_orphan_catalog_can_close_without_final_result(tmp_path, monkeypatch):
|
||||||
|
from test_owned_idle_cleanup import owned_fixture
|
||||||
|
from cbb_refresh_verify import residual_sessions
|
||||||
|
|
||||||
|
root, job, _, _, state = owned_fixture(tmp_path, monkeypatch, 'catalog')
|
||||||
|
(root/'result.json').unlink()
|
||||||
|
monkeypatch.setattr(residual_sessions, 'orphaned_catalog_session', lambda _: True, raising=False)
|
||||||
|
session_record.write_session_record(root/'worker-state.json',
|
||||||
|
dict(operation_id='owned', phase='NATIVE_CALL', processes=[dict(role='native', pid=12,
|
||||||
|
created_handle='native-created', image='D:/Mentor/LibraryManager.exe', owner_sid='owner', session_id=1)]))
|
||||||
|
assert not residual_sessions.finish_owned_idle_session(root/'session.json')
|
||||||
|
worker_state = session_record.read_session_record(root/'worker-state.json', evidence_root=root)
|
||||||
|
session_record.write_session_record(root/'worker-state.json', {**worker_state, 'phase': 'POSTCALL'})
|
||||||
|
assert residual_sessions.finish_owned_idle_session(root/'session.json')
|
||||||
|
assert state['posts'] == [(100, 12, 16)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_recheck_archives_exited_catalog_only_after_fresh_proof(qtbot, tmp_path, monkeypatch):
|
||||||
|
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
|
||||||
|
|
||||||
|
library = tmp_path/'lib.lmc'
|
||||||
|
library.touch()
|
||||||
|
session = dict(operation_id='finished-catalog', operation='catalog', library=str(library),
|
||||||
|
status='UNCONFIRMED', processes_exited=True, detail='待核对',
|
||||||
|
path=str(tmp_path/'history/session.json'), recorded_at='2026-11-23T00:00:00Z',
|
||||||
|
processes=[dict(role='native', pid=111)])
|
||||||
|
proven = set()
|
||||||
|
monkeypatch.setattr(library_lock, 'inspect_residual_sessions',
|
||||||
|
lambda *_: {'library': str(library), 'sessions': []})
|
||||||
|
monkeypatch.setattr(session_record, 'discover_sessions',
|
||||||
|
lambda *a, **kw: [] if proven else [session, session.copy()])
|
||||||
|
monkeypatch.setattr(session_record, 'retained_session_states', lambda _: [])
|
||||||
|
monkeypatch.setattr(session_record, 'reconcile_session_record',
|
||||||
|
lambda path, **kw: proven.add(path) or {'status': 'RELEASED', 'release_proof': {'status': 'RELEASE_CONFIRMED'}})
|
||||||
|
archived = []
|
||||||
|
monkeypatch.setattr(session_record, 'record_session_release', lambda proof, rows: archived.extend(rows) or [])
|
||||||
|
dialog = ResidualReleaseDialog(library, tmp_path/'release-checks')
|
||||||
|
qtbot.addWidget(dialog)
|
||||||
|
qtbot.waitUntil(lambda: not dialog.busy)
|
||||||
|
assert not proven
|
||||||
|
assert dialog.runtime_label.text().count('PID 111') == 1
|
||||||
|
dialog.refresh_button.click()
|
||||||
|
qtbot.waitUntil(lambda: not dialog.busy)
|
||||||
|
assert len(proven) == 1 and archived == [session] and not dialog.runtime_label.text()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(('phase', 'safe', 'exited', 'hidden'), [
|
||||||
|
('FINISHED', True, True, True),
|
||||||
|
('FINISHED', True, False, False),
|
||||||
|
('POSTCALL', True, True, False),
|
||||||
|
('UNCONFIRMED', False, True, False),
|
||||||
|
])
|
||||||
|
def test_discovery_hides_only_completed_read_only_catalog(tmp_path, monkeypatch, phase, safe, exited, hidden):
|
||||||
|
import json
|
||||||
|
|
||||||
|
record = tmp_path/'session.json'
|
||||||
|
library = tmp_path/'lib.lmc'
|
||||||
|
session_record.write_session_record(record, dict(operation_id='catalog-result',
|
||||||
|
operation='catalog', worker_role='catalog_readonly', library=str(library), block=None))
|
||||||
|
(tmp_path/'result.json').write_text(json.dumps({'safe_to_continue': safe}), encoding='utf-8')
|
||||||
|
monkeypatch.setattr(session_record, 'inspect_session_record', lambda *a, **kw: {
|
||||||
|
'status': 'UNCONFIRMED' if exited else 'ACTIVE', 'phase': phase,
|
||||||
|
'processes_exited': exited,
|
||||||
|
})
|
||||||
|
|
||||||
|
found = session_record.discover_sessions(tmp_path)
|
||||||
|
assert bool(found) == (not hidden)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('proved', [True, False])
|
||||||
|
def test_cancelled_prewrite_can_dismiss_exact_late_load_failure(qtbot, tmp_path, monkeypatch, proved):
|
||||||
|
import json
|
||||||
|
from contextlib import nullcontext
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from test_owned_idle_cleanup import owned_fixture
|
||||||
|
from cbb_refresh_verify import failed_session, residual_sessions
|
||||||
|
|
||||||
|
root, job, result, windows, state = owned_fixture(tmp_path, monkeypatch)
|
||||||
|
result.update(status='CANCELLED', error_category='TASK_HANDOFF', write_outcome=None)
|
||||||
|
(root/'result.json').write_text(json.dumps(result), encoding='utf-8')
|
||||||
|
frame = windows[0]
|
||||||
|
frame['documents'] = [99]
|
||||||
|
windows.append(dict(hwnd=200, title='Expedition PCB', desktop=job['desktop'], children=[],
|
||||||
|
enabled=True, **{'class': '#32770'}))
|
||||||
|
baseline = {'started_ns': 123}
|
||||||
|
monkeypatch.setattr(failed_session, 'cancelled_prewrite_startup', lambda *a: baseline if proved else None)
|
||||||
|
monkeypatch.setattr(residual_sessions, '_window_desktop', lambda *a, **kw: nullcontext())
|
||||||
|
monkeypatch.setattr(failed_session, '_startup_snapshot', lambda *a: 'exact load failure')
|
||||||
|
monkeypatch.setattr(failed_session, '_cancel_target',
|
||||||
|
lambda _: ('database_load_log', SimpleNamespace(handle=201)))
|
||||||
|
def post(window, hwnd, pid, message):
|
||||||
|
state['posts'].append((hwnd, pid, message))
|
||||||
|
if hwnd == 201:
|
||||||
|
windows.pop()
|
||||||
|
frame['documents'].clear()
|
||||||
|
else:
|
||||||
|
state['native_alive'] = False
|
||||||
|
ticks = [0.]
|
||||||
|
monkeypatch.setattr(residual_sessions.time, 'monotonic', lambda: ticks[0])
|
||||||
|
monkeypatch.setattr(residual_sessions.time, 'sleep', lambda delay: ticks.__setitem__(0, ticks[0]+delay))
|
||||||
|
monkeypatch.setattr(residual_sessions, '_post_window_message', post)
|
||||||
|
original = (root/'result.json').read_bytes()
|
||||||
|
assert residual_sessions.finish_owned_idle_session(root/'session.json') is proved
|
||||||
|
assert state['posts'] == ([(201, 12, 245), (100, 12, 16)] if proved else [])
|
||||||
|
assert (root/'result.json').read_bytes() == original
|
||||||
@@ -228,6 +228,7 @@ def test_confirmed_native_close_transfers_mapping_to_current_library(qtbot, tmp_
|
|||||||
path_lease=old, process=SimpleNamespace(poll=lambda: 0))
|
path_lease=old, process=SimpleNamespace(poll=lambda: 0))
|
||||||
window._poll_native_backup(); qtbot.waitUntil(lambda: not window.busy)
|
window._poll_native_backup(); qtbot.waitUntil(lambda: not window.busy)
|
||||||
assert window._native_backup_session is None
|
assert window._native_backup_session is None
|
||||||
|
qtbot.waitUntil(lambda: window._lease_pending == 0)
|
||||||
assert backend.cancelled == [] and current.created
|
assert backend.cancelled == [] and current.created
|
||||||
window.close()
|
window.close()
|
||||||
qtbot.waitUntil(lambda: backend.cancelled == [current.drive])
|
qtbot.waitUntil(lambda: backend.cancelled == [current.drive])
|
||||||
|
|||||||
@@ -90,3 +90,33 @@ def test_full_snapshot_helper_does_not_filter_unknown_descendants(tmp_path, monk
|
|||||||
assert len(queries) == 1 and 'WHERE' not in queries[0]
|
assert len(queries) == 1 and 'WHERE' not in queries[0]
|
||||||
row = json.loads(job.with_name('result.json').read_text('utf-8'))['owners'][0]
|
row = json.loads(job.with_name('result.json').read_text('utf-8'))['owners'][0]
|
||||||
assert row['name'] == 'custom-native-child.exe' and row['created'] == 'creation-time'
|
assert row['name'] == 'custom-native-child.exe' and row['created'] == 'creation-time'
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('contents', [None, b'broken-json', b'[]', b'\xff'])
|
||||||
|
def test_readonly_helper_quietly_rejects_unavailable_request(tmp_path, contents):
|
||||||
|
from cbb_refresh_verify.application import main
|
||||||
|
|
||||||
|
request = tmp_path/'request.json'
|
||||||
|
if contents is not None:
|
||||||
|
request.write_bytes(contents)
|
||||||
|
assert main(['--owner-probe', str(request)]) == 1
|
||||||
|
assert not request.with_name('result.json').exists()
|
||||||
|
|
||||||
|
|
||||||
|
def test_readonly_helper_quietly_exits_when_supervisor_removes_probe(tmp_path, monkeypatch):
|
||||||
|
from cbb_refresh_verify.owner_probe import owner_probe_main
|
||||||
|
from types import SimpleNamespace
|
||||||
|
import win32com.client
|
||||||
|
|
||||||
|
probe = tmp_path/'probe'
|
||||||
|
probe.mkdir()
|
||||||
|
request = probe/'request.json'
|
||||||
|
request.write_text('{"names":["ExpeditionPCB.exe"]}', encoding='utf-8')
|
||||||
|
|
||||||
|
def enumerate_then_clean(_):
|
||||||
|
request.unlink()
|
||||||
|
probe.rmdir()
|
||||||
|
return []
|
||||||
|
|
||||||
|
monkeypatch.setattr(win32com.client, 'GetObject', lambda _: SimpleNamespace(ExecQuery=enumerate_then_clean))
|
||||||
|
assert owner_probe_main(request) == 1
|
||||||
+16
-3
@@ -14,7 +14,20 @@ def test_spec_packages_adaptive_dialog_rules_and_uia_modules():
|
|||||||
assert 'pywinauto' in text
|
assert 'pywinauto' in text
|
||||||
|
|
||||||
|
|
||||||
def test_spec_analysis_includes_pywin32_timezone_dynamic_import():
|
def test_spec_analysis_includes_pywin32_timezone_dynamic_import(tmp_path):
|
||||||
|
captured = _capture_spec_analysis(tmp_path)
|
||||||
|
assert 'win32timezone' in captured['hiddenimports']
|
||||||
|
|
||||||
|
|
||||||
|
def test_spec_copies_quick_start_next_to_executable(tmp_path):
|
||||||
|
target = tmp_path / 'CbbRefreshVerify-Background'
|
||||||
|
target.mkdir()
|
||||||
|
_capture_spec_analysis(target)
|
||||||
|
guide = (target / '使用说明.txt').read_text(encoding='utf-8')
|
||||||
|
assert 'CbbRefreshVerify.exe' in guide and '--data-root' in guide
|
||||||
|
|
||||||
|
|
||||||
|
def _capture_spec_analysis(target):
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
captured = {}
|
captured = {}
|
||||||
def analysis(*args, **kwargs):
|
def analysis(*args, **kwargs):
|
||||||
@@ -23,6 +36,6 @@ def test_spec_analysis_includes_pywin32_timezone_dynamic_import():
|
|||||||
path = Path('packaging/CbbRefreshVerify.spec')
|
path = Path('packaging/CbbRefreshVerify.spec')
|
||||||
namespace = {'SPECPATH': str(path.parent.resolve()), 'Analysis': analysis,
|
namespace = {'SPECPATH': str(path.parent.resolve()), 'Analysis': analysis,
|
||||||
'PYZ': lambda *a, **k: None, 'EXE': lambda *a, **k: None,
|
'PYZ': lambda *a, **k: None, 'EXE': lambda *a, **k: None,
|
||||||
'COLLECT': lambda *a, **k: None}
|
'COLLECT': lambda *a, **k: SimpleNamespace(name=str(target))}
|
||||||
exec(compile(path.read_text(encoding='utf-8'), str(path), 'exec'), namespace)
|
exec(compile(path.read_text(encoding='utf-8'), str(path), 'exec'), namespace)
|
||||||
assert 'win32timezone' in captured['hiddenimports']
|
return captured
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import json
|
||||||
from contextlib import nullcontext
|
from contextlib import nullcontext
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
from dataclasses import replace
|
from dataclasses import replace
|
||||||
@@ -112,3 +113,253 @@ 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
|
changed=replace(original,controls=tuple(replace(c,handle=c.handle+1) if c.control_id==6 else c
|
||||||
for c in original.controls))
|
for c in original.controls))
|
||||||
assert controller.handle(changed,(changed,),**kwargs).error_code=='DATABASE_RECOVERY_REQUIRED'
|
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()
|
||||||
|
|
||||||
|
shared_address = shared.parent/'cdbsvr/sAddress.adr'
|
||||||
|
shared_address.parent.mkdir()
|
||||||
|
address_bytes = b'shared-server\n127.0.0.1\n192.168.0.6\n10001\n'
|
||||||
|
shared_address.write_bytes(address_bytes)
|
||||||
|
held = win32file.CreateFile(str(shared), win32con.GENERIC_READ, 0, None,
|
||||||
|
win32con.OPEN_EXISTING, 0, None)
|
||||||
|
try:
|
||||||
|
skipped, _ = run('shared-address-occupied', 7)
|
||||||
|
assert skipped.error_code == 'PCB_OPEN_SKIPPED'
|
||||||
|
assert str(shared) in skipped.detail
|
||||||
|
finally:
|
||||||
|
held.Close()
|
||||||
|
unsupported, evidence = run('shared-address-verified-binding', 7)
|
||||||
|
assert unsupported.error_code == 'PCB_OPEN_SKIPPED'
|
||||||
|
assert 'SHARED_ICDB_INSPECTION_UNAVAILABLE' in unsupported.detail
|
||||||
|
denial = json.loads((evidence/'pcb-open-resource-denied.json').read_text(encoding='utf-8'))
|
||||||
|
assert denial['database'] == str(shared.parent)
|
||||||
|
assert denial['address'] == str(shared_address)
|
||||||
|
assert denial['exclusive_file_observed'] is True
|
||||||
|
assert shared_address.read_bytes() == address_bytes
|
||||||
|
shared_address.unlink()
|
||||||
|
|
||||||
|
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'
|
||||||
|
|
||||||
|
def test_shared_address_is_bound_to_shared_database_without_a_project_prj(tmp_path):
|
||||||
|
from cbb_refresh_verify.file_probe import _snapshot
|
||||||
|
|
||||||
|
library = tmp_path / 'lib.lmc'
|
||||||
|
library.write_bytes(b'fixture')
|
||||||
|
symbols = tmp_path / 'SymbolLibs'
|
||||||
|
database = symbols / '__ReusableBlocksSymb'
|
||||||
|
address = database / 'cdbsvr/sAddress.adr'
|
||||||
|
address.parent.mkdir(parents=True)
|
||||||
|
address.write_text('fixture address')
|
||||||
|
(database / 'icdb.dat').write_bytes(b'fixture')
|
||||||
|
|
||||||
|
proof = _snapshot(library, (symbols,))
|
||||||
|
|
||||||
|
assert proof['inspection_targets'] == [{
|
||||||
|
'scope': 'shared_symbols', 'database': str(database), 'address': str(address)
|
||||||
|
}]
|
||||||
|
assert str(address) in proof['binding_files']
|
||||||
|
assert str(database / 'icdb.dat') in proof['exclusive_files']
|
||||||
@@ -117,6 +117,7 @@ def batch_cli(tmp_path, monkeypatch):
|
|||||||
def __enter__(self): return self
|
def __enter__(self): return self
|
||||||
def __exit__(self, *_): pass
|
def __exit__(self, *_): pass
|
||||||
def retain_for_recovery(self): retained.append(self.drive)
|
def retain_for_recovery(self): retained.append(self.drive)
|
||||||
|
Lease.mentor_path.write_bytes(b'library')
|
||||||
monkeypatch.setattr(network.LibraryPathLease, 'acquire', lambda _: Lease())
|
monkeypatch.setattr(network.LibraryPathLease, 'acquire', lambda _: Lease())
|
||||||
monkeypatch.setattr(network, 'select_library_file', lambda path: path)
|
monkeypatch.setattr(network, 'select_library_file', lambda path: path)
|
||||||
monkeypatch.setattr(reader, 'read_library_fast', lambda *a, **kw: LibraryReadResult((
|
monkeypatch.setattr(reader, 'read_library_fast', lambda *a, **kw: LibraryReadResult((
|
||||||
@@ -166,3 +167,37 @@ def test_retained_mapping_logs_context_and_confirmed_release_guidance(batch_cli,
|
|||||||
assert 'Z:' in notice and r'\\server\share' in notice
|
assert 'Z:' in notice and r'\\server\share' in notice
|
||||||
assert '释放残留会话' in notice and '确认' in notice
|
assert '释放残留会话' in notice and '确认' in notice
|
||||||
assert 'net use' not in notice.lower()
|
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]
|
||||||
|
|
||||||
|
|
||||||
|
def test_batch_cli_uses_bounded_session_admission(batch_cli, monkeypatch):
|
||||||
|
from cbb_refresh_verify.operation_queue import NativeQueue, QueueUnavailable
|
||||||
|
|
||||||
|
app, runner, _, _, _ = batch_cli
|
||||||
|
calls = []
|
||||||
|
def admit(self, action, **kwargs):
|
||||||
|
calls.append(kwargs)
|
||||||
|
raise QueueUnavailable(kwargs['context'].library, timed_out=True)
|
||||||
|
monkeypatch.setattr(NativeQueue, 'run', admit)
|
||||||
|
def run(requests, **kwargs):
|
||||||
|
assert kwargs['context'].library == str(requests[0].lmc_file)
|
||||||
|
with pytest.raises(QueueUnavailable):
|
||||||
|
kwargs['item_executor'](requests[0], lambda: pytest.fail('unexpected write'))
|
||||||
|
return [VerifyResult('SKIPPED') for _ in requests]
|
||||||
|
monkeypatch.setattr(runner, 'run_batch', run)
|
||||||
|
assert app.main(['--batch-lmc', 'lib.lmc', '--block', 'One', '--block', 'Two']) == 2
|
||||||
|
assert len(calls) == 1
|
||||||
|
assert calls[0]['wait_for_release_seconds'] == 120
|
||||||
@@ -290,3 +290,84 @@ 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')
|
print(f'catalog rows={size} load={loaded:.3f}s local_actions={elapsed:.3f}s')
|
||||||
assert elapsed < 2.0
|
assert elapsed < 2.0
|
||||||
assert window.selected_records() == ()
|
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
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('prewrite', (True, False))
|
||||||
|
def test_prewrite_cancellation_can_resubmit_and_rechecks_ready(qtbot, tmp_path, monkeypatch, prewrite):
|
||||||
|
calls = []
|
||||||
|
reads = []
|
||||||
|
|
||||||
|
def verify(request):
|
||||||
|
calls.append(request.block_name)
|
||||||
|
window.stop.set()
|
||||||
|
return VerifyResult('CANCELLED', safe_to_continue=False, cancelled_before_write=prewrite)
|
||||||
|
|
||||||
|
def read(names, library):
|
||||||
|
reads.append(names)
|
||||||
|
return {'Beta': 'READY' if len(reads) > 1 else 'PENDING'}
|
||||||
|
|
||||||
|
window = load_window(qtbot, tmp_path, monkeypatch, verifier=verify,
|
||||||
|
status_refresher=lambda *_: pytest.fail('cancelled batch started a status refresh'))
|
||||||
|
window.catalog_reader = object()
|
||||||
|
monkeypatch.setattr(window, '_execution_status_reader', lambda *_: read)
|
||||||
|
window.search_edit.setText('beta')
|
||||||
|
window.batch_button.click()
|
||||||
|
qtbot.waitUntil(lambda: not window.busy)
|
||||||
|
assert calls == ['Beta']
|
||||||
|
assert window.visible_records()[0].status == ('PENDING' if prewrite else 'UNKNOWN')
|
||||||
|
assert window.batch_button.isEnabled() == prewrite
|
||||||
|
if not prewrite:
|
||||||
|
return
|
||||||
|
|
||||||
|
window.batch_button.click()
|
||||||
|
qtbot.waitUntil(lambda: not window.busy)
|
||||||
|
assert reads == [('Beta',), ('Beta',)]
|
||||||
|
assert calls == ['Beta']
|
||||||
|
assert window.cbb_table.item(1, 3).text().startswith('SKIPPED:')
|
||||||
Reference in new issue
Block a user