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

@@ -0,0 +1,39 @@
# Full-review follow-up: comments 344 / 345 / 348 / 326
This revision follows the new November 9 full reviews. The old November 6 deep-review backlog remains outside the user's previously selected scope.
## Backend: #10 / 344
- Status scans default to fresh queries. The low-level explicit checkpoint reuse API remains for compatibility with controlled read-only scans; production status queries continue to use `resume=False`. Its lightweight fingerprint is not described as proof that payload databases are unchanged.
- Change reports include rule version, compared scope, excluded directory categories/suffixes and positional runtime rules from the classifier constants. Unrelated CBB content is still explicitly outside comparison. Counts in the management result refer to compared engineering files.
- Removed the tests-only `pcb_bridge.execution_outcome` helper with optimistic release defaults; active production release checks remain authoritative.
- SHA-256 is computed during streaming of unlocked primary files instead of a separate preliminary source pass. The final source SHA-256 and target SHA-256 remain. This reduces three source reads to two without dropping same-size/same-mtime mutation detection. The review's suggested removal of final source hashing was not adopted because it would weaken the requested source-change check.
Backend commit `e8a1714`; 287 focused regressions passed. Details and exact command are in `docs/reviews/2026-11-05-native-backend.md`.
## UI/CLI: #11 / 345
- Replaced repeated same-purpose result windows with lifecycle-managed dialogs. Task recovery associations survive independent result windows; deleted dialogs/actions are forgotten. Forward integration keeps #12's enabled release/resume paths and recreates a resume action if its old summary was closed.
- Closing waits visibly, including a persistent still-waiting notice after 120 seconds. It does not promise a kill deadline or interrupt a write. The final idle check includes the independent lifecycle pool.
- Optional positive CLI `--limit` bounds requested names in order. Omission retains the existing all-target behavior rather than silently dropping work. Logs distinguish selected/total/remaining and explain retained mappings after exceptions or unsafe results, pointing to confirmed release instead of an unconditional network-drive deletion.
- Removed `if False` branches/dead reload field in the standalone UI PR; forward integration retains the later enabled release behavior. File line-ending rules from the prior tip remain.
UI commit `342a726`; 65 targeted UI/CLI tests passed on its branch. Integration keeps PR13 stop propagation; CLI test doubles were updated to accept and assert that stop input.
## Residual release: #12 / 348
The unreadable-window poisoning and oversized repeated-output findings target the old `5eb4b2d` tree and are already fixed in `651b539`. This revision additionally displays confirmation scope and actual execution result as separate columns, and counts allowed-but-unreleased rows with their reasons. Preview consent never overrides a fresh activity/identity refusal. Residual commit `14c9a74`; 35 targeted tests passed.
## Runtime and queue: #13 / 326
- Native management launch/open/create/close/quit/Add submission/Remove launch and editor entry use `dispatch_native`. It records the pending phase before callback entry, synchronous return records POSTCALL, callback failure records UNCONFIRMED, and asynchronous submission requires its existing explicit result acknowledgment. Save/failure-close helpers retain their atomic registration/start gate.
- Identity recording for an already-started Remove uses explicit continuation semantics: it must match the operation's current pending phase, cannot authorize a new call, and may continue tracking/waiting after supervisor loss. A real boundary regression demonstrates that loss immediately after Popen cannot abandon its wait. `required=False` controls journal errors, not permission to dispatch after supervisor loss.
- Pre-proof snapshots freeze alias generation, block and operation ID. Full-library proofs and operation receipts list `reconciled_blocks` and exact retained sessions; a replaced operation is not acknowledged.
- Cached queue reasons name the retained CBB and expose a release entry in verification, ICDB and management waiting states. NativeQueue emits an updated notice only when the cached wait reason changes, so a task transitioning from running to retained cannot leave a hidden dead-end action. Queue predicates do no filesystem/native I/O.
- The queued release's mapping finalizer runs inside the serialized release action before it admits the waiting native ticket. The completion signal skips later destructive mapping cleanup. This prevents an old proof from clearing a new task's mapping retention. Both normal confirmation and native Cancel use this finalizer. Closing the residual panel does not mark the still-queued parent action finished.
## Validation and limits
The final focused integration run passed 211 tests. New tests were first observed failing for missing dispatch/receipt facts, dispatch veto after accepted Remove, missing queue explanations, changed wait reasons, stale mapping cleanup and dialog lifecycle boundaries. Independent review's two queue timing findings were corrected and re-reviewed with no remaining important introduced finding.
Full-suite counts, source hashes and immutable XML copies are in the accompanying validation JSON. Compilation/diff checks and icon equality are checked on the integrated tree. No frozen package was rebuilt; the old iconfix package does not contain this revision. No real Mentor Save/Close/Add/Remove or shared/network/cross-machine acceptance was performed. ICDB automatic Repair remains off. No merge to main, formal release, issue closure, native address/lock deletion, foreground mouse control, or native process termination is authorized by this validation.
+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)
+1
View File
@@ -150,6 +150,7 @@ def test_released_batch_can_resume_only_its_unexecuted_items(qtbot, tmp_path, mo
window.release_dialog.close()
qtbot.waitUntil(lambda: not window.busy)
assert window.summary.isVisible()
action = window._resume_batch_action
assert action.isEnabled()
calls = []
monkeypatch.setattr(window, '_run', lambda names, **kw: calls.append((names, kw)))
@@ -31,6 +31,8 @@ def test_dispatch_veto_is_not_swallowed_by_optional_journal_mode(tmp_path, monke
with pytest.raises(RuntimeError, match='WORKER_CANCELLED'):
sessions.dispatch_native(job, lambda: pytest.fail('native call after supervisor loss'), required=False)
assert sessions.read_session_record(tmp_path/'worker-state.json', evidence_root=tmp_path)['phase'] == 'PRECALL'
with pytest.raises(RuntimeError, match='WORKER_STATE_UNCONFIRMED'):
sessions.update_worker_state(job, 'NATIVE_CALL', continuation=True)
def test_dispatch_refuses_new_call_if_required_journal_cannot_be_written(tmp_path, monkeypatch):
@@ -89,3 +91,32 @@ def test_release_snapshot_cannot_ack_a_replaced_operation(tmp_path, monkeypatch)
sessions.acknowledge_library_release(dict(status='RELEASE_CONFIRMED', library=str(library)), snapshot)
assert not sessions.library_available(library)
assert sessions.reconciled_retained_sessions(snapshot) == []
def test_parent_loss_after_remove_started_still_records_and_waits(tmp_path, monkeypatch):
import os
from types import SimpleNamespace
from cbb_refresh_verify import native_management as native
lost = Event()
monkeypatch.setattr(desktop, '_supervisor_lost', lost)
job = dict(operation='remove', library=str(tmp_path/'lib.lmc'), desktop='CbbManagement_test',
mentor_home=str(tmp_path), name='A', partition='Logical-Physical', timeout_seconds=1,
supervisor_pid=os.getpid(), operation_id='accepted-remove', session_record_path=str(tmp_path/'session.json'))
request = tmp_path/'request.json'; request.write_text(json.dumps(job))
monkeypatch.setattr(native, '_current_desktop', lambda: (None, job['desktop']))
monkeypatch.setattr(native.NativeManagementAdapter, 'capabilities',
lambda _: {'remove': SimpleNamespace(supported=True)})
monkeypatch.setattr(sessions, 'process_identity', lambda pid: dict(pid=pid, created_handle='native',
image='CleanWGLib.exe', owner_sid='S-1-test', session_id=1))
waited = []
def wait(timeout):
state = sessions.read_session_record(tmp_path/'worker-state.json', evidence_root=tmp_path)
assert state['phase'] == 'NATIVE_CALL' and state['processes'][0]['pid'] == 123456
waited.append(True)
return 0
def launch(*args, **kwargs):
lost.set()
return SimpleNamespace(pid=123456, wait=wait)
monkeypatch.setattr(native.subprocess, 'Popen', launch)
native.management_worker_main(request)
assert waited == [True], 'loss during accepted launch abandoned the native owner'
+158
View File
@@ -0,0 +1,158 @@
from pathlib import Path
from threading import Event
from cbb_refresh_verify import session_record as sessions
def retain(monkeypatch, library):
key = 'controlled-session'
monkeypatch.setattr(sessions, '_retained_libraries', {key: {sessions._library_key(library)}})
monkeypatch.setattr(sessions, '_retained_results', {key: dict(block='BlockedCBB', operation_id='test',
library=str(library), status='UNCONFIRMED', detail='Close result unknown')})
def test_cached_wait_reason_names_retained_block_without_file_io(tmp_path, monkeypatch):
library = tmp_path/'lib.lmc'
retain(monkeypatch, library)
monkeypatch.setattr(Path, 'resolve', lambda *a, **kw: (_ for _ in ()).throw(AssertionError('queue filesystem I/O')))
detail = sessions.library_wait_reason(library)
assert 'BlockedCBB' in detail and '残留' in detail
assert sessions.library_wait_reason(tmp_path/'other.lmc') == ''
def test_queued_action_has_visible_release_entry_and_resumes_after_proof(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify.verify_runner import VerifyResult
window = load_window(qtbot, tmp_path, monkeypatch)
window.show()
library = window.mentor_lmc_path
retain(monkeypatch, library)
finished = Event()
window._start(lambda: VerifyResult('PASS'), lambda _: finished.set())
qtbot.waitUntil(lambda: 'BlockedCBB' in window.status_label.text())
assert window.queue_release_button.isVisible() and window.queue_release_button.isEnabled()
opened = []
monkeypatch.setattr(window, 'check_library_release', lambda **kwargs: opened.append(kwargs))
window.queue_release_button.click()
assert opened == [{'queued': True}]
sessions._retained_libraries.clear()
window.native_queue.wake()
qtbot.waitUntil(finished.is_set)
qtbot.waitUntil(lambda: not window.busy)
assert not window.queue_release_button.isVisible()
def test_release_entry_does_not_clear_the_busy_state_of_a_waiting_ticket(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify import library_lock
window = load_window(qtbot, tmp_path, monkeypatch)
library = window.mentor_lmc_path
retain(monkeypatch, library)
monkeypatch.setattr(library_lock, 'inspect_residual_sessions',
lambda _: dict(library=str(library), sessions=[]))
window.busy = True
window._queue_wait_library = str(library)
window.check_library_release(queued=True)
qtbot.waitUntil(lambda: not window.release_dialog.busy)
window.release_dialog.close()
qtbot.waitUntil(lambda: not window._queue_release_mode)
assert window.busy
window.busy = False
def test_release_mapping_cleanup_finishes_before_waiting_ticket_resumes(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify import library_lock
window = load_window(qtbot, tmp_path, monkeypatch)
cleaned, finished = Event(), Event()
library = window.mentor_lmc_path
retain(monkeypatch, library)
monkeypatch.setattr(library_lock, 'inspect_residual_sessions',
lambda _: dict(library=str(library), sessions=[]))
def backend_release(*a, **kw):
sessions._retained_libraries.clear()
return dict(status='RELEASE_CONFIRMED', sessions=[], proof=dict(status='RELEASE_CONFIRMED',
library=str(library), evidence_path='controlled-proof.json'))
monkeypatch.setattr(library_lock, 'release_residual_sessions', backend_release)
def finalize(*a, **kw):
assert window.native_queue.active, 'proof cleanup must complete inside serialized release'
cleaned.set()
monkeypatch.setattr('cbb_refresh_verify.network_path.release_retained_path_leases', finalize)
def action():
assert cleaned.is_set(), 'new native operation began before old mapping release completed'
finished.set()
window._start(action, lambda _: None)
qtbot.waitUntil(lambda: window._queue_wait_library is not None)
window.check_library_release(queued=True)
qtbot.waitUntil(lambda: not window.release_dialog.busy)
window.release_dialog.confirm_button.click()
qtbot.waitUntil(finished.is_set)
qtbot.waitUntil(lambda: not window.release_dialog.busy)
qtbot.waitUntil(lambda: not window.busy)
window.release_dialog.close()
def test_wait_reason_updates_when_active_task_becomes_a_retained_session(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
window = load_window(qtbot, tmp_path, monkeypatch)
library = window.mentor_lmc_path
retain(monkeypatch, library)
sessions._retained_libraries.clear()
active = Event()
release = Event()
from threading import Thread
first = Thread(target=lambda: window.native_queue.run(lambda: (active.set(), release.wait(5))))
first.start()
qtbot.waitUntil(active.is_set)
try:
window._start(lambda: None, lambda _: None)
qtbot.waitUntil(lambda: '已排队' in window.status_label.text())
assert window._queue_wait_library is None
sessions._retained_libraries['controlled-session'] = {sessions._library_key(library)}
release.set(); first.join(3)
qtbot.waitUntil(lambda: 'BlockedCBB' in window.status_label.text())
assert not window.queue_release_button.isHidden()
finally:
release.set(); first.join(3)
sessions._retained_libraries.clear(); window.native_queue.wake()
qtbot.waitUntil(lambda: not window.busy)
def test_management_wait_shows_same_block_and_emits_release_target(qtbot, tmp_path, monkeypatch):
from cbb_refresh_verify.ui.management_dialog import ManagementDialog
from cbb_refresh_verify.management import ManagementRequest
from cbb_refresh_verify.operation_queue import NativeQueue
from PySide6.QtWidgets import QMessageBox
library = tmp_path/'lib.lmc'
retain(monkeypatch, library)
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **kw: QMessageBox.Yes)
dialog = ManagementDialog([ManagementRequest('remove', library, 'A')], runner=lambda *a, **kw: [])
dialog.native_queue = NativeQueue()
qtbot.addWidget(dialog); dialog.show()
targets = []
dialog.release_requested.connect(targets.append)
dialog.execute_button.click()
qtbot.waitUntil(lambda: 'BlockedCBB' in dialog.status_label.text())
assert dialog.release_wait_button.isVisible()
dialog.release_wait_button.click()
assert targets == [library]
dialog.stop.set()
qtbot.waitUntil(lambda: not dialog.busy)
def test_close_waits_for_independent_release_worker(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify.ui.workers import ServiceWorker
window = load_window(qtbot, tmp_path, monkeypatch)
window.show()
started, release = Event(), Event()
worker = ServiceWorker(lambda: (started.set(), release.wait(5)))
window.lifecycle_pool.start(worker)
qtbot.waitUntil(started.is_set)
try:
window.close()
qtbot.wait(40)
assert window.isVisible(), 'window closed while independent release still owned callbacks'
finally:
release.set()
qtbot.waitUntil(lambda: not window.isVisible())
+4 -2
View File
@@ -122,7 +122,8 @@ def batch_cli(tmp_path, monkeypatch):
monkeypatch.setattr(reader, 'read_library_fast', lambda *a, **kw: LibraryReadResult((
CbbRecord('Ready', 'LP', status='READY'), CbbRecord('One', 'LP'),
CbbRecord('Two', 'LP'), CbbRecord('Three', 'LP'))))
def run(requests):
def run(requests, **kwargs):
assert kwargs.get('stop') is not None
requested.extend(request.block_name for request in requests)
return [VerifyResult('PASS') for _ in requests]
monkeypatch.setattr(runner, 'run_batch', run)
@@ -154,7 +155,8 @@ def test_batch_cli_rejects_nonpositive_limit(batch_cli, value):
@pytest.mark.parametrize('raised', [False, True])
def test_retained_mapping_logs_context_and_confirmed_release_guidance(batch_cli, monkeypatch, raised):
app, runner, log, _, retained = batch_cli
def run(_):
def run(_, **kwargs):
assert kwargs.get('stop') is not None
if raised: raise RuntimeError('native writer status unknown')
return [VerifyResult('FAIL', safe_to_continue=False)]
monkeypatch.setattr(runner, 'run_batch', run)