fix: hand off late cancelled startup cleanup once

This commit is contained in:
阿白叔 committed 2026-11-17 13:13:24 +08:00
1 parent 906cfc06be
commit 5e9509e573
5 files changed
+256 -7

No files matched your search

+80 -5
View File
@@ -651,7 +651,11 @@ def _cancelled_diagnostic_record(row):
if baseline is None or _load_evidence(job,row['pid'],baseline,require_autosave=False) is None:
continue
matches.append(dict(job=job, record_path=str(path), operation_id=operation,
closed_frame=closes[0]['hwnd'] if closes else None))
closed_frame=closes[0]['hwnd'] if closes else None,
declined_buttons=[e['hwnd'] for e in events if e.get('stage')=='startup_prompt_no'
and e.get('pcb_pid')==row['pid'] and e.get('control_id')==7 and e.get('hwnd')],
dismissed_tips=[e['hwnd'] for e in events if e.get('stage')=='startup_tip_dismissed'
and e.get('pcb_pid')==row['pid'] and e.get('hwnd')]))
except (OSError, pywintypes.error, ValueError, KeyError, TypeError):
continue
return matches[0] if len(matches) == 1 else None
@@ -680,12 +684,12 @@ def _legacy_diagnostic_windows(row):
return result
def _close_registered_startup(row, handle, proof, *, stop=None):
def _close_registered_startup(row, handle, proof, *, stop=None, deadline=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()+30 # One proved cancelled-startup intent; generic close still uses 3 seconds.
if deadline is None:deadline = time.monotonic()+30
def active_owner():
check_active()
if stop is not None and stop.is_set():
@@ -704,7 +708,13 @@ def _close_registered_startup(row, handle, proof, *, stop=None):
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']; dismissed_tips = set()
state = {'clicked':set()}; closed = proof['closed_frame']; dismissed_tips = set(proof.get('dismissed_tips',()))
def read_bound_windows():
windows=_legacy_diagnostic_windows(bound)
for window in windows:
if any(c['hwnd'] in proof.get('declined_buttons',()) for c in window['children']):
state['clicked'].add(window['hwnd'])
return windows
try:
while time.monotonic() < deadline:
if win32event.WaitForSingleObject(handle, 0) == win32con.WAIT_OBJECT_0:
@@ -732,7 +742,7 @@ def _close_registered_startup(row, handle, proof, *, stop=None):
break # Never stack another Close after a legacy Tip acknowledgement.
try:
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),
post=post,emit=lambda **event:None,read_windows=read_bound_windows,
identity_check=confirmed)
except RuntimeError as error:
if not str(error).startswith('STARTUP_WINDOW_CHANGED:'):
@@ -745,6 +755,69 @@ def _close_registered_startup(row, handle, proof, *, stop=None):
return {'release_status':'WAITING','detail':'已请求取消启动清理,等待原生退出后重新检查'}
def _ordinary_startup_close(row, handle, proof, *, stop=None):
"""One persisted retained phase, serialized with existing explicit release."""
import win32con, win32event
from .session_record import read_session_record, write_session_record
from .operation_queue import native_phase
waiting = {'release_status':'WAITING','detail':'取消启动清理已交接或原生执行通道忙,继续观察'}
mutex=win32event.CreateMutex(None,False,r'Local\CbbRefreshVerify795')
acquired=False
try:
acquired=win32event.WaitForSingleObject(mutex,0) in (win32con.WAIT_OBJECT_0,win32con.WAIT_ABANDONED)
if not acquired or stop is not None and stop.is_set():return waiting
path=Path(proof['record_path'])
record=read_session_record(path,evidence_root=path.parent)
if 'retained_startup_cleanup' in record or _cancelled_diagnostic_record(row)!=proof:return waiting
# Complete loaded identity and every prompt are checked before consuming
# the one-shot intent. Unknown/multiple documents remain observation-only.
from .diagnostic_open import _target_frame, _pending_prompt
windows=_legacy_diagnostic_windows(dict(row,cleanup_desktop=proof['job']['desktop']))
frame=_target_frame(windows,Path(proof['job']['pcb']).stem,require_ready=False)
if frame is None:return waiting
for window in windows:
_pending_prompt([window],closing=proof['closed_frame'] is not None,frame=frame,
pcb_name=Path(proof['job']['pcb']).name)
if _cancelled_diagnostic_record(row)!=proof or stop is not None and stop.is_set():return waiting
deadline=time.monotonic()+30
record['retained_startup_cleanup']=dict(operation_id=proof['operation_id'],
pcb_pid=row['pid'],owner_pid=os.getpid(),state='CLAIMED',closed_frame=proof['closed_frame'],
deadline_monotonic=deadline,identity={k:row[k] for k in ('created_handle','image','owner_sid','session_id')})
write_session_record(path,record) # Durable before No/Close; never removed or retried.
with native_phase(read_only=True):
return _close_registered_startup(row,handle,proof,stop=stop,deadline=deadline)
except (OSError,ValueError,RuntimeError):
return waiting
finally:
if acquired:win32event.ReleaseMutex(mutex)
mutex.Close()
def resume_cancelled_startup(path, *, stop=None):
"""Observer-only entry for one late loaded, positively proved ordinary cancel."""
from .session_record import _session
from .failed_session import cancelled_prewrite_startup
path=Path(path)
try:
session,state,identities=_session(path,path.parent)
if 'retained_startup_cleanup' in session or stop is not None and stop.is_set():return False
job=json.loads(path.with_name('request.json').read_text(encoding='utf-8'))
if job.get('diagnostic_only') is not False:return False
native=[p for p in identities if p.get('role')=='native'
and Path(p['image']).name.casefold()=='expeditionpcb.exe']
if len(native)!=1 or cancelled_prewrite_startup(job,native[0]['pid']) is None:return False
plan=inspect_residual_sessions(session['library'],block_names=(session['block'],))
rows=[r for r in plan['sessions'] if r['pid']==native[0]['pid']]
if len(rows)!=1:return False
row=dict(rows[0],session_records=[dict(path=str(path),operation_id=session['operation_id'])])
proof=_cancelled_diagnostic_record(row)
if proof is None:return False # Includes exact worker/helper exit and fresh loaded logs.
_request_close(row,stop=stop)
return True
except (OSError,ValueError,KeyError,TypeError,RuntimeError):
return False
def _request_close(row, *, stop=None):
import win32con, win32event
with _process_handle(row['pid']) as handle:
@@ -766,6 +839,8 @@ def _request_close(row, *, stop=None):
return {'release_status':'WAITING','detail':'取消启动会话的用户或 Windows 会话未确认'}
if stop is not None and stop.is_set():
return {'release_status':'CANCELLED','detail':'已停止释放'}
if proof['job'].get('diagnostic_only') is False:
return _ordinary_startup_close(row,handle,proof,stop=stop)
from .session_record import handoff_session
record_path = Path(proof['record_path'])
handoff_session(record_path, evidence_root=record_path.parent, observe_only=False)
+10 -1
View File
@@ -1,4 +1,4 @@
"""Bounded, observation-only journal for native calls that outlive a task."""
"""Bounded registration and observation for native calls that outlive a task."""
from contextlib import ExitStack
from datetime import datetime, timezone
import json
@@ -407,6 +407,15 @@ 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'] == 'ACTIVE' and not observation_only and not stop.is_set():
try:
from .residual_sessions import resume_cancelled_startup
if resume_cancelled_startup(path, stop=stop):
# Cleanup is not release proof. Re-read all held identities
# and independently prove the resource release as usual.
result = _reconcile(Path(path), Path(evidence_root), handles, stack)
except Exception:
logging.getLogger(__name__).warning('Retained startup cleanup unavailable', exc_info=True)
if result['status'] == 'IDENTITY_CHANGED' and not observation_only:
try:
from .library_lock import release_retained_library