fix: resume CBB batches after verified native release

This commit is contained in:
阿白叔 committed 2026-11-25 09:28:05 +08:00
1 parent c76b755f13
commit 5bab125122
18 files changed
+642 -60

No files matched your search

+39 -7
View File
@@ -1,6 +1,6 @@
from __future__ import annotations
import argparse, os, sys
from contextlib import contextmanager
from contextlib import contextmanager, ExitStack
from pathlib import Path
from typing import Sequence
from .network_path import NetworkPathError
@@ -195,21 +195,42 @@ def main(argv: Sequence[str] | None = None) -> int:
return dialog_agent_main(args.dialog_agent)
if 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)
data_root = args.data_root
try:
data_root = resolve_data_root(data_root)
context = configure(data_root)
except (OSError, ValueError, RuntimeError):
location = data_root if data_root is not None else '默认数据目录'
return _report_entry_error(f'DATA_ROOT_UNWRITABLE: 无法写入数据目录 {location}。'
'请指定可写的 --data-root。', command_line=command_line)
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.info("application_start")
try:
if args.batch_lmc:
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 .batch_status import authoritative_status_map
from .network_path import LibraryPathLease, select_library_file, validate_library_file
@@ -254,7 +275,8 @@ def main(argv: Sequence[str] | None = None) -> int:
lease.drive or '-', lease.remote_root or '-', lease.display_path,
mentor_path, reason)
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 .residual_sessions import recoverable_orphan_session
@@ -277,7 +299,12 @@ def main(argv: Sequence[str] | None = None) -> int:
wait_for_release_seconds=120,
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)
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:
retain_mapping('batch_exception')
raise
@@ -292,10 +319,15 @@ def main(argv: Sequence[str] | None = None) -> int:
from .ui.main_window import MainWindow, application_icon_path
if args.smoke_test:
os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')
from PySide6.QtWidgets import QApplication
app = QApplication.instance() or QApplication([sys.executable])
from PySide6.QtWidgets import QApplication
app = QApplication.instance() or QApplication([sys.executable])
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()
if icon_path.is_file():
from PySide6.QtGui import QIcon
+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
+27 -4
View File
@@ -26,13 +26,21 @@ def hold_release_files(library, roots=None, *, saved_project=None, timeout_secon
process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
try:
deadline = time.monotonic()+max(.1, min(10, timeout_seconds))
started = time.monotonic()
deadline = started + max(.1, min(10, timeout_seconds))
result_path = job.with_name('result.json')
while True:
if stop is not None and stop.is_set():
raise InterruptedError('FILE_PROBE_CANCELLED')
if time.monotonic() >= deadline:
raise TimeoutError('FILE_PROBE_TIMEOUT: 文件占用检查超时,未证明释放')
try:
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
@@ -116,10 +124,12 @@ def _shared_server_shutdown(address, data, database, entries):
'log': str(log), 'log_sha256': hashlib.sha256(raw).hexdigest()}
def _snapshot(library, roots):
def _snapshot(library, roots, progress=lambda stage, path: None):
from .scoped_manifest import scan_tree
progress('library_metadata', library)
entries = {library: library.lstat()}
for root in roots:
progress('scan_root', root)
if root.exists():
entries.update(scan_tree(root))
native = sorted(path for path, info in entries.items() if stat.S_ISREG(info.st_mode)
@@ -131,6 +141,7 @@ def _snapshot(library, roots):
from .icdb_ownership import shared_symbol_database
shared = shared_symbol_database(library)
for address in addresses:
progress('read_address', address)
data = address.read_bytes()
signatures[str(address)] = hashlib.sha256(data).hexdigest()
database = address.parent.parent
@@ -219,8 +230,18 @@ def file_probe_main(job):
request = json.loads(job.read_text('utf-8'))
result = {'token': request['token'], 'status': 'UNCONFIRMED'}
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:
def checked_path(value):
progress('validate_path', value)
path = Path(value).absolute()
for part in (path, *path.parents):
try:
@@ -236,7 +257,7 @@ def file_probe_main(job):
raise ValueError('文件探测范围不属于所选库')
def read_snapshot():
if request.get('saved_project') is None:
return _snapshot(library, roots)
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)
@@ -244,12 +265,14 @@ def file_probe_main(job):
with ExitStack() as stack:
handles = []
for path in snapshot['exclusive_files']:
progress('open_exclusive', path)
opening = path
handle = win32file.CreateFile(path, win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
stack.callback(handle.Close)
handles.append(int(handle))
for path in snapshot['binding_files']:
progress('open_binding', path)
opening = path
handle = win32file.CreateFile(path, win32con.GENERIC_READ, win32con.FILE_SHARE_READ,
None, win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
+18 -5
View File
@@ -104,7 +104,8 @@ def has_retained_library(library):
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."""
if not required:
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='正在复核历史记录对应的实际占用')
try:
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)
except Exception as error:
notify('previous_release_unconfirmed', detail=str(error))
@@ -602,7 +605,8 @@ def _prove_library_released(library, block_name=None, *, block_names=(), allow_u
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.
The upload sidecar is never deleted. This acknowledges process release,
@@ -643,9 +647,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}
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]
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 ())
if infer_scope:
recorded_blocks = [record.get('block_name') for record in records if record]
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
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')}}
+5
View File
@@ -1024,6 +1024,11 @@ def worker_main(request_path):
phase = {'save_start': 'NATIVE_CALL', 'integration_action': 'NATIVE_CALL',
'integration_action_complete': 'POSTCALL', 'saved_and_closed': 'RELEASE_CHECK',
'complete': 'FINISHED', 'failed': 'UNCONFIRMED'}.get(event.get('stage'))
if (event.get('stage') == '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'))):
# The watchdog may retire this worker before its first native write.
phase = 'PRECALL'
identities = [(role, event.get(key)) for role, key in
(('native', 'pcb_pid'), ('native', 'lm_pid'))
if event.get(key)]
+19 -11
View File
@@ -1135,24 +1135,28 @@ def _open_catalog_manager_library(pid):
def _check_catalog_owners(library, processes):
"""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()
manager_pids = [pid for pid, *_ in processes]
target_dependencies = _catalog_shared_dependencies(library)
observed_libraries = {}
for pid in manager_pids:
try:
current = _open_catalog_manager_library(pid)
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:
other = current.resolve(strict=True)
if library.samefile(other):
detail = '当前库已在另一个 Library Manager 中打开'
elif any(left[2] == right[2] or (left[1] and left[:2] == right[:2])
for left in target_dependencies for right in _catalog_shared_dependencies(other)):
detail = '另一个 Library Manager 正在使用相同的共享符号库'
else:
continue
observed_libraries[pid] = str(other)
continue
except (OSError, ValueError) as error:
detail = f'无法确认另一中心库的资源范围:{error}'
raise NativeOperationError(f'LIBRARY_MANAGER_BUSY: PID {pid} · {detail}。',
@@ -1162,6 +1166,7 @@ def _check_catalog_owners(library, processes):
except OSError as error:
raise NativeOperationError(f'LIBRARY_MANAGER_BUSY: PID {manager_pids} · 当前库资源占用未确认:{error}',
safe_to_continue=True, blocking_manager_pids=manager_pids) from error
return observed_libraries
def _catalog_native(job, root):
@@ -1200,6 +1205,7 @@ def _catalog_com(job, root):
if name != job['desktop'] or not name.startswith('CbbManagement_'):
raise RuntimeError('拒绝在非本次私有桌面读取原生目录。')
previous_managers = _process_details('LibraryManager.exe')
existing_libraries = {}
if previous_managers:
if job.get('worker_role') != 'catalog_readonly' or job.get('include_engineering_identity', True):
raise RuntimeError('LIBRARY_MANAGER_BUSY: 已有 Library Manager 运行,请关闭后重试。')
@@ -1208,7 +1214,7 @@ def _catalog_com(job, root):
pids = sorted(pid for pid, *_ in previous_managers)
raise NativeOperationError(f'LIBRARY_MANAGER_BUSY: PID {pids} · 当前安装尚未验证并行目录读取。',
safe_to_continue=True, blocking_manager_pids=pids)
_check_catalog_owners(job['library'], previous_managers)
existing_libraries = _check_catalog_owners(job['library'], previous_managers)
except Exception as error:
error.safe_to_continue = True
raise
@@ -1257,6 +1263,8 @@ def _catalog_com(job, root):
continue
app = library = None
result = {'success': False, 'safe_to_continue': False}
if existing_libraries:
result['existing_manager_libraries'] = existing_libraries
watcher = None
try:
_require_management_continuation(job, root)
+3 -1
View File
@@ -13,7 +13,7 @@ class QueueCancelled(RuntimeError):
class QueueUnavailable(RuntimeError):
"""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.sessions = tuple(sessions)
self.timed_out = timed_out
@@ -24,6 +24,8 @@ class QueueUnavailable(RuntimeError):
details.append(' / '.join(filter(None, (block, session.get('operation_id'),
resources, session.get('path')))))
message = f'NATIVE_SESSION_PENDING: {self.library} 的已登记会话待释放,当前项未启动。'
if detail:
details.insert(0, detail)
super().__init__(message + (' ' + ';'.join(details) if details else ''))
+90 -16
View File
@@ -919,6 +919,64 @@ def _worker_save_facts(state, identities):
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
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', 'startup_prewrite_ready', 'pcb_baseline', '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, ready, baseline, 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]
def recoverable_orphan_session(path):
from .session_record import IDENTITY_KEYS, MAX_BYTES, read_session_record, _session
import stat
@@ -930,8 +988,6 @@ def recoverable_orphan_session(path):
desktop = str(session.get('desktop', ''))
if operation == 'verify' and desktop.startswith('CbbVerify_'):
_, state, identities = _session(path, path.parent)
if not _saved_and_closed(_worker_save_facts(state, identities)):
return False
elif (operation != 'catalog' or session.get('worker_role') != 'catalog_readonly'
or not desktop.startswith('CbbManagement_')):
return False
@@ -962,7 +1018,10 @@ def recoverable_orphan_session(path):
lost = read_session_record(path.with_name('supervisor-lost.json'), evidence_root=path.parent)
if lost.get('operation_id') != session['operation_id'] or lost.get('phase') != 'SUPERVISOR_LOST':
return False
return _recorded_process_exited(identity)
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):
return False
@@ -1042,6 +1101,10 @@ def finish_owned_idle_session(path, *, stop=None):
return False
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]
orphan_client = None
if operation == 'verify' and result is None and not _saved_and_closed(_worker_save_facts(state, identities)):
orphan_client = _orphan_prewrite_client(path, job, session, state, identities)
clients = [orphan_client] if orphan_client is not None else []
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'])):
return False
@@ -1070,8 +1133,8 @@ def finish_owned_idle_session(path, *, stop=None):
for c in w.get('children',[])) for w in windows)):
return None
return close_target(client_name, windows, incomplete=_window_error(snapshot,client['pid']))[0]
def load_failure_button():
from .failed_session import _startup_snapshot, _cancel_target
def startup_prompt():
from .failed_session import _startup_snapshot, _cancel_target, _tip_target
snapshot = _process_windows({client['pid']}, include_hidden_documents=True)
windows = snapshot.get(client['pid'], [])
if (_window_error(snapshot, client['pid']) or not windows
@@ -1082,23 +1145,26 @@ def finish_owned_idle_session(path, *, stop=None):
return None
with _window_desktop(desktop):
observed = _startup_snapshot(modals[0]['hwnd'], client['pid'])
tip = _tip_target(observed) if orphan_client is not None and modals[0]['title'] == 'Tip of the Day' else None
if tip is not None:
return observed, tip.handle, 'tip'
target = _cancel_target(observed)
if target is None or target[0] != 'database_load_log':
return None
return observed, target[1].handle
if target is not None and (orphan_client is not None or target[0] == 'database_load_log'):
return observed, target[1].handle, target[0]
return None
if not same_client(): return False
if (cancelled_before_write is not None
and cancelled_prewrite_startup(job, client['pid']) != cancelled_before_write):
return False
target = empty_target()
failure = load_failure_button() if target is None and cancelled_before_write is not None else None
if (target is None and failure is None) or stop is not None and stop.is_set(): return False
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 prompt is None) or stop is not None and stop.is_set(): return False
check_active()
current, _, _ = _session(path, path.parent)
if current != session: return False
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)
write_session_record(path, {**session,'owned_idle_cleanup':claim})
# Re-read after durable I/O; never act on a window that gained a document.
@@ -1107,7 +1173,7 @@ def finish_owned_idle_session(path, *, stop=None):
or latest.get('owned_idle_cleanup') != claim
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 (empty_target() != target if failure is None else load_failure_button() != failure)
or (empty_target() != target if prompt is None else startup_prompt() != prompt)
or (cancelled_before_write is not None
and cancelled_prewrite_startup(job, client['pid']) != cancelled_before_write)
or read_result() != result or result is None and not recoverable_orphan_session(path)
@@ -1118,8 +1184,14 @@ def finish_owned_idle_session(path, *, stop=None):
write_session_record(path, latest)
return False
with native_phase(read_only=True):
if failure is not None:
_post_window_message({'desktop': desktop}, failure[1], client['pid'], win32con.BM_CLICK)
if prompt is not None:
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
while time.monotonic() < deadline and same_client():
if stop is not None and stop.is_set():
@@ -1129,7 +1201,9 @@ def finish_owned_idle_session(path, *, stop=None):
break
time.sleep(.1)
if (target is not None and (not same_client() or empty_target() != target
or cancelled_prewrite_startup(job, client['pid']) != cancelled_before_write)):
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
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)
@@ -1263,7 +1337,7 @@ def _finish_library_release(library, evidence, block_names=(), stop=None):
from .library_lock import release_retained_library
return release_retained_library(library, evidence,
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):
+6 -1
View File
@@ -1924,7 +1924,12 @@ class MainWindow(QWidget):
f'正在 ICDB 批量检查:共 {len(names)} 个 CBB' if maintenance
else f'正在校验:共 {len(names)} 个 CBB')
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(
req,
progress=lambda e: self._emit_job(job, 'event', e),
@@ -110,7 +110,7 @@ class ResidualReleaseDialog(QDialog):
for index, session in enumerate(sessions):
allowed = session.get('consent_allowed')
permission = '允许' if allowed is True else '未允许' if allowed is False else '待确认'
outcome = {'RELEASED': '已释放', 'WAITING': '未释放', 'IDENTITY_CHANGED': '身份已变化',
outcome = {'RELEASED': '客户端已退出', 'WAITING': '未退出', 'IDENTITY_CHANGED': '身份已变化',
'OBSERVED': '仅观察,未关闭',
'CANCELLED': '已停止', 'REQUESTING': '执行中', 'NOT_STARTED': '尚未执行'}.get(
session.get('release_status'), '待执行')
@@ -178,7 +178,7 @@ class ResidualReleaseDialog(QDialog):
self._start(execute, done)
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.
if (proof.get('status') != 'RELEASE_CONFIRMED'
or Path(proof.get('library', '')).absolute() != self.library.absolute()
@@ -191,7 +191,7 @@ class ResidualReleaseDialog(QDialog):
def _finalize_release_result(self, result):
"""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'
and Path(proof.get('library', '')).absolute() == self.library.absolute()
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
for row in result['sessions'])
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 ''))
else:
self.message.setText(f'已释放 {count} 个会话,其余会话或库状态仍待确认。'
self.message.setText(f'{count} 个客户端已退出,库释放仍待确认。'
+ ('\n'+result['detail'] if result.get('detail') 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]
+34
View File
@@ -1589,6 +1589,40 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
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
deadline = time.monotonic() + timeout_seconds
previous = None
while True:
context.check_active()
if library_available(library, live_only=True):
try:
recheck_previous_release(library, Path(request.evidence_dir)/'previous-release',
block_name=request.block_name, stop=context.stop, infer_scope=True)
except LibraryBusy as error:
detail = str(error)
else:
context.check_active()
return
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,
context=None):
"""Run serially; isolate failures and skip writes to resources still retained."""
+1 -1
View File
@@ -416,7 +416,7 @@ def test_residual_refresh_details_confirm_and_close(residual, qtbot):
qtbot.waitUntil(lambda: not d.busy)
assert len(residual.releases) == 1 and residual.releases[0]['force'] is False
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)
assert not d.isVisible()
+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
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():
import subprocess, sys
code = (
+29
View File
@@ -0,0 +1,29 @@
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)
+45 -8
View File
@@ -23,9 +23,10 @@ def test_status_scan_delivers_progress_after_each_record(tmp_path):
assert snapshots == [(1, 2, 1), (2, 2, 2)]
@pytest.mark.parametrize('include_identity', [False, True])
def test_catalog_registration_only_skips_project_identities(tmp_path, monkeypatch, include_identity):
@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, unknown_foreign):
import win32com.client
import win32process
from cbb_refresh_verify import mentor_adapter
lmc = tmp_path / 'lib.lmc'
@@ -42,15 +43,26 @@ def test_catalog_registration_only_skips_project_identities(tmp_path, monkeypatc
Partitions=lambda _: SimpleNamespace(Count=1, Item=lambda _: partition))
app = SimpleNamespace(OpenLibrary=lambda _: library, Quit=lambda: None)
exe = tmp_path / 'lm/win32/bin/LibraryManager.exe'
no_owners = iter([[], [(123, str(exe), '', 0)]])
monkeypatch.setattr(mentor_adapter, '_process_details', lambda _: next(no_owners))
previous = [(321, str(exe), '', 0)] if unknown_foreign else []
snapshots = iter([previous, [*previous, (123, str(exe), '', 0)]])
monkeypatch.setattr(mentor_adapter, '_process_details', lambda _: next(snapshots))
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',
lambda: (SimpleNamespace(EnumDesktopWindows=lambda: []), 'CbbManagement_test'))
lambda: (SimpleNamespace(EnumDesktopWindows=lambda: [42] if unknown_foreign else []),
'CbbManagement_test'))
monkeypatch.setattr(win32com.client, 'DispatchEx', lambda _: app)
result = native._catalog_com({'operation': 'catalog', 'worker_role': 'catalog_readonly',
'include_engineering_identity': include_identity, 'library': str(lmc),
'desktop': 'CbbManagement_test', 'mentor_home': str(tmp_path), 'supervisor_pid': __import__('os').getpid()}, tmp_path)
assert result['success']
assert result['native_pids'] == [123]
if unknown_foreign:
assert result['existing_manager_libraries'] == {321: None}
assert hashed == ([project] if include_identity else [])
@@ -77,14 +89,15 @@ def test_catalog_distinguishes_foreign_and_conflicting_manager(tmp_path, monkeyp
def held(library):
raise OSError('shared database handle is occupied')
monkeypatch.setattr(native, '_probe_catalog_files', held)
if scope == 'foreign':
if scope in {'foreign', 'unknown'}:
native._check_catalog_owners(target, owners)
else:
with pytest.raises(RuntimeError, match='LIBRARY_MANAGER_BUSY.*123'):
native._check_catalog_owners(target, owners)
def test_catalog_rejects_reused_foreign_com_proxy_without_mutating_it(tmp_path, monkeypatch):
@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
from cbb_refresh_verify import mentor_adapter
@@ -99,7 +112,7 @@ 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))
before = [(123, 'LibraryManager.exe', f'LibraryManager.exe "{other}"', 0)]
monkeypatch.setattr(mentor_adapter, '_process_details', lambda _: before)
monkeypatch.setattr(native, '_open_catalog_manager_library', lambda _: other, raising=False)
monkeypatch.setattr(native, '_open_catalog_manager_library', lambda _: other if title_resolved else None)
monkeypatch.setattr(native, '_current_desktop',
lambda: (SimpleNamespace(EnumDesktopWindows=lambda: []), 'CbbManagement_test'))
@@ -119,6 +132,30 @@ def test_catalog_rejects_reused_foreign_com_proxy_without_mutating_it(tmp_path,
assert result['native_pids'] == []
assert result['no_new_manager'] is True
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)])
+110
View File
@@ -177,3 +177,113 @@ 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 state['posts'] == ([(201, 12, 245), (100, 12, 16)] if proved else [])
assert (root/'result.json').read_bytes() == original
@pytest.mark.parametrize('obstacle', [None, 'tip', 'read_write', 'unknown_prompt', 'save',
'uncertain_phase', 'live_supervisor', 'live_worker',
'wrong_pcb', 'possible_write'])
def test_restarted_verify_closes_exact_prewrite_orphan(tmp_path, monkeypatch, obstacle):
import json
from contextlib import nullcontext
from types import SimpleNamespace
from test_owned_idle_cleanup import owned_fixture
from cbb_refresh_verify import failed_session, residual_sessions
root, job, _, windows, state = owned_fixture(tmp_path, monkeypatch)
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='startup_prewrite_ready', worker_identity=session['processes'][0],
baseline=dict(started_ns=42, files={}), **binding),
dict(stage='pcb_baseline', pids=[]),
dict(stage='pcb_worker_started', pcb_pid=12, command=command)]
if obstacle == 'possible_write':
rows.append(dict(stage='startup_supervisor_write_possible', **binding))
(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', 'read_write', 'unknown_prompt'):
frame = windows[0]
frame['enabled'] = False
windows.append(dict(hwnd=200, title='Tip of the Day' if obstacle == 'tip' else 'Expedition PCB',
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'] = True
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())
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)
recovered = residual_sessions.finish_owned_idle_session(path)
assert recovered is (obstacle in (None, 'tip', 'read_write'))
expected_posts = [(201, 12, 245)] if obstacle in ('tip', 'read_write') else []
if recovered:
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_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 == [('PRECALL', [('native', 12)]), ('NATIVE_CALL', [])]
+36
View File
@@ -307,3 +307,39 @@ def test_arbitrary_guard_filename_is_preserved_and_primary(tmp_path, monkeypatch
with pytest.raises(locks.LibraryBusy):
locks.release_retained_library(library, tmp_path/'release')
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
import sys
script = tmp_path/'slow_probe.py'
library = tmp_path/'lib.lmc'
script.write_text(
"import json, sys, time\n"
"from pathlib import Path\n"
"job = Path(sys.argv[-1])\n"
"job.with_name('progress.json').write_text(json.dumps("
"{'stage': 'open_exclusive', 'path': 'SymbolLibs/icdb.dat'}))\n"
"time.sleep(30)\n",
encoding='utf-8')
start = file_probe.subprocess.Popen
monkeypatch.setattr(file_probe.subprocess, 'Popen',
lambda command, **kwargs: start([sys.executable, str(script), command[-1]], **kwargs))
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')
+2 -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)
assert len(calls) == 1 and calls[0]['sessions'] == plan['sessions']
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()