fix: bound task handoff and preserve native writer ownership

This commit is contained in:
阿白叔 committed 2026-11-16 18:57:36 +08:00
1 parent 0440b2efbf
commit ddff6bd857
18 files changed
+1397 -118

No files matched your search

+102 -39
View File
@@ -545,14 +545,57 @@ def _cleanup_session_processes(root, *, lm_pid, target_pid, pcb, pcb_baseline, l
def run_verify(request, *, progress=None, flag_reader=None, process_runner=None, port_check=None,
dialog_supervisor_factory=None, version_prompt=None, stop=None):
# Cover contents checking, native work and final state reads with one
# session-wide mutex. The worker-stage lock below is reentrant on Windows.
import win32event, win32con
dialog_supervisor_factory=None, version_prompt=None, stop=None, context=None,
admission_timeout_seconds=10):
from .operation_queue import BatchTaskContext, TaskHandoff, current_context, task_stop
options = dict(progress=progress, flag_reader=flag_reader, process_runner=process_runner,
port_check=port_check, dialog_supervisor_factory=dialog_supervisor_factory,
version_prompt=version_prompt)
bound = current_context()
if bound is None:
# Management may call Verify while holding a same-thread lease. Do not
# transfer that transaction to a different thread.
import threading
from .library_lock import _guard, _owners
with _guard:
nested = any(v['thread'] == threading.get_ident() and v['depth'] > 0
for v in _owners.values())
if not nested:
from .operation_queue import request_library_keys
bound = context or BatchTaskContext(library=str(request.lmc_file),
aliases=tuple(sorted(request_library_keys(request))), targets=(request.block_name,))
try:
return bound.run(lambda: run_verify(request, stop=stop, **options),
stop=stop, timeout_seconds=admission_timeout_seconds)
except TaskHandoff as error:
result = _handoff_verify_result(error)
_notify_progress(bound.guard_callback(progress) if progress else None,
dict(stage='task_handoff', operation_id=bound.operation_id,
library=bound.library, status=result.status, resource_scope=error.scope))
return result
if bound is not None and progress is not None:
options['progress'] = bound.guard_callback(progress)
return _run_verify_task(request, stop=task_stop(stop), **options)
def _handoff_verify_result(error):
known = error.result if isinstance(error.result, VerifyResult) else None
result = known or VerifyResult('CANCELLED' if error.cancelled else 'TIMEOUT')
return replace(result, status='FAIL' if result.status == 'PASS' else result.status,
stderr=result.stderr or str(error), safe_to_continue=False,
error_stage=result.error_stage or 'admission_or_finalization',
error_category=result.error_category or 'TASK_HANDOFF',
release_proof=dict(lease_state='PENDING', resource_scope=error.scope,
blocked_resources=error.scope.get('resources', [])))
def _run_verify_task(request, *, progress=None, flag_reader=None, process_runner=None, port_check=None,
dialog_supervisor_factory=None, version_prompt=None, stop=None):
# Admission/finalization keep only the library lease. Native launch paths
# acquire the host channel after slow metadata has returned.
from .operation_queue import check_active
from .com_runtime import initialize_com, uninitialize_com
initialized = initialize_com()
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
acquired = False
library_lock = None
previous_release = None
release_confirmed = True
@@ -563,11 +606,7 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
from .library_lock import _supervisor_alive
return bool(remaining_clients) and not any(_supervisor_alive(pid) for pid in remaining_clients)
try:
acquired = win32event.WaitForSingleObject(mutex, 0) in (
win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
if not acquired:
return VerifyResult('BLOCKED', stderr='已有 CBB 校验任务运行,请等待结束。',
safe_to_continue=True, error_category='NATIVE_CHANNEL_BUSY')
check_active()
if request.maintenance:
from .maintenance_entry import run_icdb_check
return run_icdb_check(request, progress=progress, stop=stop)
@@ -576,10 +615,13 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
if Path(request.lmc_file).is_file():
try:
previous_release = recheck_previous_release(request.lmc_file,
Path(request.evidence_dir)/'previous-release', block_name=request.block_name, progress=progress)
Path(request.evidence_dir)/'previous-release', block_name=request.block_name,
progress=progress, stop=stop)
check_active()
library_lock = LibraryLock(request.lmc_file, checkpoint=False,
safe_to_release=clients_released)
library_lock.__enter__()
check_active()
except LibraryBusy as error:
return VerifyResult('FAIL', stderr=str(error), error_category='LIBRARY_IN_USE')
except (OSError, ValueError, RuntimeError, pywintypes.error) as error:
@@ -691,14 +733,12 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
if library_lock is not None:
library_lock.__exit__(None, None, None)
finally:
if acquired:
win32event.ReleaseMutex(mutex)
mutex.Close()
uninitialize_com(initialized)
def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_runner=None,
port_check=None, dialog_supervisor_factory=None, version_prompt=None, stop=None):
from .operation_queue import remember_result
timing = RunTimings()
result = _run_verify(request, timing=timing, progress=progress, flag_reader=flag_reader,
process_runner=process_runner, port_check=port_check,
@@ -722,6 +762,7 @@ def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_
result = replace(result, status='FAIL', stderr='原生会话或自动化客户端尚未退出。')
except (OSError, ValueError, KeyError):
pass
remember_result(result)
if result.status not in {'PASS', 'SKIPPED', 'QUEUE_STOP', 'CANCELLED'} and result.evidence_path:
job_path = result.evidence_path.with_name('request.json')
if job_path.is_file():
@@ -764,6 +805,7 @@ def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_
if result.status not in {"PASS", "SKIPPED"} else ""),
error_stage=(result.error_stage or (unfinished[-1] if unfinished else 'execution')
if result.status not in {"PASS", "SKIPPED"} else ""))
remember_result(result)
if result.evidence_path:
_write_optional_evidence(result.evidence_path, {'block_name': request.block_name, **asdict(result)})
_write_optional_evidence(result.evidence_path.with_name('performance.json'), {
@@ -819,7 +861,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
except Exception:
# Cleanup must never hide or change the verification result.
pass
return replace(result, evidence_path=result_path)
from .operation_queue import remember_result
return remember_result(replace(result, evidence_path=result_path))
if stop is not None and stop.is_set():
return finish(VerifyResult('CANCELLED', stderr='已取消,未启动校验。'))
@@ -843,7 +886,9 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
'detail': ' '.join(command)})
timing.begin('content_check')
try:
exit_code, stdout, stderr, timed_out = runner(command, request.timeout_seconds, Path(request.lmc_file).parent)
from .operation_queue import native_channel
with native_channel():
exit_code, stdout, stderr, timed_out = runner(command, request.timeout_seconds, Path(request.lmc_file).parent)
finally:
timing.end('content_check')
combined = '\n'.join(part for part in (stdout, stderr) if part)
@@ -915,17 +960,15 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
from .desktop_worker import DesktopWorker
from .dialog_supervisor import AgentDialogBackend, DialogSupervisor, Win32DialogBackend
from .dialog_models import DialogPhase
import win32event, win32con
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
lock_status = win32event.WaitForSingleObject(mutex, 0)
if lock_status not in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED):
mutex.Close()
return finish(VerifyResult('BLOCKED', stderr='已有 CBB 校验任务运行;本次未启动。',
safe_to_continue=True, error_category='NATIVE_CHANNEL_BUSY'))
from .operation_queue import check_active, native_channel
check_active()
worker_launch_attempted = False
native = native_channel()
phase_entered = False
try:
timing.begin('worker_setup')
with (root/'worker.log').open('w', encoding='utf-8') as log:
check_active()
worker_launch_attempted = True
if request.interactive_input:
process = DesktopWorker(
@@ -965,6 +1008,13 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
)
if stop is not None and stop.is_set():
raise InterruptedError('VERIFY_CANCELLED: 启动已取消,未启动 PCB')
check_active()
try:
native.__enter__()
phase_entered = True
except RuntimeError as error:
return finish(VerifyResult('BLOCKED', stderr=str(error), safe_to_continue=False,
error_category='NATIVE_CHANNEL_BUSY'))
Path(job['start_gate']).touch()
while process.poll() is None:
if stop is not None and stop.is_set():
@@ -1188,6 +1238,10 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
{'stage': 'session_observation', 'block': request.block_name, **state}))
_notify_progress(progress, {'stage': 'session_handoff', 'block': request.block_name,
'detail': '已转后台观察,可查看状态'})
if getattr(process, 'native_write_pending', lambda: None)() is not False:
from .operation_queue import hold_native_handoff
hold_native_handoff(process, process.session_record_path)
worker_exited = process.poll() is not None
except Exception as error:
close_errors.append(str(error))
if 'process' in locals():
@@ -1279,8 +1333,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
except OSError:
pass
finally:
win32event.ReleaseMutex(mutex)
mutex.Close()
if phase_entered:
native.__exit__(None, None, None)
if result.status == 'PASS' and not request.diagnostic_only:
timing.begin('library_flag')
@@ -1290,9 +1344,10 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
if progress:
_notify_progress(progress, {'stage': 'library_flag_probe', 'block': request.block_name, **record})
try:
probe = read_library_flag_with_retry(
flag_reader or read_library_flag_if_available, Path(request.lmc_file),
request.block_name, on_attempt=record_attempt)
with native_channel():
probe = read_library_flag_with_retry(
flag_reader or read_library_flag_if_available, Path(request.lmc_file),
request.block_name, on_attempt=record_attempt)
result = apply_post_verify_status(result, probe)
result = replace(result, bridge_attempts=tuple(bridge_records))
_write_optional_evidence(root/'bridge-status.json', bridge_records)
@@ -1304,20 +1359,27 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
return finish(result)
def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=None, item_executor=None):
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."""
if max_workers != 1:
raise ValueError('Only serial Verify is supported for the shared Library Manager session')
if context is not None:
stop = stop if stop is not None else context.stop
progress = context.guard_callback(progress) if progress is not None else None
if verifier is None:
verifier = lambda request: run_verify(request, flag_reader=read_library_flag_if_available, stop=stop) # noqa: E731
verifier = lambda request: run_verify(request, flag_reader=read_library_flag_if_available,
stop=stop, context=context) # noqa: E731
results = []
queue_stop = False
retained_libraries = set()
for request in requests:
library_key = str(getattr(request, 'lmc_file', '__injected_verifier_scope__')).casefold()
if queue_stop or (stop is not None and stop.is_set()):
from .operation_queue import request_library_keys
library_keys = request_library_keys(request, context)
if (queue_stop or stop is not None and stop.is_set()
or context is not None and context.stop.is_set()):
result = VerifyResult('SKIPPED', stderr='队列已停止,未操作此 CBB')
elif library_key in retained_libraries:
elif library_keys.intersection(retained_libraries):
result = VerifyResult('SKIPPED', stderr='同库原生会话尚未释放,未启动新的写入')
else:
try:
@@ -1325,18 +1387,19 @@ def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=Non
result = verifier(request)
if not result.safe_to_continue:
from .operation_lifecycle import recheck_failed_release
result = recheck_failed_release(request.lmc_file, request.block_name, result)
result = recheck_failed_release(request.lmc_file, request.block_name, result, stop=stop)
return result
result = item_executor(request, execute) if item_executor is not None else execute()
except Exception as error:
from .operation_queue import QueueCancelled
from .operation_queue import QueueCancelled, TaskHandoff
# An unexpected exception cannot establish database safety.
result = VerifyResult('CANCELLED' if isinstance(error, QueueCancelled) else 'FAIL',
stderr=str(error), safe_to_continue=isinstance(error, QueueCancelled))
result = (_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)
# Never start another writer after an unconfirmed native shutdown.
if not result.safe_to_continue:
retained_libraries.add(library_key)
retained_libraries.update(library_keys)
queue_stop = queue_stop or result.status in {'QUEUE_STOP', 'CANCELLED'}
if queue_stop and stop is not None:
stop.set()