fix: resume CBB batches after verified native release
This commit is contained in:
1 parent
c76b755f13
commit
5bab125122
18 files changed
+642
-60
No files matched your search
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -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)
|
||||
|
||||
@@ -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')}}
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 ''))
|
||||
|
||||
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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."""
|
||||
|
||||
Reference in new issue
Block a user