fix: hand off UI shutdown without releasing native ownership

This commit is contained in:
阿白叔 committed 2026-11-16 23:28:36 +08:00
1 parent cd7a5e0ca1
commit dbc685b9a5
10 files changed
+454 -52

No files matched your search

@@ -103,7 +103,7 @@ class BackupRecoveryDialog(QDialog):
self.status_label.setText('相同任务已提交,未重复执行。')
return
self.busy = True
self.context = BatchTaskContext(str(request.lmc_file), targets=(name,))
self.context = BatchTaskContext(str(request.lmc_file), targets=(name,), native_policy='external')
context = self.context
self.stop = context.stop
self._set_enabled(False)
+2 -1
View File
@@ -16,7 +16,8 @@ class IcdbCheckTask(QObject):
self.requests = tuple(requests)
self.queue, self.report_root = queue, report_root
self.path_lease = path_lease
self.context = BatchTaskContext(str(self.requests[0].lmc_file), targets=tuple(r.block_name for r in self.requests))
self.context = BatchTaskContext(str(self.requests[0].lmc_file),
targets=tuple(r.block_name for r in self.requests), native_policy='external')
self.status_reader = status_reader
self.verifier = verifier or (lambda req: run_verify(req, progress=self._emit_event,
stop=self.stop, version_prompt=choice_prompt))
+62 -37
View File
@@ -77,10 +77,6 @@ STATUS_LABELS = {
'CRASHED': '状态桥崩溃',
}
# Qt must not destroy a pool whose native observer is still handing off.
_shutdown_pools = set()
def application_icon_path():
return Path(__file__).resolve().parents[1] / 'assets' / 'cbb_refresh_verify.ico'
@@ -137,6 +133,9 @@ class MainWindow(QWidget):
self._lease_pending = 0
self._lease_workers = set()
self._lease_contexts = set()
self._shutdown_leases = {}
self._retention_intents = {}
self._retention_ready = set()
self._mapping_busy = 0
self._mapping_owners = Counter()
self._mapping_auto_owners = set()
@@ -367,7 +366,9 @@ class MainWindow(QWidget):
def _new_job(self, kind, *, library=None, targets=(), lease=None):
library = str(library or self.mentor_lmc_path or self.lmc_edit.text())
lease = self.library_lease if lease is None else lease
context = BatchTaskContext(library, aliases=tuple(_library_path_keys(library, lease)), targets=tuple(targets))
policy = 'external' if kind in ('verify','management','recovery','icdb','catalog','status','native_session') else 'restricted'
context = BatchTaskContext(library, aliases=tuple(_library_path_keys(library, lease)),
targets=tuple(targets), native_policy=policy)
job = SimpleNamespace(context=context, kind=kind, revision=self._view_revision,
lease=lease, requests=(), records={}, active=True, keep_session=False)
self._jobs[context.operation_id] = job
@@ -399,9 +400,11 @@ class MainWindow(QWidget):
paused.resume()
job.active = False
self._jobs.pop(job.context.operation_id, None)
job.context.close(timeout_seconds=0)
state = job.context.close(timeout_seconds=0)
if job.lease is not None and job.lease is not self.library_lease:
if not any(other.lease is job.lease for other in self._jobs.values()):
if state['pending'] or id(job.lease) in self._shutdown_leases:
self._retain_path_lease(job.lease)
elif not any(other.lease is job.lease for other in self._jobs.values()):
self._close_path_lease(job.lease)
if self._job_current(job): self._finished()
@@ -420,11 +423,20 @@ class MainWindow(QWidget):
self.logging_context.logger.warning('library_lease_release_failed error=%s', error)
def _close_path_lease(self, lease):
if id(lease) in self._shutdown_leases: return
if id(lease) in self._retention_intents and id(lease) not in self._retention_ready: return
self._lease_action(lease.close)
def _retain_path_lease(self, lease, *, hold_busy=False):
if lease is not None:
self._lease_action(lease.retain_for_recovery, hold_busy=hold_busy)
self._retention_intents[id(lease)] = lease
self._retention_ready.discard(id(lease))
def retained(_):
self._retention_ready.add(id(lease))
if (not self._closing and lease is not self.library_lease
and not any(job.lease is lease for job in self._jobs.values())):
self._close_path_lease(lease)
self._lease_action(lease.retain_for_recovery, retained, hold_busy=hold_busy, completed_always=True)
def _lease_action(self, action, completed=None, failed=None, *, hold_busy=False,
library=None, completed_always=False):
@@ -442,7 +454,8 @@ class MainWindow(QWidget):
self.busy = True
self._update()
library = library or getattr(getattr(action,'__self__',None),'mentor_path',None)
context = BatchTaskContext(str(library or self.mentor_lmc_path or self.loaded_path or self.data_root))
context = BatchTaskContext(str(library or self.mentor_lmc_path or self.loaded_path or self.data_root),
native_policy='restricted')
self._lease_contexts.add(context)
worker = ServiceWorker(lambda:context.run(action))
self._lease_workers.add(worker)
@@ -636,6 +649,7 @@ class MainWindow(QWidget):
revision, owner_job, lease = self._view_revision, self._current_job, self.library_lease
self.release_dialog = ResidualReleaseDialog(library, self.data_root/'release-checks', self)
dialog = self.release_dialog
dialog.path_lease = lease
self._dialogs.append(dialog)
self.release_dialog.native_queue = self.native_queue
from cbb_refresh_verify.network_path import release_retained_path_leases
@@ -644,7 +658,7 @@ class MainWindow(QWidget):
self.release_dialog.before_release.connect(lambda:release_check.cancel()
if release_check is not None and release_check.active else None)
self.release_dialog.released.connect(lambda result: self._complete_library_release(
library, result, lease=lease, revision=revision))
library, result, lease=lease, revision=revision, owner_job=owner_job))
self.release_dialog.finished.connect(lambda *_:self._release_dialog_finished()
if revision == self._view_revision and owner_job is self._current_job else None)
self.busy = True; self._update()
@@ -669,20 +683,26 @@ class MainWindow(QWidget):
self.summary.setText('会话已释放,可以继续未执行项。')
self.summary.show()
def _complete_library_release(self, library, result, *, lease=None, revision=None):
def _complete_library_release(self, library, result, *, lease=None, revision=None, owner_job=None):
from cbb_refresh_verify.network_path import release_retained_path_leases
lease = self.library_lease if lease is None else lease
revision = self._view_revision if revision is None else revision
if revision is None:
revision, owner_job = self._view_revision, self._current_job
def current():
return not self._closing and revision == self._view_revision and owner_job is self._current_job
def ready():
self._management_unsafe_libraries.discard(_path_key(library))
if revision == self._view_revision and not self._closing: self._library_release_ready(library, result)
if lease is not None and not getattr(lease, '_retained_for_recovery', False):
self._retention_intents.pop(id(lease), None)
self._retention_ready.discard(id(lease))
if current(): self._library_release_ready(library, result)
try:
if (not isinstance(result, dict) or result.get('status') != 'RELEASE_CONFIRMED'
or not (_library_path_keys(result.get('library'), lease)
& _library_path_keys(library, lease))):
raise ValueError('RELEASE_PROOF_UNCONFIRMED: 释放证明未确认或不属于当前中心库。')
except Exception as error:
if revision == self._view_revision: self._display_error(error)
if current(): self._display_error(error)
return
if result.get('mapping_cleanup_complete') is True:
ready()
@@ -694,8 +714,8 @@ class MainWindow(QWidget):
if lease is not None: lease.retain_for_recovery()
raise
self._lease_action(release, lambda _: ready(),
lambda error:self._display_error(error) if revision == self._view_revision else None,
hold_busy=revision == self._view_revision, library=library, completed_always=True)
lambda error:self._display_error(error) if current() else None,
hold_busy=current(), library=library, completed_always=True)
def _library_release_ready(self, library, result):
current_library = _path_key(self.mentor_lmc_path or self.lmc_edit.text().strip())
@@ -1382,7 +1402,7 @@ class MainWindow(QWidget):
def _start_catalog(self, read_job, initial, lease, library, deliver):
from cbb_refresh_verify.models import CbbRecord, LibraryReadResult
context = BatchTaskContext(str(library), aliases=tuple(_library_path_keys(library, lease)))
context = BatchTaskContext(str(library), aliases=tuple(_library_path_keys(library, lease)), native_policy='external')
job = SimpleNamespace(context=context, kind='catalog', revision=read_job.revision,
lease=lease, requests=(), records={}, active=True, keep_session=False)
self._jobs[context.operation_id] = job
@@ -1851,7 +1871,8 @@ class MainWindow(QWidget):
if callback:
callback(records)
library, lease = self.mentor_lmc_path or self.loaded_path, self.library_lease
self._start(lambda: self._read_affected_records(targets, library=library, lease=lease), refreshed)
job = self._new_job('status', library=library, targets=targets, lease=lease)
self._start(lambda: self._read_affected_records(targets, library=library, lease=lease), refreshed, job=job)
return True
def _progress(self, event):
@@ -2167,8 +2188,16 @@ class MainWindow(QWidget):
else:
self._closing = True
self._close_started = time.monotonic()
for job in tuple(self._jobs.values()):
job.context.close(timeout_seconds=0)
owned = {**self._retention_intents, **{id(job.lease):job.lease for job in self._jobs.values()
if job.lease is not None and (job.active or job.keep_session or job.context.snapshot()['pending'])}}
for dialog in self._dialogs:
lease = getattr(dialog,'path_lease',None)
if lease is not None and getattr(dialog,'busy',False): owned[id(lease)] = lease
if self._native_backup_session is not None:
lease = self._native_backup_session.path_lease
if lease is not None: owned[id(lease)] = lease
self._shutdown_leases.update(owned)
handoffs = [job.context.shutdown() for job in tuple(self._jobs.values())]
for context in tuple(self._lease_contexts): context.close(timeout_seconds=0)
for context in tuple(self._lifecycle_contexts): context.close(timeout_seconds=0)
self.native_queue.wake()
@@ -2180,19 +2209,26 @@ class MainWindow(QWidget):
if dialog is not None and getattr(dialog, 'busy', False):
dialog.stop.set()
context = getattr(dialog, 'context', None)
if context is not None: context.close(timeout_seconds=0)
if context is not None: handoffs.append(context.shutdown())
self.busy = True; self._update()
self.setWindowTitle('CBB 刷新校验 · 等待任务安全结束')
self.status_label.setText('正在等待当前操作安全结束,完成后关闭。')
self.close_wait_timer.start()
retained = None
if self._native_backup_session is not None:
self.native_backup_timer.stop()
retained = self._native_backup_session.path_lease
lease, self.library_lease = self.library_lease, None
def release():
if retained is not None: retained.retain_for_recovery()
if lease is not None and lease is not retained: lease.close()
for retained in owned.values(): retained.retain_for_recovery()
if lease is not None and id(lease) not in owned: lease.close()
# Original worker/session registrations already precede native
# admission; this receipt records the UI shutdown, never release.
from cbb_refresh_verify.session_record import write_session_record
receipt = self.data_root/'shutdown'/('close-'+str(time.time_ns())+'.json')
receipt.parent.mkdir(parents=True, exist_ok=True)
write_session_record(receipt,
dict(status='UNCONFIRMED',safe_to_continue=False,task_scopes=handoffs,
retained_mappings=[dict(display=str(getattr(item,'display_path','')),
mentor=str(getattr(item,'mentor_path',''))) for item in owned.values()]))
self._lease_action(release)
self._close_when_idle()
event.ignore()
@@ -2213,20 +2249,9 @@ class MainWindow(QWidget):
active = active or bool(pool is not None and pool.activeThreadCount())
except RuntimeError:
pass # Qt may already have deleted a closed dialog's pool.
if (self._lease_pending or active) and time.monotonic()-getattr(self,'_close_started',time.monotonic()) < 30:
if self._lease_pending or active:
QTimer.singleShot(20, self._close_when_idle)
return
if active:
for pool in (self.lifecycle_pool, self.lease_pool):
pool.setParent(None)
_shutdown_pools.add(pool)
for owner in owners:
pool = getattr(owner, 'pool', None)
if pool is not None:
try:
pool.setParent(None)
_shutdown_pools.add(pool)
except RuntimeError: pass
self.close_wait_timer.stop()
self._close_ready = True
self.close()
@@ -59,7 +59,7 @@ class ManagementDialog(QDialog):
evidence_dir=self.template.evidence_dir.parent/'reimport-recovery', **kwargs)
self.busy = False
self.executed = False
self.context = BatchTaskContext(str(self.template.library))
self.context = BatchTaskContext(str(self.template.library), native_policy='external')
self.stop = self.context.stop
self.ui_job = None
self.admit = None
@@ -177,7 +177,7 @@ class ManagementDialog(QDialog):
if self.admit is not None and not self.admit(tuple(requests)):
self.status_label.setText('相同任务已提交,未重复执行。')
return
self.context = BatchTaskContext(str(self.template.library), targets=tuple(r.name for r in requests))
self.context = BatchTaskContext(str(self.template.library), targets=tuple(r.name for r in requests), native_policy='external')
context = self.context
self.stop = context.stop
self.busy = True; self.executed = True