fix: clear verified queue blockers and exit idle orphan workers

This commit is contained in:
阿白叔 committed 2026-11-09 10:11:36 +08:00
1 parent 96e179ba65
commit ca39fb3517
16 files changed
+537 -70

No files matched your search

+56 -20
View File
@@ -1,6 +1,8 @@
"""Launch automation on a private Windows desktop, never the input desktop."""
import subprocess
import os
import logging
from contextlib import contextmanager
from pathlib import Path
import threading
import win32con
@@ -13,6 +15,39 @@ import win32service
_automation_clients = []
_automation_clients_lock = threading.Lock()
_supervisor_lost = threading.Event()
_native_phases = {}
def _phase_pending(phase):
if phase not in ('PRECALL', 'POSTCALL', 'RELEASE_CHECK', 'FINISHED', 'NATIVE_CALL', 'CLOSING'):
return None
from .operation_lifecycle import stop_disposition
return stop_disposition(call_started=phase != 'PRECALL',
call_returned=phase in ('POSTCALL', 'RELEASE_CHECK', 'FINISHED'),
identity_confirmed=True) == 'WAIT_FOR_RETURN'
@contextmanager
def worker_phase(operation_id, phase):
with _automation_clients_lock:
if _supervisor_lost.is_set() and phase in ('NATIVE_CALL', 'CLOSING'):
raise RuntimeError('WORKER_CANCELLED: 监督器已退出,未提交新的原生调用')
_native_phases[operation_id] = phase
yield
def _record_write_pending(record_path, operation_id=None):
if record_path is None:
return None
from .session_record import read_session_record
path = Path(record_path).with_name('worker-state.json')
try:
state = read_session_record(path, evidence_root=path.parent)
if operation_id is not None and state['operation_id'] != operation_id:
return None
return _phase_pending(state.get('phase'))
except (OSError, ValueError):
return None
def launch_save_helper(command, *, start_gate=None, identity_path=None, operation_id=None, **kwargs):
@@ -58,13 +93,29 @@ def start_supervisor_watchdog(supervisor_pid, *, cancel_path=None, stop_clients=
def watch():
try:
win32event.WaitForSingleObject(parent, win32event.INFINITE)
_supervisor_lost.set()
with _automation_clients_lock:
_supervisor_lost.set()
if cancel_path is not None:
Path(cancel_path).touch()
try:
Path(cancel_path).touch()
except OSError:
logging.getLogger(__name__).warning('Unable to record orphan cancellation', exc_info=True)
if session_record_path is not None:
from .session_record import write_session_record
write_session_record(Path(session_record_path).with_name('supervisor-lost.json'),
{'operation_id': operation_id, 'phase': 'SUPERVISOR_LOST'})
try:
write_session_record(Path(session_record_path).with_name('supervisor-lost.json'),
{'operation_id': operation_id, 'phase': 'SUPERVISOR_LOST'})
except (OSError, ValueError):
logging.getLogger(__name__).warning('Unable to record supervisor loss', exc_info=True)
while True:
with _automation_clients_lock:
pending = _record_write_pending(session_record_path, operation_id)
# The same gate blocks new calls/helpers after loss. A stale
# POSTCALL on disk cannot override an active in-memory call.
if (pending is False and _phase_pending(_native_phases.get(operation_id)) is False
and all(helper.poll() is not None for helper in _automation_clients)):
os._exit(75) # This Python worker only; native children remain untouched.
threading.Event().wait(.2)
finally:
parent.Close()
@@ -232,22 +283,7 @@ class DesktopWorker:
register_worker_session(self, job)
def native_write_pending(self):
if not getattr(self, 'session_record_path', None):
return None
from .session_record import read_session_record
path = self.session_record_path.with_name('worker-state.json')
try:
state = read_session_record(path, evidence_root=path.parent)
from .operation_lifecycle import stop_disposition
phase = state.get('phase')
started = (False if phase == 'PRECALL' else True if phase in
('NATIVE_CALL', 'CLOSING', 'POSTCALL', 'RELEASE_CHECK', 'FINISHED') else None)
returned = (False if phase in ('PRECALL', 'NATIVE_CALL', 'CLOSING') else True if phase in
('POSTCALL', 'RELEASE_CHECK', 'FINISHED') else None)
return stop_disposition(call_started=started, call_returned=returned,
identity_confirmed=True) in ('WAIT_FOR_RETURN', 'OBSERVE_UNCONFIRMED')
except (OSError, ValueError):
return None
return _record_write_pending(getattr(self, 'session_record_path', None))
def request_stop(self):
if not hasattr(self, 'cancel_path'):
+3
View File
@@ -528,6 +528,8 @@ def release_retained_library(library, evidence_dir, *, block_name=None):
"""
import win32con, win32event, win32file
library = Path(library).resolve(strict=True)
from .session_record import retained_session_snapshot, acknowledge_library_release
retained = retained_session_snapshot(library)
evidence = Path(evidence_dir).resolve()
if evidence.is_relative_to(library.parent) or library.parent.is_relative_to(evidence):
raise ValueError('释放检查证据必须位于目标库之外。')
@@ -584,6 +586,7 @@ def release_retained_library(library, evidence_dir, *, block_name=None):
if owner:
owner['handle'].Close()
del _owners[lease.key]
acknowledge_library_release(record, retained, block_name=scoped)
return record
finally:
if external is not None:
+2 -13
View File
@@ -928,19 +928,6 @@ def execute_job(job, emit):
lm_session.close()
def _terminate_pid(pid, *, timeout=20):
"""Terminate a validated automation helper PID, never its native children."""
try:
subprocess.run(
[str(Path(os.environ.get('WINDIR', r'C:\Windows'))/'System32'/'taskkill.exe'), '/PID', str(int(pid)), '/F'],
capture_output=True,
timeout=timeout,
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0),
)
except Exception:
pass
def cleanup_verify_processes(lm_pid, worker_pid, worker_parent_pid=None, *,
expected_pcb=None, baseline_pids=(), emit=None):
"""Observe native process release without interrupting database writes.
@@ -1025,6 +1012,8 @@ def worker_main(request_path):
try:
if job.get('supervisor_pid'):
from .session_record import update_worker_state
update_worker_state(job, 'PRECALL')
from .desktop_worker import start_supervisor_watchdog
start_supervisor_watchdog(job['supervisor_pid'], cancel_path=job.get('cancel_signal'), stop_clients=True,
supervisor_identity=job.get('supervisor_identity'),
@@ -1224,6 +1224,8 @@ def management_worker_main(request_path):
raise RuntimeError('原生管理操作仅允许在本次私有桌面执行。')
_require_management_continuation(job, root)
if job.get('cancel_signal'):
from .session_record import update_worker_state
update_worker_state(job, 'PRECALL')
from .desktop_worker import start_supervisor_watchdog
start_supervisor_watchdog(job['supervisor_pid'], cancel_path=job['cancel_signal'],
supervisor_identity=job.get('supervisor_identity'),
@@ -512,6 +512,10 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, ca
or Path(proof.get('library', '')).resolve() != library):
raise ValueError('释放证明与当前库不一致')
result['status'] = 'RELEASE_CONFIRMED'
from .session_record import record_session_release
errors = record_session_release(proof, plan.get('runtime_sessions', []))
if errors:
result['evidence_error'] = ';'.join(errors)
except BaseException as error:
result.update(status='PARTIAL', detail=f'{type(error).__name__}: {error}')
if not isinstance(error, Exception):
+120 -30
View File
@@ -15,6 +15,7 @@ IDENTITY_KEYS = ('pid', 'created_handle', 'image', 'owner_sid', 'session_id')
_observers = {}
_observer_guard = threading.Lock()
_retained_libraries = {}
_retained_results = {}
def _library_key(library):
@@ -28,6 +29,61 @@ def library_available(library):
return not any(key in aliases for aliases in _retained_libraries.values())
def retained_session_snapshot(library):
key = _library_key(library)
with _observer_guard:
return {path: (aliases, _retained_results.get(path, {}).get('block'))
for path, aliases in _retained_libraries.items() if key in aliases}
def acknowledge_library_release(proof, snapshot, *, block_name=None):
"""Called under fresh proof handles; never clear a newer handoff."""
if proof.get('status') != 'RELEASE_CONFIRMED':
return
key = _library_key(proof['library'])
with _observer_guard:
records = [dict(_retained_results.get(path, {}), path=path)
for path, (aliases, block) in snapshot.items()
if key in aliases and _retained_libraries.get(path) is aliases
and (block_name is None or block == block_name)]
record_session_release(proof, records)
with _observer_guard:
for path, (aliases, block) in snapshot.items():
if (key in aliases and _retained_libraries.get(path) is aliases
and (block_name is None or block == block_name)):
_retained_libraries.pop(path, None)
_retained_results.pop(path, None)
def record_session_release(proof, records):
"""Persist a past proof only for the pre-proof operation, never replay it."""
errors = []
if proof.get('status') != 'RELEASE_CONFIRMED':
return errors
library = Path(proof['library']).resolve()
for record in records:
try:
path = Path(record['path'])
session = read_session_record(path, evidence_root=path.parent)
if (session['operation_id'] != record.get('operation_id')
or Path(session['library']).resolve() != library):
continue
write_session_record(path.with_name('observation-release-'+uuid4().hex+'.json'), {
'operation_id': session['operation_id'], 'library': str(library),
'status': 'RELEASED', 'release_proof': proof})
except (OSError, ValueError, KeyError) as error:
errors.append(str(error))
logging.getLogger(__name__).warning('Unable to record session release', exc_info=True)
return errors
def retained_session_states(library):
key = _library_key(library)
with _observer_guard:
return [dict(_retained_results[path], path=path) for path, aliases in _retained_libraries.items()
if key in aliases and path in _retained_results]
def register_worker_session(worker, job):
"""The launcher must persist identity before opening the worker's gate."""
path = Path(job['session_record_path'])
@@ -43,26 +99,28 @@ def update_worker_state(job, phase, *, identities=(), write_outcome=None, requir
if required:
raise ValueError('原生写入缺少会话记录位置,未提交新的调用')
return False
path = Path(job['session_record_path']).with_name('worker-state.json')
try:
state = ({'operation_id': job['operation_id'], 'processes': []} if not path.exists()
else read_session_record(path, evidence_root=path.parent))
if state['operation_id'] != job['operation_id']:
raise ValueError('工作状态操作身份不一致')
for role, pid in identities:
if pid and not any(p['pid'] == pid for p in state['processes']):
state['processes'].append({'role': role, **process_identity(pid)})
state['phase'] = phase
if write_outcome is not None:
state['write_outcome'] = write_outcome
write_session_record(path, state)
return True
except Exception:
if required:
raise
# An unavailable journal cannot interrupt an already executing COM call.
logging.getLogger(__name__).warning('Worker session journal unavailable', exc_info=True)
return False
from .desktop_worker import worker_phase
with worker_phase(job['operation_id'], phase):
path = Path(job['session_record_path']).with_name('worker-state.json')
try:
state = ({'operation_id': job['operation_id'], 'processes': []} if not path.exists()
else read_session_record(path, evidence_root=path.parent))
if state['operation_id'] != job['operation_id']:
raise ValueError('工作状态操作身份不一致')
for role, pid in identities:
if pid and not any(p['pid'] == pid for p in state['processes']):
state['processes'].append({'role': role, **process_identity(pid)})
state['phase'] = phase
if write_outcome is not None:
state['write_outcome'] = write_outcome
write_session_record(path, state)
return True
except Exception:
if required:
raise
# An unavailable journal cannot interrupt an already executing COM call.
logging.getLogger(__name__).warning('Worker session journal unavailable', exc_info=True)
return False
def process_identity(pid):
@@ -135,11 +193,12 @@ def _session(path, root):
def _result(status, detail='', *, session=None, state=None, proof=None):
return {'status': status, 'detail': detail, 'library': (session or {}).get('library'),
'block': (session or {}).get('block'),
'operation_id': (session or {}).get('operation_id'),
'phase': (state or {}).get('phase', 'UNCONFIRMED'), 'release_proof': proof}
def _reconcile(path, root, handles, stack):
def _reconcile(path, root, handles, stack, *, release=True):
import pywintypes, win32api, win32con, win32event
from .residual_sessions import _handle_identity, _force_ownership
session, state, processes = _session(path, root)
@@ -176,6 +235,8 @@ def _reconcile(path, root, handles, stack):
active = True
if active:
return _result('ACTIVE', '原生调用尚未确认返回', session=session, state=state)
if not release:
return _result('UNCONFIRMED', '记录中的进程已退出,需确认库占用已释放', session=session, state=state)
from .library_lock import release_retained_library
try:
proof = release_retained_library(session['library'], Path(path).parent/'release-proof',
@@ -197,17 +258,28 @@ def reconcile_session_record(path, *, evidence_root):
return _result('UNCONFIRMED', str(error))
def observe_retained_session(path, *, evidence_root, stop=None, progress=None, process=None):
def inspect_session_record(path, *, evidence_root):
"""Observe process identities without touching the production library."""
with ExitStack() as stack:
try:
return _reconcile(Path(path), Path(evidence_root), {}, stack, release=False)
except Exception as error:
return _result('UNCONFIRMED', str(error))
def observe_retained_session(path, *, evidence_root, stop=None, progress=None, process=None,
observe_only=False):
stop = stop if stop is not None else threading.Event()
observation = Path(path).with_name('observation-' + uuid4().hex + '.json')
with ExitStack() as stack:
handles = {}
while True:
try:
result = _reconcile(Path(path), Path(evidence_root), handles, stack)
result = _reconcile(Path(path), Path(evidence_root), handles, stack, release=not observe_only)
except Exception as error:
result = _result('UNCONFIRMED', str(error))
if process is not None and process.poll() is not None and getattr(process, 'cbb_library', None):
if (not observe_only and process is not None and process.poll() is not None
and getattr(process, 'cbb_library', None)):
try:
from .library_lock import release_retained_library
proof = release_retained_library(process.cbb_library, Path(path).parent/'release-proof')
@@ -216,7 +288,7 @@ def observe_retained_session(path, *, evidence_root, stop=None, progress=None, p
session={'library': str(process.cbb_library)}, proof=proof)
except Exception:
pass
if result['status'] == 'IDENTITY_CHANGED':
if result['status'] == 'IDENTITY_CHANGED' and not observe_only:
try:
from .library_lock import release_retained_library
proof = release_retained_library(result['library'], Path(path).parent/'release-proof')
@@ -233,7 +305,8 @@ def observe_retained_session(path, *, evidence_root, stop=None, progress=None, p
progress(result)
except Exception:
logging.getLogger(__name__).warning('Observation callback failed', exc_info=True)
if result['status'] == 'RELEASED' or stop.is_set():
if (result['status'] == 'RELEASED' or stop.is_set()
or observe_only and result['status'] != 'ACTIVE'):
return result
if not handles and process is not None and process.poll() is None:
stop.wait(1)
@@ -243,24 +316,38 @@ def observe_retained_session(path, *, evidence_root, stop=None, progress=None, p
stop.wait(5 if result['status'] in ('UNCONFIRMED', 'IDENTITY_CHANGED') else 1)
def handoff_session(path, *, evidence_root, process=None, progress=None, stop=None):
def handoff_session(path, *, evidence_root, process=None, progress=None, stop=None, observe_only=False):
"""Retain exact handles in memory until the observer independently releases."""
key = str(Path(path).absolute()).casefold()
try:
session = read_session_record(path, evidence_root=evidence_root)
library = session['library']
except (OSError, ValueError, KeyError):
session = {}
library = getattr(process, 'cbb_library', None)
aliases = {_library_key(library), _library_key(Path(library).resolve())} if library else set()
with _observer_guard:
if key in _observers:
return
_retained_libraries[key] = aliases
_retained_results[key] = {'status': 'UNCONFIRMED', 'phase': 'UNCONFIRMED',
'library': str(library) if library else None, 'block': session.get('block'),
'detail': '正在核对残留会话', 'operation_id': session.get('operation_id')}
def notify(value):
with _observer_guard:
if _retained_libraries.get(key) is aliases:
previous = _retained_results[key]
_retained_results[key] = {**previous, **value,
'library': value.get('library') or previous['library'],
'operation_id': value.get('operation_id') or previous['operation_id'],
'block': value.get('block') or previous['block']}
if progress is not None:
progress(value)
def observe():
result = None
try:
result = observe_retained_session(path, evidence_root=evidence_root, progress=progress,
stop=stop, process=process)
result = observe_retained_session(path, evidence_root=evidence_root, progress=notify,
stop=stop, process=process, observe_only=observe_only)
if process is not None and process.poll() is not None:
process.close()
return result
@@ -269,6 +356,7 @@ def handoff_session(path, *, evidence_root, process=None, progress=None, stop=No
_observers.pop(key, None)
if result and result['status'] == 'RELEASED':
_retained_libraries.pop(key, None)
_retained_results.pop(key, None)
thread = threading.Thread(target=observe, name='retained-native-session', daemon=True)
_observers[key] = (thread, process)
thread.start()
@@ -308,7 +396,9 @@ def discover_sessions(evidence_root, *, library=None):
continue
if library is not None and _library_key(value.get('library', '')) != _library_key(library):
continue
value = {**value, 'path': str(path), **reconcile_session_record(path, evidence_root=root)}
observed = inspect_session_record(path, evidence_root=root)
value = {**value, **observed, 'library': value.get('library'),
'block': value.get('block'), 'operation_id': value['operation_id'], 'path': str(path)}
except (OSError, ValueError):
continue
found.append(value)
+1
View File
@@ -457,6 +457,7 @@ class MainWindow(QWidget):
for session in sessions:
if session['status'] == 'ACTIVE':
handoff_session(session['path'], evidence_root=root,
observe_only=True,
progress=lambda value: notify({'stage': 'session_observation', **value}))
return unfinished, sessions
worker = ServiceWorker(inspect)
@@ -30,6 +30,9 @@ class ResidualReleaseDialog(QDialog):
self.message = QLabel('正在检查当前库关联的会话…')
self.message.setWordWrap(True)
layout.addWidget(self.message)
self.runtime_label = QLabel()
self.runtime_label.setWordWrap(True)
layout.addWidget(self.runtime_label)
self.table = QTableWidget(0, 6)
self.table.setHorizontalHeaderLabels(['工程', '程序', 'PID', '状态', '窗口位置', '程序路径'])
self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
@@ -155,6 +158,7 @@ class ResidualReleaseDialog(QDialog):
or any(r.get('release_status') != 'RELEASED' for r in result['sessions'])):
return False
self.plan = None
self.runtime_label.clear()
self.released.emit(proof)
return True
@@ -191,10 +195,19 @@ class ResidualReleaseDialog(QDialog):
elif not plan['sessions']:
text += '确认后将复查库占用状态。'
self.message.setText(text)
states = {'ACTIVE': '进行中', 'UNCONFIRMED': '待核对', 'IDENTITY_CHANGED': '待核对'}
self.runtime_label.setText('\n'.join(
f'{states.get(row["status"], "待核对")} · {row.get("block") or "当前库"} · '
f'{row.get("detail") or "操作状态需重新核对"}' for row in plan.get('runtime_sessions', [])))
def inspect():
from cbb_refresh_verify.network_path import select_library_file
from cbb_refresh_verify.session_record import discover_sessions, retained_session_states
library = self.library if self.library.suffix.casefold() == '.lmc' else select_library_file(self.library)
return inspect_residual_sessions(library)
plan = inspect_residual_sessions(library)
states = {row['path']: row for row in retained_session_states(library)}
states.update({str(Path(row['path']).absolute()).casefold(): row for row in
discover_sessions(self.evidence_dir.parent, library=library)})
return {**plan, 'runtime_sessions': list(states.values())}
self._start(inspect, ready)
def force_release(self):