fix: preserve accepted native calls and explain retained queue waits

This commit is contained in:
阿白叔 committed 2026-11-09 14:33:44 +08:00
1 parent d0a5ce5d17
commit 78ff118f82
13 files changed
+357 -30

No files matched your search

+5 -2
View File
@@ -28,9 +28,12 @@ def _phase_pending(phase):
@contextmanager
def worker_phase(operation_id, phase):
def worker_phase(operation_id, phase, *, continuation=False):
with _automation_clients_lock:
if _supervisor_lost.is_set() and phase in ('NATIVE_CALL', 'CLOSING'):
existing = continuation and _native_phases.get(operation_id) == phase and _phase_pending(phase) is True
if continuation and not existing:
raise RuntimeError('WORKER_STATE_UNCONFIRMED: 尚无已派发的原生调用可继续登记')
if _supervisor_lost.is_set() and phase in ('NATIVE_CALL', 'CLOSING') and not existing:
raise RuntimeError('WORKER_CANCELLED: 监督器已退出,未提交新的原生调用')
_native_phases[operation_id] = phase
yield
+3 -2
View File
@@ -798,7 +798,8 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None)
pythoncom.PumpWaitingMessages(); time.sleep(.1)
raise TimeoutError(f'原生窗口未出现:{title}')
_require_add_supervisor(job, root)
app.OnReusableBlocksEditor()
from .session_record import dispatch_native
dispatch_native(job, lambda: app.OnReusableBlocksEditor())
_require_add_supervisor(job, root)
editor = await_window('Reusable Blocks')
tabs = Desktop(backend='uia').window(handle=editor).descendants(control_type='TabItem')
@@ -1271,7 +1272,7 @@ def management_worker_main(request_path):
except (FileNotFoundError, PermissionError):
result['safe_to_continue'] = True
raise
update_worker_state(job, 'NATIVE_CALL', identities=[('native', process.pid)])
update_worker_state(job, 'NATIVE_CALL', identities=[('native', process.pid)], continuation=True)
try:
_write_json(root/'native-process.json', {'pid': process.pid, 'command': command})
except OSError:
+10 -5
View File
@@ -15,9 +15,10 @@ class NativeQueue:
def wake(self):
with self.condition: self.condition.notify_all()
def run(self, action, *, stop=None, waiting=None, ready=lambda: True):
def run(self, action, *, stop=None, waiting=None, ready=lambda: True, wait_state=None):
ticket = object()
acquired, notified = False, False
previous_state = None
with self.condition: self.pending.append((ticket, ready))
try:
while not acquired:
@@ -30,10 +31,14 @@ class NativeQueue:
self.active = acquired = True
else:
self.condition.wait(.1)
if not acquired and not notified and waiting is not None:
notified = True
try: waiting()
except Exception: pass
if not acquired and waiting is not None:
try:
current_state = wait_state() if wait_state is not None else None
if not notified or current_state != previous_state:
waiting()
notified, previous_state = True, current_state
except Exception:
pass
if stop is not None and stop.is_set():
raise QueueCancelled('已取消排队,未启动原生操作。')
return action()
+12 -3
View File
@@ -96,6 +96,15 @@ def retained_session_states(library):
if key in aliases and path in _retained_results]
def library_wait_reason(library):
"""Cached explanation for queue admission; never probe disk or native clients."""
key = _library_key(library)
with _observer_guard:
retained = [path for path, aliases in _retained_libraries.items() if key in aliases]
names = sorted({_retained_results.get(path, {}).get('block') or '当前库' for path in retained})
return '该库有残留会话('+', '.join(names)+'),请查看并处理。' if names else ''
def register_worker_session(worker, job):
"""The launcher must persist identity before opening the worker's gate."""
path = Path(job['session_record_path'])
@@ -106,14 +115,14 @@ def register_worker_session(worker, job):
worker.cbb_library = job['library']
def update_worker_state(job, phase, *, identities=(), write_outcome=None, required=False):
"""required controls journal I/O; a supervisor-loss dispatch veto always raises."""
def update_worker_state(job, phase, *, identities=(), write_outcome=None, required=False, continuation=False):
"""required controls I/O; only existing same-phase calls may continue recording after supervisor loss."""
if not job.get('session_record_path'):
if required:
raise ValueError('原生写入缺少会话记录位置,未提交新的调用')
return False
from .desktop_worker import worker_phase
with worker_phase(job['operation_id'], phase):
with worker_phase(job['operation_id'], phase, continuation=continuation):
path = Path(job['session_record_path']).with_name('worker-state.json')
try:
state = ({'operation_id': job['operation_id'], 'processes': []} if not path.exists()
+4 -2
View File
@@ -65,7 +65,7 @@ class IcdbCheckTask(QObject):
if self.paused: return
request = self.requests[len(self.results)]
def check():
from ..session_record import library_available
from ..session_record import library_available, library_wait_reason
try:
def execute():
if request.block_name in self.ready_names:
@@ -75,9 +75,11 @@ class IcdbCheckTask(QObject):
self.event.emit({'stage': 'icdb_check_start', 'block': request.block_name})
return self.verifier(request)
return self.queue.run(execute, stop=self.stop,
wait_state=lambda: (self.paused, library_wait_reason(request.lmc_file)),
ready=lambda: not self.paused and library_available(request.lmc_file),
waiting=lambda: self.event.emit({'stage': 'waiting_native_slot', 'block': request.block_name,
'detail': '已排队,等待当前原生操作结束'}))
'library': str(request.lmc_file), 'retained': not library_available(request.lmc_file),
'detail': library_wait_reason(request.lmc_file) or '已排队,等待当前原生操作结束'}))
except QueueCancelled as error:
return VerifyResult('CANCELLED', stderr=str(error))
except Exception as error:
+60 -8
View File
@@ -134,6 +134,8 @@ class MainWindow(QWidget):
self._mapping_auto_idle = False
self._mapping_finish_waiters = []
self._closing = self._close_ready = False
self._queue_wait_library = None
self._queue_release_mode = False
self.close_wait_timer = QTimer(self)
self.close_wait_timer.setSingleShot(True)
self.close_wait_timer.setInterval(120_000)
@@ -312,6 +314,10 @@ class MainWindow(QWidget):
self.section_stack.addWidget(management)
layout.addWidget(self.section_stack)
layout.addWidget(self.status_label)
self.queue_release_button = QPushButton('查看残留会话…')
self.queue_release_button.hide()
self.queue_release_button.clicked.connect(lambda: self.check_library_release(queued=True))
layout.addWidget(self.queue_release_button)
self.runtime_log_toggle = QToolButton(); self.runtime_log_toggle.setText('查看运行日志')
self.runtime_log_toggle.setCheckable(True)
self.runtime_log_toggle.toggled.connect(self.output.setVisible)
@@ -413,6 +419,8 @@ class MainWindow(QWidget):
self.backup_restore_button.setEnabled(ready and bool(
self._eligible_names(checked_only=bool(self.selected_records()))))
self.release_library_button.setEnabled(not self.busy and bool(self.lmc_edit.text().strip()))
self.queue_release_button.setVisible(self._queue_wait_library is not None)
self.queue_release_button.setEnabled(self._queue_wait_library is not None and not self._closing)
reasons = []
for operation, widget in (('add', self.add_button), ('update', self.update_button), ('remove', self.remove_button)):
reason = self._management_block_reason(operation)
@@ -484,13 +492,24 @@ class MainWindow(QWidget):
self.output.append(f'未完成会话:{session.get("block") or ""} · '
f'{phase} · {session.get("detail", "")}\n{session["path"]}')
def check_library_release(self):
if self.busy or not self.lmc_edit.text().strip():
def check_library_release(self, checked=False, *, queued=False):
allowed_queue = queued and self._queue_wait_library is not None
if (self.busy and not allowed_queue) or not self.lmc_edit.text().strip():
return
from shiboken6 import isValid
previous = getattr(self, 'release_dialog', None)
if previous is not None and isValid(previous) and previous.isVisible():
previous.raise_()
return
from .residual_release_dialog import ResidualReleaseDialog
library = Path(self.mentor_lmc_path or self.lmc_edit.text().strip())
library = Path(self._queue_wait_library if allowed_queue else self.mentor_lmc_path or self.lmc_edit.text().strip())
self._queue_release_mode = bool(allowed_queue and self.busy)
self.release_dialog = ResidualReleaseDialog(library, self.data_root/'release-checks', self)
self.release_dialog.native_queue = self.native_queue
if self._queue_release_mode:
from cbb_refresh_verify.network_path import release_retained_path_leases
lease = self.library_lease
self.release_dialog.release_finalizer = lambda proof: release_retained_path_leases(proof, current_lease=lease)
self.release_dialog.before_release.connect(self._stop_icdb_check)
self.release_dialog.released.connect(lambda result: self._complete_library_release(self.release_dialog.library, result))
self.release_dialog.finished.connect(self._release_dialog_finished)
@@ -498,10 +517,20 @@ class MainWindow(QWidget):
self.release_dialog.show()
def _release_dialog_finished(self, _=None):
if self._queue_release_mode:
self._queue_release_mode = False
self._update()
return
if self._defer_mapping_finish(self._release_dialog_finished): return
self._finished()
pending = getattr(self, '_resume_batch', None)
if pending and pending['released'] and getattr(self, 'summary', None) is not None:
if pending and pending['released']:
if getattr(self, 'summary', None) is None:
self.summary = self._new_result_summary('_batch_summary')
self.summary.setWindowTitle('继续未执行项')
self._resume_batch_action = self.summary.addButton('继续未执行项', QMessageBox.ActionRole)
self._resume_batch_action.clicked.connect(self._resume_released_batch)
self._update()
self.summary.setText('会话已释放,可以继续未执行项。')
self.summary.show()
@@ -515,6 +544,9 @@ class MainWindow(QWidget):
except Exception as error:
self._failed(error)
return
if result.get('mapping_cleanup_complete') is True:
self._library_release_ready(library, result)
return
lease = self.library_lease
def release():
try:
@@ -600,6 +632,7 @@ class MainWindow(QWidget):
self.management_dialog = ManagementDialog(requests, self, adapter=self.management_adapter,
recovery_from=recovery_from)
self.management_dialog.native_queue = self.native_queue
self.management_dialog.release_requested.connect(self._open_waiting_release)
self.management_dialog.before_execute.connect(lambda names: self._invalidate_check_targets(requests[0].library, names))
self._management_results = []
self.management_dialog.completed.connect(self._management_completed)
@@ -607,6 +640,12 @@ class MainWindow(QWidget):
self.busy = True; self._update()
self.management_dialog.show()
def _open_waiting_release(self, library):
from cbb_refresh_verify.session_record import library_available
if not library_available(library):
self._queue_wait_library = str(library)
self.check_library_release(queued=True)
def reimport_failed(self):
if self.busy or not self._reimport_offers or not self.management_capabilities['update'].supported:
return
@@ -778,12 +817,14 @@ class MainWindow(QWidget):
self.pool.start(self.worker)
def _queued_action(self, action):
from cbb_refresh_verify.session_record import library_available
from cbb_refresh_verify.session_record import library_available, library_wait_reason
library = getattr(self, 'mentor_lmc_path', None) or self.lmc_edit.text()
return lambda: self.native_queue.run(action, stop=self.stop,
ready=lambda: library_available(library),
wait_state=lambda: library_wait_reason(library),
waiting=lambda: self.signals.event.emit({'stage': 'waiting_native_slot',
'detail': '已排队,等待当前原生操作结束'}))
'library': str(library), 'retained': not library_available(library),
'detail': library_wait_reason(library) or '已排队,等待当前原生操作结束'}))
def _icdb_active(self):
return self.icdb_task is not None and self.icdb_task.active
@@ -844,7 +885,13 @@ class MainWindow(QWidget):
name, stage = str(event.get('block', '')), str(event.get('stage', ''))
detail = str(event.get('detail') or stage)
self.icdb_phase.setText(f'{name} · '+({'icdb_check_start': '正在检查',
'icdb_startup_check': '正在打开工程', 'waiting_native_slot': '已排队,等待执行'}.get(stage, detail)))
'icdb_startup_check': '正在打开工程'}.get(stage, detail)))
if stage == 'waiting_native_slot':
self._queue_wait_library = event.get('library') if event.get('retained') else None
self._update()
elif stage == 'icdb_check_start':
self._queue_wait_library = None
self._update()
if not self.busy: self.status_label.setText('后台 ICDB 检查:'+self.icdb_phase.text())
if self.logging_context:
self.logging_context.logger.info('icdb_background block=%s stage=%s detail=%s', name, stage, detail)
@@ -1399,6 +1446,10 @@ class MainWindow(QWidget):
from shiboken6 import isValid
if not isValid(self) or not isValid(self.cbb_table):
return
if event.get('stage') == 'waiting_native_slot':
self._queue_wait_library = event.get('library') if event.get('retained') else None
self.status_label.setText(event.get('detail', '已排队,等待执行'))
self._update()
if event.get('stage') in ('session_handoff', 'save_stop_requested'):
self.status_label.setText(event.get('detail', '当前状态无法确认'))
if (event.get('stage') == 'session_observation' and event.get('status') == 'RELEASED'
@@ -1602,6 +1653,7 @@ class MainWindow(QWidget):
if self.version_dialog is not None:
self.version_dialog.reject()
self.version_dialog = None
self._queue_wait_library = None
self.busy = False; self._update()
def open_logs(self):
@@ -1648,7 +1700,7 @@ class MainWindow(QWidget):
owners = [self, *self.icdb_tasks]
for name in ('management_dialog', 'backup_dialog', 'release_dialog'):
owners.append(getattr(self, name, None))
active = False
active = bool(self.lifecycle_pool.activeThreadCount())
for owner in owners:
try:
pool = getattr(owner, 'pool', None)
+14 -4
View File
@@ -38,6 +38,7 @@ class ManagementSignals(QObject):
class ManagementDialog(QDialog):
completed = Signal(object)
before_execute = Signal(object)
release_requested = Signal(object)
def __init__(self, requests, parent=None, *, adapter=None, runner=None, recovery_from=None):
super().__init__(parent)
@@ -73,6 +74,9 @@ class ManagementDialog(QDialog):
self.auto_verify.setVisible(self.operation != 'remove')
self.status_label = QLabel(MANUAL_BACKUP_NOTICE + ' 更新会先移除再重新导入,失败时请使用手动备份恢复。')
self.status_label.setWordWrap(True)
self.release_wait_button = QPushButton('查看残留会话…')
self.release_wait_button.hide()
self.release_wait_button.clicked.connect(lambda: self.release_requested.emit(self.template.library))
self.output = QTextEdit(); self.output.setReadOnly(True)
self.output.document().setMaximumBlockCount(2000)
self.output.hide()
@@ -93,7 +97,8 @@ class ManagementDialog(QDialog):
layout.addWidget(QLabel(f'目标库:{self.template.library}'))
layout.addWidget(self.table)
layout.addWidget(self.sources_button); layout.addWidget(self.auto_verify)
layout.addWidget(self.status_label); layout.addWidget(self.logs_button); layout.addWidget(self.output)
layout.addWidget(self.status_label); layout.addWidget(self.release_wait_button)
layout.addWidget(self.logs_button); layout.addWidget(self.output)
buttons = QHBoxLayout()
for widget in (self.execute_button, self.stop_button, self.close_button): buttons.addWidget(widget)
layout.addLayout(buttons)
@@ -171,11 +176,14 @@ class ManagementDialog(QDialog):
progress=self.signals.progress.emit)
if self.native_queue is None: return action()
from ..operation_queue import QueueCancelled
from ..session_record import library_available
from ..session_record import library_available, library_wait_reason
try:
return self.native_queue.run(action, stop=self.stop, waiting=lambda: self.signals.progress.emit(
{'stage': 'waiting_native_slot', 'detail': '已排队,等待当前检查结束'}),
ready=lambda: library_available(self.template.library))
{'stage': 'waiting_native_slot',
'retained': not library_available(self.template.library),
'detail': library_wait_reason(self.template.library) or '已排队,等待当前检查结束'}),
ready=lambda: library_available(self.template.library),
wait_state=lambda: library_wait_reason(self.template.library))
except QueueCancelled as error:
from ..management import ManagementResult
return [ManagementResult(r.operation, r.library, r.name, r.partition, r.source, r.auto_verify,
@@ -194,6 +202,7 @@ class ManagementDialog(QDialog):
def _progress(self, event):
stage = str(event.get('stage', ''))
self.release_wait_button.setVisible(stage == 'waiting_native_slot' and bool(event.get('retained')))
text = f'{event.get("block", "")} {STAGE_LABELS.get(stage, RESULT_LABELS.get(stage, "正在处理"))}'
if stage == 'waiting_native_slot': text = str(event.get('detail', '已排队,等待执行'))
self.output.append(str(event))
@@ -239,6 +248,7 @@ class ManagementDialog(QDialog):
request.source, request.auto_verify, 'complete', 'RECOVERY_REQUIRED', False, str(error))])
def _finished(self):
self.release_wait_button.hide()
self.busy = False; self._enabled(True)
def reject(self):
@@ -19,6 +19,7 @@ class ResidualReleaseDialog(QDialog):
self.library, self.evidence_dir = Path(library), Path(evidence_dir)
self.plan = None
self.native_queue = None
self.release_finalizer = None
self.busy = False
self.stop = Event()
self._refresh_after = False
@@ -142,7 +143,8 @@ class ResidualReleaseDialog(QDialog):
from cbb_refresh_verify.residual_sessions import request_native_cancel
self.before_release.emit(); self.stop.clear()
def execute():
action = lambda: request_native_cancel(session, self.library, self.evidence_dir, stop=self.stop)
action = lambda: self._finalize_release_result(
request_native_cancel(session, self.library, self.evidence_dir, stop=self.stop))
return self.native_queue.run(action, stop=self.stop) if self.native_queue is not None else action()
def done(result):
self.message.setText(result.get('detail') or '\n'.join(r.get('detail', '') for r in result['sessions']))
@@ -167,6 +169,16 @@ class ResidualReleaseDialog(QDialog):
self.released.emit(proof)
return True
def _finalize_release_result(self, result):
"""Complete mapping cleanup before the serialized release admits new work."""
proof = result.get('proof', {})
if (self.release_finalizer is not None and proof.get('status') == 'RELEASE_CONFIRMED'
and Path(proof.get('library', '')).absolute() == self.library.absolute()
and all(row.get('release_status') == 'RELEASED' for row in result['sessions'])):
self.release_finalizer(proof)
return {**result, 'proof': {**proof, 'mapping_cleanup_complete': True}}
return result
def answer_prompt(self):
if self.busy or not self.plan: return
row = self.table.currentRow()
@@ -248,7 +260,9 @@ class ResidualReleaseDialog(QDialog):
pending = sum(row.get('release_status') != 'RELEASED' for row in allowed)
self.message.setText(self.message.text()+f'\n确认允许 {len(allowed)} 项,其中未释放 {pending} 项。')
def execute():
action = lambda: release_residual_sessions(plan, self.evidence_dir, stop=self.stop, force=force)
def action():
result = release_residual_sessions(plan, self.evidence_dir, stop=self.stop, force=force)
return self._finalize_release_result(result)
return self.native_queue.run(action, stop=self.stop) if self.native_queue is not None else action()
self._start(execute, done)