fix: reconcile cancelled sessions and resume queued native work

This commit is contained in:
阿白叔 committed 2026-11-17 08:37:23 +08:00
1 parent 845ae58690
commit 7cc65f78da
10 files changed
+637 -18

No files matched your search

+11 -4
View File
@@ -365,14 +365,16 @@ def _pending_prompt(windows, *, closing=False, frame=None, session=None, clicked
return False
def cancelled_startup_step(job, pcb_pid, state, *, closed_frame, deadline, post, emit):
def cancelled_startup_step(job, pcb_pid, state, *, closed_frame, deadline, post, emit,
read_windows=None, identity_check=None):
"""Finish only the owned no-write diagnostic startup; never establish PASS.
Cancellation already ended supervisor polling. Cleanup is its sole prompt
actor and uses the caller's original deadline and single-close state.
"""
from types import SimpleNamespace
windows = _windows(pcb_pid)
read_windows = read_windows or (lambda: _windows(pcb_pid))
windows = read_windows()
if any(window['pid'] != pcb_pid for window in windows):
raise RuntimeError('STARTUP_PROCESS_UNCONFIRMED')
current = _target_frame(windows, Path(job['pcb']).stem, require_ready=False)
@@ -387,7 +389,11 @@ def cancelled_startup_step(job, pcb_pid, state, *, closed_frame, deadline, post,
if closed_frame is not None and frame['hwnd'] != closed_frame:
raise RuntimeError('STARTUP_DOCUMENT_CHANGED')
if old is None:
if _load_evidence(job, pcb_pid, job['diagnostic_log_baseline'], require_autosave=False) is None:
# Explicit legacy cleanup supplies already checked registration. It is
# revalidated immediately before every action, never used as open proof.
confirmed = (identity_check is not None or
_load_evidence(job, pcb_pid, job['diagnostic_log_baseline'], require_autosave=False) is not None)
if not confirmed:
return closed_frame, False
state['frame'] = frame
# Validate every window before allowing a known No. An unknown sibling
@@ -402,7 +408,8 @@ def cancelled_startup_step(job, pcb_pid, state, *, closed_frame, deadline, post,
raise
actions = []
def act(hwnd, message):
if _windows(pcb_pid) != windows or time.monotonic() >= deadline:
if (read_windows() != windows or identity_check is not None and not identity_check()
or time.monotonic() >= deadline):
raise RuntimeError('STARTUP_ACTION_UNCONFIRMED: native state or deadline changed')
post(hwnd, message)
actions.append((hwnd, message))
+9 -2
View File
@@ -390,6 +390,13 @@ class NativeQueue:
def run(self, action, *, stop=None, waiting=None, ready=lambda: True, wait_state=None,
context=None, timeout_seconds=10):
def available_now():
if not ready():
return False
if context is None:
return True # Explicit recovery controls must still reach their retained clients.
from .session_record import _live_library_available
return all(_live_library_available(path) for path in (context.library, *context.aliases))
ticket = [object(), False]
acquired, notified = False, False
previous_state = None
@@ -401,7 +408,7 @@ class NativeQueue:
self.pending.append(ticket)
try:
while not acquired:
available = ready() # Call only this ticket's predicate, outside the queue lock.
available = available_now() # Cached predicates only, outside the queue lock.
with self.condition:
if (self.closed or stop is not None and stop.is_set()
or context is not None and (context.stop.is_set() or context.stop_after_current.is_set())):
@@ -412,7 +419,7 @@ class NativeQueue:
self.active = acquired = True
else:
self.condition.wait(.1)
if acquired and not ready():
if acquired and not available_now():
with self.condition:
ticket[1] = self.active = acquired = False
self.condition.notify_all()
+160
View File
@@ -570,6 +570,161 @@ def _dismiss_startup_tip(row, handle, windows, *, incomplete=None, dismissed=(),
return tip['hwnd']
def _cancelled_diagnostic_record(row):
"""Existing complete registration can authorize cleanup, never validation."""
import stat
import pywintypes, win32con, win32event
from .session_record import _session, IDENTITY_KEYS, active_write_records
from .failed_session import _command_args
if row.get('scope_confirmed') is not True or row.get('name', '').casefold() != 'expeditionpcb.exe':
return None
def same(a, b):
return os.path.normcase(os.path.abspath(str(a))) == os.path.normcase(os.path.abspath(str(b)))
def read(path, *, lines=False):
if path.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
raise ValueError('STARTUP_RECORD_REPARSE_POINT')
with path.open('rb') as stream:
data = stream.read(1024*1024+1)
if len(data) > 1024*1024:
raise ValueError('STARTUP_RECORD_TOO_LARGE')
return [json.loads(line) for line in data.splitlines()] if lines else json.loads(data)
matches = []
for record in row.get('session_records', ()):
try:
path = Path(record['path']); root = path.parent
session, state, identities = _session(path, root)
job, result = read(root/'request.json'), read(root/'result.json')
operation = session['operation_id']
scope = session.get('resource_scope', {})
if (record.get('operation_id') != operation or job.get('operation_id') != operation
or job.get('diagnostic_only') is not True or job.get('interactive_input') is not False
or job.get('operation') != 'verify' or session.get('operation') != 'verify'
or not all(same(value, row['library']) for value in (job['library'], job['lmc_file'], session['library']))
or not same(job['root'], root) or not same(job['session_record_path'], path)
or job.get('desktop') != session.get('desktop') or not job['desktop'].startswith('CbbVerify_')
or scope.get('scope_state') != 'DECLARED' or scope.get('operation_id') != operation
or not same(scope.get('library', ''), row['library'])
or scope.get('projects') != [job['project']]
or not Path(job['pcb']).is_relative_to(Path(job['project']).parent)
or not same(job['cancel_signal'], session['cancel_signal'])
or Path(job['cancel_signal']).parent != root or not Path(job['cancel_signal']).is_file()
or result.get('status') != 'CANCELLED' or result.get('error_stage') != 'PCB_STARTING'
or result.get('write_outcome', {}).get('save_state') != 'UNKNOWN'
or state.get('phase') != 'UNCONFIRMED' or (root/'save.log').exists()):
continue
native = [p for p in identities if p.get('role') == 'native' and p['pid'] == row['pid']]
workers = [p for p in identities if p.get('role') in ('worker', 'helper')]
if (len(native) != 1 or not workers
or any(native[0][k] != row.get(k) for k in IDENTITY_KEYS)
or any(p.get('role') not in ('worker','helper','native','supervisor') for p in identities)):
continue
for worker in workers:
try:
with _process_handle(worker['pid']) as held:
if win32event.WaitForSingleObject(held, 0) != win32con.WAIT_OBJECT_0:
raise ValueError('STARTUP_WORKER_STILL_ACTIVE')
except (OSError, pywintypes.error) as error:
if getattr(error, 'winerror', None) != 87:
raise
args = _command_args(row['command'])
if ('-reusablecircuit' not in [a.casefold() for a in args]
or not any(same(a, job['pcb']) for a in args[1:])):
continue
events = read(root/'events.jsonl', lines=True)
if (not any(e.get('stage') == 'pcb_worker_started' and e.get('pcb_pid') == row['pid'] for e in events)
or not any(e.get('stage') == 'pcb_baseline' and row['pid'] not in e.get('pids', []) for e in events)
or any(str(e.get('stage', '')).startswith(('save', 'integration', 'validate', 'failure_close'))
or e.get('stage') == 'diagnostic_complete' for e in events)):
continue
closes = [e for e in events if e.get('stage') in ('startup_close_requested', 'diagnostic_wm_close')]
if len(closes) > 1 or any(e.get('pcb_pid') != row['pid'] or not e.get('hwnd') for e in closes):
continue
if any(r.get('operation_id') != operation for r in active_write_records(row['library'])):
continue
matches.append(dict(job=job, record_path=str(path), operation_id=operation,
closed_frame=closes[0]['hwnd'] if closes else None))
except (OSError, pywintypes.error, ValueError, KeyError, TypeError):
continue
return matches[0] if len(matches) == 1 else None
def _legacy_diagnostic_windows(row):
"""Adapt the existing complete private-desktop snapshot for diagnostic policy."""
import win32con, win32gui
snapshot = _process_windows({row['pid']})
if _window_error(snapshot, row['pid']):
raise ValueError('STARTUP_WINDOW_UNCONFIRMED')
result = []
for window in snapshot.get(row['pid'], []):
if window.get('desktop') != row['cleanup_desktop']:
raise ValueError('STARTUP_DESKTOP_UNCONFIRMED')
benign = (not window['title'] and window['class'] in ('UAC_InputIndicatorOverlayWnd', 'UAC Input Indicator'))
benign = benign or (window['class'] == 'Internet Explorer_Hidden' and not window['title']
and not window['children'] and window.get('rect', [1,1,2,2])[:2] == window.get('rect', [1,1,2,2])[2:])
if benign:
continue
with _window_desktop(window['desktop']):
children = [dict(c, parent=win32gui.GetParent(c['hwnd']), visible=True) for c in window['children']]
result.append(dict(hwnd=window['hwnd'], pid=row['pid'], **{'class':window['class']},
text=window['title'], enabled=window['enabled'], children=children,
owner=int(win32gui.GetWindow(window['hwnd'], win32con.GW_OWNER) or 0)))
return result
def _close_registered_startup(row, handle, proof, *, stop=None):
import pywintypes, win32con, win32event
from .diagnostic_open import cancelled_startup_step
from .operation_queue import check_active
job = proof['job']; bound = dict(row, cleanup_desktop=job['desktop'])
deadline = time.monotonic()+3
def active_owner():
check_active()
if stop is not None and stop.is_set():
return False
owner = _force_ownership(handle,row['pid'])
return (owner.get('force_user_confirmed') is True
and win32event.WaitForSingleObject(handle,0) == win32con.WAIT_TIMEOUT
and _handle_identity(handle) == {k:row.get(k) for k in ('created_handle','image')}
and all(owner.get(k) == row.get(k) for k in ('owner_sid','session_id')))
def confirmed():
if not active_owner():return False
fresh = next((p for p in query_process_snapshot() if p['pid'] == row['pid']), None)
return (fresh is not None and all(fresh.get(k) == row.get(k) for k in ('created','command','executable','name'))
and _cancelled_diagnostic_record(row) == proof)
def post(hwnd, message):
if not active_owner() or time.monotonic() >= deadline:
raise ValueError('STARTUP_ACTION_UNCONFIRMED')
_post_window_message({'desktop':job['desktop']}, hwnd, row['pid'], message)
state = {'clicked':set()}; closed = proof['closed_frame']
try:
while time.monotonic() < deadline:
if win32event.WaitForSingleObject(handle, 0) == win32con.WAIT_OBJECT_0:
return {'release_status':'RELEASED','detail':'已正常结束已取消的诊断启动'}
if not active_owner():
break
snapshot = _process_windows({row['pid']})
# Only this fully proved no-write operation may bypass its historical
# UNCONFIRMED label; other operations were vetoed by the proof above.
tip_row = {k:v for k,v in row.items() if k not in ('runtime_phase','library')}
if closed is not None:
tip_row['startup_frame'] = closed
has_tip = any(w['title'] == 'Tip of the Day' for w in snapshot.get(row['pid'],[]))
if has_tip and confirmed() and _dismiss_startup_tip(tip_row,handle,snapshot.get(row['pid'],[]),
incomplete=_window_error(snapshot,row['pid']),deadline=deadline,stop=stop) is not None:
while time.monotonic() < deadline:
if win32event.WaitForSingleObject(handle,100) == win32con.WAIT_OBJECT_0:
return {'release_status':'RELEASED','detail':'已关闭启动提示并正常退出'}
if stop is not None and stop.is_set():break
break # Never stack another Close after a legacy Tip acknowledgement.
closed,_ = cancelled_startup_step(job,row['pid'],state,closed_frame=closed,deadline=deadline,
post=post,emit=lambda **event:None,read_windows=lambda:_legacy_diagnostic_windows(bound),
identity_check=confirmed)
time.sleep(.1)
except (OSError, pywintypes.error, ValueError, RuntimeError) as error:
return {'release_status':'WAITING','detail':str(error)}
return {'release_status':'WAITING','detail':'已请求取消启动清理,等待原生退出后重新检查'}
def _request_close(row, *, stop=None):
import win32con, win32event
with _process_handle(row['pid']) as handle:
@@ -584,6 +739,8 @@ def _request_close(row, *, stop=None):
return {'release_status': 'WAITING', 'detail': '该会话窗口读取不完整,请重新检查:'+error}
if stop is not None and stop.is_set():
return {'release_status': 'CANCELLED', 'detail': '已停止释放'}
if proof := _cancelled_diagnostic_record(row):
return _close_registered_startup(row, handle, proof, stop=stop)
if _dismiss_startup_tip(row, handle, windows, stop=stop) is not None:
# Legacy startup cleanup may already have sent WM_CLOSE. Only wait
# for it here; never stack another close behind this acknowledgement.
@@ -795,6 +952,9 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, ca
if not save():
return result
try:
if not force and not cancel_native:
row['session_records'] = [{k:r.get(k) for k in ('path','operation_id')}
for r in plan.get('runtime_sessions', []) if r.get('path')]
outcome = (_request_native_cancel(row, stop=stop) if cancel_native else
(_force_close if force else _request_close)(row, stop=stop))
except Exception as error:
+25 -2
View File
@@ -22,13 +22,30 @@ def _library_key(library):
return os.path.normcase(os.path.normpath(str(library)))
def library_available(library):
def library_available(library, *, live_only=False):
"""Cached queue predicate: no file, process or network queries."""
if live_only:
return _live_library_available(library)
key = _library_key(library)
with _observer_guard:
return not any(key in aliases for aliases in _retained_libraries.values())
def _live_library_available(library):
"""Ignore stale retention, but wait for an actual registered observer."""
key = _library_key(library)
with _observer_guard:
for path, aliases in _retained_libraries.items():
observer = _observers.get(path)
if key not in aliases or observer is None or not observer[0].is_alive():
continue
state = _retained_results.get(path, {})
if (state.get('observer_initializing') is True or state.get('status') == 'ACTIVE'
or state.get('owned_worker_alive') is True):
return False
return True
def retained_session_snapshot(library):
key = _library_key(library)
with _observer_guard:
@@ -396,6 +413,10 @@ def observe_retained_session(path, *, evidence_root, stop=None, progress=None, p
result = {**result, 'status': 'RELEASED', 'identity_changed': True, 'release_proof': proof}
except Exception as error:
result['detail'] += f';资源释放待确认:{error}'
try:
result['owned_worker_alive'] = process is not None and process.poll() is None
except Exception:
result['owned_worker_alive'] = False
try:
write_session_record(observation, {**result, 'operation_id': result['operation_id'] or 'unknown'})
except (OSError, ValueError):
@@ -432,12 +453,14 @@ def handoff_session(path, *, evidence_root, process=None, progress=None, stop=No
_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')}
'detail': '正在核对残留会话', 'operation_id': session.get('operation_id'),
'observer_initializing': True}
def notify(value):
with _observer_guard:
if _retained_libraries.get(key) is aliases:
previous = _retained_results[key]
_retained_results[key] = {**previous, **value,
'observer_initializing': False,
'library': value.get('library') or previous['library'],
'operation_id': value.get('operation_id') or previous['operation_id'],
'block': value.get('block') or previous['block']}
+1 -1
View File
@@ -136,7 +136,7 @@ class IcdbCheckTask(QObject):
return None, str(error)
def bounded_write():
try:
return BatchTaskContext(str(self.requests[0].lmc_file)).run(write)
return BatchTaskContext(str(self.requests[0].lmc_file)).run(write, metadata_only=True)
except Exception as error:
return None, str(error)
self.worker = ServiceWorker(bounded_write)
+28 -9
View File
@@ -230,7 +230,7 @@ def _run_process(command, timeout_seconds, cwd, *, evidence_root=None):
return run_content_check(command, timeout_seconds, cwd, evidence_root=evidence_root)
def _stop_worker(process, *, timeout=5):
def _stop_worker(process, *, timeout=5, wait_for_native_write=True):
"""Request stop without interrupting a possibly unreturned native call."""
try:
if hasattr(process, 'request_stop'):
@@ -243,7 +243,7 @@ def _stop_worker(process, *, timeout=5):
process.wait(timeout=timeout)
except Exception:
pending = getattr(process, 'native_write_pending', lambda: False)()
if pending is not False and not getattr(process, '_stop_wait_complete', False):
if wait_for_native_write and pending is not False and not getattr(process, '_stop_wait_complete', False):
from .defaults import NATIVE_WRITE_STOP_WAIT_SECONDS
try:
process.wait(timeout=max(0, NATIVE_WRITE_STOP_WAIT_SECONDS - timeout))
@@ -1070,7 +1070,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
'已请求停止,等待当前原生操作返回')
_notify_progress(progress, {'stage': 'save_stop_requested', 'block': request.block_name,
'detail': detail})
_stop_worker(process)
_stop_worker(process, wait_for_native_write=not request.diagnostic_only)
return finish(VerifyResult('CANCELLED', stderr='已取消当前校验。',
safe_to_continue=False, error_stage=phase.value))
if events.exists():
@@ -1237,7 +1237,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
target_pid=target_pid,
observation=last_post_verify_observation,
)
_stop_worker(process)
_stop_worker(process, wait_for_native_write=not request.diagnostic_only)
if dispatch_failure is not None:
status, detail = dispatch_failure
if progress:
@@ -1260,7 +1260,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
result = VerifyResult(**outcome)
except Exception as error:
if 'process' in locals() and process.poll() is None:
_stop_worker(process)
_stop_worker(process, wait_for_native_write=not request.diagnostic_only)
launch_release = getattr(error, 'worker_launch_release', None) if 'process' not in locals() else None
if not worker_launch_attempted:
launch_release = {'process_created': False, 'worker_exited': True,
@@ -1279,6 +1279,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
finally:
close_errors = []
worker_exited = False
observer_started = False
automation_release = {'safe_to_continue': False}
if 'process' not in locals() or process.poll() is not None or getattr(process, 'session_record_path', None):
# A gated worker owns its writer barrier and inherited sidecar.
@@ -1293,18 +1294,17 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
try:
worker_exited = process.poll() is not None
if not worker_exited:
worker_exited = _stop_worker(process)
worker_exited = _stop_worker(process, wait_for_native_write=not request.diagnostic_only)
if hasattr(process, 'automation_release_state'):
automation_release = process.automation_release_state()
else:
automation_release = {'safe_to_continue': worker_exited, 'remaining_pids': []}
if worker_exited:
process.close()
elif getattr(process, 'session_record_path', None):
if not worker_exited and getattr(process, 'session_record_path', None):
from .session_record import handoff_session
handoff_session(process.session_record_path, evidence_root=root,
process=process, progress=lambda state: _notify_progress(progress,
{'stage': 'session_observation', 'block': request.block_name, **state}))
observer_started = True
_notify_progress(progress, {'stage': 'session_handoff', 'block': request.block_name,
'detail': '已转后台观察,可查看状态'})
from .operation_queue import hold_native_handoff
@@ -1353,6 +1353,25 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
'automation_release': automation_release, 'worker_exited': worker_exited}
release_result['remaining_pids'] = sorted(set(release_result.get('remaining_pids', []))
| set(automation_release.get('remaining_pids', [])))
if worker_exited:
try:
if (release_result.get('safe_to_continue') is not True
and getattr(process, 'session_record_path', None)):
if not observer_started:
from .session_record import handoff_session
# Retain the exact worker handle until registered
# native clients exit and the observer obtains proof.
handoff_session(process.session_record_path, evidence_root=root,
process=process, progress=lambda state: _notify_progress(progress,
{'stage': 'session_observation', 'block': request.block_name, **state}))
observer_started = True
_notify_progress(progress, {'stage': 'session_handoff', 'block': request.block_name,
'detail': '工作进程已退出,原生会话继续后台观察'})
else:
process.close()
except Exception as error:
release_result = {**release_result, 'safe_to_continue': False,
'close_errors': [*close_errors, str(error)]}
try:
from .operation_lifecycle import classify_save_state
save_lines = ((root/'save.log').read_text('utf-8', errors='replace').splitlines()