fix: skip unavailable items and isolate batch failures

This commit is contained in:
阿白叔 committed 2026-11-19 10:06:04 +08:00
1 parent 07eab61695
commit 3bde847ff7
13 files changed
+592 -36

No files matched your search

@@ -463,6 +463,7 @@ def check_target_window(job, pcb_pid, *, emit, error_reader, launcher_process=No
if not session.pcb_alive():
raise RuntimeError('DIAGNOSTIC_OPEN_UNCONFIRMED: target PCB exited before loaded evidence')
windows = scan(deadline)
_cancel(job)
if any(window['pid'] != int(pcb_pid) for window in windows):
raise RuntimeError('DIAGNOSTIC_PID_MISMATCH')
frame = _target_frame(windows, Path(job['pcb']).stem, require_ready=False)
+28 -9
View File
@@ -171,7 +171,7 @@ def _may_have_mutated(record):
def run_management(request, *, adapter=None, verifier=None, idle_check=None, progress=None, stop=None, version_prompt=None,
write_admission=None):
from .verify_runner import VerifyRequest, run_verify
from .verify_runner import VerifyRequest, run_verify, _notify_progress
from .backup_recovery import _idle_check
from contextlib import ExitStack
from .operation_queue import check_active, native_channel, task_stop, remember_result
@@ -216,7 +216,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
_write_json(report, {**asdict(request), 'stage': stage, 'status': 'RUNNING',
'safe_to_continue': False, 'history': history, 'backup_policy': 'manual'})
if progress:
progress({'stage': stage, 'block': request.name, 'operation': request.operation, **details})
_notify_progress(progress, {'stage': stage, 'block': request.name, 'operation': request.operation, **details})
def finish(status, detail='', safe=True):
nonlocal change_report
remember_result(ManagementResult(request.operation, request.library, request.name, request.partition,
@@ -465,7 +465,8 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
def run_management_batch(requests, *, stop=None, progress=None, item_executor=None, context=None, **kwargs):
from threading import Event
from .write_admission import WriteAdmission
from .operation_queue import QueueCancelled, TaskHandoff, request_library_keys, remember_result, current_context
from .verify_runner import _notify_progress
from .operation_queue import QueueCancelled, QueueUnavailable, TaskHandoff, request_library_keys, remember_result, current_context
context = context or current_context()
if context is not None:
stop = stop if stop is not None else context.stop
@@ -474,19 +475,30 @@ def run_management_batch(requests, *, stop=None, progress=None, item_executor=No
stop = Event()
kwargs.setdefault('write_admission',WriteAdmission(prompt=kwargs.get('version_prompt'),stop=stop))
results = []
retained_libraries = set()
retained_libraries = {}
cancelled = False
for request in requests:
keys = request_library_keys(request, context)
stopped = (cancelled or stop.is_set() or context is not None
and (context.stop.is_set() or context.stop_after_current.is_set()))
if not stopped:
for index in {retained_libraries[key][1] for key in keys.intersection(retained_libraries)}:
previous = next(value[0] for value in retained_libraries.values() if value[1] == index)
from .operation_lifecycle import recheck_failed_release
refreshed = recheck_failed_release(previous.library, previous.name, results[index], stop=stop)
if refreshed.safe_to_continue:
results[index] = refreshed
retained_libraries = {k:v for k,v in retained_libraries.items() if v[1] != index}
if stopped or keys.intersection(retained_libraries):
previous = (retained_libraries[next(iter(keys.intersection(retained_libraries)))][0]
if not stopped else None)
result = ManagementResult(request.operation, request.library, request.name, request.partition,
request.source, request.auto_verify, 'complete', 'SKIPPED', True,
'队列已停止,未操作此 CBB' if stopped else '同库原生会话尚未释放,未启动新的写入')
request.source, request.auto_verify, 'admission', 'SKIPPED', True,
'队列已停止,未操作此 CBB' if stopped else
f'PREVIOUS_SESSION_UNRELEASED: 前项 {previous.name} 的同库会话尚未释放,当前项未启动。')
results.append(result)
if progress:
progress({'stage': result.status, 'block': result.name, 'detail': result.detail})
_notify_progress(progress, {'stage': result.status, 'block': result.name, 'detail': result.detail})
continue
def action():
result = run_management(request, progress=progress, stop=stop, **kwargs)
@@ -497,6 +509,9 @@ def run_management_batch(requests, *, stop=None, progress=None, item_executor=No
return result
try:
result = item_executor(request, action) if item_executor is not None else action()
except QueueUnavailable as error:
result = ManagementResult(request.operation, request.library, request.name, request.partition,
request.source, request.auto_verify, 'admission', 'SKIPPED', True, str(error))
except QueueCancelled as error:
known = error.result if isinstance(error, TaskHandoff) else None
if isinstance(known, ManagementResult):
@@ -510,12 +525,16 @@ def run_management_batch(requests, *, stop=None, progress=None, item_executor=No
request.source, request.auto_verify, 'complete',
'TIMEOUT' if isinstance(error, TaskHandoff) and not error.cancelled else 'CANCELLED',
not isinstance(error, TaskHandoff), str(error))
except Exception as error:
result = ManagementResult(request.operation, request.library, request.name, request.partition,
request.source, request.auto_verify, 'exception', 'RECOVERY_REQUIRED', False,
'BATCH_ITEM_EXCEPTION: '+str(error))
results.append(result)
if progress:
progress({'stage': result.status, 'block': result.name, 'detail': result.detail,
_notify_progress(progress, {'stage': result.status, 'block': result.name, 'detail': result.detail,
'evidence_path': str(result.evidence_path or '')})
if not result.safe_to_continue:
retained_libraries.update(keys)
retained_libraries.update({key:(request, len(results)-1) for key in keys})
if result.status == 'CANCELLED':
cancelled = True
return results
@@ -6,13 +6,13 @@ def recheck_failed_release(library, block, result, *, stop=None, timeout_seconds
"""Refresh resource facts after a late exit; keep the original business failure."""
if result.safe_to_continue or not result.evidence_path:
return result
from .operation_queue import BatchTaskContext, TaskHandoff, current_context, task_stop
from .operation_queue import BatchTaskContext, QueueCancelled, current_context, task_stop
if current_context() is None:
context = BatchTaskContext(library=str(library), targets=(block,))
try:
return context.run(lambda: recheck_failed_release(library, block, result, stop=stop),
stop=stop, timeout_seconds=timeout_seconds)
except TaskHandoff:
except QueueCancelled:
return result
stop = task_stop(stop)
from pathlib import Path
+18 -2
View File
@@ -11,6 +11,14 @@ class QueueCancelled(RuntimeError):
pass
class QueueUnavailable(RuntimeError):
"""Admission failed before action dispatch; this task created no native session."""
def __init__(self, library):
self.library = str(library)
super().__init__('NATIVE_SESSION_PENDING: '+self.library+
' 的已登记会话仍在运行或初始化,当前项未启动。')
class TaskHandoff(QueueCancelled):
"""The call is still observable; this is never a release receipt."""
def __init__(self, context, *, cancelled=False, result=None):
@@ -409,14 +417,19 @@ class NativeQueue:
for context in contexts)
def run(self, action, *, stop=None, waiting=None, ready=lambda: True, wait_state=None,
context=None, timeout_seconds=10):
context=None, timeout_seconds=10, skip_unavailable=False):
def available_now():
if not ready():
return False
if context is None:
return True # Explicit recovery controls must still reach their retained clients.
from .session_record import _live_library_available
return all(_live_library_available(path) for path in (context.library, *context.aliases))
for path in (context.library, *context.aliases):
if not _live_library_available(path):
if skip_unavailable:
raise QueueUnavailable(path)
return False
return True
ticket = [object(), False]
acquired, notified = False, False
previous_state = None
@@ -428,6 +441,9 @@ class NativeQueue:
self.pending.append(ticket)
try:
while not acquired:
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())):
raise QueueCancelled('已取消排队,未启动原生操作。')
available = available_now() # Cached predicates only, outside the queue lock.
with self.condition:
if (self.closed or stop is not None and stop.is_set()
@@ -113,13 +113,17 @@ class BackupRecoveryDialog(QDialog):
options = {'version_prompt': lambda choice:self._emit(context, 'choice',choice),'stop':context.stop} if self.recoverer is None else {}
action = lambda: recoverer(request, source, progress=lambda event:self._emit(context, 'progress',event), **options)
if self.native_queue is None: return context.run(action)
from ..operation_queue import QueueCancelled
from ..operation_queue import QueueCancelled, QueueUnavailable
def restore():
self._emit(context, 'progress',{'stage': 'queue_acquired'})
return action()
try:
return self.native_queue.run(restore, stop=context.stop, context=context, waiting=lambda: self._emit(context, 'progress',
return self.native_queue.run(restore, stop=context.stop, context=context, skip_unavailable=True, waiting=lambda: self._emit(context, 'progress',
{'stage': 'waiting_native_slot', 'detail': '已排队,等待当前检查结束'}))
except QueueUnavailable as error:
from ..verify_runner import VerifyResult
return VerifyResult('SKIPPED', stderr=str(error), error_category='NATIVE_SESSION_PENDING',
error_stage='admission')
except QueueCancelled as error:
from ..operation_queue import TaskHandoff
from ..verify_runner import VerifyResult, _handoff_verify_result
+21 -7
View File
@@ -1,7 +1,7 @@
"""A check batch owns its snapshot and yields the native queue after each CBB."""
from PySide6.QtCore import QObject, QThreadPool, Signal
from .workers import ServiceWorker
from ..operation_queue import QueueCancelled, BatchTaskContext
from ..operation_queue import QueueCancelled, QueueUnavailable, BatchTaskContext, request_library_keys
from ..verify_runner import VerifyResult, run_verify, write_batch_report
from ..icdb_maintenance import write_maintenance_report
@@ -30,7 +30,7 @@ class IcdbCheckTask(QObject):
self.running = False
self.report = None
self.report_error = ''
self.retained_libraries = set()
self.retained_libraries = {}
self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1)
def _emit_event(self, event):
@@ -66,9 +66,6 @@ class IcdbCheckTask(QObject):
if self.stop.is_set():
self.results.extend(VerifyResult('SKIPPED', stderr='队列已停止,未操作此 CBB')
for _ in self.requests[len(self.results):])
while len(self.results) < len(self.requests) and str(
self.requests[len(self.results)].lmc_file).casefold() in self.retained_libraries:
self.results.append(VerifyResult('SKIPPED', stderr='同库原生会话尚未释放,未启动新的检查'))
if len(self.results) == len(self.requests):
self._report(); return
if self.paused: return
@@ -76,6 +73,19 @@ class IcdbCheckTask(QObject):
def check():
from ..session_record import library_available, library_wait_reason
try:
keys = request_library_keys(request, self.context)
for index in {self.retained_libraries[key] for key in keys.intersection(self.retained_libraries)}:
previous = self.requests[index]
from ..operation_lifecycle import recheck_failed_release
refreshed = recheck_failed_release(previous.lmc_file, previous.block_name,
self.results[index], stop=self.stop)
if refreshed.safe_to_continue:
self.results[index] = refreshed
self.retained_libraries = {k:v for k,v in self.retained_libraries.items() if v != index}
if keys.intersection(self.retained_libraries):
index = self.retained_libraries[next(iter(keys.intersection(self.retained_libraries)))]
return VerifyResult('SKIPPED', error_category='PREVIOUS_SESSION_UNRELEASED',
error_stage='admission', stderr=f'前项 {self.requests[index].block_name} 的同库会话尚未释放,当前项未启动。')
def execute():
if self.status_reader is not None:
statuses = self.status_reader((request.block_name,), request.lmc_file)
@@ -92,12 +102,15 @@ class IcdbCheckTask(QObject):
from ..operation_lifecycle import recheck_failed_release
result = recheck_failed_release(request.lmc_file, request.block_name, result)
return result
return self.queue.run(execute, stop=self.stop, context=self.context,
return self.queue.run(execute, stop=self.stop, context=self.context, skip_unavailable=True,
wait_state=lambda: (self.paused, library_wait_reason(request.lmc_file)),
ready=lambda: not self.paused,
waiting=lambda: self._emit_event({'stage': 'waiting_native_slot', 'block': request.block_name,
'library': str(request.lmc_file), 'retained': not library_available(request.lmc_file),
'detail': library_wait_reason(request.lmc_file) or '已排队,等待当前原生操作结束'}))
except QueueUnavailable as error:
return VerifyResult('SKIPPED', stderr=str(error), error_category='NATIVE_SESSION_PENDING',
error_stage='admission')
except QueueCancelled as error:
from ..operation_queue import TaskHandoff
from ..verify_runner import _handoff_verify_result
@@ -116,7 +129,8 @@ class IcdbCheckTask(QObject):
request = self.requests[len(self.results)]
name = request.block_name
if not result.safe_to_continue:
self.retained_libraries.add(str(request.lmc_file).casefold())
self.retained_libraries.update({key:len(self.results)
for key in request_library_keys(request, self.context)})
self.results.append(result)
if result.status in ('CANCELLED', 'QUEUE_STOP'): self.stop.set()
self.item_done.emit(name, result)
+7 -7
View File
@@ -1059,7 +1059,7 @@ class MainWindow(QWidget):
event['detail'] = label+'中…'
emit(event)
return action()
return lambda: self.native_queue.run(execute, stop=stop, context=job.context if job else None,
return lambda: self.native_queue.run(execute, stop=stop, context=job.context if job else None, skip_unavailable=True,
wait_state=lambda: library_wait_reason(library),
waiting=lambda: emit({'stage': 'waiting_native_slot',
'library': str(library), 'retained': not library_available(library),
@@ -1442,7 +1442,7 @@ class MainWindow(QWidget):
return result, reasons, lease, library, False
# Full-library status and preflight follow native catalog IO; ten seconds
# is not enough even on a local 364-entry library. Keep one bounded task.
worker = ServiceWorker(lambda:self.native_queue.run(reconcile, context=context, timeout_seconds=120))
worker = ServiceWorker(lambda:self.native_queue.run(reconcile, context=context, timeout_seconds=120, skip_unavailable=True))
self._lifecycle_workers.add(worker)
def completed(payload):
if self._job_current(read_job): deliver(payload)
@@ -1789,12 +1789,12 @@ class MainWindow(QWidget):
safe = all(result.safe_to_continue for result in results)
self._emit_job(job, 'batch_ready', (results, report))
refresh = None
if safe and not job.context.stop.is_set():
from cbb_refresh_verify.operation_queue import QueueCancelled
if safe and affected and not job.context.stop.is_set():
from cbb_refresh_verify.operation_queue import QueueCancelled, QueueUnavailable
try:
refresh = self._queued_action(lambda: self._read_affected_records(affected, library=library, lease=job.lease),
label='批次已结束,状态刷新', library=library, job=job)()
except QueueCancelled:
except (QueueCancelled, QueueUnavailable):
pass # Cancelling the refresh must not erase completed item results.
return results, report, affected, refresh
self._start(action, self._batch_refreshed, queued=False, job=job, bounded=False)
@@ -2158,8 +2158,8 @@ class MainWindow(QWidget):
'已请求取消;检查将停止,原生写入只等待安全结束,不强制终止。'); self._update()
def _failed(self, error):
from cbb_refresh_verify.operation_queue import QueueCancelled
if self.library_lease is not None and not isinstance(error, QueueCancelled):
from cbb_refresh_verify.operation_queue import QueueCancelled, QueueUnavailable
if self.library_lease is not None and not isinstance(error, (QueueCancelled, QueueUnavailable)):
self._retain_path_lease(self.library_lease, hold_busy=True)
self._display_error(error)
@@ -193,12 +193,12 @@ class ManagementDialog(QDialog):
action = lambda: self.runner(requests, adapter=self.adapter, stop=context.stop,
progress=lambda event:self._emit(context, 'progress',event),**choices)
if self.native_queue is None: return context.run(action)
from ..operation_queue import QueueCancelled
from ..operation_queue import QueueCancelled, QueueUnavailable
from ..session_record import library_available, library_wait_reason
try:
if self.runner is run_management_batch:
def item(request, action):
return self.native_queue.run(action, stop=context.stop, context=context,
return self.native_queue.run(action, stop=context.stop, context=context, skip_unavailable=True,
wait_state=lambda: library_wait_reason(request.library),
waiting=lambda: self._emit(context, 'progress',{'stage': 'waiting_native_slot',
'retained': not library_available(request.library),
@@ -206,11 +206,15 @@ class ManagementDialog(QDialog):
return self.runner(requests, adapter=self.adapter, stop=context.stop,
progress=lambda event:self._emit(context, 'progress',event), item_executor=item,
version_prompt=lambda choice:self._emit(context, 'choice',choice), context=context)
return self.native_queue.run(action, stop=context.stop, context=context, waiting=lambda: self._emit(context, 'progress',
return self.native_queue.run(action, stop=context.stop, context=context, skip_unavailable=True, waiting=lambda: self._emit(context, 'progress',
{'stage': 'waiting_native_slot',
'retained': not library_available(self.template.library),
'detail': library_wait_reason(self.template.library) or '已排队,等待当前检查结束'}),
wait_state=lambda: library_wait_reason(self.template.library))
except QueueUnavailable as error:
from ..management import ManagementResult
return [ManagementResult(r.operation, r.library, r.name, r.partition, r.source, r.auto_verify,
'admission', 'SKIPPED', True, str(error)) for r in requests]
except QueueCancelled as error:
from ..operation_queue import TaskHandoff
from ..management import ManagementResult
+8 -4
View File
@@ -1505,7 +1505,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=None, item_executor=None,
context=None):
"""Run serially and stop when database/session safety is unconfirmed."""
"""Run serially; isolate failures and skip writes to resources still retained."""
if max_workers != 1:
raise ValueError('Only serial Verify is supported for the shared Library Manager session')
if context is not None:
@@ -1535,7 +1535,9 @@ def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=Non
or context is not None and context.stop.is_set()):
result = VerifyResult('SKIPPED', stderr='队列已停止,未操作此 CBB')
elif library_keys.intersection(retained_libraries):
result = VerifyResult('SKIPPED', stderr='同库原生会话尚未释放,未启动新的写入')
previous, index = retained_libraries[next(iter(library_keys.intersection(retained_libraries)))]
result = VerifyResult('SKIPPED', error_category='PREVIOUS_SESSION_UNRELEASED',
error_stage='admission', stderr=f'前项 {getattr(previous, "block_name", previous)} 的同库会话尚未释放,当前项未启动。')
else:
try:
def execute():
@@ -1546,9 +1548,11 @@ def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=Non
return result
result = item_executor(request, execute) if item_executor is not None else execute()
except Exception as error:
from .operation_queue import QueueCancelled, TaskHandoff
from .operation_queue import QueueCancelled, QueueUnavailable, TaskHandoff
# An unexpected exception cannot establish database safety.
result = (_handoff_verify_result(error) if isinstance(error, TaskHandoff) else
result = (VerifyResult('SKIPPED', stderr=str(error), error_category='NATIVE_SESSION_PENDING',
error_stage='admission') if isinstance(error, QueueUnavailable) else
_handoff_verify_result(error) if isinstance(error, TaskHandoff) else
VerifyResult('CANCELLED' if isinstance(error, QueueCancelled) else 'FAIL',
stderr=str(error), safe_to_continue=isinstance(error, QueueCancelled)))
results.append(result)