Compare commits

...
27 Commits
Author SHA1 Message Date
阿白叔 8b870a46ae release: prepare CBB Refresh Verify 0.2.5 2026-11-26 17:50:15 +08:00
阿白叔 dfb819e7dd fix: wait for native iCDB shutdown after a completed save 2026-11-25 21:51:49 +08:00
阿白叔 81a5d1ae4b test: keep release preview assertions scoped to the fixture 2026-11-25 18:44:52 +08:00
阿白叔 7d9a107921 fix: persist canceled batch reports while native cleanup continues 2026-11-25 18:28:10 +08:00
阿白叔 becaf2e8e4 fix: cancel orphaned PCB before its license completes 2026-11-25 18:08:14 +08:00
阿白叔 e4fc37a291 fix: cancel owned prewrite PCB at the license selector 2026-11-25 17:54:01 +08:00
阿白叔 d45a29503d test: scope the passive release assertion to its library 2026-11-25 17:36:29 +08:00
阿白叔 0c02ff6966 fix: cancel superseded release probes without stopping the batch 2026-11-25 16:15:26 +08:00
阿白叔 b9d52e84cd fix: stop duplicate observers after confirmed library release 2026-11-25 15:41:33 +08:00
阿白叔 4e7efe4f41 fix: resume orphan cleanup after a startup prompt 2026-11-25 14:44:06 +08:00
阿白叔 33a41b25fb fix: prove retained database release before batch admission 2026-11-25 14:33:32 +08:00
阿白叔 b3d69ee722 fix: close a proven design after interrupted PCB startup 2026-11-25 14:18:52 +08:00
阿白叔 9fa9625dba test: separate passive release preview from observer cleanup 2026-11-25 13:47:03 +08:00
阿白叔 a63861f0e2 test: use the Windows snapshot in catalog wait integration tests 2026-11-25 12:13:09 +08:00
阿白叔 b015827e97 fix: retry catalog when the blocking process exits 2026-11-25 12:03:05 +08:00
阿白叔 75612cd4da fix: report known catalog conflicts before WMI startup 2026-11-25 11:53:07 +08:00
阿白叔 0ee24d7beb fix: allow bounded full-library release scans to complete 2026-11-25 11:25:06 +08:00
阿白叔 edd1e088af fix: keep the post-save release result through slow file probes 2026-11-25 11:19:34 +08:00
阿白叔 2e87627ef1 test: verify release wording and cancelled item resubmission 2026-11-25 11:02:28 +08:00
阿白叔 6a716052f4 fix: dismiss a verified prewrite startup tip during release 2026-11-25 10:26:16 +08:00
阿白叔 2722d09b59 fix: preserve a queued retry while an identified Mentor save runs 2026-11-25 10:10:21 +08:00
阿白叔 6aed02d26b fix: allow same-window retry after early PCB cancellation 2026-11-25 10:02:11 +08:00
阿白叔 806c1696ab fix: recognize native startup journal order during recovery 2026-11-25 09:48:26 +08:00
阿白叔 5bab125122 fix: resume CBB batches after verified native release 2026-11-25 09:28:05 +08:00
阿白叔 c76b755f13 fix: reconcile native save release and resume affected CBB batches 2026-11-24 13:34:56 +08:00
阿白叔 443668aa4b fix: retain native save completion through cancellation and restart 2026-11-24 08:48:33 +08:00
阿白叔 18349413c5 fix: queue catalog reads while recovered sessions exit 2026-11-23 21:52:24 +08:00
50 changed files with 2303 additions and 205 deletions

No files matched your search

+2 -1
View File
@@ -43,4 +43,5 @@ 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') for guide in ('使用说明.txt', '现场使用须知.md', 'Known-Issues.md', 'Release-Notes.md'):
copyfile(project_root / 'packaging' / guide, Path(coll.name) / guide)
+10
View File
@@ -0,0 +1,10 @@
# 0.2.5 已知问题
| 编号 | 现场现象 | 处理方式 | 后续安排 |
| --- | --- | --- | --- |
| KI-1 | 共享多地址 `sAddress.adr` 场景下,取消后同一窗口重跑可能等待约 119 秒,随后返回 `NATIVE_SESSION_PENDING`。 | 确认写入结束及资源可用后,重启应用、重新读库再提交。 | 计划在 0.2.6 修复。 |
| KI-2 | 强杀或崩溃后可能遗留 `ExpeditionPCB.exe`,重启等待约 120 秒后停止。 | 核对工程、进程身份和保存状态。确认安全后处理本任务残留,再重启。 | 计划在 0.2.6 完善原生进程回收。 |
| KI-3 | 共享多地址 ADR 无法确认时,相关 CBB 可能自动跳过。 | 由库维护人员核对地址及实际会话,按单项跟踪。 | 计划在 0.2.6 修复。 |
| KI-4 | 保存失败、真实磁盘满和写入中断后的数据完整性仍缺现场覆盖。 | 首次写入前手工备份。异常后核对保存、关库和重新打开结果。 | 补齐故障测试和现场证据。 |
完整处置步骤见随包的《现场使用须知》。 [现场验收结论](https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795/issues/21#issuecomment-642)
+24
View File
@@ -0,0 +1,24 @@
# CBB 刷新校验 0.2.5
0.2.5 是 Windows x64 正式版,使用定位为有人值守的批量校验。完整解压 ZIP,运行 `CbbRefreshVerify.exe`。首次现场使用请先运行已知正常的单块,再运行小批量。
## 相对 0.2.4 的改动
- 目录读取按目标中心库和共享资源判定占用。独立外库可以保持打开。确有同库或共享资源占用时,程序显示原因并在释放后重试。
- 同一数据目录复用已有主窗口。不同数据目录的实例写入同一库时,通过库级锁协调。
- 无效输入和不可写的数据目录返回明确提示,包括 `INPUT_MISSING`、`INPUT_SUFFIX`、`INPUT_EMPTY` 和 `DATA_ROOT_UNWRITABLE`。
- 正常保存并关闭 PCB 后,最多等待 240 秒确认 iCDB 文件释放。确认释放后继续查询 READY,持续占用时报告释放待确认及最后查到的占用路径。
- 在现场 11 块批量样本中,单块耗时约 23–29 秒。独立外库保持打开时,目标库目录读完耗时 14.1 秒。
## 验收与使用范围
现场验收使用候选构建 `dfb819e7`,环境为 Windows 11、Mentor EE 7.9.5 和 364 项隔离中心库,成绩为 **97/110(88.2/100,B)**。正式版在该构建基础上更新版本号与随包文档。 [现场评分与通过条件](https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795/issues/21#issuecomment-642) · [PR #22 发布验收](https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795/pulls/22#issuecomment-643)
| 编号 | 发布时的已知问题 |
| --- | --- |
| KI-1 | 多地址共享 ADR 场景下,取消后同窗重跑可能需要重启。 |
| KI-2 | 崩溃后仍可能残留 PCB 进程,需要现场核对并清理。 |
| KI-3 | 无法确认共享多地址 ADR 的工程可能跳过,需单独跟踪。 |
| KI-4 | 保存失败、真实磁盘满和写入中断后的现场证据待补。 |
随包提供《现场使用须知》、`Known-Issues.md` 及文件 SHA-256 清单。发布页单独提供 ZIP 的 SHA-256。
+5 -1
View File
@@ -1,9 +1,13 @@
CBB 刷新校验使用说明 CBB 刷新校验 0.2.5 使用说明
将 ZIP 完整解压到可写文件夹,保留 CbbRefreshVerify.exe 和 _internal, 将 ZIP 完整解压到可写文件夹,保留 CbbRefreshVerify.exe 和 _internal,
双击 CbbRefreshVerify.exe。目标电脑需要安装 Mentor EE 7.9.5, 双击 CbbRefreshVerify.exe。目标电脑需要安装 Mentor EE 7.9.5,
并能访问中心库及其依赖。写入或恢复前请手动保留可用备份。 并能访问中心库及其依赖。写入或恢复前请手动保留可用备份。
本版用于有人值守的批量校验。首次现场使用请先跑单块和小批量。
打开随包的《现场使用须知》和 Known-Issues.md,了解取消后重跑、
异常退出和共享 iCDB 地址待确认时的处理方式。
在「检验」页选择 .lmc 文件并点击「读取 CBB」。目录预览先出现, 在「检验」页选择 .lmc 文件并点击「读取 CBB」。目录预览先出现,
READY 和待验证状态会随后由 Mentor 核对。确认中心库和目标工程后 READY 和待验证状态会随后由 Mentor 核对。确认中心库和目标工程后
开始校验。校验会保存工程,经 Mentor 确认为 READY 才显示通过。 开始校验。校验会保存工程,经 Mentor 确认为 READY 才显示通过。
+20
View File
@@ -0,0 +1,20 @@
# CBB 刷新校验 0.2.5 现场使用须知
## 首次运行
1. 下载 Windows x64 ZIP,对照发布页的 `SHA256SUMS.txt` 校验 ZIP。完整解压到可写目录,保留 `CbbRefreshVerify.exe` 和 `_internal`。
2. 确认本机已安装 Mentor EE 7.9.5,可以访问目标中心库及共享库。首次写入或恢复前,手工备份目标库及相关工程。
3. 在「检验」页读取目标 `.lmc`,核对库路径、目录条目和 READY 状态。先跑一个已知正常的 CBB,确认保存、关库、资源释放及最终 READY。随后跑一个小批量,检查批次报告、失败原因和后续工程是否继续执行。
## 取消、崩溃和共享数据库占用
- **取消后重跑。** 等待当前操作结束并保留批次报告。若同窗重提显示共享地址待确认或 `NATIVE_SESSION_PENDING`,避免连续提交。确认写入已结束、相关资源可用后,关闭并重启应用,重新读取当前库再提交。
- **崩溃后残留 PCB。** 先核对任务的工程路径、PID、程序路径和日志。进入保存阶段时,等待保存或关库结果,随后检查工程能否打开及库状态。需要结束残留时,仅在已确认是本次任务、已停止写入且可以安全关闭的情况下,从释放界面处理或由操作员通过任务管理器结束该进程。保留外部 Mentor 会话,确认工程及共享库释放后再重启。
- **多地址 `sAddress.adr`。** 按备注和证据核对实际共享数据库及其持有会话。无法确认时,将该工程单独跟踪,请库维护人员确认占用后重提。保留原生地址文件和锁文件。
- **保存失败或磁盘满。** 暂停该库的写操作。保留日志、批次报告和恢复证据,核对剩余空间、保存结果及工程状态,再按备份恢复流程判断是否恢复。
## 值守范围和问题记录
0.2.5 面向有人值守的批量校验。需要安排无人值守时,由现场配套定时重启和残留进程看护。重启应安排在批次收尾后,进程清理需确认任务归属及写入状态。状态不明时交给操作员核对。
在「检验」页点击「打开日志目录」获取日志。反馈时附上版本、操作时间、目标库、CBB 名称、阶段、批次报告及证据路径。具体限制见随包的 `Known-Issues.md`。
+1 -1
View File
@@ -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.4b6" version = "0.2.5"
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
View File
@@ -1 +1 @@
__version__ = "0.2.4b6" __version__ = "0.2.5"
+43 -8
View File
@@ -1,6 +1,6 @@
from __future__ import annotations from __future__ import annotations
import argparse, os, sys import argparse, os, sys
from contextlib import contextmanager from contextlib import contextmanager, ExitStack
from pathlib import Path from pathlib import Path
from typing import Sequence from typing import Sequence
from .network_path import NetworkPathError from .network_path import NetworkPathError
@@ -195,21 +195,42 @@ 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)
with ExitStack() as startup:
return _run_application(args, startup)
def _run_application(args, startup):
command_line = bool(args.batch_lmc or args.smoke_test) command_line = bool(args.batch_lmc or args.smoke_test)
data_root = args.data_root data_root = args.data_root
try: try:
data_root = resolve_data_root(data_root) data_root = resolve_data_root(data_root)
context = configure(data_root)
except (OSError, ValueError, RuntimeError): except (OSError, ValueError, RuntimeError):
location = data_root if data_root is not None else '默认数据目录' location = data_root if data_root is not None else '默认数据目录'
return _report_entry_error(f'DATA_ROOT_UNWRITABLE: 无法写入数据目录 {location}。' return _report_entry_error(f'DATA_ROOT_UNWRITABLE: 无法写入数据目录 {location}。'
'请指定可写的 --data-root。', command_line=command_line) '请指定可写的 --data-root。', command_line=command_line)
if not command_line:
import pywintypes
from PySide6.QtWidgets import QApplication
from .desktop_instance import DesktopInstanceUnavailable, desktop_instance
app = QApplication.instance() or QApplication([sys.executable])
try:
activation_name = startup.enter_context(desktop_instance(data_root))
except (DesktopInstanceUnavailable, pywintypes.error) as error:
return _report_entry_error(str(error), command_line=False)
if activation_name is None:
return 0
try:
context = configure(data_root)
except (OSError, ValueError, RuntimeError):
return _report_entry_error(f'DATA_ROOT_UNWRITABLE: 无法写入数据目录 {data_root}。'
'请指定可写的 --data-root。', command_line=command_line)
logger = context.logger logger = context.logger
logger.info("application_start") 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, wait_for_batch_release, 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, validate_library_file from .network_path import LibraryPathLease, select_library_file, validate_library_file
@@ -254,8 +275,10 @@ 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 .operation_queue import BatchTaskContext, NativeQueue, request_library_keys from .operation_queue import (BatchTaskContext, NativeQueue, QueueCancelled,
QueueUnavailable, request_library_keys)
from .session_record import discover_sessions, handoff_session from .session_record import discover_sessions, handoff_session
from .residual_sessions import recoverable_orphan_session
aliases = tuple(request_library_keys(requests[0])) aliases = tuple(request_library_keys(requests[0]))
task = BatchTaskContext(str(mentor_path), aliases=aliases, task = BatchTaskContext(str(mentor_path), aliases=aliases,
@@ -267,14 +290,21 @@ def main(argv: Sequence[str] | None = None) -> int:
continue continue
old_request = VerifyRequest(Path(old_session['library']), names[0], context.root) old_request = VerifyRequest(Path(old_session['library']), names[0], context.root)
if request_library_keys(old_request).intersection(aliases): if request_library_keys(old_request).intersection(aliases):
handoff_session(old_session['path'], evidence_root=context.root, observe_only=True) path = old_session['path']
handoff_session(path, evidence_root=context.root,
observe_only=lambda path=path: not recoverable_orphan_session(path))
def admit(_request, action): def admit(_request, action):
return queue.run(action, stop=task.stop, context=task, return queue.run(action, stop=task.stop, context=task,
wait_for_release_seconds=120, wait_for_release_seconds=120,
waiting=lambda: logger.info('batch_waiting_for_session_release library=%s', mentor_path)) waiting=lambda: logger.info('batch_waiting_for_session_release library=%s', mentor_path))
wait_for_batch_release(requests[0], task, progress=lambda event: logger.info(
'batch_waiting_for_session_release library=%s detail=%s', mentor_path, event['detail']))
results = run_batch(requests, stop=task.stop, context=task, item_executor=admit) results = run_batch(requests, stop=task.stop, context=task, item_executor=admit)
except (QueueCancelled, QueueUnavailable) as error:
logger.info('batch_admission_stopped library=%s detail=%s', mentor_path, error)
return _report_entry_error(str(error), command_line=True)
except Exception: except Exception:
retain_mapping('batch_exception') retain_mapping('batch_exception')
raise raise
@@ -289,10 +319,15 @@ def main(argv: Sequence[str] | None = None) -> int:
from .ui.main_window import MainWindow, application_icon_path from .ui.main_window import MainWindow, application_icon_path
if args.smoke_test: if args.smoke_test:
os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen') os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')
from PySide6.QtWidgets import QApplication from PySide6.QtWidgets import QApplication
app = QApplication.instance() or QApplication([sys.executable]) app = QApplication.instance() or QApplication([sys.executable])
configure_qt_application(app) configure_qt_application(app)
window = MainWindow(logging_context=context); window.show() window = MainWindow(logging_context=context)
if not command_line:
from .desktop_instance import listen_for_activation
server = listen_for_activation(activation_name, window, logger)
startup.callback(server.close)
window.show()
icon_path = application_icon_path() icon_path = application_icon_path()
if icon_path.is_file(): if icon_path.is_file():
from PySide6.QtGui import QIcon from PySide6.QtGui import QIcon
+4 -1
View File
@@ -101,7 +101,10 @@ def _native_scope_match(command, *, roots=(), files=()):
def _project_text(path): def _project_text(path):
data = path.read_bytes() return _decode_project_text(path.read_bytes())
def _decode_project_text(data):
if data.startswith((b'\xff\xfe', b'\xfe\xff')): if data.startswith((b'\xff\xfe', b'\xfe\xff')):
return data.decode('utf-16') return data.decode('utf-16')
try: try:
+100
View File
@@ -0,0 +1,100 @@
"""Keep one desktop window per data directory in a Windows session."""
from contextlib import contextmanager
import ctypes
import hashlib
import os
import time
class DesktopInstanceUnavailable(RuntimeError):
pass
def _request_activation(name):
from PySide6.QtNetwork import QLocalSocket
socket = QLocalSocket()
try:
socket.connectToServer(name)
if not socket.waitForConnected(100):
return False
if not socket.canReadLine() and not socket.waitForReadyRead(500):
return False
pid = bytes(socket.readLine()).strip()
if not pid.isdigit() or not 0 < int(pid) < 2**32:
return False
# A launcher that owns foreground focus can pass it to the existing GUI.
ctypes.windll.user32.AllowSetForegroundWindow(int(pid))
socket.write(b'activate\n')
socket.flush()
if not socket.canReadLine() and not socket.waitForReadyRead(500):
return False
return bytes(socket.readLine()) == b'activated\n'
finally:
socket.abort()
@contextmanager
def desktop_instance(data_root):
import win32con
import win32event
import win32ts
directory = os.path.normcase(str(data_root.resolve()))
digest = hashlib.sha256(directory.encode('utf-8')).hexdigest()
session = win32ts.ProcessIdToSessionId(os.getpid())
name = f'CbbRefreshVerify795-desktop-{session}-{digest}'
mutex = win32event.CreateMutex(None, False, f'Local\\{name}')
acquired = False
try:
deadline = time.monotonic() + 5
while True:
acquired = win32event.WaitForSingleObject(mutex, 0) in (
win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
if acquired:
yield name
return
if _request_activation(name):
yield None
return
if time.monotonic() >= deadline:
raise DesktopInstanceUnavailable('同一数据目录的窗口正在运行,暂时无法唤起。')
time.sleep(.05)
finally:
if acquired:
win32event.ReleaseMutex(mutex)
mutex.Close()
def listen_for_activation(name, window, logger):
from PySide6.QtNetwork import QLocalServer
server = QLocalServer(window)
server.setSocketOptions(QLocalServer.SocketOption.UserAccessOption)
def receive(socket):
if not socket.canReadLine():
return
if bytes(socket.readLine()) == b'activate\n':
if window.isMinimized():
window.showNormal()
else:
window.show()
window.raise_()
window.activateWindow()
logger.info('desktop_instance_activated pid=%s', os.getpid())
socket.write(b'activated\n')
socket.disconnectFromServer()
def connect():
while server.hasPendingConnections():
socket = server.nextPendingConnection()
socket.readyRead.connect(lambda socket=socket: receive(socket))
socket.disconnected.connect(socket.deleteLater)
socket.write(f'{os.getpid()}\n'.encode('ascii'))
server.newConnection.connect(connect)
if not server.listen(name):
raise DesktopInstanceUnavailable(f'无法启动窗口唤起服务:{server.errorString()}')
return server
+4
View File
@@ -299,6 +299,10 @@ def launch_save_helper(command, *, start_gate=None, identity_path=None, operatio
return helper return helper
def supervisor_has_exited():
return _supervisor_lost.is_set()
def start_supervisor_watchdog(supervisor_pid, *, cancel_path=None, stop_clients=False, def start_supervisor_watchdog(supervisor_pid, *, cancel_path=None, stop_clients=False,
session_record_path=None, operation_id=None, supervisor_identity=None): session_record_path=None, operation_id=None, supervisor_identity=None):
"""Record stop intent; a watchdog cannot interrupt an in-flight COM call. """Record stop intent; a watchdog cannot interrupt an in-flight COM call.
+27
View File
@@ -76,6 +76,20 @@ def _tip_target(snapshot):
return target if target is not None and target.class_name == 'Button' else None return target if target is not None and target.class_name == 'Button' else None
def _startup_license_cancel(snapshot):
if snapshot.window_class != '#32770' or snapshot.title:
return None
controls = snapshot.controls
buttons = {(c.control_id, c.name) for c in controls if c.class_name == 'Button' and c.enabled}
expected = {(5225, 'Select the desired product license'), (1, 'OK'), (2, 'Cancel')}
if (buttons not in (expected, expected | {(57670, '')})
or not any(c.control_id == 1522 and c.class_name == 'GXWND' for c in controls)):
return None
options = [c for c in controls if c.control_id == 2 and c.class_name == 'Button'
and c.name == 'Cancel' and c.enabled]
return options[0] if len(options) == 1 else None
def _database_log_declined(root, pcb_pid): def _database_log_declined(root, pcb_pid):
"""The supervisor can dismiss this exact failed-open question before cleanup.""" """The supervisor can dismiss this exact failed-open question before cleanup."""
from dataclasses import fields from dataclasses import fields
@@ -228,6 +242,7 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
cancelled_open = _database_log_declined(root, pcb_pid) cancelled_open = _database_log_declined(root, pcb_pid)
decline_owner = None decline_owner = None
dismissed_tips = set() dismissed_tips = set()
license_cancelled = False
close_handle = None close_handle = None
close_identity = None close_identity = None
close_frame = None close_frame = None
@@ -346,6 +361,18 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
break break
if dismissed: if dismissed:
continue # Prove the Tip disappeared; it does not prove a cancelled open. continue # Prove the Tip disappeared; it does not prove a cancelled open.
if cancelled_prewrite and not license_cancelled:
visible = [w for w in windows if win32gui.GetClassName(w) not in (
'UAC_InputIndicatorOverlayWnd', 'UAC Input Indicator')]
if len(visible) == 1 and win32gui.GetClassName(visible[0]) == '#32770':
prompt = _startup_snapshot(visible[0], pcb_pid)
cancel = _startup_license_cancel(prompt)
if cancel is not None and _startup_snapshot(visible[0], pcb_pid) == prompt:
cleanup_post(cancel.handle, win32con.BM_CLICK)
license_cancelled = True
emit(stage='startup_license_cancelled', pcb_pid=pcb_pid, hwnd=visible[0],
control_id=cancel.control_id)
continue
if declined_hwnd is None: if declined_hwnd is None:
for hwnd in windows: for hwnd in windows:
if win32gui.GetClassName(hwnd) != '#32770': if win32gui.GetClassName(hwnd) != '#32770':
+155 -17
View File
@@ -2,7 +2,7 @@
from contextlib import contextmanager, ExitStack from contextlib import contextmanager, ExitStack
import hashlib import hashlib
import json import json
from pathlib import Path from pathlib import Path, PureWindowsPath
import re import re
import stat import stat
import subprocess import subprocess
@@ -13,31 +13,51 @@ from uuid import uuid4
@contextmanager @contextmanager
def hold_release_files(library, roots=None, *, timeout_seconds=10, stop=None): def hold_release_files(library, roots=None, *, saved_project=None, timeout_seconds=None, stop=None):
"""Only this pure probe may be terminated. stdin EOF releases its handles.""" """Only this pure probe may be terminated. stdin EOF releases its handles."""
from .operation_queue import native_phase
with tempfile.TemporaryDirectory(prefix='cbb-file-probe-') as folder: with tempfile.TemporaryDirectory(prefix='cbb-file-probe-') as folder:
job = Path(folder)/'request.json' job = Path(folder)/'request.json'
token = uuid4().hex token = uuid4().hex
job.write_text(json.dumps({'token': token, 'library': str(library), job.write_text(json.dumps({'token': token, 'library': str(library),
'roots': [str(p) for p in roots] if roots is not None else None}), 'utf-8') 'roots': [str(p) for p in roots] if roots is not None else None,
'saved_project': [str(p) for p in saved_project] if saved_project is not None else None}), 'utf-8')
command = ([sys.executable] if getattr(sys, 'frozen', False) else command = ([sys.executable] if getattr(sys, 'frozen', False) else
[sys.executable, '-m', 'cbb_refresh_verify']) + ['--file-probe', str(job)] [sys.executable, '-m', 'cbb_refresh_verify']) + ['--file-probe', str(job)]
process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0)) stderr=subprocess.DEVNULL, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
try: try:
deadline = time.monotonic()+max(.1, min(10, timeout_seconds)) started = time.monotonic()
limit = 30 if roots is None and saved_project is None else 10
budget = limit if timeout_seconds is None else min(limit, timeout_seconds)
deadline = started + max(.1, budget)
result_path = job.with_name('result.json') result_path = job.with_name('result.json')
while not result_path.exists(): # The isolated helper has its own deadline and cancel signal.
if stop is not None and stop.is_set(): with native_phase(read_only=True):
raise InterruptedError('FILE_PROBE_CANCELLED') while True:
if time.monotonic() >= deadline: if stop is not None and stop.is_set():
raise TimeoutError('FILE_PROBE_TIMEOUT: 文件占用检查超时,未证明释放') raise InterruptedError('FILE_PROBE_CANCELLED')
if process.poll() is not None: if time.monotonic() >= deadline:
raise OSError('FILE_PROBE_UNCONFIRMED: 文件探测未返回证据') try:
time.sleep(.02) progress = json.loads(job.with_name('progress.json').read_text('utf-8'))
except (OSError, ValueError):
progress = {}
stage = progress.get('stage', 'startup')
path = progress.get('path', str(library))
raise TimeoutError(f'FILE_PROBE_TIMEOUT: 文件占用检查超时'
f'({time.monotonic()-started:.1f}s,{stage},{path}),未证明释放')
try:
record = json.loads(result_path.read_text('utf-8'))
break
except FileNotFoundError:
if process.poll() is not None and not result_path.exists():
raise OSError('FILE_PROBE_UNCONFIRMED: 文件探测未返回证据') from None
except PermissionError:
# Windows may temporarily share-lock a newly published receipt.
pass
time.sleep(.02)
if stop is not None and stop.is_set(): if stop is not None and stop.is_set():
raise InterruptedError('FILE_PROBE_CANCELLED') raise InterruptedError('FILE_PROBE_CANCELLED')
record = json.loads(result_path.read_text('utf-8'))
if record.get('token') != token or record.get('status') != 'HELD' or process.poll() is not None: if record.get('token') != token or record.get('status') != 'HELD' or process.poll() is not None:
error = OSError('FILE_PROBE_UNCONFIRMED: '+str(record.get('error', '探测身份或句柄失效'))) error = OSError('FILE_PROBE_UNCONFIRMED: '+str(record.get('error', '探测身份或句柄失效')))
error.winerror = record.get('winerror') error.winerror = record.get('winerror')
@@ -65,10 +85,56 @@ def hold_release_files(library, roots=None, *, timeout_seconds=10, stop=None):
process.wait(3) process.wait(3)
def _snapshot(library, roots): def _shared_server_shutdown(address, data, database, entries):
"""Bind the retained advertisement to the exact native server shutdown."""
lines = data.decode('ascii', errors='replace').splitlines()
if len(lines) < 6 or lines[-1] != '.' or not re.fullmatch(r'(?:[0-9a-f]{4}-){11}[0-9a-f]{4}', lines[0], re.I):
return None
guid = lines[0]
session = re.fullmatch(r'(\d{4}-\d{2}-\d{2}) \d{2}\.\d{2}\.\d{2}-([1-9]\d{0,9})', lines[-2])
if session is None:
return None
log = address.parent/'log'/session[0]/(session[1].replace('-', '.')+'.txt')
if (log not in entries or not stat.S_ISREG(entries[log].st_mode)
or max(entries[database].st_mtime_ns, entries[address].st_mtime_ns) > entries[log].st_mtime_ns):
return None
with log.open('rb') as stream:
raw = stream.read(2*1024*1024+1)
if len(raw) > 2*1024*1024:
return None
from .icdb_recovery import decode_log
messages = re.findall(r'^\[[^\r\n]+\] \[[^\r\n]+\] \[\d+\] ([^\r\n]*)', decode_log(raw), re.M)
if not messages or messages[-1] != 'S: STOP' or messages.count('S: STOP') != 1:
return None
close_prefix = f'Single file [{database}] closed with size ['.casefold()
last_close = next((message for message in reversed(messages)
if message.casefold().startswith(close_prefix)), '')
if not last_close.casefold().startswith(close_prefix + f'{entries[database].st_size} ('):
return None
ordered = (
lambda line: line.startswith('iCDB Server ver.'),
lambda line: line.startswith('Machine [') and line.endswith(f' PID [{session[2]}]'),
lambda line: line.casefold().startswith(f'S: Project path [{database.parent}] on file system ['.casefold()),
lambda line: line == f'S: Server GUID [{guid}]',
lambda line: line == 'S: Wrote data to server address file',
lambda line: line == 'iCDB Server PI: Database closed',
lambda line: line == last_close,
lambda line: line.casefold() == f'AT: ERROR: Could not remove server address file [{address}]'.casefold(),
)
remaining = iter(messages[:-1])
if not all(any(matches(message) for message in remaining) for matches in ordered):
return None
return {'server_guid': guid, 'server_pid': int(session[2]), 'database': str(database.parent),
'log': str(log), 'log_sha256': hashlib.sha256(raw).hexdigest()}
def _snapshot(library, roots, progress=lambda stage, path: None):
from .scoped_manifest import scan_tree from .scoped_manifest import scan_tree
progress('library_metadata', library)
entries = {library: library.lstat()} entries = {library: library.lstat()}
for root in roots: for root in roots:
progress('scan_root', root)
if root.exists(): if root.exists():
entries.update(scan_tree(root)) entries.update(scan_tree(root))
native = sorted(path for path, info in entries.items() if stat.S_ISREG(info.st_mode) native = sorted(path for path, info in entries.items() if stat.S_ISREG(info.st_mode)
@@ -76,15 +142,20 @@ def _snapshot(library, roots):
if library not in native: if library not in native:
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, shared_shutdowns = [], {}, {}
from .icdb_ownership import shared_symbol_database from .icdb_ownership import shared_symbol_database
shared = shared_symbol_database(library) shared = shared_symbol_database(library)
for address in addresses: for address in addresses:
progress('read_address', address)
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: if address == shared/'cdbsvr/sAddress.adr' and shared/'icdb.dat' in native:
targets.append({'scope': 'shared_symbols', 'database': str(shared), 'address': str(address)}) targets.append({'scope': 'shared_symbols', 'database': str(shared), 'address': str(address)})
with_shutdown = _shared_server_shutdown(address, data, shared/'icdb.dat', entries)
if with_shutdown is not None:
shared_shutdowns[str(address)] = with_shutdown
signatures[with_shutdown['log']] = with_shutdown['log_sha256']
continue continue
matches = [] matches = []
for project in database.parent.glob('*.prj'): for project in database.parent.glob('*.prj'):
@@ -101,6 +172,7 @@ def _snapshot(library, roots):
signatures[str(matches[0])] = hashlib.sha256(matches[0].read_bytes()).hexdigest() signatures[str(matches[0])] = hashlib.sha256(matches[0].read_bytes()).hexdigest()
return {'exclusive_files': [str(p) for p in native], 'addresses': [str(p) for p in addresses], return {'exclusive_files': [str(p) for p in native], 'addresses': [str(p) for p in addresses],
'inspection_targets': targets, 'signatures': signatures, 'binding_files': sorted(signatures), 'inspection_targets': targets, 'signatures': signatures, 'binding_files': sorted(signatures),
'shared_shutdowns': shared_shutdowns,
'resource_scope': {'library': str(library), 'roots': [str(p) for p in roots], 'resource_scope': {'library': str(library), 'roots': [str(p) for p in roots],
'projects': sorted(str(p) for p in entries if p.suffix.casefold() == '.prj'), 'projects': sorted(str(p) for p in entries if p.suffix.casefold() == '.prj'),
'shared_dependencies': sorted(str(p.parent) for p in native 'shared_dependencies': sorted(str(p.parent) for p in native
@@ -108,6 +180,54 @@ def _snapshot(library, roots):
'databases': sorted({str(p.parent) for p in native if p.name.casefold() == 'icdb.dat'})}} 'databases': sorted({str(p.parent) for p in native if p.name.casefold() == 'icdb.dat'})}}
def _saved_project_snapshot(library, project, pcb, checked_path):
from .backup_recovery import _decode_project_text
from .icdb_ownership import database_directories
if (project.suffix.casefold() != '.prj' or not project.is_relative_to(library.parent)
or pcb.suffix.casefold() != '.pcb' or not pcb.is_relative_to(project.parent)):
raise ValueError('保存释放检查的工程范围不属于所选库')
candidates = {path/'icdb.dat': False for path in database_directories(library, project, pcb)}
signatures = {}
auxiliary = checked_path(pcb.parent/'pcb.prj')
configs = (project, auxiliary) if auxiliary.exists() and auxiliary != project else (project,)
for config in configs:
if not config.is_file():
raise ValueError(f'保存释放检查缺少工程配置:{config}')
with config.open('rb') as stream:
data = stream.read(1024*1024+1)
if len(data) > 1024*1024:
raise ValueError(f'工程配置过大:{config}')
references = re.findall(r'^KEY[ \t]+iCDBDir\b[^\r\n]*', _decode_project_text(data), re.I | re.M)
signatures[str(config)] = hashlib.sha256(data).hexdigest()
if not references:
continue
reference = (re.fullmatch(r'KEY[ \t]+iCDBDir[ \t]+"([^"\r\n]+)"[ \t]*', references[0], re.I)
if len(references) == 1 else None)
if reference is None or PureWindowsPath(reference[1]).anchor:
raise ValueError(f'工程 iCDBDir 必须唯一且为相对路径:{config}')
target = checked_path(config.parent/reference[1]/'icdb.dat')
if not target.is_relative_to(project.parent):
raise ValueError(f'工程 iCDBDir 越出工程范围:{config}')
candidates[target] = True
files = [str(library)]
for candidate, required in candidates.items():
path = checked_path(candidate)
try:
info = path.lstat()
except FileNotFoundError:
if required:
raise ValueError(f'工程引用的数据库不存在:{path}') from None
continue
if not stat.S_ISREG(info.st_mode):
raise ValueError(f'数据库路径不是普通文件:{path}')
files.append(str(path))
return {'exclusive_files': list(dict.fromkeys(files)), 'binding_files': list(signatures),
'signatures': signatures}
def file_probe_main(job): def file_probe_main(job):
"""No native launch, writes, repair, address deletion or process termination.""" """No native launch, writes, repair, address deletion or process termination."""
import win32con, win32file import win32con, win32file
@@ -115,8 +235,18 @@ def file_probe_main(job):
request = json.loads(job.read_text('utf-8')) request = json.loads(job.read_text('utf-8'))
result = {'token': request['token'], 'status': 'UNCONFIRMED'} result = {'token': request['token'], 'status': 'UNCONFIRMED'}
opening = None opening = None
def progress(stage, path):
try:
pending = job.with_name('progress.pending')
pending.write_text(json.dumps({'stage': stage, 'path': str(path)}), 'utf-8')
pending.replace(job.with_name('progress.json'))
except OSError:
pass # Diagnostics must not change the result of the probe.
try: try:
def checked_path(value): def checked_path(value):
progress('validate_path', value)
path = Path(value).absolute() path = Path(value).absolute()
for part in (path, *path.parents): for part in (path, *path.parents):
try: try:
@@ -130,23 +260,31 @@ def file_probe_main(job):
roots = [checked_path(p) for p in request['roots']] if request['roots'] is not None else [library.parent] roots = [checked_path(p) for p in request['roots']] if request['roots'] is not None else [library.parent]
if library.suffix.casefold() != '.lmc' or any(not p.is_relative_to(library.parent) for p in roots): if library.suffix.casefold() != '.lmc' or any(not p.is_relative_to(library.parent) for p in roots):
raise ValueError('文件探测范围不属于所选库') raise ValueError('文件探测范围不属于所选库')
snapshot = _snapshot(library, roots) def read_snapshot():
if request.get('saved_project') is None:
return _snapshot(library, roots, progress)
project, pcb = (checked_path(path) for path in request['saved_project'])
return _saved_project_snapshot(library, project, pcb, checked_path)
snapshot = read_snapshot()
with ExitStack() as stack: with ExitStack() as stack:
handles = [] handles = []
for path in snapshot['exclusive_files']: for path in snapshot['exclusive_files']:
progress('open_exclusive', path)
opening = path opening = path
handle = win32file.CreateFile(path, win32con.GENERIC_READ, 0, None, handle = win32file.CreateFile(path, win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None) win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
stack.callback(handle.Close) stack.callback(handle.Close)
handles.append(int(handle)) handles.append(int(handle))
for path in snapshot['binding_files']: for path in snapshot['binding_files']:
progress('open_binding', path)
opening = path opening = path
handle = win32file.CreateFile(path, win32con.GENERIC_READ, win32con.FILE_SHARE_READ, handle = win32file.CreateFile(path, win32con.GENERIC_READ, win32con.FILE_SHARE_READ,
None, win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None) None, win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
stack.callback(handle.Close) stack.callback(handle.Close)
handles.append(int(handle)) handles.append(int(handle))
opening = None opening = None
if _snapshot(library, roots) != snapshot: if read_snapshot() != snapshot:
raise ValueError('占用检查期间资源集合变化') raise ValueError('占用检查期间资源集合变化')
pending = job.with_name('result.pending') pending = job.with_name('result.pending')
pending.write_text(json.dumps({**result, **snapshot, 'status': 'HELD', 'handles': handles}), 'utf-8') pending.write_text(json.dumps({**result, **snapshot, 'status': 'HELD', 'handles': handles}), 'utf-8')
+47
View File
@@ -1,5 +1,10 @@
"""Known native database owners touched by a CBB verification operation.""" """Known native database owners touched by a CBB verification operation."""
from pathlib import Path from pathlib import Path
import time
# EE 7.9.5 has taken over three minutes to close a saved Work database.
SAVED_DATABASE_RELEASE_TIMEOUT_SECONDS = 240
def session_resource_scope(job): def session_resource_scope(job):
@@ -33,6 +38,46 @@ def unreleased_addresses(lmc_file, project, pcb):
if (path/'cdbsvr/sAddress.adr').exists()] if (path/'cdbsvr/sAddress.adr').exists()]
def wait_for_saved_database_release(library, project, pcb, *, stop=None,
report_pending=lambda **event: None,
timeout_seconds=SAVED_DATABASE_RELEASE_TIMEOUT_SECONDS):
"""Check scoped files after PCB exits, outside the host native channel."""
from .file_probe import hold_release_files
from .operation_queue import native_phase, note_metadata_progress
deadline = time.monotonic() + timeout_seconds
last_lock = None
while True:
try:
# The file helper has its own bounded deadline. Preserve its result
# if a single SMB probe reaches the generic metadata timeout.
with native_phase(read_only=True), hold_release_files(
library, saved_project=(project, pcb), timeout_seconds=deadline-time.monotonic(), stop=stop) as proof:
return {**proof, 'status': 'RELEASE_CONFIRMED', 'blocked_resources': []}
except (OSError, ValueError) as error:
winerror = getattr(error, 'winerror', None)
blocked = getattr(error, 'blocked_resources', [])
remaining = deadline - time.monotonic()
if stop is not None and stop.is_set():
return {'status': 'UNCONFIRMED', 'detail': '已取消释放检查',
'blocked_resources': last_lock['blocked_resources'] if last_lock else blocked}
if winerror in (32, 33):
if remaining > 0 and (last_lock is None or blocked != last_lock['blocked_resources']):
report_pending(blocked_resources=blocked)
last_lock = {'status': 'IN_USE', 'detail': str(error), 'winerror': winerror,
'blocked_resources': blocked}
elif not isinstance(error, TimeoutError) or last_lock is None:
return {'status': 'UNCONFIRMED', 'detail': str(error), 'winerror': winerror,
'blocked_resources': blocked}
if remaining <= 0:
detail = last_lock['detail']
if isinstance(error, TimeoutError):
detail = f'最后确认的占用:{detail}。最后一次探测:{error}'
return {**last_lock, 'detail': detail}
note_metadata_progress()
time.sleep(min(1, remaining))
def inspect_release_addresses(snapshot, *, stop=None): def inspect_release_addresses(snapshot, *, stop=None):
"""An address is a reason for native inspection, never an occupancy verdict.""" """An address is a reason for native inspection, never an occupancy verdict."""
import tempfile import tempfile
@@ -42,6 +87,8 @@ def inspect_release_addresses(snapshot, *, stop=None):
results = [] results = []
for item in snapshot['inspection_targets']: for item in snapshot['inspection_targets']:
if item.get('scope') == 'shared_symbols': if item.get('scope') == 'shared_symbols':
if item['address'] in snapshot.get('shared_shutdowns', {}):
continue
raise LibraryBusy('SHARED_ICDB_INSPECTION_UNAVAILABLE: 共享符号库地址需要原生核对:' raise LibraryBusy('SHARED_ICDB_INSPECTION_UNAVAILABLE: 共享符号库地址需要原生核对:'
+ item['address']) + item['address'])
target = RepairTarget(Path(item['project']), Path(item['database'])) target = RepairTarget(Path(item['project']), Path(item['database']))
+24 -6
View File
@@ -104,7 +104,8 @@ def has_retained_library(library):
return bool(owner and owner['retained']) return bool(owner and owner['retained'])
def recheck_previous_release(library, evidence_dir, *, block_name=None, required=False, progress=None, stop=None): def recheck_previous_release(library, evidence_dir, *, block_name=None, required=False, progress=None,
stop=None, infer_scope=False):
"""Historical records trigger fresh proof, never process termination or repair.""" """Historical records trigger fresh proof, never process termination or repair."""
if not required: if not required:
with _library_guard(LibraryLock(library).key): with _library_guard(LibraryLock(library).key):
@@ -131,6 +132,8 @@ def recheck_previous_release(library, evidence_dir, *, block_name=None, required
notify('previous_release_check', detail='正在复核历史记录对应的实际占用') notify('previous_release_check', detail='正在复核历史记录对应的实际占用')
try: try:
options = {'stop': stop} if stop is not None else {} options = {'stop': stop} if stop is not None else {}
if infer_scope:
options['infer_scope'] = True
proof = release_retained_library(library, evidence_dir, block_name=block_name, **options) proof = release_retained_library(library, evidence_dir, block_name=block_name, **options)
except Exception as error: except Exception as error:
notify('previous_release_unconfirmed', detail=str(error)) notify('previous_release_unconfirmed', detail=str(error))
@@ -373,6 +376,9 @@ def _owner_matches_scope(item, library, roots):
return None return None
candidates = [] candidates = []
worker_flags = {'--verify-worker', '--repair-worker', '--management-worker', '--native-backup-worker'} worker_flags = {'--verify-worker', '--repair-worker', '--management-worker', '--native-backup-worker'}
path_flags = {'-icdb', '-project', '-p'}
if ntpath.basename(str(item.get('name') or args[0])).casefold() == 'icdbnetserver.exe':
path_flags.add('-db')
for index, arg in enumerate(args[1:], 1): for index, arg in enumerate(args[1:], 1):
if arg.casefold() in worker_flags and index + 1 < len(args): if arg.casefold() in worker_flags and index + 1 < len(args):
try: try:
@@ -388,7 +394,7 @@ def _owner_matches_scope(item, library, roots):
value = arg.split('=', 1)[1] if arg.startswith('-') and '=' in arg else arg value = arg.split('=', 1)[1] if arg.startswith('-') and '=' in arg else arg
if (ntpath.isabs(value) and (ntpath.splitext(value)[1].casefold() in ('.prj', '.pcb', '.lmc') if (ntpath.isabs(value) and (ntpath.splitext(value)[1].casefold() in ('.prj', '.pcb', '.lmc')
or arg.casefold().startswith(('-project=', '-icdb=')) or arg.casefold().startswith(('-project=', '-icdb='))
or args[index - 1].casefold() in ('-icdb', '-project', '-p'))): or args[index - 1].casefold() in path_flags)):
candidates.append(value) candidates.append(value)
normalized_roots = [ntpath.normcase(ntpath.normpath(str(root))) for root in roots] normalized_roots = [ntpath.normcase(ntpath.normpath(str(root))) for root in roots]
expected_library = ntpath.normcase(ntpath.normpath(str(library))) expected_library = ntpath.normcase(ntpath.normpath(str(library)))
@@ -599,7 +605,8 @@ def _prove_library_released(library, block_name=None, *, block_names=(), allow_u
uninitialize_com(initialized) uninitialize_com(initialized)
def release_retained_library(library, evidence_dir, *, block_name=None, block_names=(), stop=None): def release_retained_library(library, evidence_dir, *, block_name=None, block_names=(), stop=None,
infer_scope=False):
"""Reconcile historical leases after fresh owner/address/access proof. """Reconcile historical leases after fresh owner/address/access proof.
The upload sidecar is never deleted. This acknowledges process release, The upload sidecar is never deleted. This acknowledges process release,
@@ -623,6 +630,8 @@ def release_retained_library(library, evidence_dir, *, block_name=None, block_na
if stop is not None and stop.is_set(): if stop is not None and stop.is_set():
raise InterruptedError('已停止释放检查') raise InterruptedError('已停止释放检查')
with _library_guard(lease.key): with _library_guard(lease.key):
if stop is not None and stop.is_set():
raise InterruptedError('已停止释放检查')
owner = _owners.get(lease.key) owner = _owners.get(lease.key)
if owner and (not owner['retained'] or owner['depth']): if owner and (not owner['retained'] or owner['depth']):
raise LibraryBusy('本应用操作仍在使用库锁。') raise LibraryBusy('本应用操作仍在使用库锁。')
@@ -640,9 +649,18 @@ def release_retained_library(library, evidence_dir, *, block_name=None, block_na
before = {path: path.read_bytes() if path.exists() else None for path in checkpoints} before = {path: path.read_bytes() if path.exists() else None for path in checkpoints}
unknown = any(data is not None and checkpoint_record(path) is None for path, data in before.items()) unknown = any(data is not None and checkpoint_record(path) is None for path, data in before.items())
records = [checkpoint_record(path) for path, data in before.items() if data is not None] records = [checkpoint_record(path) for path, data in before.items() if data is not None]
scoped_blocks = (requested_blocks if requested_blocks and all(record if infer_scope:
and record.get('block_name') in requested_blocks for record in records) recorded_blocks = [record.get('block_name') for record in records if record]
and (owner is None or owner.get('block_name') in requested_blocks) else ()) if owner:
recorded_blocks.append(owner.get('block_name'))
recorded_blocks.extend(block for _, block, _ in retained.values())
scoped_blocks = tuple(dict.fromkeys(recorded_blocks)) if all(recorded_blocks) and not unknown else ()
if any(name in ('.', '..') or any(c in name for c in '\\/:*?"<>|') for name in scoped_blocks):
scoped_blocks = ()
else:
scoped_blocks = (requested_blocks if requested_blocks and all(record
and record.get('block_name') in requested_blocks for record in records)
and (owner is None or owner.get('block_name') in requested_blocks) else ())
scoped = scoped_blocks[0] if len(scoped_blocks) == 1 else None scoped = scoped_blocks[0] if len(scoped_blocks) == 1 else None
reconciled = [{'kind': 'checkpoint', 'path': str(path), 'recognized': metadata is not None, reconciled = [{'kind': 'checkpoint', 'path': str(path), 'recognized': metadata is not None,
**{key: (metadata or {}).get(key) for key in ('block_name', 'lease_id', 'pid', 'status', 'time')}} **{key: (metadata or {}).get(key) for key in ('block_name', 'lease_id', 'pid', 'status', 'time')}}
+37 -9
View File
@@ -755,9 +755,15 @@ def execute_job(job, emit):
command=list(command), strategy='reusable_circuit_direct') command=list(command), strategy='reusable_circuit_direct')
pcb_deadline = (dispatch_deadline if job.get('native_lm_verify') else pcb_deadline = (dispatch_deadline if job.get('native_lm_verify') else
time.monotonic()+pcb_startup_timeout_seconds(job['timeout'])) time.monotonic()+pcb_startup_timeout_seconds(job['timeout']))
cancelled_startup = False
while time.monotonic() < pcb_deadline: while time.monotonic() < pcb_deadline:
if job.get('cancel_signal') and Path(job['cancel_signal']).exists(): if not cancelled_startup and job.get('cancel_signal') and Path(job['cancel_signal']).exists():
raise RuntimeError('VERIFY_CANCELLED: PCB 启动期间收到停止请求') if not prewrite_eligible or launcher_process is None:
raise RuntimeError('VERIFY_CANCELLED: PCB 启动期间收到停止请求')
cancelled_startup = True
# Cancellation after CreateProcess may precede discovery of its
# child. Bind the exact client for cleanup without attaching COM.
pcb_deadline = min(pcb_deadline, time.monotonic()+5)
records = _process_details('ExpeditionPCB.exe') records = _process_details('ExpeditionPCB.exe')
worker = select_reusable_circuit_worker( worker = select_reusable_circuit_worker(
records, records,
@@ -786,6 +792,8 @@ def execute_job(job, emit):
pass pass
break break
time.sleep(.2) time.sleep(.2)
if cancelled_startup or job.get('cancel_signal') and Path(job['cancel_signal']).exists():
raise RuntimeError('VERIFY_CANCELLED: PCB 启动期间收到停止请求')
if worker_pid is None: if worker_pid is None:
if job.get('native_lm_verify'): if job.get('native_lm_verify'):
raise RuntimeError('VERIFY_DISPATCH_FAILED: LM 菜单返回但未观察到目标 PCB,未执行校验') raise RuntimeError('VERIFY_DISPATCH_FAILED: LM 菜单返回但未观察到目标 PCB,未执行校验')
@@ -844,6 +852,8 @@ def execute_job(job, emit):
cscript = Path(os.environ.get('WINDIR', r'C:\Windows'))/'SysWOW64'/'cscript.exe' cscript = Path(os.environ.get('WINDIR', r'C:\Windows'))/'SysWOW64'/'cscript.exe'
from .desktop_worker import launch_save_helper from .desktop_worker import launch_save_helper
helper_gate = root/'start-save.signal' helper_gate = root/'start-save.signal'
from .residual_sessions import OrphanedVerifySavePrompt
orphaned_prompt = OrphanedVerifySavePrompt(job, worker_pid, emit)
with (root/'save.log').open('w', encoding='utf-8') as log: with (root/'save.log').open('w', encoding='utf-8') as log:
helper = launch_save_helper([str(cscript), '//nologo', str(script), job['project'], helper = launch_save_helper([str(cscript), '//nologo', str(script), job['project'],
Path(job['pcb']).name, str(job.get('cancel_signal') or ''), str(helper_gate)], Path(job['pcb']).name, str(job.get('cancel_signal') or ''), str(helper_gate)],
@@ -861,11 +871,12 @@ def execute_job(job, emit):
last_markers = current last_markers = current
from .runtime_timing import parse_save_progress from .runtime_timing import parse_save_progress
emit(stage='save_progress', helper_exited=False, **parse_save_progress('\n'.join(current))) emit(stage='save_progress', helper_exited=False, **parse_save_progress('\n'.join(current)))
orphaned_prompt.poll(current)
time.sleep(.2) time.sleep(.2)
code = helper.returncode code = helper.returncode
save_log = (root/'save.log').read_bytes().decode('utf-8', errors='replace') save_log = (root/'save.log').read_bytes().decode('utf-8', errors='replace')
from .runtime_timing import parse_save_progress from .runtime_timing import parse_save_progress
emit(stage='save_progress', helper_exited=True, **parse_save_progress(save_log)) emit(stage='save_progress', helper_exited=True, helper_exit_code=code, **parse_save_progress(save_log))
markers = set(save_log.splitlines()) markers = set(save_log.splitlines())
from .operation_lifecycle import classify_save_state from .operation_lifecycle import classify_save_state
write_facts = classify_save_state(save_log.splitlines(), helper_exited=True, native_released=None) write_facts = classify_save_state(save_log.splitlines(), helper_exited=True, native_released=None)
@@ -1018,25 +1029,42 @@ def worker_main(request_path):
def emit(**event): def emit(**event):
from .session_record import update_worker_state from .session_record import update_worker_state
stage = event.get('stage')
phase = {'save_start': 'NATIVE_CALL', 'integration_action': 'NATIVE_CALL', phase = {'save_start': 'NATIVE_CALL', 'integration_action': 'NATIVE_CALL',
'integration_action_complete': 'POSTCALL', 'saved_and_closed': 'RELEASE_CHECK', 'integration_action_complete': 'POSTCALL', 'saved_and_closed': 'RELEASE_CHECK',
'complete': 'FINISHED', 'failed': 'UNCONFIRMED'}.get(event.get('stage')) 'complete': 'FINISHED', 'failed': 'UNCONFIRMED'}.get(stage)
if (stage in ('pcb_launch', 'pcb_worker_started') and job.get('diagnostic_only') is False
and not (job.get('native_lm_verify') or job.get('post_repair_consent')
or job.get('interactive_input'))):
# Keep the worker alive through PID registration after supervisor loss.
phase = 'UNCONFIRMED' if stage == 'pcb_launch' else 'PRECALL'
identities = [(role, event.get(key)) for role, key in identities = [(role, event.get(key)) for role, key in
(('native', 'pcb_pid'), ('native', 'lm_pid'), ('helper', 'helper_pid')) (('native', 'pcb_pid'), ('native', 'lm_pid'))
if event.get(key)] if event.get(key)]
facts = None facts = None
continuing_save = False
if event.get('stage') == 'save_progress': if event.get('stage') == 'save_progress':
from .operation_lifecycle import classify_save_state from .operation_lifecycle import classify_save_state
facts = classify_save_state(event.get('markers', ()), facts = classify_save_state(event.get('markers', ()),
helper_exited=event.get('helper_exited'), native_released=None) helper_exited=event.get('helper_exited'), native_released=None)
phase = ('POSTCALL' if event.get('helper_exited') is True else facts['save_close_confirmed'] = (
'CLOSING' if 'CLOSE_START' in event.get('markers', ()) else 'NATIVE_CALL') event.get('helper_exited') is True and event.get('helper_exit_code') == 0
if phase or identities: and facts['interrupted'] is False
update_worker_state(job, phase or 'UNCONFIRMED', identities=identities, write_outcome=facts) and save_log_has_core_markers('\n'.join(event.get('markers', ())))
)
# Save and Close run in one already admitted helper.
continuing_save = event.get('helper_exited') is not True
phase = 'NATIVE_CALL' if continuing_save else 'POSTCALL'
registered_startup = stage == 'pcb_worker_started' and phase == 'PRECALL'
if (phase or identities) and not registered_startup:
update_worker_state(job, phase or 'UNCONFIRMED', identities=identities,
write_outcome=facts, continuation=continuing_save)
event.update(time=time.strftime('%Y-%m-%d %H:%M:%S'), block=job['block_name'], event.update(time=time.strftime('%Y-%m-%d %H:%M:%S'), block=job['block_name'],
monotonic_seconds=time.monotonic()) monotonic_seconds=time.monotonic())
with (root/'events.jsonl').open('a', encoding='utf-8') as stream: with (root/'events.jsonl').open('a', encoding='utf-8') as stream:
stream.write(json.dumps(event, ensure_ascii=False) + '\n') stream.write(json.dumps(event, ensure_ascii=False) + '\n')
if registered_startup:
update_worker_state(job, phase, identities=identities)
try: try:
if job.get('supervisor_pid'): if job.get('supervisor_pid'):
+35 -13
View File
@@ -1134,34 +1134,43 @@ def _open_catalog_manager_library(pid):
return next(iter(paths)) if len(paths) == 1 else None return next(iter(paths)) if len(paths) == 1 else None
def _check_catalog_owners(library, processes): def _check_catalog_owners(library, processes, *, known_conflicts_only=False):
"""A foreign LM is compatible only with a disjoint library and free target resources.""" """Screen existing managers before starting a separately owned catalog instance."""
library = Path(library).resolve() library = Path(library).resolve()
manager_pids = [pid for pid, *_ in processes] manager_pids = [pid for pid, *_ in processes]
target_dependencies = _catalog_shared_dependencies(library) target_dependencies = _catalog_shared_dependencies(library)
observed_libraries = {}
for pid in manager_pids: for pid in manager_pids:
try: try:
current = _open_catalog_manager_library(pid) current = _open_catalog_manager_library(pid)
if current is None: if current is None:
detail = '无法确认已运行的 Library Manager 对应哪个库' # Some existing managers expose no absolute path in their title.
# Probe the target resources and enforce private COM ownership at launch.
observed_libraries[pid] = None
continue
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: else:
other = current.resolve(strict=True) observed_libraries[pid] = str(other)
if library.samefile(other): continue
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: except (OSError, ValueError) as error:
if known_conflicts_only:
continue
detail = f'无法确认另一中心库的资源范围:{error}' detail = f'无法确认另一中心库的资源范围:{error}'
raise NativeOperationError(f'LIBRARY_MANAGER_BUSY: PID {pid} · {detail}。', raise NativeOperationError(f'LIBRARY_MANAGER_BUSY: PID {pid} · {detail}。',
safe_to_continue=True, blocking_manager_pids=(pid,)) safe_to_continue=True, blocking_manager_pids=(pid,))
if known_conflicts_only:
return observed_libraries
try: try:
_probe_catalog_files(library) _probe_catalog_files(library)
except OSError as error: except OSError as error:
raise NativeOperationError(f'LIBRARY_MANAGER_BUSY: PID {manager_pids} · 当前库资源占用未确认:{error}', raise NativeOperationError(f'LIBRARY_MANAGER_BUSY: PID {manager_pids} · 当前库资源占用未确认:{error}',
safe_to_continue=True, blocking_manager_pids=manager_pids) from error safe_to_continue=True, blocking_manager_pids=manager_pids) from error
return observed_libraries
def _catalog_native(job, root): def _catalog_native(job, root):
@@ -1199,16 +1208,27 @@ 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('拒绝在非本次私有桌面读取原生目录。')
read_registrations = (job.get('worker_role') == 'catalog_readonly'
and not job.get('include_engineering_identity', True))
if read_registrations:
from .owner_probe import snapshot_process_ids
try:
pids = snapshot_process_ids('LibraryManager.exe')
if pids:
_check_catalog_owners(job['library'], [(pid,) for pid in pids], known_conflicts_only=True)
except OSError:
pass # The full owner and file checks still run before activation.
previous_managers = _process_details('LibraryManager.exe') previous_managers = _process_details('LibraryManager.exe')
existing_libraries = {}
if previous_managers: if previous_managers:
if job.get('worker_role') != 'catalog_readonly' or job.get('include_engineering_identity', True): if not read_registrations:
raise RuntimeError('LIBRARY_MANAGER_BUSY: 已有 Library Manager 运行,请关闭后重试。') raise RuntimeError('LIBRARY_MANAGER_BUSY: 已有 Library Manager 运行,请关闭后重试。')
expected = Path(job['mentor_home'])/'lm/win32/bin/LibraryManager.exe' expected = Path(job['mentor_home'])/'lm/win32/bin/LibraryManager.exe'
if hash_file(expected) != _BINARY_PROOF['lm/win32/bin/LibraryManager.exe']: if hash_file(expected) != _BINARY_PROOF['lm/win32/bin/LibraryManager.exe']:
pids = sorted(pid for pid, *_ in previous_managers) pids = sorted(pid for pid, *_ in previous_managers)
raise NativeOperationError(f'LIBRARY_MANAGER_BUSY: PID {pids} · 当前安装尚未验证并行目录读取。', raise NativeOperationError(f'LIBRARY_MANAGER_BUSY: PID {pids} · 当前安装尚未验证并行目录读取。',
safe_to_continue=True, blocking_manager_pids=pids) safe_to_continue=True, blocking_manager_pids=pids)
_check_catalog_owners(job['library'], previous_managers) existing_libraries = _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
@@ -1257,6 +1277,8 @@ def _catalog_com(job, root):
continue continue
app = library = None app = library = None
result = {'success': False, 'safe_to_continue': False} result = {'success': False, 'safe_to_continue': False}
if existing_libraries:
result['existing_manager_libraries'] = existing_libraries
watcher = None watcher = None
try: try:
_require_management_continuation(job, root) _require_management_continuation(job, root)
+78 -9
View File
@@ -1,5 +1,5 @@
"""Cooperative FIFO admission for this application's native operations.""" """Cooperative FIFO admission for this application's native operations."""
from contextlib import contextmanager from contextlib import contextmanager, nullcontext
from dataclasses import dataclass, field from dataclasses import dataclass, field
import ntpath import ntpath
from threading import Condition, Event, RLock, Thread, local from threading import Condition, Event, RLock, Thread, local
@@ -13,7 +13,7 @@ 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, sessions=(), *, timed_out=False): def __init__(self, library, sessions=(), *, timed_out=False, detail=''):
self.library = str(library) self.library = str(library)
self.sessions = tuple(sessions) self.sessions = tuple(sessions)
self.timed_out = timed_out self.timed_out = timed_out
@@ -24,6 +24,8 @@ class QueueUnavailable(RuntimeError):
details.append(' / '.join(filter(None, (block, session.get('operation_id'), details.append(' / '.join(filter(None, (block, session.get('operation_id'),
resources, session.get('path'))))) resources, session.get('path')))))
message = f'NATIVE_SESSION_PENDING: {self.library} 的已登记会话待释放,当前项未启动。' message = f'NATIVE_SESSION_PENDING: {self.library} 的已登记会话待释放,当前项未启动。'
if detail:
details.insert(0, detail)
super().__init__(message + (' ' + ';'.join(details) if details else '')) super().__init__(message + (' ' + ';'.join(details) if details else ''))
@@ -91,6 +93,8 @@ class _Call:
shutdown_handoff: bool = False shutdown_handoff: bool = False
native_handoff: str = '' native_handoff: str = ''
handoff_cancelled: bool = False handoff_cancelled: bool = False
queue_pause: object = None
queued_for_slot: bool = False
phase_started: float = field(default_factory=time.monotonic) phase_started: float = field(default_factory=time.monotonic)
result: object = None result: object = None
last_result: object = None last_result: object = None
@@ -110,6 +114,11 @@ def task_stop(fallback=None):
return getattr(_local, 'call', None) or fallback return getattr(_local, 'call', None) or fallback
def allow_other_libraries():
call = getattr(_local, 'call', None)
return call.queue_pause() if call is not None and call.queue_pause is not None else nullcontext()
def check_active(): def check_active():
call = getattr(_local, 'call', None) call = getattr(_local, 'call', None)
if call is not None and call.is_set(): if call is not None and call.is_set():
@@ -393,7 +402,8 @@ class BatchTaskContext:
call.abandoned = True call.abandoned = True
raise TaskHandoff(self, cancelled=cancelled, result=call.last_result) raise TaskHandoff(self, cancelled=cancelled, result=call.last_result)
elapsed = time.monotonic()-call.phase_started elapsed = time.monotonic()-call.phase_started
if not call.native_depth and not call.commit_depth and (call.abandoned or elapsed >= timeout_seconds): expired = not call.queued_for_slot and elapsed >= timeout_seconds
if not call.native_depth and not call.commit_depth and (call.abandoned or expired):
cancelled = call.is_set() cancelled = call.is_set()
call.abandoned = True call.abandoned = True
raise TaskHandoff(self, cancelled=cancelled, result=call.last_result) raise TaskHandoff(self, cancelled=cancelled, result=call.last_result)
@@ -402,6 +412,13 @@ class BatchTaskContext:
return call.result return call.result
@dataclass(eq=False)
class _Ticket:
roots: frozenset
ready: bool = False
paused: bool = False
class NativeQueue: class NativeQueue:
def __init__(self): def __init__(self):
self.condition = Condition() self.condition = Condition()
@@ -447,9 +464,62 @@ class NativeQueue:
raise QueueUnavailable(path, retained_session_states(path), timed_out=True) raise QueueUnavailable(path, retained_session_states(path), timed_out=True)
return False return False
return True return True
ticket = [object(), False] roots = frozenset(ntpath.dirname(_path_key(path))
for path in (context.library, *context.aliases)) if context is not None else frozenset()
ticket = _Ticket(roots)
acquired, notified = False, False acquired, notified = False, False
previous_state = None previous_state = None
def first_ready():
paused = [entry for entry in self.pending if entry.paused]
return next((entry for entry in self.pending if entry.ready and not any(
owner is not entry and (not entry.roots or owner.roots & entry.roots)
for owner in paused)), None)
@contextmanager
def pause():
nonlocal acquired
call = _local.call
with self.condition:
can_pause = acquired and not call.native_depth and not call.commit_depth
if can_pause:
ticket.ready, ticket.paused = False, True
self.active = acquired = False
self.condition.notify_all()
if not can_pause:
# Nested Verify may still be part of a management transaction.
yield
return
try:
yield
finally:
with _tasks_guard:
call.queued_for_slot = True
try:
with self.condition:
ticket.ready = True
while ticket in self.pending and not self.closed and not call.is_set():
if not self.active and first_ready() is ticket:
self.active = acquired = True
break
self.condition.wait(.1)
ticket.paused = ticket.ready = False
self.condition.notify_all()
if not acquired:
raise QueueCancelled('已取消等待原生通道,未提交新的调用。')
finally:
with _tasks_guard:
call.queued_for_slot = False
call.phase_started = time.monotonic()
def run_admitted():
call = _local.call
previous_pause, call.queue_pause = call.queue_pause, pause
try:
return action()
finally:
call.queue_pause = previous_pause
with self.condition: with self.condition:
if self.closed: if self.closed:
raise QueueCancelled('队列已关闭,未启动新的操作。') raise QueueCancelled('队列已关闭,未启动新的操作。')
@@ -466,15 +536,14 @@ class NativeQueue:
if (self.closed or stop is not None and stop.is_set() if (self.closed or stop is not None and stop.is_set()
or context is not None and (context.stop.is_set() or context.stop_after_current.is_set())): or context is not None and (context.stop.is_set() or context.stop_after_current.is_set())):
raise QueueCancelled('已取消排队,未启动原生操作。') raise QueueCancelled('已取消排队,未启动原生操作。')
ticket[1] = bool(available) ticket.ready = bool(available)
first = next((entry for entry in self.pending if entry[1]), None) if not self.active and first_ready() is ticket:
if not self.active and first is ticket:
self.active = acquired = True self.active = acquired = True
else: else:
self.condition.wait(.1) self.condition.wait(.1)
if acquired and not available_now(): if acquired and not available_now():
with self.condition: with self.condition:
ticket[1] = self.active = acquired = False ticket.ready = self.active = acquired = False
self.condition.notify_all() self.condition.notify_all()
if not acquired and waiting is not None: if not acquired and waiting is not None:
try: try:
@@ -487,7 +556,7 @@ class NativeQueue:
if (stop is not None and stop.is_set() if (stop is not None and stop.is_set()
or context is not None and context.stop_after_current.is_set()): or context is not None and context.stop_after_current.is_set()):
raise QueueCancelled('已取消排队,未启动原生操作。') raise QueueCancelled('已取消排队,未启动原生操作。')
return context.run(action, stop=stop, timeout_seconds=timeout_seconds) if context else action() return context.run(run_admitted, stop=stop, timeout_seconds=timeout_seconds) if context else action()
finally: finally:
with self.condition: with self.condition:
self.pending = [entry for entry in self.pending if entry is not ticket] self.pending = [entry for entry in self.pending if entry is not ticket]
+36
View File
@@ -7,6 +7,42 @@ import sys
import tempfile import tempfile
def snapshot_process_ids(name):
"""Read executable names from the local process table without starting WMI."""
import ctypes
from ctypes import wintypes
class ProcessEntry(ctypes.Structure):
_fields_ = [('size', wintypes.DWORD), ('usage', wintypes.DWORD), ('pid', wintypes.DWORD),
('heap_id', ctypes.c_size_t), ('module_id', wintypes.DWORD), ('threads', wintypes.DWORD),
('parent', wintypes.DWORD), ('priority', wintypes.LONG), ('flags', wintypes.DWORD),
('name', wintypes.WCHAR * 260)]
kernel = ctypes.WinDLL('kernel32', use_last_error=True)
kernel.CreateToolhelp32Snapshot.argtypes = [wintypes.DWORD, wintypes.DWORD]
kernel.CreateToolhelp32Snapshot.restype = wintypes.HANDLE
kernel.CloseHandle.argtypes = [wintypes.HANDLE]
for step in (kernel.Process32FirstW, kernel.Process32NextW):
step.argtypes = [wintypes.HANDLE, ctypes.POINTER(ProcessEntry)]
step.restype = wintypes.BOOL
handle = kernel.CreateToolhelp32Snapshot(2, 0) # TH32CS_SNAPPROCESS
if handle == ctypes.c_void_p(-1).value:
raise ctypes.WinError(ctypes.get_last_error())
try:
entry = ProcessEntry(size=ctypes.sizeof(ProcessEntry))
found = []
processing = kernel.Process32FirstW(handle, ctypes.byref(entry))
while processing:
if entry.name.casefold() == name.casefold():
found.append(entry.pid)
processing = kernel.Process32NextW(handle, ctypes.byref(entry))
if ctypes.get_last_error() != 18: # ERROR_NO_MORE_FILES
raise ctypes.WinError(ctypes.get_last_error())
return found
finally:
kernel.CloseHandle(handle)
def query_owners(names, *, timeout_seconds=10): def query_owners(names, *, timeout_seconds=10):
names = tuple(names) names = tuple(names)
if not names or any(not re.fullmatch(r'[\w.-]+\.exe', name, re.I) for name in names): if not names or any(not re.fullmatch(r'[\w.-]+\.exe', name, re.I) for name in names):
+6 -1
View File
@@ -118,6 +118,8 @@ def resource_guard(job, allowed_pids, *, require_complete_proof=False):
or str(address) not in files['binding_files'] or str(address) not in files['binding_files']
or shared/'icdb.dat' not in {Path(p).resolve() for p in files['exclusive_files']}): or shared/'icdb.dat' not in {Path(p).resolve() for p in files['exclusive_files']}):
raise ValueError(f'SHARED_ICDB_BINDING_UNCONFIRMED: {address}') raise ValueError(f'SHARED_ICDB_BINDING_UNCONFIRMED: {address}')
if str(address) in files.get('shared_shutdowns', {}):
continue
_write_json(Path(job['root'])/'pcb-open-resource-denied.json', { _write_json(Path(job['root'])/'pcb-open-resource-denied.json', {
'status': 'SHARED_ICDB_INSPECTION_UNAVAILABLE', 'status': 'SHARED_ICDB_INSPECTION_UNAVAILABLE',
'operation_id': job.get('operation_id'), 'library': str(library), 'operation_id': job.get('operation_id'), 'library': str(library),
@@ -130,6 +132,8 @@ def resource_guard(job, allowed_pids, *, require_complete_proof=False):
raise ValueError(f"PCB_OPEN_DATABASE_UNCONFIRMED: 地址未绑定实际工程配置:{item['database']}") 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):
if item.get('scope') == 'shared_symbols':
continue
target = RepairTarget(Path(item['project']), Path(item['database'])) target = RepairTarget(Path(item['project']), Path(item['database']))
evidence = Path(job['root'])/('open-inspection-'+str(index)) evidence = Path(job['root'])/('open-inspection-'+str(index))
result = run_native_repair(target, evidence, mentor_bin=job.get('mentor_bin'), result = run_native_repair(target, evidence, mentor_bin=job.get('mentor_bin'),
@@ -157,7 +161,8 @@ def resource_guard(job, allowed_pids, *, require_complete_proof=False):
'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,
'exclusive_files': files['exclusive_files'], 'addresses': files['addresses'], 'exclusive_files': files['exclusive_files'], 'addresses': files['addresses'],
'native_inspections': inspections, 'repair_confirmed': False}) 'native_inspections': inspections, 'shared_shutdowns': files.get('shared_shutdowns', {}),
'repair_confirmed': False})
yield yield
+273 -52
View File
@@ -394,6 +394,78 @@ def _save_question(windows, *, incomplete=None):
return None return None
class OrphanedVerifySavePrompt:
"""Continue the registered worker's already started Save after supervisor loss."""
def __init__(self, job, pcb_pid, emit, *, clock=time.monotonic):
self.job = job
self.pid = pcb_pid
self.emit = emit
self.clock = clock
self.pending = None
self.clicked = False
def poll(self, markers):
from .desktop_worker import supervisor_has_exited
if (self.clicked or 'SAVE_START' not in markers
or any(marker == 'SAVE_OK' or marker.startswith(('SAVE_REJECTED', 'SAVE_RESULT_UNKNOWN'))
for marker in markers)
or not supervisor_has_exited()
or self.job.get('interactive_input') is not False
or not self.job.get('desktop', '').startswith('CbbVerify_')
or not self.job.get('session_record_path')):
return
from .session_record import IDENTITY_KEYS, process_identity, read_session_record
import win32con
state_path = Path(self.job['session_record_path']).with_name('worker-state.json')
try:
state = read_session_record(state_path, evidence_root=state_path.parent)
if (state['operation_id'] != self.job['operation_id']
or state.get('phase') != 'NATIVE_CALL'):
self.pending = None
return
identity = next((row for row in state['processes']
if row['role'] == 'native' and row['pid'] == self.pid), None)
actual = process_identity(self.pid) if identity is not None else None
if actual is None or any(actual[key] != identity[key] for key in IDENTITY_KEYS):
self.pending = None
return
windows = _process_windows({self.pid})
matches = []
for window in windows.get(self.pid, ()):
if (window['desktop'] != self.job['desktop'] or window['class'] != '#32770'
or window['title'] != 'Expedition PCB' or not window['enabled']):
continue
texts = [child['text'].strip().casefold() for child in window['children']
if child['class'] == 'Static' and child['text'].strip()]
buttons = [child for child in window['children'] if child['class'] == 'Button']
if (texts == ['do you want to save the reusable block cell?']
and sorted(item['id'] for item in buttons) == [6, 7]
and all(item['enabled'] for item in buttons)):
button = next(item['hwnd'] for item in buttons if item['id'] == 6)
matches.append((window, button))
if self.pid in windows.incomplete or len(matches) != 1:
self.pending = None
return
window, button = matches[0]
now = self.clock()
signature = (window['hwnd'], button)
if self.pending is None or self.pending[0] != signature:
self.pending = (signature, now)
return
if now - self.pending[1] < 3:
return
_post_window_message(window, button, self.pid, win32con.BM_CLICK)
self.clicked = True
self.emit(stage='orphaned_save_confirmed', native_pid=self.pid, hwnd=window['hwnd'],
rule_id='reusable-block-save', accepted_control=[6])
except Exception:
# Read errors must leave the already executing native write alone.
self.pending = None
def _cancel_question(name, windows, *, incomplete=None): def _cancel_question(name, windows, *, incomplete=None):
if (name.casefold() != 'icdbprojectbackup.exe' if (name.casefold() != 'icdbprojectbackup.exe'
or native_activity(name, windows, incomplete=incomplete)['status'] != 'ACTIVE'): or native_activity(name, windows, incomplete=incomplete)['status'] != 'ACTIVE'):
@@ -832,15 +904,92 @@ def _recorded_process_exited(identity):
return error.winerror == 87 return error.winerror == 87
def orphaned_catalog_session(path): def _saved_and_closed(facts):
return (isinstance(facts, dict) and facts.get('interrupted') is False
and all(facts.get(key) == value for key, value in (
('save_state', 'COMMITTED'), ('close_state', 'CLOSED'), ('helper_state', 'EXITED'))))
def _worker_save_facts(state, identities):
if (state.get('phase') in ('POSTCALL', 'RELEASE_CHECK', 'FINISHED', 'UNCONFIRMED')
and any(p.get('role') == 'helper' for p in identities)):
facts = state.get('write_outcome')
if isinstance(facts, dict) and facts.get('save_close_confirmed') is True:
return facts
return None
def _orphan_prewrite_client(path, job, session, state, identities):
"""Identify the registered PCB from the ordinary Verify startup journal."""
import stat
from .mentor_adapter import is_reusable_circuit_pcb
from .session_record import IDENTITY_KEYS, MAX_BYTES, read_session_record from .session_record import IDENTITY_KEYS, MAX_BYTES, read_session_record
scope = session.get('resource_scope', {})
stop_signal = Path(job['cancel_signal'])
if (job.get('diagnostic_only') is not False or job.get('native_lm_verify')
or job.get('post_repair_consent') or job.get('interactive_input') is not False
or state.get('phase') not in ('PRECALL', 'UNCONFIRMED')
or state.get('write_outcome') is not None or any(p.get('role') == 'helper' for p in identities)
or scope.get('operation_id') != job['operation_id'] or scope.get('scope_state') != 'DECLARED'
or scope.get('library') != job['library'] or scope.get('projects') != [job['project']]
or not Path(job['project']).is_relative_to(Path(job['library']).parent)
or not Path(job['pcb']).is_relative_to(Path(job['project']).parent)
or session.get('cancel_signal') != job['cancel_signal']
or stop_signal.parent != path.parent or not stop_signal.is_file()
or (path.parent/'save.log').exists()):
return None
lost = read_session_record(path.with_name('supervisor-lost.json'), evidence_root=path.parent)
if lost.get('operation_id') != job['operation_id'] or lost.get('phase') != 'SUPERVISOR_LOST':
return None
journal = path.with_name('events.jsonl')
if journal.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
return None
with journal.open('rb') as stream:
data = stream.read(MAX_BYTES + 1)
if len(data) > MAX_BYTES or not data.endswith(b'\n'):
return None
events = [json.loads(line) for line in data.splitlines()]
if any(str(event.get('stage', '')).startswith(('save', 'integration', 'validate', 'failure_close'))
or event.get('stage') in ('startup_write_admitted', 'startup_supervisor_write_possible',
'identity_verified', 'startup_close_requested', 'diagnostic_wm_close')
for event in events):
return None
stages = ('startup_supervisor_no_write', 'pcb_baseline', 'startup_prewrite_ready', 'pcb_worker_started')
startup = [event for event in events if event.get('stage') in stages]
if tuple(event['stage'] for event in startup) != stages:
return None
waiting, baseline, ready, started = startup
if any(event.get(key) != job[key] for event in (waiting, ready)
for key in ('operation_id', 'project', 'pcb', 'desktop')):
return None
worker = ready.get('worker_identity', {})
if not any(p.get('role') == 'worker' and all(worker.get(key) == p[key] for key in IDENTITY_KEYS)
for p in identities):
return None
pid = started['pcb_pid']
if pid in baseline['pids']:
return None
clients = [p for p in identities if p.get('role') == 'native' and p['pid'] == pid]
if len(clients) != 1 or not is_reusable_circuit_pcb(clients[0]['image'], started['command'], job['pcb']):
return None
return clients[0], ready.get('baseline')
def recoverable_orphan_session(path):
from .session_record import IDENTITY_KEYS, MAX_BYTES, read_session_record, _session
import stat import stat
path = Path(path) path = Path(path)
try: try:
session = read_session_record(path, evidence_root=path.parent) session = read_session_record(path, evidence_root=path.parent)
if (session.get('operation') != 'catalog' or session.get('worker_role') != 'catalog_readonly' operation = session.get('operation')
or not str(session.get('desktop', '')).startswith('CbbManagement_')): desktop = str(session.get('desktop', ''))
if operation == 'verify' and desktop.startswith('CbbVerify_'):
_, state, identities = _session(path, path.parent)
elif (operation != 'catalog' or session.get('worker_role') != 'catalog_readonly'
or not desktop.startswith('CbbManagement_')):
return False return False
request = path.with_name('request.json') request = path.with_name('request.json')
if request.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT: if request.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
@@ -854,18 +1003,25 @@ def orphaned_catalog_session(path):
('operation_id', 'operation', 'library', 'desktop', 'worker_role')) ('operation_id', 'operation', 'library', 'desktop', 'worker_role'))
or Path(job['session_record_path']).resolve() != path.resolve()): or Path(job['session_record_path']).resolve() != path.resolve()):
return False return False
if operation == 'verify' and (job.get('interactive_input') is not False
or job.get('block') != session.get('block') or job.get('lmc_file') != session['library']
or Path(job.get('root', '')).resolve() != path.parent.resolve()):
return False
identity = job['supervisor_identity'] identity = job['supervisor_identity']
if (not isinstance(identity, dict) or any(identity.get(key) is None for key in IDENTITY_KEYS) 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 type(identity['pid']) is not int or identity['pid'] <= 0
or identity['pid'] != job.get('supervisor_pid')): or identity['pid'] != job.get('supervisor_pid')):
return False return False
if session.get('supervisor_identity') != identity: if session.get('supervisor_identity') != identity:
if session.get('supervisor_identity') is not None: if operation != 'catalog' or session.get('supervisor_identity') is not None:
return False return False
lost = read_session_record(path.with_name('supervisor-lost.json'), evidence_root=path.parent) 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': if lost.get('operation_id') != session['operation_id'] or lost.get('phase') != 'SUPERVISOR_LOST':
return False return False
return _recorded_process_exited(identity) if not _recorded_process_exited(identity):
return False
return (operation == 'catalog' or _saved_and_closed(_worker_save_facts(state, identities))
or _orphan_prewrite_client(path, job, session, state, identities) is not None)
except (OSError, ValueError, TypeError, KeyError, AttributeError): except (OSError, ValueError, TypeError, KeyError, AttributeError):
return False return False
@@ -885,13 +1041,13 @@ def finish_owned_idle_session(path, *, stop=None):
if not acquired or stop is not None and stop.is_set(): return False if not acquired or stop is not None and stop.is_set(): return False
session, state, identities = _session(path, path.parent) session, state, identities = _session(path, path.parent)
if 'owned_idle_cleanup' in session: return False if 'owned_idle_cleanup' in session: return False
def read(name): def read(name, *, lines=False):
item = path.with_name(name) item = path.with_name(name)
if item.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT: if item.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
raise ValueError('OWNED_CLEANUP_REPARSE_POINT') raise ValueError('OWNED_CLEANUP_REPARSE_POINT')
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(line) for line in data.splitlines()] if lines else json.loads(data)
job = read('request.json') job = read('request.json')
if not isinstance(job, 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'))
@@ -907,32 +1063,37 @@ def finish_owned_idle_session(path, *, stop=None):
result = read_result() result = read_result()
if result is None: if result is None:
if (state.get('phase') not in ('PRECALL', 'POSTCALL', 'RELEASE_CHECK', 'FINISHED', 'UNCONFIRMED') if (state.get('phase') not in ('PRECALL', 'POSTCALL', 'RELEASE_CHECK', 'FINISHED', 'UNCONFIRMED')
or not orphaned_catalog_session(path)): or not recoverable_orphan_session(path)):
return False return False
elif not isinstance(result, dict) or result.get('safe_to_continue') is not False: elif not isinstance(result, dict) or result.get('safe_to_continue') is not False:
return False return False
cancelled_before_write = None cancelled_before_write = None
if operation == 'verify': if operation == 'verify':
if result is None:
return False
facts = result.get('write_outcome') or {}
failed_open = (result.get('error_stage') == 'PCB_STARTING'
and result.get('error_category') in ('MENTOR_DATABASE_LOAD_FAILED','ICDB_REPAIR_REQUIRED')
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
and all(facts.get(k) == v for k,v in (
('save_state','COMMITTED'),('close_state','CLOSED'),('helper_state','EXITED'))))
if (not desktop.startswith('CbbVerify_') or job.get('interactive_input') is not False if (not desktop.startswith('CbbVerify_') or job.get('interactive_input') is not False
or result.get('status') not in ('FAIL','BLOCKED','TIMEOUT','CANCELLED') or Path(job.get('root', '')).resolve() != path.parent.resolve()
or result.get('block_name') != job['block'] or job.get('lmc_file') != job['library']):
or Path(result.get('evidence_path','')).resolve() != path.with_name('result.json').resolve() return False
or Path(job.get('root','')).resolve() != path.parent.resolve() if result is not None:
or job.get('lmc_file') != job['library'] if (result.get('status') not in ('FAIL', 'BLOCKED', 'TIMEOUT', 'CANCELLED')
or not (failed_open or saved_closed or cancelled_before_write is not None)): return False or result.get('block_name') != job['block']
or Path(result.get('evidence_path', '')).resolve() != path.with_name('result.json').resolve()):
return False
facts = result.get('write_outcome')
worker_facts = _worker_save_facts(state, identities)
provisional = (isinstance(facts, dict) and facts.get('helper_state') in ('RUNNING', 'UNKNOWN')
and facts.get('interrupted') is False and facts.get('save_state') != 'REJECTED'
and facts.get('close_state') != 'FAILED')
if facts is None or provisional or (session.get('supervisor_identity') and _saved_and_closed(facts)):
facts = worker_facts
failed_open = (result.get('error_stage') == 'PCB_STARTING'
and result.get('error_category') in ('MENTOR_DATABASE_LOAD_FAILED', 'ICDB_REPAIR_REQUIRED')
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)
if not (failed_open or _saved_and_closed(facts) 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'
@@ -940,6 +1101,13 @@ def finish_owned_idle_session(path, *, stop=None):
return False return False
workers = [p for p in identities if p.get('role') in ('worker','helper')] workers = [p for p in identities if p.get('role') in ('worker','helper')]
clients = [p for p in identities if p.get('role') == 'native' and Path(p['image']).name.casefold() == client_name] clients = [p for p in identities if p.get('role') == 'native' and Path(p['image']).name.casefold() == client_name]
orphan_client = None
orphan_baseline = None
if operation == 'verify' and result is None and not _saved_and_closed(_worker_save_facts(state, identities)):
orphan = _orphan_prewrite_client(path, job, session, state, identities)
if orphan is not None:
orphan_client, orphan_baseline = orphan
clients = [orphan_client] if orphan_client is not None else []
if not workers or len(clients) != 1: return False if not workers or len(clients) != 1: return False
if any(r.get('operation_id') != session['operation_id'] for r in active_write_records(session['library'])): if any(r.get('operation_id') != session['operation_id'] for r in active_write_records(session['library'])):
return False return False
@@ -960,16 +1128,29 @@ def finish_owned_idle_session(path, *, stop=None):
and owner.get('force_user_confirmed') is True and owner.get('force_user_confirmed') is True
and _handle_identity(handle) == {k:client[k] for k in ('created_handle','image')} and _handle_identity(handle) == {k:client[k] for k in ('created_handle','image')}
and all(owner.get(k) == client[k] for k in ('owner_sid','session_id'))) and all(owner.get(k) == client[k] for k in ('owner_sid','session_id')))
def empty_target(): def idle_target():
snapshot = _process_windows({client['pid']}, include_hidden_documents=True) snapshot = _process_windows({client['pid']}, include_hidden_documents=True)
windows = snapshot.get(client['pid'], []) windows = snapshot.get(client['pid'], [])
if (any(w.get('desktop') != desktop or w.get('documents') if any(w.get('desktop') != desktop or any(
or any(c['class'].casefold().startswith('afx:') and c.get('visible') is False c['class'].casefold().startswith('afx:') and c.get('visible') is False
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] target, _ = close_target(client_name, windows, incomplete=_window_error(snapshot, client['pid']))
def load_failure_button(): if target is None or not any(w.get('documents') for w in windows):
from .failed_session import _startup_snapshot, _cancel_target return target
if not isinstance(orphan_baseline, dict) or not {'started_ns', 'files'} <= orphan_baseline.keys():
return None
# PCB can finish loading after its worker has stopped. Close
# only the design independently bound by this launch's logs.
from .diagnostic_open import _load_evidence, _target_frame
frames = _legacy_diagnostic_windows(dict(client, cleanup_desktop=desktop))
frame = _target_frame(frames, Path(job['pcb']).stem)
if (frame and frame['hwnd'] == target['hwnd']
and _load_evidence(job, client['pid'], orphan_baseline, require_autosave=False) is not None):
return target
return None
def startup_prompt():
from .failed_session import _startup_snapshot, _cancel_target, _tip_target, _startup_license_cancel
snapshot = _process_windows({client['pid']}, include_hidden_documents=True) snapshot = _process_windows({client['pid']}, include_hidden_documents=True)
windows = snapshot.get(client['pid'], []) windows = snapshot.get(client['pid'], [])
if (_window_error(snapshot, client['pid']) or not windows if (_window_error(snapshot, client['pid']) or not windows
@@ -978,25 +1159,44 @@ def finish_owned_idle_session(path, *, stop=None):
modals = [w for w in windows if w['class'] == '#32770'] modals = [w for w in windows if w['class'] == '#32770']
if len(modals) != 1: if len(modals) != 1:
return None return None
with _window_desktop(desktop): if session.get('owned_startup_prompt') == modals[0]['hwnd']:
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 None
return observed, target[1].handle with _window_desktop(desktop):
modal = modals[0]
observed = _startup_snapshot(modal['hwnd'], client['pid'])
tip = _tip_target(observed) if modal['title'] == 'Tip of the Day' else None
if tip is not None:
# A preceding cleanup can leave this same Tip visible; no repeated action.
if any(event.get('pcb_pid') == client['pid'] and
(event.get('stage') == 'startup_close_requested'
or event.get('stage') == 'startup_tip_dismissed'
and event.get('hwnd') == modal['hwnd'])
for event in read('events.jsonl', lines=True)):
return None
return observed, tip.handle, 'tip', modal['hwnd']
if orphan_client is not None and all(w is modal or (
w['class'] in ('UAC_InputIndicatorOverlayWnd', 'UAC Input Indicator')
and not w.get('documents')) for w in windows):
license_cancel = _startup_license_cancel(observed)
if license_cancel is not None:
return observed, license_cancel.handle, 'license_cancel', modal['hwnd']
target = _cancel_target(observed)
if target is not None and (orphan_client is not None or target[0] == 'database_load_log'):
return observed, target[1].handle, target[0], modal['hwnd']
return None
if not same_client(): return False if not same_client(): return False
if (cancelled_before_write is not None if (cancelled_before_write is not None
and cancelled_prewrite_startup(job, client['pid']) != cancelled_before_write): and cancelled_prewrite_startup(job, client['pid']) != cancelled_before_write):
return False return False
target = empty_target() target = idle_target()
failure = load_failure_button() if target is None and cancelled_before_write is not None else None prompt = startup_prompt() if target is None and (cancelled_before_write is not None or orphan_client is not None) else None
if (target is None and failure is None) or stop is not None and stop.is_set(): return False if (target is None and prompt 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'] if target is not None else failure[1], status='REQUESTED',hwnd=target['hwnd'] if target is not None else prompt[1],
desktop=desktop) 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.
@@ -1005,24 +1205,37 @@ def finish_owned_idle_session(path, *, stop=None):
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 read('request.json') != job or not same_client() or read('request.json') != job
or (empty_target() != target if failure is None else load_failure_button() != failure) or (idle_target() != target if prompt is None else startup_prompt() != prompt)
or (cancelled_before_write is not None or (cancelled_before_write is not None
and cancelled_prewrite_startup(job, client['pid']) != cancelled_before_write) 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 read_result() != result or result is None and not recoverable_orphan_session(path)
or stop is not None and stop.is_set()): return False or stop is not None and stop.is_set()):
# Nothing was sent. The still-matching claim can be retried.
if latest.get('owned_idle_cleanup') == claim:
latest.pop('owned_idle_cleanup')
write_session_record(path, latest)
return False
with native_phase(read_only=True): with native_phase(read_only=True):
if failure is not None: if prompt is not None:
_post_window_message({'desktop': desktop}, failure[1], client['pid'], win32con.BM_CLICK) if prompt[2] == 'tip':
snapshot = _process_windows({client['pid']})
row = dict(client, name=client_name, scope_confirmed=True)
_dismiss_startup_tip(row, handle, snapshot.get(client['pid'], []),
incomplete=_window_error(snapshot, client['pid']), stop=stop)
else:
_post_window_message({'desktop': desktop}, prompt[1], client['pid'], win32con.BM_CLICK)
deadline = time.monotonic() + 5 deadline = time.monotonic() + 5
while time.monotonic() < deadline and same_client(): while time.monotonic() < deadline and same_client():
if stop is not None and stop.is_set(): if stop is not None and stop.is_set():
break break
target = empty_target() target = idle_target()
if target is not None: if target is not None:
break break
time.sleep(.1) time.sleep(.1)
if (target is not None and (not same_client() or empty_target() != target if (target is not None and (not same_client() or idle_target() != target
or cancelled_prewrite_startup(job, client['pid']) != cancelled_before_write)): or orphan_client is not None and not recoverable_orphan_session(path)
or cancelled_before_write is not None
and cancelled_prewrite_startup(job, client['pid']) != cancelled_before_write)):
target = None target = None
if target is not None and (stop is None or not stop.is_set()): 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) _post_window_message(target, target['hwnd'], client['pid'], win32con.WM_CLOSE)
@@ -1032,6 +1245,14 @@ def finish_owned_idle_session(path, *, stop=None):
break break
if stop is not None and stop.is_set(): if stop is not None and stop.is_set():
break break
elif prompt is not None:
# Allow a later close after the confirmed startup prompt
# disappears and the design completes loading.
latest = read('session.json')
if latest.get('owned_idle_cleanup') == claim:
latest.pop('owned_idle_cleanup')
latest['owned_startup_prompt'] = prompt[3]
write_session_record(path, latest)
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'],
@@ -1156,7 +1377,7 @@ def _finish_library_release(library, evidence, block_names=(), stop=None):
from .library_lock import release_retained_library from .library_lock import release_retained_library
return release_retained_library(library, evidence, return release_retained_library(library, evidence,
block_name=block_names[0] if len(block_names) == 1 else None, block_name=block_names[0] if len(block_names) == 1 else None,
block_names=block_names, stop=stop) block_names=block_names, stop=stop, infer_scope=not block_names)
def _request_native_cancel(row, *, stop=None): def _request_native_cancel(row, *, stop=None):
+40 -11
View File
@@ -82,6 +82,9 @@ def acknowledge_library_release(proof, snapshot, *, block_name=None):
and (block_name is None or block == block_name)): and (block_name is None or block == block_name)):
_retained_libraries.pop(path, None) _retained_libraries.pop(path, None)
_retained_results.pop(path, None) _retained_results.pop(path, None)
observer = _observers.get(path)
if observer and len(observer) > 2:
observer[2].set()
def _proof_covers_session(proof, session): def _proof_covers_session(proof, session):
@@ -164,7 +167,7 @@ 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'): if (protection == 'catalog_readonly' or job.get('operation') == 'verify') and job.get('supervisor_identity'):
record['supervisor_identity'] = job['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
@@ -322,6 +325,7 @@ def _reconcile(path, root, handles, stack, *, release=True, stop=None):
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)
active = False active = False
active_helper = False
for identity in processes: for identity in processes:
if identity.get('role') == 'supervisor': if identity.get('role') == 'supervisor':
continue continue
@@ -352,8 +356,11 @@ def _reconcile(path, root, handles, stack, *, release=True, stop=None):
handle = handles[key] handle = handles[key]
if handle is not None and win32event.WaitForSingleObject(handle, 0) != win32con.WAIT_OBJECT_0: if handle is not None and win32event.WaitForSingleObject(handle, 0) != win32con.WAIT_OBJECT_0:
active = True active = True
active_helper |= identity.get('role') == 'helper'
if active: if active:
return _result('ACTIVE', '原生调用尚未确认返回', session=session, state=state) saving = active_helper and session.get('operation') == 'verify' and state.get('phase') == 'NATIVE_CALL'
detail = 'Mentor 正在保存,结束后自动复核释放。' if saving else '原生调用尚未确认返回'
return {**_result('ACTIVE', detail, session=session, state=state), 'active_save': saving}
if not release: if not release:
return {**_result('UNCONFIRMED', '记录中的进程已退出,需确认库占用已释放', return {**_result('UNCONFIRMED', '记录中的进程已退出,需确认库占用已释放',
session=session, state=state), 'processes_exited': True} session=session, state=state), 'processes_exited': True}
@@ -397,14 +404,17 @@ def observe_retained_session(path, *, evidence_root, stop=None, progress=None, p
while True: while True:
observation_only = read_only() observation_only = read_only()
try: try:
result = _reconcile(Path(path), Path(evidence_root), handles, stack, release=not observation_only) result = _reconcile(Path(path), Path(evidence_root), handles, stack,
release=not observation_only and not stop.is_set(), stop=stop)
except Exception as error: except Exception as error:
result = _result('UNCONFIRMED', str(error)) result = _result('UNCONFIRMED', str(error))
if (not observation_only and process is not None and process.poll() is not None if (not observation_only and not stop.is_set()
and process is not None and process.poll() is not None
and getattr(process, 'cbb_library', None)): and getattr(process, 'cbb_library', None)):
try: try:
from .library_lock import release_retained_library from .library_lock import release_retained_library
proof = release_retained_library(process.cbb_library, Path(path).parent/'release-proof') proof = release_retained_library(process.cbb_library, Path(path).parent/'release-proof',
stop=stop)
if proof.get('status') == 'RELEASE_CONFIRMED': if proof.get('status') == 'RELEASE_CONFIRMED':
result = _result('RELEASED', '会话记录不可读;由原进程句柄及独立资源证明确认释放', result = _result('RELEASED', '会话记录不可读;由原进程句柄及独立资源证明确认释放',
session={'library': str(process.cbb_library)}, proof=proof) session={'library': str(process.cbb_library)}, proof=proof)
@@ -416,13 +426,15 @@ def observe_retained_session(path, *, evidence_root, stop=None, progress=None, p
if resume_cancelled_startup(path, stop=stop) or finish_owned_idle_session(path, stop=stop): if resume_cancelled_startup(path, stop=stop) or finish_owned_idle_session(path, stop=stop):
# Cleanup is not release proof. Re-read all held identities # Cleanup is not release proof. Re-read all held identities
# and independently prove the resource release as usual. # and independently prove the resource release as usual.
result = _reconcile(Path(path), Path(evidence_root), handles, stack) result = _reconcile(Path(path), Path(evidence_root), handles, stack,
release=not stop.is_set(), stop=stop)
except Exception: except Exception:
logging.getLogger(__name__).warning('Retained startup cleanup unavailable', exc_info=True) logging.getLogger(__name__).warning('Retained startup cleanup unavailable', exc_info=True)
if result['status'] == 'IDENTITY_CHANGED' and not observation_only: if result['status'] == 'IDENTITY_CHANGED' and not observation_only and not stop.is_set():
try: try:
from .library_lock import release_retained_library from .library_lock import release_retained_library
proof = release_retained_library(result['library'], Path(path).parent/'release-proof') proof = release_retained_library(result['library'], Path(path).parent/'release-proof',
stop=stop)
if proof.get('status') == 'RELEASE_CONFIRMED': if proof.get('status') == 'RELEASE_CONFIRMED':
result = {**result, 'status': 'RELEASED', 'identity_changed': True, 'release_proof': proof} result = {**result, 'status': 'RELEASED', 'identity_changed': True, 'release_proof': proof}
except Exception as error: except Exception as error:
@@ -453,6 +465,23 @@ def observe_retained_session(path, *, evidence_root, stop=None, progress=None, p
def handoff_session(path, *, evidence_root, process=None, progress=None, stop=None, observe_only=False): def handoff_session(path, *, evidence_root, process=None, progress=None, stop=None, observe_only=False):
"""Retain exact handles in memory until the observer independently releases.""" """Retain exact handles in memory until the observer independently releases."""
retired = threading.Event()
class ObservationStop:
def is_set(self):
return retired.is_set() or (stop is not None and stop.is_set())
def wait(self, seconds):
if stop is None:
return retired.wait(seconds)
import time
deadline = time.monotonic() + seconds
while not self.is_set():
remaining = deadline - time.monotonic()
if remaining <= 0:
return False
retired.wait(min(.1, remaining))
return True
key = str(Path(path).absolute()).casefold() key = str(Path(path).absolute()).casefold()
try: try:
session = read_session_record(path, evidence_root=evidence_root) session = read_session_record(path, evidence_root=evidence_root)
@@ -484,7 +513,7 @@ def handoff_session(path, *, evidence_root, process=None, progress=None, stop=No
if progress is not None: if progress is not None:
progress(value) progress(value)
def observation_only(): def observation_only():
if not observe_only: if not (observe_only() if callable(observe_only) else observe_only):
return False return False
with _observer_guard: with _observer_guard:
value = _retained_results.get(key, {}) value = _retained_results.get(key, {})
@@ -495,7 +524,7 @@ def handoff_session(path, *, evidence_root, process=None, progress=None, stop=No
result = None result = None
try: try:
result = observe_retained_session(path, evidence_root=evidence_root, progress=notify, result = observe_retained_session(path, evidence_root=evidence_root, progress=notify,
stop=stop, process=process, observe_only=observation_only) stop=ObservationStop(), process=process, observe_only=observation_only)
if process is not None and process.poll() is not None: if process is not None and process.poll() is not None:
process.close() process.close()
return result return result
@@ -509,7 +538,7 @@ def handoff_session(path, *, evidence_root, process=None, progress=None, stop=No
_retained_libraries.pop(key, None) _retained_libraries.pop(key, None)
_retained_results.pop(key, None) _retained_results.pop(key, None)
thread = threading.Thread(target=observe, name='retained-native-session', daemon=True) thread = threading.Thread(target=observe, name='retained-native-session', daemon=True)
_observers[key] = (thread, process) _observers[key] = (thread, process, retired)
thread.start() thread.start()
+55 -26
View File
@@ -18,6 +18,7 @@ from PySide6.QtWidgets import (QWidget, QLineEdit, QPushButton, QFormLayout,
QTableWidget, QTableWidgetItem, QHeaderView, QCheckBox, QVBoxLayout, QProgressBar, QComboBox, QTableWidget, QTableWidgetItem, QHeaderView, QCheckBox, QVBoxLayout, QProgressBar, QComboBox,
QTabBar, QStackedWidget, QSizePolicy, QDialog, QDialogButtonBox, QPlainTextEdit) QTabBar, QStackedWidget, QSizePolicy, QDialog, QDialogButtonBox, QPlainTextEdit)
from PySide6.QtWidgets import QStyle from PySide6.QtWidgets import QStyle
from shiboken6 import isValid
def _path_key(value): def _path_key(value):
@@ -134,7 +135,8 @@ class MainWindow(QWidget):
self._diagnostic_evidence = {} self._diagnostic_evidence = {}
self.pool = QThreadPool(self); self.pool.setMaxThreadCount(8) self.pool = QThreadPool(self); self.pool.setMaxThreadCount(8)
self.lifecycle_pool = QThreadPool(self); self.lifecycle_pool.setMaxThreadCount(1) self.lifecycle_pool = QThreadPool(self); self.lifecycle_pool.setMaxThreadCount(1)
self.lease_pool = QThreadPool(self); self.lease_pool.setMaxThreadCount(1) self.lease_pool = QThreadPool()
self.lease_pool.setMaxThreadCount(1)
self._lifecycle_workers = set() self._lifecycle_workers = set()
self._lifecycle_contexts = set() self._lifecycle_contexts = set()
self._lease_pending = 0 self._lease_pending = 0
@@ -408,22 +410,24 @@ class MainWindow(QWidget):
if signal == 'version_choice': value.choose('cancel') if signal == 'version_choice': value.choose('cancel')
def _finish_job(self, job): def _finish_job(self, job):
view_alive = isValid(self) and isValid(self.cbb_table)
if job.keep_session: if job.keep_session:
if self._job_current(job): self._finished() if view_alive and self._job_current(job): self._finished()
return return
paused = getattr(job, 'paused_check', None) paused = getattr(job, 'paused_check', None)
if paused is not None and paused.active and not paused.stop.is_set() and not self._closing: if view_alive and paused is not None and paused.active and not paused.stop.is_set() and not self._closing:
paused.resume() paused.resume()
job.active = False job.active = False
self._jobs.pop(job.context.operation_id, None) self._jobs.pop(job.context.operation_id, None)
state = job.context.close(timeout_seconds=0) state = job.context.close(timeout_seconds=0)
if job.lease is not None and job.lease is not self.library_lease: if job.lease is not None and (not view_alive or job.lease is not self.library_lease):
if state['pending'] or id(job.lease) in self._shutdown_leases: if state['pending'] or id(job.lease) in self._shutdown_leases:
self._retain_path_lease(job.lease) self._retain_path_lease(job.lease)
elif not any(other.lease is job.lease for other in self._jobs.values()): elif not any(other.lease is job.lease for other in self._jobs.values()):
self._close_path_lease(job.lease) self._close_path_lease(job.lease)
if self._job_current(job): self._finished() if view_alive:
else: self._update() if self._job_current(job): self._finished()
else: self._update()
def _release_library_lease(self): def _release_library_lease(self):
lease, self.library_lease = self.library_lease, None lease, self.library_lease = self.library_lease, None
@@ -457,7 +461,10 @@ class MainWindow(QWidget):
def _lease_action(self, action, completed=None, failed=None, *, hold_busy=False, def _lease_action(self, action, completed=None, failed=None, *, hold_busy=False,
library=None, completed_always=False): library=None, completed_always=False):
# The serial pool orders retain before every subsequent close. # The serial pool outlives the view and orders retain before close.
if not isValid(self) or not isValid(self.cbb_table):
self.lease_pool.start(ServiceWorker(action))
return
owner = (self._view_revision, id(self._current_job)) owner = (self._view_revision, id(self._current_job))
def current(): def current():
from shiboken6 import isValid from shiboken6 import isValid
@@ -477,7 +484,10 @@ class MainWindow(QWidget):
worker = ServiceWorker(lambda:context.run(action)) worker = ServiceWorker(lambda:context.run(action))
self._lease_workers.add(worker) self._lease_workers.add(worker)
if completed is not None: if completed is not None:
worker.signals.succeeded.connect(lambda result:completed(result) if completed_always or current() else None) def ready(result):
if isValid(self) and isValid(self.cbb_table) and (completed_always or current()):
completed(result)
worker.signals.succeeded.connect(ready)
worker.signals.failed.connect(lambda error:(failed or self._display_error)(error) if current() else None) worker.signals.failed.connect(lambda error:(failed or self._display_error)(error) if current() else None)
def finished(): def finished():
self._lease_workers.discard(worker) self._lease_workers.discard(worker)
@@ -605,7 +615,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 from cbb_refresh_verify.residual_sessions import recoverable_orphan_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))
@@ -619,9 +629,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']) path = session['path']
handoff_session(session['path'], evidence_root=root, handoff_session(path, evidence_root=root,
observe_only=not recover_catalog, observe_only=lambda path=path: not recoverable_orphan_session(path),
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))
@@ -994,7 +1004,8 @@ class MainWindow(QWidget):
def _eligible_names(self, *, checked_only=False, require_status=False): def _eligible_names(self, *, checked_only=False, require_status=False):
records = self.selected_records() if checked_only else self.visible_records() records = self.selected_records() if checked_only else self.visible_records()
return [r.name for r in records if r.status != 'READY' and r.name not in self.skipped_names return [r.name for r in records if r.status != 'READY' and r.name not in self.skipped_names
and (not require_status or self.catalog_reader is None or r.status == 'PENDING')] and (not require_status or self.catalog_reader is None or r.status == 'PENDING'
or r.status_source == 'cancelled_verify')]
def _maintenance_names(self): def _maintenance_names(self):
records = self.selected_records() or self.visible_records() records = self.selected_records() or self.visible_records()
@@ -1527,11 +1538,12 @@ class MainWindow(QWidget):
def attempt(evidence): def attempt(evidence):
return self.native_queue.run(lambda: reconcile(evidence), context=context, return self.native_queue.run(lambda: reconcile(evidence), context=context,
timeout_seconds=120, skip_unavailable=True) timeout_seconds=120, wait_for_release_seconds=CATALOG_MANAGER_WAIT_SECONDS,
waiting=lambda: phase('catalog_waiting', '等待后台会话退出或原生队列空闲,随后自动读取。'))
def scan(): def scan():
from cbb_refresh_verify.native_management import NativeOperationError from cbb_refresh_verify.native_management import NativeOperationError
from cbb_refresh_verify.owner_probe import query_owners from cbb_refresh_verify.owner_probe import snapshot_process_ids
try: try:
return attempt(root) return attempt(root)
@@ -1544,13 +1556,12 @@ class MainWindow(QWidget):
while time.monotonic() < deadline: while time.monotonic() < deadline:
context.check_active() context.check_active()
try: try:
owners = query_owners(('LibraryManager.exe',), owners = snapshot_process_ids('LibraryManager.exe')
timeout_seconds=min(2, max(.1, deadline - time.monotonic()))) except OSError:
except (OSError, RuntimeError):
context.stop.wait(1) context.stop.wait(1)
continue continue
context.check_active() context.check_active()
if not owners or blockers and blockers.isdisjoint(owner['pid'] for owner in owners): if not owners or blockers and blockers.isdisjoint(owners):
return attempt(root/'retry') return attempt(root/'retry')
context.stop.wait(1) context.stop.wait(1)
context.check_active() context.check_active()
@@ -1913,7 +1924,12 @@ class MainWindow(QWidget):
f'正在 ICDB 批量检查:共 {len(names)} 个 CBB' if maintenance f'正在 ICDB 批量检查:共 {len(names)} 个 CBB' if maintenance
else f'正在校验:共 {len(names)} 个 CBB') else f'正在校验:共 {len(names)} 个 CBB')
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,
wait_for_batch_release)
if self.verifier is None:
wait_for_batch_release(requests[0], job.context,
progress=lambda value: self._emit_job(job, 'event', value),
timeout_seconds=VERIFY_RELEASE_WAIT_SECONDS)
verify = self.verifier or (lambda req: run_verify( verify = self.verifier or (lambda req: run_verify(
req, req,
progress=lambda e: self._emit_job(job, 'event', e), progress=lambda e: self._emit_job(job, 'event', e),
@@ -1944,8 +1960,9 @@ class MainWindow(QWidget):
'detail': result.stderr or result.stdout})) 'detail': result.stderr or result.stdout}))
report = None report = None
try: try:
report = BatchTaskContext(str(library)).run(lambda: report_root = self.data_root/'reports'
write_batch_report(requests, results, self.data_root/'reports')) report = BatchTaskContext(str(report_root), native_policy='restricted').run(
lambda: write_batch_report(requests, results, report_root))
if maintenance: if maintenance:
from cbb_refresh_verify.icdb_maintenance import write_maintenance_report from cbb_refresh_verify.icdb_maintenance import write_maintenance_report
write_maintenance_report(requests, results, report, ()) write_maintenance_report(requests, results, report, ())
@@ -1987,7 +2004,7 @@ class MainWindow(QWidget):
finally: finally:
pythoncom.CoUninitialize() pythoncom.CoUninitialize()
def _apply_refreshed_records(self, payload): def _apply_refreshed_records(self, payload, *, cancelled_retries=()):
names, statuses, reasons, error = payload names, statuses, reasons, error = payload
self._publish_check_statuses(self.mentor_lmc_path or self.loaded_path, self._publish_check_statuses(self.mentor_lmc_path or self.loaded_path,
{name: statuses.get(name, 'UNKNOWN') for name in names}) {name: statuses.get(name, 'UNKNOWN') for name in names})
@@ -1999,7 +2016,13 @@ class MainWindow(QWidget):
status = statuses.get(name, 'UNKNOWN') status = statuses.get(name, 'UNKNOWN')
if status not in STATUS_LABELS: if status not in STATUS_LABELS:
status = 'UNKNOWN' status = 'UNKNOWN'
self._records_by_name[name] = replace(self._records_by_name[name], status=status) record = self._records_by_name[name]
source = record.status_source
if name in cancelled_retries:
source = 'cancelled_verify'
elif source == 'cancelled_verify':
source = 'unknown' if status == 'UNKNOWN' else 'authoritative'
self._records_by_name[name] = replace(record, status=status, status_source=source)
self.ready_names.discard(name) self.ready_names.discard(name)
if reasons is not None: if reasons is not None:
self.skip_reasons.pop(name, None) self.skip_reasons.pop(name, None)
@@ -2081,7 +2104,7 @@ class MainWindow(QWidget):
elif event.get('stage') == 'native_slot_acquired': elif event.get('stage') == 'native_slot_acquired':
self.status_label.setText(event.get('detail') or '正在执行当前任务…') self.status_label.setText(event.get('detail') or '正在执行当前任务…')
self._update() self._update()
if event.get('stage') in ('session_handoff', 'save_stop_requested'): if event.get('stage') in ('session_handoff', 'save_stop_requested', 'post_save_release_pending'):
self.status_label.setText(event.get('detail', '当前状态无法确认')) self.status_label.setText(event.get('detail', '当前状态无法确认'))
if (event.get('stage') == 'session_observation' and event.get('status') == 'RELEASED' if (event.get('stage') == 'session_observation' and event.get('status') == 'RELEASED'
and event.get('release_proof')): and event.get('release_proof')):
@@ -2211,7 +2234,11 @@ class MainWindow(QWidget):
elif affected: 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) cancelled = {request.block_name for request, result in zip(self._batch_requests, results)
if result.status == 'CANCELLED' and request.block_name in self._records_by_name
and (self._records_by_name[request.block_name].status == 'PENDING'
or self._records_by_name[request.block_name].status_source == 'cancelled_verify')}
self._apply_refreshed_records((tuple(affected), {}, None, reason), cancelled_retries=cancelled)
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)
@@ -2456,6 +2483,8 @@ class MainWindow(QWidget):
self.status_label.setText('当前操作尚未结束,仍在等待安全关闭。') self.status_label.setText('当前操作尚未结束,仍在等待安全关闭。')
def _close_when_idle(self): def _close_when_idle(self):
if not isValid(self):
return
owners = [self, *self.icdb_tasks, *self._dialogs] owners = [self, *self.icdb_tasks, *self._dialogs]
for name in ('management_dialog', 'backup_dialog', 'release_dialog'): for name in ('management_dialog', 'backup_dialog', 'release_dialog'):
owners.append(getattr(self, name, None)) owners.append(getattr(self, name, None))
@@ -110,7 +110,7 @@ class ResidualReleaseDialog(QDialog):
for index, session in enumerate(sessions): for index, session in enumerate(sessions):
allowed = session.get('consent_allowed') allowed = session.get('consent_allowed')
permission = '允许' if allowed is True else '未允许' if allowed is False else '待确认' permission = '允许' if allowed is True else '未允许' if allowed is False else '待确认'
outcome = {'RELEASED': '已释放', 'WAITING': '未释放', 'IDENTITY_CHANGED': '身份已变化', outcome = {'RELEASED': '客户端已退出', 'WAITING': '未退出', 'IDENTITY_CHANGED': '身份已变化',
'OBSERVED': '仅观察,未关闭', 'OBSERVED': '仅观察,未关闭',
'CANCELLED': '已停止', 'REQUESTING': '执行中', 'NOT_STARTED': '尚未执行'}.get( 'CANCELLED': '已停止', 'REQUESTING': '执行中', 'NOT_STARTED': '尚未执行'}.get(
session.get('release_status'), '待执行') session.get('release_status'), '待执行')
@@ -178,7 +178,7 @@ class ResidualReleaseDialog(QDialog):
self._start(execute, done) self._start(execute, done)
def _accept_release_proof(self, result): def _accept_release_proof(self, result):
proof = result.get('proof', {}) proof = result.get('proof') or {}
# Both paths were canonicalized by the worker; GUI comparison must not touch SMB. # Both paths were canonicalized by the worker; GUI comparison must not touch SMB.
if (proof.get('status') != 'RELEASE_CONFIRMED' if (proof.get('status') != 'RELEASE_CONFIRMED'
or Path(proof.get('library', '')).absolute() != self.library.absolute() or Path(proof.get('library', '')).absolute() != self.library.absolute()
@@ -191,7 +191,7 @@ class ResidualReleaseDialog(QDialog):
def _finalize_release_result(self, result): def _finalize_release_result(self, result):
"""Complete mapping cleanup before the serialized release admits new work.""" """Complete mapping cleanup before the serialized release admits new work."""
proof = result.get('proof', {}) proof = result.get('proof') or {}
if (self.release_finalizer is not None and proof.get('status') == 'RELEASE_CONFIRMED' if (self.release_finalizer is not None and proof.get('status') == 'RELEASE_CONFIRMED'
and Path(proof.get('library', '')).absolute() == self.library.absolute() and Path(proof.get('library', '')).absolute() == self.library.absolute()
and release_targets_complete(result['sessions'])): and release_targets_complete(result['sessions'])):
@@ -303,10 +303,10 @@ class ResidualReleaseDialog(QDialog):
count = sum(row['release_status'] == 'RELEASED' and row.get('scope_confirmed') is not False count = sum(row['release_status'] == 'RELEASED' and row.get('scope_confirmed') is not False
for row in result['sessions']) for row in result['sessions'])
if self._accept_release_proof(result): if self._accept_release_proof(result):
self.message.setText(f'已释放 {count} 个会话,旧占用记录已解除。' self.message.setText(f'库已释放,已确认 {count} 个客户端退出。'
+ ('\n记录保存失败:'+result['evidence_error'] if result.get('evidence_error') else '')) + ('\n记录保存失败:'+result['evidence_error'] if result.get('evidence_error') else ''))
else: else:
self.message.setText(f'已释放 {count} 个会话,其余会话或库状态仍待确认。' self.message.setText(f'{count} 个客户端已退出,库释放仍待确认。'
+ ('\n'+result['detail'] if result.get('detail') else '可查看原生提示、处理保存或请求取消后重新检查。') + ('\n'+result['detail'] if result.get('detail') else '可查看原生提示、处理保存或请求取消后重新检查。')
+ ('\n记录保存失败:'+result['evidence_error'] if result.get('evidence_error') else '')) + ('\n记录保存失败:'+result['evidence_error'] if result.get('evidence_error') else ''))
allowed = [row for row in result['sessions'] if row.get('consent_allowed') is True] allowed = [row for row in result['sessions'] if row.get('consent_allowed') is True]
+112 -9
View File
@@ -1441,6 +1441,36 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
release_result = {**(release_result or {}), 'icdb_addresses': addresses} release_result = {**(release_result or {}), 'icdb_addresses': addresses}
except OSError as error: except OSError as error:
close_errors.append(str(error)) close_errors.append(str(error))
try:
save_lines = (root/'save.log').read_text('utf-8', errors='replace').splitlines()
except FileNotFoundError:
save_lines = []
except OSError as error:
save_lines = []
close_errors.append(str(error))
if (worker_exited and automation_release.get('safe_to_continue') and not close_errors
and release_result.get('safe_to_continue') and not request.diagnostic_only
and {'SAVE_START', 'SAVE_OK', 'IS_SAVED', 'CLOSE_OK'}.issubset(save_lines)):
from .icdb_ownership import wait_for_saved_database_release
from .operation_queue import allow_other_libraries, task_stop
timing.begin('database_release')
try:
with allow_other_libraries():
database_release = wait_for_saved_database_release(
request.lmc_file, project, pcb, stop=task_stop(stop),
report_pending=lambda *, blocked_resources: _notify_progress(progress, {
'stage': 'post_save_release_pending', 'block': request.block_name,
'detail': '已保存,等待 iCDB 释放数据库'
+ (':' + '、'.join(blocked_resources) if blocked_resources else ''),
'blocked_resources': blocked_resources}))
except Exception as error:
database_release = {'status': 'UNCONFIRMED', 'detail': str(error),
'blocked_resources': []}
finally:
timing.end('database_release')
release_result = {**release_result, 'database_release': database_release,
'blocked_resources': database_release['blocked_resources'],
'safe_to_continue': database_release['status'] == 'RELEASE_CONFIRMED'}
if close_errors: if close_errors:
release_result = {**(release_result or {}), 'safe_to_continue': False, release_result = {**(release_result or {}), 'safe_to_continue': False,
'close_errors': close_errors} 'close_errors': close_errors}
@@ -1470,12 +1500,24 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
'close_errors': [*close_errors, str(error)]} 'close_errors': [*close_errors, str(error)]}
try: try:
from .operation_lifecycle import classify_save_state from .operation_lifecycle import classify_save_state
save_lines = ((root/'save.log').read_text('utf-8', errors='replace').splitlines() facts = classify_save_state(save_lines,
if (root/'save.log').is_file() else [])
_write_optional_evidence(root/'write-outcome.json', classify_save_state(save_lines,
helper_exited=(False if automation_release.get('remaining_pids') else helper_exited=(False if automation_release.get('remaining_pids') else
True if worker_exited and automation_release.get('safe_to_continue') else None), True if worker_exited and automation_release.get('safe_to_continue') else None),
native_released=release_result.get('safe_to_continue') is True)) native_released=release_result.get('safe_to_continue') is True)
if 'SAVE_START' in save_lines and getattr(process, 'session_record_path', None):
from .session_record import read_session_record
try:
state = read_session_record(root/'worker-state.json', evidence_root=root)
except (OSError, ValueError):
state = {}
receipt = state.get('write_outcome')
confirmed = (state.get('operation_id') == job['operation_id']
and isinstance(receipt, dict) and receipt.get('save_close_confirmed') is True)
facts['save_close_confirmed'] = confirmed
if facts['helper_state'] == 'EXITED' and not confirmed:
facts['interrupted'] = True
facts['detail'] = '缺少保存助手正常退出的完整记录'
_write_optional_evidence(root/'write-outcome.json', facts)
(root/'session-release.json').write_text(json.dumps({ (root/'session-release.json').write_text(json.dumps({
**(release_result or {}), 'block': request.block_name, **(release_result or {}), 'block': request.block_name,
'library': str(request.lmc_file), 'worker_exited': worker_exited, 'library': str(request.lmc_file), 'worker_exited': worker_exited,
@@ -1490,8 +1532,17 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
pass pass
if not release_result or not release_result.get('safe_to_continue'): if not release_result or not release_result.get('safe_to_continue'):
if 'result' in locals(): if 'result' in locals():
result = replace(result, status='FAIL' if result.status == 'PASS' else result.status, safe_to_continue=False, database_release = (release_result or {}).get('database_release')
stderr=(result.stderr + '\nPCB_RELEASE_UNCONFIRMED: 未确认原生会话退出').strip()) if database_release and database_release['status'] != 'RELEASE_CONFIRMED':
result = replace(result, status='FAIL' if result.status == 'PASS' else result.status,
safe_to_continue=False, error_category='ICDB_RELEASE_PENDING', error_stage='release_check',
release_proof=database_release,
stderr=(result.stderr + '\nICDB_RELEASE_PENDING: 已保存,数据库释放未确认。'
+ database_release['detail']).strip())
else:
result = replace(result, status='FAIL' if result.status == 'PASS' else result.status,
safe_to_continue=False,
stderr=(result.stderr + '\nPCB_RELEASE_UNCONFIRMED: 未确认原生会话退出').strip())
recovery = {'desktop': job['desktop'], 'project': str(project), recovery = {'desktop': job['desktop'], 'project': str(project),
'pcb': str(pcb), 'release': release_result, 'pcb': str(pcb), 'release': release_result,
'action': '停止批次;检查原生会话及数据库;不要删除锁文件或自动恢复。'} 'action': '停止批次;检查原生会话及数据库;不要删除锁文件或自动恢复。'}
@@ -1540,6 +1591,49 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
return finish(result) return finish(result)
def wait_for_batch_release(request, context, *, progress=None, timeout_seconds=120):
"""Wait outside the native queue so controls and unrelated libraries can run."""
from .library_lock import LibraryBusy, recheck_previous_release
from .operation_queue import QueueUnavailable
from .session_record import library_available, library_wait_reason, retained_session_states
library = request.lmc_file
if not Path(library).is_file():
return
started = time.monotonic()
deadline = started + timeout_seconds
previous = None
while True:
context.check_active()
if library_available(library, live_only=True):
try:
# A restarted observer owns no in-process LibraryLock.
# Its exited client still requires a proof for the recorded scope.
recheck_previous_release(library, Path(request.evidence_dir)/'previous-release',
block_name=request.block_name, stop=context.stop, infer_scope=True,
required=not library_available(library))
except LibraryBusy as error:
detail = str(error)
else:
context.check_active()
return
else:
sessions = retained_session_states(library)
if any(value.get('active_save') is True for value in sessions):
deadline = max(deadline, started + request.timeout_seconds)
detail = 'Mentor 正在保存,结束后自动复核释放。'
else:
detail = library_wait_reason(library)
if detail != previous:
_notify_progress(progress, {'stage': 'waiting_native_slot', 'library': str(library),
'retained': True, 'detail': detail})
previous = detail
remaining = deadline - time.monotonic()
if remaining <= 0:
raise QueueUnavailable(library, retained_session_states(library), timed_out=True, detail=detail)
context.stop.wait(min(1, remaining))
def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=None, item_executor=None, def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=None, item_executor=None,
context=None): context=None):
"""Run serially; isolate failures and skip writes to resources still retained.""" """Run serially; isolate failures and skip writes to resources still retained."""
@@ -1569,6 +1663,15 @@ def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=Non
if refreshed.safe_to_continue: if refreshed.safe_to_continue:
results[index] = refreshed results[index] = refreshed
retained_libraries = {k:v for k,v in retained_libraries.items() if v[1] != index} retained_libraries = {k:v for k,v in retained_libraries.items() if v[1] != index}
cached_timeout = None
if library_keys.intersection(timed_out_admissions):
from .session_record import library_available
for key in library_keys.intersection(timed_out_admissions):
blocked_library, previous_result = timed_out_admissions[key]
if not library_available(blocked_library, live_only=True):
cached_timeout = previous_result
break
del timed_out_admissions[key]
if (queue_stop or stop is not None and stop.is_set() if (queue_stop or stop is not None and stop.is_set()
or context is not None and context.stop.is_set()): or context is not None and context.stop.is_set()):
result = VerifyResult('SKIPPED', stderr='队列已停止,未操作此 CBB') result = VerifyResult('SKIPPED', stderr='队列已停止,未操作此 CBB')
@@ -1576,8 +1679,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): elif cached_timeout is not None:
result = timed_out_admissions[next(iter(library_keys.intersection(timed_out_admissions)))] result = cached_timeout
else: else:
try: try:
def execute(): def execute():
@@ -1598,7 +1701,7 @@ def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=Non
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: if isinstance(error, QueueUnavailable) and error.timed_out:
timed_out_admissions.update(dict.fromkeys(library_keys, result)) timed_out_admissions.update(dict.fromkeys(library_keys, (error.library, 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:
+37
View File
@@ -110,3 +110,40 @@ def test_supervisor_crash_preserves_registered_save_caller_and_native(tmp_path):
if win32process.GetExitCodeProcess(handle) == 259: if win32process.GetExitCodeProcess(handle) == 259:
win32process.TerminateProcess(handle, 0) win32process.TerminateProcess(handle, 0)
handle.Close() handle.Close()
def test_registered_save_records_completion_after_supervisor_loss(tmp_path, monkeypatch):
from threading import Event
from cbb_refresh_verify import desktop_worker, session_record
root = tmp_path
state_path = root/'worker-state.json'
job = {'root': str(root), 'block_name': 'CBB', 'operation_id': 'save-orphan',
'session_record_path': str(root/'session.json')}
request = root/'request.json'
request.write_text(json.dumps(job), encoding='utf-8')
lost = Event()
monkeypatch.setattr(desktop_worker, '_supervisor_lost', lost)
monkeypatch.setattr(desktop_worker, '_native_phases', {})
def execute(job, emit):
emit(stage='save_start')
emit(stage='save_helper', helper_pid=987)
lost.set()
emit(stage='save_progress', markers=['SAVE_START', 'SAVE_OK', 'CLOSE_START'],
helper_exited=False)
state = session_record.read_session_record(state_path, evidence_root=root)
assert state['phase'] == 'NATIVE_CALL'
emit(stage='save_progress', markers=['SAVE_START', *FULL_SAVE.splitlines()],
helper_exited=True, helper_exit_code=0)
with pytest.raises(RuntimeError, match='WORKER_CANCELLED'):
emit(stage='integration_action')
return {'status': 'FAIL', 'stderr': 'supervisor interrupted'}
monkeypatch.setattr(adapter, 'execute_job', execute)
assert adapter.worker_main(request) == 1
state = session_record.read_session_record(state_path, evidence_root=root)
assert state['phase'] == 'POSTCALL'
facts = state['write_outcome']
assert facts['save_close_confirmed'] is True
assert (facts['save_state'], facts['close_state'], facts['helper_state']) == (
'COMMITTED', 'CLOSED', 'EXITED')
+34 -1
View File
@@ -416,7 +416,7 @@ def test_residual_refresh_details_confirm_and_close(residual, qtbot):
qtbot.waitUntil(lambda: not d.busy) qtbot.waitUntil(lambda: not d.busy)
assert len(residual.releases) == 1 and residual.releases[0]['force'] is False assert len(residual.releases) == 1 and residual.releases[0]['force'] is False
assert d.table.item(0, 6).text() == '允许' assert d.table.item(0, 6).text() == '允许'
assert d.table.item(0, 7).text() == '未释放' assert d.table.item(0, 7).text() == '未退出'
press(qtbot, d.close_button) press(qtbot, d.close_button)
assert not d.isVisible() assert not d.isVisible()
@@ -492,6 +492,39 @@ def test_result_release_and_resume_buttons_run_only_unexecuted_items(controls, q
assert [request.block_name for request in controls.runs] == ['Beta','Gamma'] assert [request.block_name for request in controls.runs] == ['Beta','Gamma']
def test_cancelled_batch_report_is_saved_during_native_handoff(controls, qtbot, monkeypatch):
from cbb_refresh_verify.operation_queue import BatchTaskContext, TaskHandoff
from cbb_refresh_verify.ui import main_window
window = controls.window
finish_native = Event()
native_finished = Event()
def pending_native():
finish_native.wait(8)
native_finished.set()
def cancelled_batch(requests, **_):
handoff = BatchTaskContext(str(controls.library))
with pytest.raises(TaskHandoff):
handoff.run(pending_native, timeout_seconds=.1)
return [VerifyResult('CANCELLED', safe_to_continue=False),
*[VerifyResult('SKIPPED') for _ in requests[1:]]]
monkeypatch.setattr(main_window, 'run_batch', cancelled_batch)
try:
with modal_click(qtbot, QMessageBox.Yes):
press(qtbot, window.batch_button)
qtbot.waitUntil(lambda: not window.busy)
reports = list((window.data_root/'reports').glob('batch-*.log'))
assert len(reports) == 1
assert 'Beta\tCANCELLED' in reports[0].read_text(encoding='utf-8-sig')
assert not native_finished.is_set()
finally:
finish_native.set()
assert native_finished.wait(3)
@pytest.mark.parametrize('entry', ['icdb_copy', 'icdb_release', 'batch_copy', 'batch_close']) @pytest.mark.parametrize('entry', ['icdb_copy', 'icdb_release', 'batch_copy', 'batch_close'])
def test_result_recovery_and_release_entries_stay_bound_to_failed_cbb(controls, qtbot, entry): def test_result_recovery_and_release_entries_stay_bound_to_failed_cbb(controls, qtbot, entry):
from dataclasses import replace from dataclasses import replace
+73
View File
@@ -111,6 +111,79 @@ def test_smoke_arguments_exit_zero_and_write_lifecycle_log(tmp_path: Path):
assert "gui_smoke_window_created" in text assert "gui_smoke_window_created" in text
def test_desktop_duplicate_activates_original_and_recovers_after_exit(tmp_path):
import os
import subprocess
import sys
import time
harness = r'''
import os, sys
from PySide6.QtWidgets import QWidget
from cbb_refresh_verify import application
from cbb_refresh_verify.ui import main_window
class Window(QWidget):
def __init__(self, *, logging_context):
super().__init__()
self.directory = logging_context.root
def show(self):
self.showMinimized()
(self.directory / f'{os.getpid()}.started').touch()
def activateWindow(self):
assert not self.isMinimized()
(self.directory / f'{os.getpid()}.activated').touch()
super().activateWindow()
main_window.MainWindow = Window
raise SystemExit(application.main(sys.argv[1:]))
'''
data = tmp_path / 'data'
independent = tmp_path / 'other'
processes = []
def start(directory):
process = subprocess.Popen([sys.executable, '-c', harness, '--data-root', str(directory)],
env={**os.environ, 'QT_QPA_PLATFORM': 'offscreen'})
processes.append(process)
return process
def wait_for_file(path):
deadline = time.monotonic() + 12
while not path.exists() and time.monotonic() < deadline:
time.sleep(.03)
assert path.is_file(), path
try:
initial = start(data)
wait_for_file(data / f'{initial.pid}.started')
duplicate = start(data / '..' / data.name.upper())
assert duplicate.wait(timeout=8) == 0
assert {path.stem for path in data.glob('*.started')} == {str(initial.pid)}
assert (data / f'{initial.pid}.activated').is_file()
other = start(independent)
wait_for_file(independent / f'{other.pid}.started')
initial.kill()
initial.wait(timeout=5)
contenders = [start(data), start(data)]
deadline = time.monotonic() + 12
while not any(process.poll() is not None for process in contenders) and time.monotonic() < deadline:
time.sleep(.03)
assert sorted((process.poll() for process in contenders), key=lambda value: value is None) == [0, None]
surviving = next(process for process in contenders if process.poll() is None)
assert {path.stem for path in data.glob('*.started')} == {str(initial.pid), str(surviving.pid)}
assert (data / f'{surviving.pid}.activated').is_file()
finally:
for process in processes:
if process.poll() is None:
process.kill()
process.wait(timeout=5)
def test_module_entrypoint_propagates_main_exit_code(): def test_module_entrypoint_propagates_main_exit_code():
import subprocess, sys import subprocess, sys
code = ( code = (
+32
View File
@@ -33,6 +33,38 @@ def test_proved_ordinary_cancel_finishes_tip_to_loaded_without_annotation_or_sec
assert messages==([(100,16),(31,245)] if prior_close else [(201,245),(31,245),(100,16)]) assert messages==([(100,16),(31,245)] if prior_close else [(201,245),(31,245),(100,16)])
@pytest.mark.parametrize('obstacle', [None, 'unknown_control', 'other_window', 'write'])
def test_cancel_at_owned_license_selector(tmp_path, monkeypatch, obstacle):
import win32gui
from cbb_refresh_verify.dialog_models import ControlSnapshot, DialogPhase, WindowSnapshot
job, records, messages, state = loaded_fixture(tmp_path, monkeypatch)
ordinary_proof(job, tmp_path, job['diagnostic_log_baseline'])
if obstacle == 'write':
(tmp_path/'save.log').touch()
controls = (ControlSnapshot(201, 5225, 'Button', 'Select the desired product license', enabled=True),
ControlSnapshot(202, 1522, 'GXWND', ''),
ControlSnapshot(203, 1, 'Button', 'OK', enabled=True),
ControlSnapshot(204, 2, 'Button', 'Cancel' if obstacle != 'unknown_control' else 'Next',
enabled=True))
snapshot = WindowSnapshot(200, 12, 'ExpeditionPCB.exe', 'pcb', '#32770', '',
DialogPhase.PCB_STARTING, controls)
monkeypatch.setattr(failed_session, '_startup_snapshot', lambda *args: snapshot)
monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn, arg:
[fn(hwnd, arg) for hwnd in ((200, 300) if obstacle == 'other_window' else (200,))])
monkeypatch.setattr(win32gui, 'GetClassName', lambda hwnd: '#32770' if hwnd == 200 else 'Afx:other')
monkeypatch.setattr(win32gui, 'GetWindowText', lambda hwnd: '')
def post(hwnd, message, *_):
messages.append((hwnd, message))
records.clear()
monkeypatch.setattr(win32gui, 'PostMessage', post)
result = failed_session.close_failed_startup(job, 12, timeout_seconds=1)
assert messages == ([(204, 245)] if obstacle is None else [])
assert result['status'] == ('CLOSED' if obstacle is None else 'RETAINED')
@pytest.mark.parametrize('obstacle',['missing_ready','missing_cancel_phase','supervisor_write','worker_write', @pytest.mark.parametrize('obstacle',['missing_ready','missing_cancel_phase','supervisor_write','worker_write',
'missing_supervisor','missing_baseline','foreign_worker','foreign_target','save','missing_cancel','interactive','native_lm']) 'missing_supervisor','missing_baseline','foreign_worker','foreign_target','save','missing_cancel','interactive','native_lm'])
def test_ordinary_cleanup_requires_positive_bound_no_write_evidence(tmp_path,monkeypatch,obstacle): def test_ordinary_cleanup_requires_positive_bound_no_write_evidence(tmp_path,monkeypatch,obstacle):
+22
View File
@@ -145,6 +145,7 @@ def test_natural_native_exit_gets_fresh_release_and_admits_waiting_scope_without
assert future.result(8)=='fresh admission' assert future.result(8)=='fresh admission'
thread.join(3) thread.join(3)
assert not thread.is_alive() and closed==[0] assert not thread.is_alive() and closed==[0]
assert not stop.is_set(), 'retiring the observer must not cancel its caller'
observations=[json.loads(p.read_text()) for p in evidence.glob('observation-*.json')] observations=[json.loads(p.read_text()) for p in evidence.glob('observation-*.json')]
assert any(o.get('status')=='RELEASED' and o['release_proof']['proof_block_name']=='A' for o in observations) assert any(o.get('status')=='RELEASED' and o['release_proof']['proof_block_name']=='A' for o in observations)
assert original.read_bytes()==before assert original.read_bytes()==before
@@ -152,3 +153,24 @@ def test_natural_native_exit_gets_fresh_release_and_admits_waiting_scope_without
gate.touch();native.wait(5);stop.set() gate.touch();native.wait(5);stop.set()
if thread:thread.join(3) if thread:thread.join(3)
cleanup(lease) cleanup(lease)
def test_stopped_observer_does_not_start_a_second_library_probe(tmp_path, monkeypatch):
from test_session_record import record
import subprocess
import sys
with subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(30)']) as native:
identity = session_record.process_identity(native.pid)
native.terminate()
native.wait(5)
path = record(tmp_path, [dict(role='native', **identity)])
stop = Event()
stop.set()
probes = []
monkeypatch.setattr('cbb_refresh_verify.library_lock.release_retained_library',
lambda *args, **kwargs: probes.append(args))
session_record.observe_retained_session(path, evidence_root=tmp_path, stop=stop)
assert probes == []
+3 -3
View File
@@ -723,11 +723,11 @@ def test_external_catalog_owner_wait_retries_once_or_cancels(qtbot, tmp_path, mo
raise NativeOperationError('LIBRARY_MANAGER_BUSY: 已有 Library Manager 运行。', safe_to_continue=True) raise NativeOperationError('LIBRARY_MANAGER_BUSY: 已有 Library Manager 运行。', safe_to_continue=True)
return Catalog(path, 1, (CatalogEntry('A', 'Logical-Physical'),)) return Catalog(path, 1, (CatalogEntry('A', 'Logical-Physical'),))
def owners(*args, **kwargs): def owners(_name):
probing.set() probing.set()
return [] if released.is_set() else [{'pid': 123}] return [] if released.is_set() else [123]
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', owners) monkeypatch.setattr('cbb_refresh_verify.owner_probe.snapshot_process_ids', owners)
window = window_for(qtbot, tmp_path, monkeypatch, window = window_for(qtbot, tmp_path, monkeypatch,
reader=lambda _: LibraryReadResult((CbbRecord('A', 'LP'),), directory_count=1), reader=lambda _: LibraryReadResult((CbbRecord('A', 'LP'),), directory_count=1),
catalog_reader=read_catalog, status_refresher=lambda names, _: {name: 'READY' for name in names}) catalog_reader=read_catalog, status_refresher=lambda names, _: {name: 'READY' for name in names})
+165
View File
@@ -0,0 +1,165 @@
import pytest
from cbb_refresh_verify.library_lock import LibraryBusy
from cbb_refresh_verify.operation_queue import BatchTaskContext, QueueUnavailable
from cbb_refresh_verify.verify_runner import VerifyRequest
def test_batch_admission_rechecks_once_before_dispatch(tmp_path, monkeypatch):
from cbb_refresh_verify import verify_runner
library = tmp_path/'library.lmc'
library.touch()
request = VerifyRequest(library, 'Next', tmp_path/'evidence')
calls = []
monkeypatch.setattr('cbb_refresh_verify.library_lock.recheck_previous_release',
lambda lib, *args, **kwargs: calls.append((lib, kwargs['infer_scope'])))
verify_runner.wait_for_batch_release(request, BatchTaskContext(str(library)))
assert calls == [(library, True)]
def test_batch_admission_reports_resource_at_entry(tmp_path, monkeypatch):
from cbb_refresh_verify import verify_runner
library = tmp_path/'library.lmc'
library.touch()
request = VerifyRequest(library, 'Next', tmp_path/'evidence')
def busy(*args, **kwargs):
raise LibraryBusy('共享符号库 icdb.dat 仍在使用')
monkeypatch.setattr('cbb_refresh_verify.library_lock.recheck_previous_release', busy)
with pytest.raises(QueueUnavailable, match='共享符号库 icdb.dat 仍在使用'):
verify_runner.wait_for_batch_release(request, BatchTaskContext(str(library)), timeout_seconds=0)
def test_batch_rechecks_recorded_session_after_client_exit(tmp_path, monkeypatch):
from cbb_refresh_verify import session_record, verify_runner
library = tmp_path / 'library.lmc'
library.touch()
request = VerifyRequest(library, 'Next', tmp_path / 'evidence')
monkeypatch.setattr(session_record, 'library_available', lambda _, live_only=False: live_only)
checks = []
def recheck(*args, **kwargs):
checks.append(kwargs.get('required', False))
if kwargs.get('required'):
raise LibraryBusy('记录中的客户端已退出,共享 iCDB 数据库仍在使用')
monkeypatch.setattr('cbb_refresh_verify.library_lock.recheck_previous_release', recheck)
with pytest.raises(QueueUnavailable, match='共享 iCDB 数据库仍在使用'):
verify_runner.wait_for_batch_release(request, BatchTaskContext(str(library)), timeout_seconds=0)
assert checks == [True]
def test_acknowledged_release_stops_only_matching_observer(tmp_path, monkeypatch):
from threading import Event
from cbb_refresh_verify import session_record as sessions
library = tmp_path / 'library.lmc'
key = str(tmp_path / 'session.json')
aliases = {sessions._library_key(library)}
stop = Event()
monkeypatch.setattr(sessions, '_retained_libraries', {key: aliases})
monkeypatch.setattr(sessions, '_retained_results', {key: {'operation_id': 'old', 'block': 'A'}})
monkeypatch.setattr(sessions, '_observers', {key: (None, None, stop)})
monkeypatch.setattr(sessions, 'record_session_release', lambda *_: [])
proof = {'library': str(library), 'status': 'RELEASE_CONFIRMED'}
snapshot = sessions.retained_session_snapshot(library)
sessions.acknowledge_library_release(proof, snapshot, block_name='B')
assert not stop.is_set()
sessions.acknowledge_library_release(proof, snapshot, block_name='A')
assert stop.is_set()
assert sessions.library_available(library)
def test_batch_waits_for_recorded_save_past_ordinary_release_deadline(tmp_path, monkeypatch):
from cbb_refresh_verify import verify_runner
from cbb_refresh_verify import session_record
library = tmp_path/'library.lmc'
library.touch()
request = VerifyRequest(library, 'Next', tmp_path/'evidence')
context = BatchTaskContext(str(library))
waiting = []
monkeypatch.setattr(session_record, 'library_available', lambda *a, **k: bool(waiting))
monkeypatch.setattr(session_record, 'retained_session_states', lambda *_: [
{'status': 'ACTIVE', 'phase': 'NATIVE_CALL', 'block': 'Previous',
'active_save': True}])
monkeypatch.setattr('cbb_refresh_verify.library_lock.recheck_previous_release', lambda *a, **k: None)
monkeypatch.setattr(context.stop, 'wait', lambda interval: waiting.append(interval))
verify_runner.wait_for_batch_release(request, context, timeout_seconds=0)
assert len(waiting) == 1
def test_completed_save_keeps_bounded_release_probe_alive(tmp_path, monkeypatch):
from contextlib import contextmanager
from threading import Event
from cbb_refresh_verify.icdb_ownership import wait_for_saved_database_release
entered, finish = Event(), Event()
@contextmanager
def probe(*args, **kwargs):
entered.set()
assert finish.wait(1)
yield {'exclusive_files': [str(tmp_path/'icdb.dat')]}
monkeypatch.setattr('cbb_refresh_verify.file_probe.hold_release_files', probe)
context = BatchTaskContext(str(tmp_path/'library.lmc'))
from threading import Thread
def finish_probe():
assert entered.wait(1)
Event().wait(.15)
finish.set()
thread = Thread(target=finish_probe)
thread.start()
try:
result = context.run(lambda: wait_for_saved_database_release(context.library,
tmp_path/'project.prj', tmp_path/'project.pcb'), timeout_seconds=.05)
assert result['status'] == 'RELEASE_CONFIRMED'
finally:
finish.set()
thread.join()
@pytest.mark.parametrize('release_after', [215, None])
def test_saved_database_waits_through_native_shutdown_and_retains_last_lock(tmp_path, monkeypatch, release_after):
from contextlib import contextmanager
from types import SimpleNamespace
from cbb_refresh_verify import icdb_ownership
class Clock:
elapsed = 0
def sleep(self, seconds):
self.elapsed += seconds
clock = Clock()
database = str(tmp_path/'Work/database/icdb.dat')
pending = []
@contextmanager
def probe(*args, timeout_seconds, **kwargs):
if timeout_seconds < 2:
clock.sleep(timeout_seconds)
raise TimeoutError('FILE_PROBE_TIMEOUT: startup')
clock.sleep(.25)
if release_after is not None and clock.elapsed >= release_after:
yield {'exclusive_files': [database]}
return
error = OSError(f'{database}: sharing violation')
error.winerror = 32
error.blocked_resources = [database]
raise error
monkeypatch.setattr(icdb_ownership, 'time', SimpleNamespace(monotonic=lambda: clock.elapsed, sleep=clock.sleep))
monkeypatch.setattr('cbb_refresh_verify.file_probe.hold_release_files', probe)
result = icdb_ownership.wait_for_saved_database_release(tmp_path/'library.lmc', tmp_path/'Work/test.prj',
tmp_path/'Work/PCB/test.pcb', report_pending=lambda **event: pending.append(event))
assert pending == [{'blocked_resources': [database]}]
if release_after is not None:
assert result['status'] == 'RELEASE_CONFIRMED'
assert clock.elapsed >= release_after
else:
assert result['status'] == 'IN_USE'
assert result['winerror'] == 32 and result['blocked_resources'] == [database]
assert database in result['detail'] and 'FILE_PROBE_TIMEOUT' in result['detail']
+137 -10
View File
@@ -23,10 +23,11 @@ def test_status_scan_delivers_progress_after_each_record(tmp_path):
assert snapshots == [(1, 2, 1), (2, 2, 2)] assert snapshots == [(1, 2, 1), (2, 2, 2)]
@pytest.mark.parametrize('include_identity', [False, True]) @pytest.mark.parametrize(('include_identity', 'unknown_foreign'), [(False, False), (True, False), (False, True)])
def test_catalog_registration_only_skips_project_identities(tmp_path, monkeypatch, include_identity): def test_catalog_registration_only_skips_project_identities(tmp_path, monkeypatch, include_identity, unknown_foreign):
import win32com.client import win32com.client
from cbb_refresh_verify import mentor_adapter import win32process
from cbb_refresh_verify import mentor_adapter, owner_probe
lmc = tmp_path / 'lib.lmc' lmc = tmp_path / 'lib.lmc'
lmc.touch() lmc.touch()
@@ -42,18 +43,50 @@ def test_catalog_registration_only_skips_project_identities(tmp_path, monkeypatc
Partitions=lambda _: SimpleNamespace(Count=1, Item=lambda _: partition)) Partitions=lambda _: SimpleNamespace(Count=1, Item=lambda _: partition))
app = SimpleNamespace(OpenLibrary=lambda _: library, Quit=lambda: None) app = SimpleNamespace(OpenLibrary=lambda _: library, Quit=lambda: None)
exe = tmp_path / 'lm/win32/bin/LibraryManager.exe' exe = tmp_path / 'lm/win32/bin/LibraryManager.exe'
no_owners = iter([[], [(123, str(exe), '', 0)]]) previous = [(321, str(exe), '', 0)] if unknown_foreign else []
monkeypatch.setattr(mentor_adapter, '_process_details', lambda _: next(no_owners)) snapshots = iter([previous, [*previous, (123, str(exe), '', 0)]])
monkeypatch.setattr(mentor_adapter, '_process_details', lambda _: next(snapshots))
monkeypatch.setattr(owner_probe, 'snapshot_process_ids', lambda _: [])
if unknown_foreign:
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))
monkeypatch.setattr(native, '_open_catalog_manager_library', lambda _: None)
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda _: (456, 123))
monkeypatch.setattr(native, '_current_desktop', monkeypatch.setattr(native, '_current_desktop',
lambda: (SimpleNamespace(EnumDesktopWindows=lambda: []), 'CbbManagement_test')) lambda: (SimpleNamespace(EnumDesktopWindows=lambda: [42] if unknown_foreign else []),
'CbbManagement_test'))
monkeypatch.setattr(win32com.client, 'DispatchEx', lambda _: app) monkeypatch.setattr(win32com.client, 'DispatchEx', lambda _: app)
result = native._catalog_com({'operation': 'catalog', 'worker_role': 'catalog_readonly', result = native._catalog_com({'operation': 'catalog', 'worker_role': 'catalog_readonly',
'include_engineering_identity': include_identity, 'library': str(lmc), 'include_engineering_identity': include_identity, 'library': str(lmc),
'desktop': 'CbbManagement_test', 'mentor_home': str(tmp_path), 'supervisor_pid': __import__('os').getpid()}, tmp_path) 'desktop': 'CbbManagement_test', 'mentor_home': str(tmp_path), 'supervisor_pid': __import__('os').getpid()}, tmp_path)
assert result['success'] assert result['success']
assert result['native_pids'] == [123]
if unknown_foreign:
assert result['existing_manager_libraries'] == {321: None}
assert hashed == ([project] if include_identity else []) assert hashed == ([project] if include_identity else [])
def test_catalog_reports_exact_same_library_before_slow_owner_lookup(tmp_path, monkeypatch):
import win32com.client
from cbb_refresh_verify import mentor_adapter, owner_probe
library = tmp_path / 'lib.lmc'
library.touch()
monkeypatch.setattr(native, '_current_desktop', lambda: (None, 'CbbManagement_test'))
monkeypatch.setattr(owner_probe, 'snapshot_process_ids', lambda name: [123], raising=False)
monkeypatch.setattr(native, '_open_catalog_manager_library', lambda pid: library)
monkeypatch.setattr(mentor_adapter, '_process_details', lambda name: pytest.fail('slow owner lookup'))
monkeypatch.setattr(win32com.client, 'DispatchEx', lambda name: pytest.fail('busy library was opened'))
with pytest.raises(native.NativeOperationError, match='LIBRARY_MANAGER_BUSY.*123') as caught:
native._catalog_com({'operation': 'catalog', 'worker_role': 'catalog_readonly',
'include_engineering_identity': False, 'library': str(library),
'desktop': 'CbbManagement_test', 'mentor_home': str(tmp_path)}, tmp_path)
assert caught.value.safe_to_continue is True
assert caught.value.blocking_manager_pids == (123,)
@pytest.mark.parametrize('scope', ['foreign', 'same', 'shared', 'unknown', 'switched', 'occupied']) @pytest.mark.parametrize('scope', ['foreign', 'same', 'shared', 'unknown', 'switched', 'occupied'])
def test_catalog_distinguishes_foreign_and_conflicting_manager(tmp_path, monkeypatch, scope): def test_catalog_distinguishes_foreign_and_conflicting_manager(tmp_path, monkeypatch, scope):
target = tmp_path/'target'/'lib.lmc' target = tmp_path/'target'/'lib.lmc'
@@ -77,16 +110,17 @@ def test_catalog_distinguishes_foreign_and_conflicting_manager(tmp_path, monkeyp
def held(library): def held(library):
raise OSError('shared database handle is occupied') raise OSError('shared database handle is occupied')
monkeypatch.setattr(native, '_probe_catalog_files', held) monkeypatch.setattr(native, '_probe_catalog_files', held)
if scope == 'foreign': if scope in {'foreign', 'unknown'}:
native._check_catalog_owners(target, owners) native._check_catalog_owners(target, owners)
else: else:
with pytest.raises(RuntimeError, match='LIBRARY_MANAGER_BUSY.*123'): with pytest.raises(RuntimeError, match='LIBRARY_MANAGER_BUSY.*123'):
native._check_catalog_owners(target, owners) native._check_catalog_owners(target, owners)
def test_catalog_rejects_reused_foreign_com_proxy_without_mutating_it(tmp_path, monkeypatch): @pytest.mark.parametrize('title_resolved', [True, False])
def test_catalog_rejects_reused_foreign_com_proxy_without_mutating_it(tmp_path, monkeypatch, title_resolved):
import win32com.client import win32com.client
from cbb_refresh_verify import mentor_adapter from cbb_refresh_verify import mentor_adapter, owner_probe
target = tmp_path/'target'/'lib.lmc' target = tmp_path/'target'/'lib.lmc'
other = tmp_path/'other'/'lib.lmc' other = tmp_path/'other'/'lib.lmc'
@@ -99,7 +133,8 @@ def test_catalog_rejects_reused_foreign_com_proxy_without_mutating_it(tmp_path,
monkeypatch.setitem(native._BINARY_PROOF, 'lm/win32/bin/LibraryManager.exe', native.hash_file(exe)) monkeypatch.setitem(native._BINARY_PROOF, 'lm/win32/bin/LibraryManager.exe', native.hash_file(exe))
before = [(123, 'LibraryManager.exe', f'LibraryManager.exe "{other}"', 0)] before = [(123, 'LibraryManager.exe', f'LibraryManager.exe "{other}"', 0)]
monkeypatch.setattr(mentor_adapter, '_process_details', lambda _: before) monkeypatch.setattr(mentor_adapter, '_process_details', lambda _: before)
monkeypatch.setattr(native, '_open_catalog_manager_library', lambda _: other, raising=False) monkeypatch.setattr(owner_probe, 'snapshot_process_ids', lambda _: [])
monkeypatch.setattr(native, '_open_catalog_manager_library', lambda _: other if title_resolved else None)
monkeypatch.setattr(native, '_current_desktop', monkeypatch.setattr(native, '_current_desktop',
lambda: (SimpleNamespace(EnumDesktopWindows=lambda: []), 'CbbManagement_test')) lambda: (SimpleNamespace(EnumDesktopWindows=lambda: []), 'CbbManagement_test'))
@@ -121,6 +156,30 @@ def test_catalog_rejects_reused_foreign_com_proxy_without_mutating_it(tmp_path,
assert 'LIBRARY_MANAGER_BUSY' in result['detail'] assert 'LIBRARY_MANAGER_BUSY' in result['detail']
@pytest.mark.parametrize('resource', ['library', 'shared_symbols'])
def test_catalog_checks_target_sharing_when_manager_title_lacks_a_path(tmp_path, monkeypatch, resource):
import win32con
import win32file
from cbb_refresh_verify.icdb_ownership import shared_symbol_database
library = tmp_path/'target.lmc'
library.touch()
shared = shared_symbol_database(library)/'icdb.dat'
shared.parent.mkdir(parents=True)
shared.touch()
locked = library if resource == 'library' else shared
monkeypatch.setattr(native, '_open_catalog_manager_library', lambda _: None)
handle = win32file.CreateFile(str(locked), win32con.GENERIC_READ, 0, None, win32con.OPEN_EXISTING, 0, None)
try:
with pytest.raises(native.NativeOperationError) as raised:
native._check_catalog_owners(library, [(123, 'LibraryManager.exe', '', 0)])
assert raised.value.blocking_manager_pids == (123,)
assert str(locked) in str(raised.value)
finally:
handle.Close()
native._check_catalog_owners(library, [(123, 'LibraryManager.exe', '', 0)])
def test_catalog_progress_and_pending_preview_are_visible(qtbot, tmp_path, monkeypatch): def test_catalog_progress_and_pending_preview_are_visible(qtbot, tmp_path, monkeypatch):
from threading import Event from threading import Event
@@ -164,6 +223,39 @@ def test_catalog_progress_and_pending_preview_are_visible(qtbot, tmp_path, monke
window.pool.waitForDone(6000) window.pool.waitForDone(6000)
def test_catalog_retries_when_exact_manager_pid_exits(qtbot, tmp_path, monkeypatch):
from cbb_refresh_verify import owner_probe
from cbb_refresh_verify.management import Catalog, CatalogEntry
from cbb_refresh_verify.models import CbbRecord, LibraryReadResult
from test_issue15_ui_integration import load, window_for
calls = []
def catalog(library, evidence):
calls.append(evidence)
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(owner_probe, 'snapshot_process_ids', lambda _: [456])
def unavailable(*args, **kwargs):
raise RuntimeError('OWNER_QUERY_TIMEOUT')
monkeypatch.setattr(owner_probe, 'query_owners', unavailable)
window = window_for(qtbot, tmp_path, monkeypatch,
reader=lambda _: LibraryReadResult((CbbRecord('A', 'LP'),), directory_count=1),
catalog_reader=catalog, status_refresher=lambda names, _: dict.fromkeys(names, 'READY'))
try:
load(window, qtbot)
qtbot.waitUntil(lambda: window.ready_names == {'A'}, timeout=1500)
assert calls == [calls[0], calls[0] / 'retry']
finally:
window._cancel_catalog_read()
window.pool.waitForDone(6000)
def test_timed_out_catalog_can_refresh_already_registered_status_only(qtbot, tmp_path, monkeypatch): 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.management import Catalog, CatalogEntry
from cbb_refresh_verify.models import CbbRecord, LibraryReadResult from cbb_refresh_verify.models import CbbRecord, LibraryReadResult
@@ -248,3 +340,38 @@ def test_catalog_switch_retains_complete_snapshot_and_ignores_duplicate_reads(qt
finally: finally:
allow_return.set() allow_return.set()
window.pool.waitForDone(6000) window.pool.waitForDone(6000)
def test_catalog_read_submitted_during_restart_releases_then_reads(qtbot, tmp_path, monkeypatch):
from threading import Event
from cbb_refresh_verify import session_record
from cbb_refresh_verify.management import Catalog, CatalogEntry
from cbb_refresh_verify.models import CbbRecord, LibraryReadResult
from test_issue15_ui_integration import load, window_for
released = Event()
calls = []
def catalog(library, evidence):
assert released.is_set()
calls.append(library)
return Catalog(library, 1, (CatalogEntry('A', 'Logical-Physical'),))
monkeypatch.setattr(session_record, '_live_library_available', lambda _: released.is_set())
window = window_for(qtbot, tmp_path, monkeypatch,
reader=lambda _: LibraryReadResult((CbbRecord('A', 'LP'),), directory_count=1),
catalog_reader=catalog, status_refresher=lambda names, _: {name: 'READY' for name in names})
try:
load(window, qtbot)
qtbot.waitUntil(lambda: '等待后台会话退出' in window.status_label.text())
assert calls == []
assert window.lmc_edit.isEnabled()
assert not window.batch_button.isEnabled()
released.set()
window.native_queue.wake()
qtbot.waitUntil(lambda: window.ready_names == {'A'})
assert len(calls) == 1
finally:
released.set()
window.native_queue.wake()
window.pool.waitForDone(6000)
+192 -3
View File
@@ -66,10 +66,10 @@ def test_catalog_recovery_only_adopts_an_exact_exited_supervisor(tmp_path, monke
job = dict(record, supervisor_pid=55, session_record_path=str(path)) job = dict(record, supervisor_pid=55, session_record_path=str(path))
(tmp_path/'request.json').write_text(json.dumps(job), encoding='utf-8') (tmp_path/'request.json').write_text(json.dumps(job), encoding='utf-8')
monkeypatch.setattr(residual_sessions, '_recorded_process_exited', lambda found: found == identity) monkeypatch.setattr(residual_sessions, '_recorded_process_exited', lambda found: found == identity)
assert residual_sessions.orphaned_catalog_session(path) assert residual_sessions.recoverable_orphan_session(path)
job['supervisor_identity'] = {**identity, 'pid': 56} job['supervisor_identity'] = {**identity, 'pid': 56}
(tmp_path/'request.json').write_text(json.dumps(job), encoding='utf-8') (tmp_path/'request.json').write_text(json.dumps(job), encoding='utf-8')
assert not residual_sessions.orphaned_catalog_session(path) assert not residual_sessions.recoverable_orphan_session(path)
def test_idle_orphan_catalog_can_close_without_final_result(tmp_path, monkeypatch): def test_idle_orphan_catalog_can_close_without_final_result(tmp_path, monkeypatch):
@@ -78,7 +78,7 @@ def test_idle_orphan_catalog_can_close_without_final_result(tmp_path, monkeypatc
root, job, _, _, state = owned_fixture(tmp_path, monkeypatch, 'catalog') root, job, _, _, state = owned_fixture(tmp_path, monkeypatch, 'catalog')
(root/'result.json').unlink() (root/'result.json').unlink()
monkeypatch.setattr(residual_sessions, 'orphaned_catalog_session', lambda _: True, raising=False) monkeypatch.setattr(residual_sessions, 'recoverable_orphan_session', lambda _: True, raising=False)
session_record.write_session_record(root/'worker-state.json', session_record.write_session_record(root/'worker-state.json',
dict(operation_id='owned', phase='NATIVE_CALL', processes=[dict(role='native', pid=12, 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)])) created_handle='native-created', image='D:/Mentor/LibraryManager.exe', owner_sid='owner', session_id=1)]))
@@ -177,3 +177,192 @@ def test_cancelled_prewrite_can_dismiss_exact_late_load_failure(qtbot, tmp_path,
assert residual_sessions.finish_owned_idle_session(root/'session.json') is proved 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 state['posts'] == ([(201, 12, 245), (100, 12, 16)] if proved else [])
assert (root/'result.json').read_bytes() == original assert (root/'result.json').read_bytes() == original
@pytest.mark.parametrize('obstacle', [None, 'tip', 'slow_tip', 'cancelled_tip', 'previously_dismissed_tip', 'license',
'read_write', 'unknown_prompt', 'save',
'uncertain_phase', 'live_supervisor', 'live_worker',
'wrong_pcb', 'possible_write', 'loaded', 'unproved_loaded'])
def test_restarted_verify_closes_exact_prewrite_orphan(tmp_path, monkeypatch, obstacle):
import json
from contextlib import nullcontext
from types import SimpleNamespace
import win32event
from test_owned_idle_cleanup import owned_fixture
from cbb_refresh_verify import diagnostic_open, failed_session, residual_sessions
root, job, result, windows, state = owned_fixture(tmp_path, monkeypatch)
create_mutex = win32event.CreateMutex
monkeypatch.setattr(win32event, 'CreateMutex', lambda *args: create_mutex(None, False, None))
path = root/'session.json'
session = session_record.read_session_record(path, evidence_root=root)
supervisor = dict(pid=10, image='C:/App/CbbRefreshVerify.exe', created_handle='supervisor-created',
owner_sid='owner', session_id=1)
job.update(supervisor_identity=supervisor, supervisor_pid=10, diagnostic_only=False,
cancel_signal=str(root/'cancel.signal'))
session.update(supervisor_identity=supervisor, cancel_signal=job['cancel_signal'],
resource_scope=dict(scope_state='DECLARED', library=job['library'],
operation_id='owned', projects=[job['project']]))
session_record.write_session_record(path, session)
(root/'request.json').write_text(json.dumps(job), encoding='utf-8')
(root/'result.json').unlink()
Path(job['cancel_signal']).touch()
session_record.write_session_record(root/'supervisor-lost.json',
{'operation_id': 'owned', 'phase': 'SUPERVISOR_LOST'})
worker_state = session_record.read_session_record(root/'worker-state.json', evidence_root=root)
if obstacle == 'uncertain_phase':
worker_state['phase'] = 'NATIVE_CALL'
session_record.write_session_record(root/'worker-state.json', worker_state)
binding = {key: job[key] for key in ('operation_id', 'project', 'pcb', 'desktop')}
command = f'"D:/Mentor/ExpeditionPCB.exe" "{job["pcb"]}" -ReusableCircuit'
if obstacle == 'wrong_pcb':
command = command.replace(job['pcb'], job['pcb'] + '.wrong')
rows = [dict(stage='startup_supervisor_no_write', **binding),
dict(stage='pcb_baseline', pids=[]),
dict(stage='startup_prewrite_ready', worker_identity=session['processes'][0],
baseline=dict(started_ns=42, files={}), **binding),
dict(stage='pcb_worker_started', pcb_pid=12, command=command)]
if obstacle in ('cancelled_tip', 'previously_dismissed_tip'):
result.update(status='CANCELLED', error_category='TASK_HANDOFF')
(root/'result.json').write_text(json.dumps(result), encoding='utf-8')
rows.append(dict(stage='startup_cancelled_prewrite', pcb_pid=12, identity_verified=False,
write_admitted=False, **binding))
if obstacle == 'previously_dismissed_tip':
rows.append(dict(stage='startup_tip_dismissed', pcb_pid=12, hwnd=200))
if obstacle == 'possible_write':
rows.append(dict(stage='startup_supervisor_write_possible', **binding))
if obstacle in ('loaded', 'unproved_loaded'):
rows.append(dict(stage='startup_cancelled_prewrite', pcb_pid=12, identity_verified=False,
write_admitted=False, **binding))
windows[0].update(title='Expedition PCB - Reusable Block - [Bad]', documents=[101])
monkeypatch.setattr(residual_sessions, '_legacy_diagnostic_windows', lambda _: [
dict(windows[0], text=windows[0]['title'], children=[
{'hwnd': 101, 'class': 'MDIClient'},
{'hwnd': 102, 'parent': 101, 'class': 'Afx:document', 'text': 'Bad'},
])])
monkeypatch.setattr(diagnostic_open, '_load_evidence', lambda *a, **kw:
{'document_identity': 'native_path_pid_logs'} if obstacle == 'loaded' else None)
(root/'events.jsonl').write_text(''.join(json.dumps(row)+'\n' for row in rows), encoding='utf-8')
if obstacle == 'save':
(root/'save.log').write_text('SAVE_START\n', encoding='utf-8')
state['worker_alive'] = obstacle == 'live_worker'
monkeypatch.setattr(residual_sessions, '_recorded_process_exited',
lambda identity: obstacle != 'live_supervisor' and identity == supervisor)
if obstacle in ('tip', 'slow_tip', 'cancelled_tip', 'previously_dismissed_tip', 'license', 'read_write', 'unknown_prompt'):
frame = windows.pop() if obstacle == 'license' else windows[0]
frame['enabled'] = False
title = {'license': ''}.get(obstacle, 'Tip of the Day' if obstacle.endswith('tip') else 'Expedition PCB')
windows.append(dict(hwnd=200, title=title,
desktop=job['desktop'], children=[], enabled=True, **{'class': '#32770'}))
def post(window, hwnd, pid, message):
observed = session_record.read_session_record(path, evidence_root=root)
assert observed['owned_idle_cleanup']['pid'] == pid
state['posts'].append((hwnd, pid, message))
if hwnd == 201:
windows.pop()
frame['enabled'] = obstacle != 'slow_tip'
if obstacle == 'license':
state['native_alive'] = False
else:
state['native_alive'] = False
def dismiss_tip(row, handle, windows, **options):
post(windows[1], 201, row['pid'], 245)
return 200
monkeypatch.setattr(residual_sessions, '_dismiss_startup_tip', dismiss_tip)
monkeypatch.setattr(residual_sessions, '_post_window_message', post)
monkeypatch.setattr(residual_sessions, '_window_desktop', lambda *_: nullcontext())
if obstacle == 'license':
from cbb_refresh_verify.dialog_models import ControlSnapshot, DialogPhase, WindowSnapshot
license_prompt = WindowSnapshot(200, 12, 'ExpeditionPCB.exe', 'pcb', '#32770', '',
DialogPhase.PCB_STARTING, (
ControlSnapshot(210, 5225, 'Button', 'Select the desired product license', enabled=True),
ControlSnapshot(211, 1522, 'GXWND', ''),
ControlSnapshot(212, 1, 'Button', 'OK', enabled=True),
ControlSnapshot(201, 2, 'Button', 'Cancel', enabled=True),
))
monkeypatch.setattr(failed_session, '_startup_snapshot', lambda *_: license_prompt)
else:
monkeypatch.setattr(failed_session, '_startup_snapshot', lambda *_: 'exact shutdown prompt')
monkeypatch.setattr(failed_session, '_tip_target', lambda _: SimpleNamespace(handle=201))
monkeypatch.setattr(failed_session, '_cancel_target', lambda _: ('read_write_access',
SimpleNamespace(handle=201)) if obstacle == 'read_write' else None)
if obstacle == 'slow_tip':
ticks = iter([0., 6., 7., 8., 9.])
monkeypatch.setattr(residual_sessions, 'time', SimpleNamespace(monotonic=lambda: next(ticks)))
recovered = residual_sessions.finish_owned_idle_session(path)
if obstacle == 'slow_tip':
assert recovered and state['posts'] == [(201, 12, 245)]
journal = session_record.read_session_record(path, evidence_root=root)
assert journal['owned_startup_prompt'] == 200 and 'owned_idle_cleanup' not in journal
frame['enabled'] = True
assert residual_sessions.finish_owned_idle_session(path)
assert state['posts'] == [(201, 12, 245), (100, 12, 16)]
return
assert recovered is (obstacle in (None, 'tip', 'cancelled_tip', 'license', 'read_write', 'loaded'))
expected_posts = [(201, 12, 245)] if obstacle in ('tip', 'cancelled_tip', 'license', 'read_write') else []
if recovered and obstacle != 'license':
expected_posts.append((100, 12, 16))
assert state['posts'] == expected_posts
if recovered:
receipt = session_record.read_session_record(root/'owned-idle-cleanup-result.json', evidence_root=root)
assert receipt['status'] == 'CLIENT_EXITED'
assert receipt['resource_release_confirmed'] is False
def test_verify_registers_ordinary_pcb_before_any_write_phase(tmp_path, monkeypatch):
import json
from cbb_refresh_verify import mentor_adapter
bound_phases = []
request = tmp_path/'request.json'
request.write_text(json.dumps(dict(root=str(tmp_path), block_name='Bad', diagnostic_only=False,
desktop='CbbVerify_owned', operation_id='owned', session_record_path=str(tmp_path/'session.json'))),
encoding='utf-8')
monkeypatch.setattr(session_record, 'update_worker_state',
lambda job, phase, **options: bound_phases.append((phase, options['identities'])))
def execute(job, emit):
emit(stage='pcb_launch')
emit(stage='pcb_worker_started', pcb_pid=12)
emit(stage='integration_action', action='UpdateNets')
return {'status': 'PASS'}
monkeypatch.setattr(mentor_adapter, 'execute_job', execute)
assert mentor_adapter.worker_main(request) == 0
assert bound_phases == [('UNCONFIRMED', []), ('PRECALL', [('native', 12)]), ('NATIVE_CALL', [])]
def test_cancel_after_launcher_still_registers_startup_for_cleanup(tmp_path, monkeypatch):
from types import SimpleNamespace
from test_verify_worker_stability import exercise_worker
from cbb_refresh_verify import failed_session, mentor_adapter, pcb_bridge
job, events, execute = exercise_worker(tmp_path, monkeypatch)
stop = tmp_path/'cancel.signal'
job.update(operation='verify', operation_id='ordinary', desktop='CbbVerify_test',
diagnostic_only=False, session_record_path=str(tmp_path/'session.json'),
cancel_signal=str(stop))
def launch(*_):
stop.touch()
return SimpleNamespace(pid=1)
worker = iter((None, (2, 'pcb', 'command', 1)))
monkeypatch.setattr(mentor_adapter, 'launch_pcb_process', launch)
monkeypatch.setattr(mentor_adapter, 'select_reusable_circuit_worker', lambda *a, **kw: next(worker))
monkeypatch.setattr(pcb_bridge, 'wait_for_target_document', lambda *a, **kw:
pytest.fail('cancelled startup must never attach to the PCB document'))
closed = []
monkeypatch.setattr(failed_session, 'close_failed_startup', lambda job, pid, **kw:
closed.append(pid) or {'status': 'CLOSED'})
with pytest.raises(RuntimeError, match='VERIFY_CANCELLED'):
execute()
assert closed == [2]
assert any(e['stage'] == 'pcb_worker_started' and e['pcb_pid'] == 2 for e in events)
assert any(e['stage'] == 'startup_cancelled_prewrite' and e['pcb_pid'] == 2 for e in events)
+30
View File
@@ -28,3 +28,33 @@ def test_batch_rechecks_owned_failure_before_skipping_next_item(tmp_path,monkeyp
assert results[0].status=='FAIL' and results[0].stderr=='original failure' assert results[0].status=='FAIL' and results[0].stderr=='original failure'
assert results[0].safe_to_continue is released assert results[0].safe_to_continue is released
assert calls==(['A','B'] if released else ['A']) assert calls==(['A','B'] if released else ['A'])
def test_batch_rechecks_admission_after_timeout_and_real_release(tmp_path, monkeypatch):
from cbb_refresh_verify import session_record
from cbb_refresh_verify.operation_queue import QueueUnavailable
library = tmp_path/'first/lib.lmc'
independent = tmp_path/'second/lib.lmc'
occupied = True
admission_calls = []
def available(path):
return Path(path) != library or not occupied
def admit(request, action):
nonlocal occupied
admission_calls.append(request.block_name)
if not available(request.lmc_file):
raise QueueUnavailable(request.lmc_file, timed_out=True)
if request.block_name == 'B':
occupied = False
return action()
monkeypatch.setattr(session_record, '_live_library_available', available)
requests = [VerifyRequest(lmc, name, tmp_path/'evidence')
for name, lmc in [('A', library), ('A2', library), ('B', independent), ('C', library)]]
results = run_batch(requests, verifier=lambda _: VerifyResult('PASS'), item_executor=admit)
assert admission_calls == ['A', 'B', 'C']
assert [result.status for result in results] == ['SKIPPED', 'SKIPPED', 'PASS', 'PASS']
assert results[0].error_category == 'NATIVE_SESSION_PENDING'
+56
View File
@@ -307,3 +307,59 @@ def test_arbitrary_guard_filename_is_preserved_and_primary(tmp_path, monkeypatch
with pytest.raises(locks.LibraryBusy): with pytest.raises(locks.LibraryBusy):
locks.release_retained_library(library, tmp_path/'release') locks.release_retained_library(library, tmp_path/'release')
assert marker.read_bytes() == b'{not a guard record' assert marker.read_bytes() == b'{not a guard record'
def test_recovery_scope_uses_interrupted_block_instead_of_new_selection(tmp_path, monkeypatch):
from cbb_refresh_verify import library_lock as locks
library = tmp_path/'lib/lib.lmc'
library.parent.mkdir()
library.touch()
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
locks._persist_blocker(library, lease_id='a'*32, block_name='Interrupted')
proof = locks.release_retained_library(library, tmp_path/'evidence',
block_name='NewSelection', infer_scope=True)
assert proof['proof_scope'] == 'BLOCK'
assert proof['proof_block_names'] == ['Interrupted']
assert proof['reconciled_foreign_blockers'] == ['Interrupted']
def test_probe_timeout_reports_last_io_phase_and_path(tmp_path, monkeypatch):
from cbb_refresh_verify import file_probe
from pathlib import Path
from types import SimpleNamespace
library = tmp_path/'lib.lmc'
def start(command, **kwargs):
Path(command[-1]).with_name('progress.json').write_text(
'{"stage": "open_exclusive", "path": "SymbolLibs/icdb.dat"}', 'utf-8')
return SimpleNamespace(stdin=SimpleNamespace(close=lambda: None), wait=lambda _: 0)
monkeypatch.setattr(file_probe.subprocess, 'Popen', start)
ticks = iter([0., 1., 1.])
monkeypatch.setattr(file_probe.time, 'monotonic', lambda: next(ticks))
with pytest.raises(TimeoutError, match=r'FILE_PROBE_TIMEOUT.*open_exclusive.*SymbolLibs/icdb.dat'):
with file_probe.hold_release_files(library, timeout_seconds=.7):
pytest.fail('a timed-out probe cannot prove release')
def test_full_library_probe_budget_accounts_for_both_tree_scans(tmp_path, monkeypatch):
from cbb_refresh_verify import file_probe
from types import SimpleNamespace
class Process:
stdin = SimpleNamespace(close=lambda: None)
def wait(self, *_):
return 0
def poll(self):
return None
monkeypatch.setattr(file_probe.subprocess, 'Popen', lambda *a, **k: Process())
ticks = iter([0., 11., 31., 32.])
monkeypatch.setattr(file_probe.time, 'monotonic', lambda: next(ticks))
monkeypatch.setattr(file_probe.time, 'sleep', lambda _: None)
with pytest.raises(TimeoutError, match=r'FILE_PROBE_TIMEOUT.*32.0s'):
with file_probe.hold_release_files(tmp_path/'lib.lmc'):
pytest.fail('the fake probe never returns a receipt')
+12
View File
@@ -593,3 +593,15 @@ def test_same_target_recovery_gate_preserves_release_and_batch_continues(setup,
adapter=adapter, idle_check=lambda *_: None) adapter=adapter, idle_check=lambda *_: None)
assert [result.status for result in results] == ['BLOCKED', 'UPLOADED'] assert [result.status for result in results] == ['BLOCKED', 'UPLOADED']
assert all(result.safe_to_continue for result in results) assert all(result.safe_to_continue for result in results)
@pytest.mark.parametrize('same_library', [True, False])
def test_release_scope_binds_native_shared_database_argument(tmp_path, same_library):
from cbb_refresh_verify.icdb_ownership import shared_symbol_database
from cbb_refresh_verify.library_lock import _owner_matches_scope
library = tmp_path/'Target/lib.lmc'
target = shared_symbol_database(library)
database = target if same_library else shared_symbol_database(tmp_path/'Foreign/lib.lmc')
owner = {'name': 'iCDBNetServer.exe', 'command': f'iCDBNetServer.exe -db "{database}"'}
assert _owner_matches_scope(owner, library, (target,)) is same_library
+5 -1
View File
@@ -813,7 +813,11 @@ def test_malformed_native_success_never_authorizes_release(tmp_path, monkeypatch
assert result['safe_to_continue'] is False assert result['safe_to_continue'] is False
@pytest.mark.parametrize('key,value', MALFORMED_SUCCESS) @pytest.mark.parametrize('key,value', [
('minimal', None),
('project', '<other>/CBB.prj'),
('evidence.confirmed', False),
])
def test_malformed_native_success_never_reopens_or_counts_repaired(tmp_path, monkeypatch, key, value): def test_malformed_native_success_never_reopens_or_counts_repaired(tmp_path, monkeypatch, key, value):
from cbb_refresh_verify import verify_runner as runner, native_repair from cbb_refresh_verify import verify_runner as runner, native_repair
from cbb_refresh_verify.icdb_maintenance import maintenance_counts from cbb_refresh_verify.icdb_maintenance import maintenance_counts
+32
View File
@@ -40,3 +40,35 @@ def test_cancelled_paused_ticket_does_not_hold_later_work():
assert outcome==['cancelled','next'] assert outcome==['cancelled','next']
finally: finally:
stop.set();queue.wake();thread.join(2) stop.set();queue.wake();thread.join(2)
def test_saved_database_wait_yields_only_to_other_library_roots(tmp_path):
from concurrent.futures import ThreadPoolExecutor
from threading import Event
from cbb_refresh_verify.operation_queue import BatchTaskContext, allow_other_libraries
queue = NativeQueue()
waiting, released = Event(), Event()
same_directory_started = Event()
current = BatchTaskContext(str(tmp_path/'first/a.lmc'))
same_directory = BatchTaskContext(str(tmp_path/'first/b.lmc'))
independent = BatchTaskContext(str(tmp_path/'second/c.lmc'))
def saved():
with allow_other_libraries():
waiting.set()
assert released.wait(4)
return 'confirmed'
with ThreadPoolExecutor(max_workers=3) as threads:
first = threads.submit(queue.run, saved, context=current)
assert waiting.wait(2)
second = threads.submit(queue.run, same_directory_started.set, context=same_directory)
try:
third = threads.submit(queue.run, lambda: 'independent', context=independent)
assert third.result(timeout=2) == 'independent'
assert not same_directory_started.is_set()
finally:
released.set()
assert first.result(timeout=2) == 'confirmed'
second.result(timeout=2)
assert same_directory_started.is_set()
+63
View File
@@ -217,3 +217,66 @@ def test_wrong_result_or_changed_state_cannot_authorize_normal_close(tmp_path,mo
monkeypatch.setattr(sessions,'write_session_record',changed_state) monkeypatch.setattr(sessions,'write_session_record',changed_state)
assert not residual.finish_owned_idle_session(root/'session.json') assert not residual.finish_owned_idle_session(root/'session.json')
assert not state['posts'] assert not state['posts']
@pytest.mark.parametrize('terminal', [True, False])
def test_save_handoff_uses_terminal_worker_receipt(tmp_path, monkeypatch, terminal):
root, _, result, _, state = owned_fixture(tmp_path, monkeypatch, 'saved')
facts = result['write_outcome']
result['write_outcome'] = dict(save_state='UNKNOWN', close_state='UNKNOWN',
helper_state='RUNNING', interrupted=False)
facts['save_close_confirmed'] = terminal
if not terminal:
facts['save_state'] = 'UNKNOWN'
state_path = root/'worker-state.json'
state_record = sessions.read_session_record(state_path, evidence_root=root)
state_record['processes'].append(dict(role='helper', pid=13, image='C:/Windows/cscript.exe',
created_handle='helper-created', owner_sid='owner', session_id=1))
sessions.write_session_record(state_path, {**state_record, 'phase': 'POSTCALL', 'write_outcome': facts})
import pywintypes
def open_process(pid, **kwargs):
if pid == 13:
raise pywintypes.error(87, 'OpenProcess', 'exited')
return nullcontext(pid)
monkeypatch.setattr(residual, '_process_handle', open_process)
result['status'] = 'CANCELLED'
(root/'result.json').write_text(json.dumps(result))
before = (root/'result.json').read_bytes()
assert residual.finish_owned_idle_session(root/'session.json') is terminal
assert bool(state['posts']) is terminal
assert (root/'result.json').read_bytes() == before
def test_crash_after_returned_save_can_close_only_with_matching_supervisor(tmp_path, monkeypatch):
import pywintypes
root, job, result, _, state = owned_fixture(tmp_path, monkeypatch, 'saved')
(root/'result.json').unlink()
journal = root/'session.json'
supervisor = dict(pid=14, image='C:/app/CbbRefreshVerify.exe', created_handle='parent-created',
owner_sid='owner', session_id=1)
session = sessions.read_session_record(journal, evidence_root=root)
sessions.write_session_record(journal, {**session, 'supervisor_identity': supervisor})
state_path = root/'worker-state.json'
journal_state = sessions.read_session_record(state_path, evidence_root=root)
helper = dict(role='helper', pid=13, image='C:/Windows/cscript.exe', created_handle='helper-created',
owner_sid='owner', session_id=1)
sessions.write_session_record(state_path, {**journal_state, 'phase': 'UNCONFIRMED',
'processes': [*journal_state['processes'], helper],
'write_outcome': {**result['write_outcome'], 'save_close_confirmed': True}})
def open_process(pid, **kwargs):
if pid in (13, 14):
raise pywintypes.error(87, 'OpenProcess', 'exited')
return nullcontext(pid)
monkeypatch.setattr(residual, '_process_handle', open_process)
request = root/'request.json'
job.update(supervisor_pid=14, supervisor_identity={**supervisor, 'created_handle': 'other'})
request.write_text(json.dumps(job), encoding='utf-8')
assert not residual.finish_owned_idle_session(journal)
job['supervisor_identity'] = supervisor
request.write_text(json.dumps(job), encoding='utf-8')
assert residual.finish_owned_idle_session(journal)
assert state['posts'] == [(100, 12, 16)]
assert not (root/'result.json').exists()
+62
View File
@@ -363,3 +363,65 @@ def test_shared_address_is_bound_to_shared_database_without_a_project_prj(tmp_pa
}] }]
assert str(address) in proof['binding_files'] assert str(address) in proof['binding_files']
assert str(database / 'icdb.dat') in proof['exclusive_files'] assert str(database / 'icdb.dat') in proof['exclusive_files']
def test_shared_address_with_matching_native_shutdown_allows_release_and_open(tmp_path, monkeypatch):
from cbb_refresh_verify import library_lock, owner_probe, pcb_open_consent
library = tmp_path/'library/lib.lmc'
work = library.parent/'ReusableBlocksLP/A/Work'
project, pcb = work/'A.prj', work/'PCB/A.pcb'
shared = library.parent/'SymbolLibs/__ReusableBlocksSymb'
database = shared/'icdb.dat'
address = shared/'cdbsvr/sAddress.adr'
log = address.parent/'log/2026-11-24 10.51.10-16972/2026.11.24.txt'
for path in (library, work/'database/icdb.dat', pcb.parent/'Layout/LayoutDB.lyt', database, log):
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')
guid = 'e3f4-cafd-6e7f-6e1b-f9bf-40b5-abf4-0b60-117c-d02d-bff6-3645'
adr = f'{guid}\n127.0.0.1\n10000\n1094\n2026-11-24 10.51.10-16972\n.\n'
address.write_text(adr)
lines = [
'iCDB Server ver.1.094, build:535943',
'Machine [LOCAL] User [operator] PID [16972]',
f'S: Project path [{shared}] on file system [NTFS]',
f'S: Server GUID [{guid}]',
'S: Wrote data to server address file',
'iCDB Server PI: Database closed',
f'Single file [{database}] closed with size [7 (0 kB)]',
f'AT: ERROR: Could not remove server address file [{address}]',
'S: STOP',
]
def write_log(events):
log.write_text('\n'.join(f'[2026.11.24 10:51:22] [0000m.11s.465ms] [0] {event}'
for event in events) + '\n')
write_log(lines)
monkeypatch.setattr(owner_probe, 'query_process_snapshot', lambda: [])
monkeypatch.setattr(owner_probe, 'query_owners', lambda *_: [])
release = library_lock.release_retained_library(library, tmp_path/'recovery', block_name='A')
assert release['status'] == 'RELEASE_CONFIRMED'
assert release['shared_shutdowns'][str(address)]['server_guid'] == guid
evidence = tmp_path/'open'
evidence.mkdir()
job = dict(root=str(evidence), lmc_file=str(library), block_name='A', project=str(project), pcb=str(pcb))
with pcb_open_consent.resource_guard(job, set(), require_complete_proof=True):
pass
proof = json.loads((evidence/'pcb-open-resource-proof.json').read_text('utf-8'))
assert proof['shared_shutdowns'] == release['shared_shutdowns']
assert address.read_text() == adr
assert database.read_bytes() == b'fixture'
import os
modified = log.stat().st_mtime_ns + 2_000_000_000
os.utime(database, ns=(modified, modified))
with pytest.raises(ValueError, match='SHARED_ICDB_INSPECTION_UNAVAILABLE'):
with pcb_open_consent.resource_guard(job, set(), require_complete_proof=True):
pytest.fail('an older server shutdown was accepted after a database change')
os.utime(database, ns=(modified, modified - 3_000_000_000))
write_log(lines[:-1]) # Database closed, but server shutdown is incomplete.
with pytest.raises(ValueError, match='SHARED_ICDB_INSPECTION_UNAVAILABLE'):
with pcb_open_consent.resource_guard(job, set(), require_complete_proof=True):
pytest.fail('incomplete native shutdown allowed read/write open')
+1 -1
View File
@@ -68,7 +68,7 @@ def test_aggregate_completed_release_checks_keep_final_proof_visible(release_wor
dialog.confirm_button.click() dialog.confirm_button.click()
qtbot.waitUntil(lambda: not dialog.busy, timeout=5000) qtbot.waitUntil(lambda: not dialog.busy, timeout=5000)
assert len(proofs) == 1, dialog.message.text() assert len(proofs) == 1, dialog.message.text()
assert '已释放 0 个会话' in dialog.message.text() assert '库已释放' in dialog.message.text() and '0 个客户端退出' in dialog.message.text()
proof = proofs[0] proof = proofs[0]
else: else:
context = operation_queue.BatchTaskContext(str(library)) context = operation_queue.BatchTaskContext(str(library))
+54 -1
View File
@@ -59,7 +59,8 @@ def test_confirm_releases_full_plan_and_only_emits_actual_library_proof(qtbot, t
qtbot.waitUntil(lambda: not dialog.busy) qtbot.waitUntil(lambda: not dialog.busy)
assert len(calls) == 1 and calls[0]['sessions'] == plan['sessions'] assert len(calls) == 1 and calls[0]['sessions'] == plan['sessions']
assert calls[0]['library'] == plan['library'] and released == [proof] assert calls[0]['library'] == plan['library'] and released == [proof]
assert '已释放 2' in dialog.message.text() assert '库已释放' in dialog.message.text()
assert '2 个客户端退出' in dialog.message.text()
assert not dialog.confirm_button.isEnabled() assert not dialog.confirm_button.isEnabled()
@@ -158,3 +159,55 @@ def test_released_batch_can_resume_only_its_unexecuted_items(qtbot, tmp_path, mo
monkeypatch.setattr(window, '_run', lambda names, **kw: calls.append((names, kw))) monkeypatch.setattr(window, '_run', lambda names, **kw: calls.append((names, kw)))
action.click() action.click()
assert calls == [(['Gamma'], {'maintenance': False, 'request_snapshot': original_remaining})] assert calls == [(['Gamma'], {'maintenance': False, 'request_snapshot': original_remaining})]
def test_orphaned_inflight_save_confirms_only_bound_prompt_after_three_seconds(tmp_path, monkeypatch):
from types import SimpleNamespace
from cbb_refresh_verify import desktop_worker, residual_sessions, session_record
desktop = 'CbbVerify_fixture'
job = {'interactive_input': False, 'desktop': desktop,
'operation_id': 'verify-fixture', 'session_record_path': str(tmp_path/'session.json')}
identity = {'role': 'native', 'pid': 75, 'created_handle': 'original',
'image': 'ExpeditionPCB.exe', 'owner_sid': 'sid', 'session_id': 1}
state = {'operation_id': job['operation_id'], 'phase': 'NATIVE_CALL', 'processes': [identity]}
actual = dict(identity)
known = {'hwnd': 1, 'title': 'Expedition PCB', 'desktop': desktop, 'class': '#32770',
'enabled': True, 'children': [
{'class': 'Static', 'text': 'Do you want to save the Reusable Block cell?'},
{'class': 'Button', 'id': 6, 'hwnd': 2, 'enabled': True},
{'class': 'Button', 'id': 7, 'hwnd': 3, 'enabled': True}]}
unrelated = {**known, 'hwnd': 9, 'desktop': 'Default'}
snapshots = SimpleNamespace(incomplete={})
snapshots.get = lambda *_: [unrelated, known]
clicks, events = [], []
monkeypatch.setattr(session_record, 'read_session_record', lambda *a, **k: state)
monkeypatch.setattr(session_record, 'process_identity', lambda pid: actual)
monkeypatch.setattr(residual_sessions, '_process_windows', lambda *_: snapshots)
monkeypatch.setattr(residual_sessions, '_post_window_message', lambda *args: clicks.append(args))
lost = False
monkeypatch.setattr(desktop_worker, 'supervisor_has_exited', lambda: lost, raising=False)
now = 10.0
prompt = residual_sessions.OrphanedVerifySavePrompt(job, 75, lambda **event: events.append(event),
clock=lambda: now)
prompt.poll(('SAVE_START',))
assert clicks == []
lost = True
prompt.poll(())
assert clicks == []
prompt.poll(('SAVE_START',))
now = 12.9
prompt.poll(('SAVE_START',))
assert clicks == []
now = 13.0
actual['created_handle'] = 'reused'
prompt.poll(('SAVE_START',))
assert clicks == []
actual['created_handle'] = 'original'
now = 14.0
prompt.poll(('SAVE_START',))
now = 17.0
prompt.poll(('SAVE_START',))
prompt.poll(('SAVE_START',))
assert [(args[0]['hwnd'], args[1], args[2]) for args in clicks] == [(1, 2, 75)]
assert events[0]['stage'] == 'orphaned_save_confirmed'
+2 -2
View File
@@ -19,8 +19,8 @@ def test_confirmed_scope_and_execution_divergence_are_visible(qtbot, tmp_path, m
qtbot.waitUntil(lambda: not dialog.busy) qtbot.waitUntil(lambda: not dialog.busy)
assert dialog.table.columnCount() == 8 assert dialog.table.columnCount() == 8
assert dialog.table.item(0, 6).text() == dialog.table.item(1, 6).text() == '允许' assert dialog.table.item(0, 6).text() == dialog.table.item(1, 6).text() == '允许'
assert dialog.table.item(0, 7).text() == '已释放' assert dialog.table.item(0, 7).text() == '客户端已退出'
assert dialog.table.item(1, 7).text() == '未释放' assert dialog.table.item(1, 7).text() == '未退出'
assert '原生操作进行中' in dialog.table.item(1, 3).text() assert '原生操作进行中' in dialog.table.item(1, 3).text()
assert '确认允许 2' in dialog.message.text() and '未释放 1' in dialog.message.text() assert '确认允许 2' in dialog.message.text() and '未释放 1' in dialog.message.text()
+33 -8
View File
@@ -13,12 +13,12 @@ from cbb_refresh_verify import session_record as sessions
from test_session_record import child, record from test_session_record import child, record
def retain_unconfirmed(root, library): def retain_unconfirmed(root, library, *, observe_only=False):
root.mkdir(parents=True) root.mkdir(parents=True)
path = root/'session.json' path = root/'session.json'
sessions.write_session_record(path, dict(operation_id=root.name, library=str(library), processes=[])) sessions.write_session_record(path, dict(operation_id=root.name, library=str(library), processes=[]))
done = Event() done = Event()
sessions.handoff_session(path, evidence_root=root, progress=lambda _: done.set()) sessions.handoff_session(path, evidence_root=root, observe_only=observe_only, progress=lambda _: done.set())
assert done.wait(3) assert done.wait(3)
with sessions._observer_guard: with sessions._observer_guard:
observer = sessions._observers.get(str(path.absolute()).casefold()) observer = sessions._observers.get(str(path.absolute()).casefold())
@@ -157,33 +157,58 @@ def test_residual_dialog_refresh_shows_runtime_blocker_without_releasing(qtbot,
library = tmp_path/'library/lib.lmc' library = tmp_path/'library/lib.lmc'
library.parent.mkdir(); library.touch() library.parent.mkdir(); library.touch()
monkeypatch.setattr(locks, 'inspect_residual_sessions', lambda *_: {'library': str(library), 'sessions': []}) monkeypatch.setattr(locks, 'inspect_residual_sessions', lambda *_: {'library': str(library), 'sessions': []})
monkeypatch.setattr(locks, 'release_retained_library', lambda *a, **kw: pytest.fail('preview mutated library')) release = locks.release_retained_library
releases = []
def check_release(target, *args, **kwargs):
if Path(target) == library:
releases.append(target)
raise OSError('Preview started a release')
return release(target, *args, **kwargs)
monkeypatch.setattr(locks, 'release_retained_library', check_release)
dialog = ResidualReleaseDialog(library, tmp_path/'release-checks') dialog = ResidualReleaseDialog(library, tmp_path/'release-checks')
qtbot.addWidget(dialog) qtbot.addWidget(dialog)
qtbot.waitUntil(lambda: not dialog.busy) qtbot.waitUntil(lambda: not dialog.busy)
retain_unconfirmed(tmp_path/'late-session', library) retain_unconfirmed(tmp_path/'late-session', library, observe_only=True)
dialog.refresh_button.click() dialog.refresh_button.click()
qtbot.waitUntil(lambda: not dialog.busy) qtbot.waitUntil(lambda: not dialog.busy)
assert dialog.plan['runtime_sessions'][0]['status'] == 'UNCONFIRMED' assert dialog.plan['runtime_sessions'][0]['status'] == 'UNCONFIRMED'
assert '待核对' in dialog.runtime_label.text() assert '待核对' in dialog.runtime_label.text()
assert not sessions.library_available(library) assert not sessions.library_available(library)
assert releases == []
def test_passive_handoff_reports_final_unconfirmed_state_without_proof(tmp_path, child, monkeypatch): def test_passive_handoff_reports_final_unconfirmed_state_without_proof(tmp_path, child, monkeypatch):
from threading import Event from threading import Event
from cbb_refresh_verify import library_lock as locks
path = record(tmp_path, [dict(role='worker', **sessions.process_identity(child.pid))]) path = record(tmp_path, [dict(role='worker', **sessions.process_identity(child.pid))])
library = tmp_path/'lib.lmc'
monkeypatch.setattr(sessions, '_retained_libraries', {}) monkeypatch.setattr(sessions, '_retained_libraries', {})
monkeypatch.setattr('cbb_refresh_verify.library_lock.release_retained_library', release = locks.release_retained_library
lambda *a, **kw: pytest.fail('startup observer released the library')) unexpected = []
def check_release(target, *args, **kwargs):
if Path(target) == library:
unexpected.append(target)
raise OSError('Passive observation attempted to release the library')
return release(target, *args, **kwargs)
monkeypatch.setattr(locks, 'release_retained_library', check_release)
terminal = Event() terminal = Event()
sessions.handoff_session(path, evidence_root=tmp_path, observe_only=True, sessions.handoff_session(path, evidence_root=tmp_path, observe_only=True,
progress=lambda value: terminal.set() if value['status'] == 'UNCONFIRMED' else None) progress=lambda value: terminal.set() if value['status'] == 'UNCONFIRMED' else None)
thread = sessions._observers[str(path.absolute()).casefold()][0]
child.terminate(); child.wait(5) child.terminate(); child.wait(5)
assert terminal.wait(3) assert terminal.wait(3)
states = sessions.retained_session_states(tmp_path/'lib.lmc') thread.join(3)
assert not thread.is_alive()
assert not unexpected
states = sessions.retained_session_states(library)
assert len(states) == 1 and states[0]['status'] == 'UNCONFIRMED' assert len(states) == 1 and states[0]['status'] == 'UNCONFIRMED'
assert states[0]['detail'] assert states[0]['detail']
assert not sessions.library_available(tmp_path/'lib.lmc') assert not sessions.library_available(library)
def test_explicit_release_marks_discovered_history_without_an_in_memory_observer(tmp_path, monkeypatch): def test_explicit_release_marks_discovered_history_without_an_in_memory_observer(tmp_path, monkeypatch):
+2 -1
View File
@@ -9,6 +9,7 @@ owned private desktop/PID, a resolved resource command and an exact PRJ.
from pathlib import Path from pathlib import Path
import ast import ast
import json import json
import re
import pytest import pytest
@@ -57,7 +58,7 @@ def test_no_input_injection_or_desktop_switching_in_production_code():
# interactive compatibility mode; the default worker remains # interactive compatibility mode; the default worker remains
# isolated and never reaches this branch. # isolated and never reaches this branch.
continue continue
if api in text: if re.search(r'\b' + re.escape(api) + r'\b', text):
offenders.append(f'{path.name}: {api}') offenders.append(f'{path.name}: {api}')
assert offenders == [], f'输入注入/桌面切换/菜单驱动 API 不得出现在生产代码: {offenders}' assert offenders == [], f'输入注入/桌面切换/菜单驱动 API 不得出现在生产代码: {offenders}'
+20
View File
@@ -364,3 +364,23 @@ def test_batch_summary_exposes_failures_only_report(qtbot, tmp_path):
window._batch_done(([VerifyResult('FAIL',stderr='Mentor error')],report)) window._batch_done(([VerifyResult('FAIL',stderr='Mentor error')],report))
assert '仅失败日志' in window.summary.detailedText() assert '仅失败日志' in window.summary.detailedText()
assert str(report.with_name('failures-20260929-test.log')) in window.summary.detailedText() assert str(report.with_name('failures-20260929-test.log')) in window.summary.detailedText()
def test_cancelled_pending_item_can_be_submitted_for_fresh_admission(qtbot, tmp_path):
records = (CbbRecord('Pending', 'LP', status='PENDING'), CbbRecord('Unconfirmed', 'LP'))
window = MainWindow(reader=lambda _: LibraryReadResult(records), data_root=tmp_path)
qtbot.addWidget(window)
window.lmc_edit.setText('lib.lmc')
window.load_library()
qtbot.waitUntil(lambda: not window.busy)
window.catalog_reader = object()
window._batch_requests = (window._request('Pending'), window._request('Unconfirmed'))
window._batch_refreshed(([VerifyResult('CANCELLED', safe_to_continue=False),
VerifyResult('FAIL', safe_to_continue=False)], None,
['Pending', 'Unconfirmed'], None))
assert window._records_by_name['Pending'].status == 'UNKNOWN'
assert window._eligible_names(require_status=True) == ['Pending']
assert window.batch_button.isEnabled()
window._apply_refreshed_records((('Pending',), {'Pending': 'READY'}, {}, ''))
assert window._eligible_names(require_status=True) == []
+1 -3
View File
@@ -362,9 +362,7 @@ def test_prewrite_cancellation_can_resubmit_and_rechecks_ready(qtbot, tmp_path,
qtbot.waitUntil(lambda: not window.busy) qtbot.waitUntil(lambda: not window.busy)
assert calls == ['Beta'] assert calls == ['Beta']
assert window.visible_records()[0].status == ('PENDING' if prewrite else 'UNKNOWN') assert window.visible_records()[0].status == ('PENDING' if prewrite else 'UNKNOWN')
assert window.batch_button.isEnabled() == prewrite assert window.batch_button.isEnabled()
if not prewrite:
return
window.batch_button.click() window.batch_button.click()
qtbot.waitUntil(lambda: not window.busy) qtbot.waitUntil(lambda: not window.busy)
+20
View File
@@ -183,3 +183,23 @@ def test_window_close_tolerates_fake_and_deleted_dialog_pools(qtbot, tmp_path, m
window.show() window.show()
window.close() window.close()
qtbot.waitUntil(lambda: not window.isVisible()) qtbot.waitUntil(lambda: not window.isVisible())
def test_late_job_retains_mapping_after_window_destruction(qtbot, tmp_path):
import shiboken6
from cbb_refresh_verify.ui.main_window import MainWindow
window = MainWindow(reader=lambda _: None, data_root=tmp_path, authoritative_status=False)
lease, entered, release, closed, calls = slow_lease(get_ident())
job = window._new_job('verify', lease=lease)
window._shutdown_leases[id(lease)] = lease
window.library_lease = None
try:
shiboken6.delete(window)
window._finish_job(job)
qtbot.waitUntil(entered.is_set)
assert calls == ['retain']
assert not closed.is_set()
finally:
release.set()
+71
View File
@@ -1036,6 +1036,77 @@ def test_saved_closed_without_cert_uses_bridge_and_never_reexecutes_verify(
assert ordering[-1] == 'failure_logs' assert ordering[-1] == 'failure_logs'
@pytest.mark.parametrize('config_name', ['CBB1.prj', 'PCB/pcb.prj'])
def test_native_save_waits_for_scoped_database_sharing_violation(tmp_path, monkeypatch, config_name):
from cbb_refresh_verify import file_probe
import win32con
import win32file
work = fixture(tmp_path)
config_path = work/config_name
database = config_path.parent/'ActualDatabase/icdb.dat'
if config_path.exists():
with config_path.open('a', encoding='utf-8') as config:
config.write('\nKEY iCDBDir "ActualDatabase"\n')
else:
config_path.write_text('KEY iCDBDir "ActualDatabase"\n', encoding='utf-8-sig')
database.parent.mkdir()
database.touch()
shared = tmp_path/'SymbolLibs/__ReusableBlocksSymb/icdb.dat'
shared.parent.mkdir(parents=True)
shared.touch()
locked = win32file.CreateFile(str(database), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, 0, None)
progress = []
released = False
class FinishedWorker:
desktop = None
returncode = 0
def __init__(self, command, *_args, **kwargs):
root = Path(command[-1]).parent
(root/'outcome.json').write_text('{"status":"PASS"}', encoding='utf-8')
(root/'save.log').write_text(
'SAVE_START\nSAVE_OK\nIS_SAVED\nCLOSE_OK\nQUIT_OK\n', encoding='utf-8')
def poll(self):
return 0
def close(self):
pass
def observe(event):
nonlocal released
progress.append(event)
if event['stage'] == 'post_save_release_pending':
# Model the original case: PCB is gone, the database is still held.
assert event['blocked_resources'] == [str(database)]
assert str(database) in event['detail']
locked.Close()
released = True
def read_status(*_args):
assert released, 'Native status read started before iCDB released the database'
return BridgeResult('READY', 'IsVerifiedReuseBlock', 1)
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', FinishedWorker)
monkeypatch.setattr('cbb_refresh_verify.verify_runner._cleanup_session_processes',
lambda *a, **kw: {'safe_to_continue': True, 'remaining_pids': []})
# Source-mode subprocess uses the same import root as the current test run.
monkeypatch.setenv('PYTHONPATH', str(Path(file_probe.__file__).parents[1]))
try:
result = run_verify(request(tmp_path), port_check=PORTS_OK, flag_reader=read_status, progress=observe)
finally:
if not released:
locked.Close()
assert result.status == 'PASS'
assert result.safe_to_continue
release = json.loads(result.evidence_path.with_name('session-release.json').read_text('utf-8'))
assert {str(shared), str(database)} <= set(release['database_release']['exclusive_files'])
assert sum(event['stage'] == 'post_save_release_pending' for event in progress) == 1
@pytest.mark.parametrize('detail, category', [ @pytest.mark.parametrize('detail, category', [
('PROJECT_INTEGRATION_FAILED: There were errors during packaging', 'MENTOR_PROJECT_INTEGRATION'), ('PROJECT_INTEGRATION_FAILED: There were errors during packaging', 'MENTOR_PROJECT_INTEGRATION'),
('DATABASE_LOAD_FAILED: DataBase Load is being terminated with 2 errors', 'MENTOR_DATABASE_LOAD_FAILED'), ('DATABASE_LOAD_FAILED: DataBase Load is being terminated with 2 errors', 'MENTOR_DATABASE_LOAD_FAILED'),