fix: complete confirmed legacy cleanup from one release intent

This commit is contained in:
阿白叔 committed 2026-11-17 09:44:49 +08:00
1 parent 7cc65f78da
commit a3f69de201
7 files changed
+189 -20

No files matched your search

+9 -5
View File
@@ -151,8 +151,9 @@ def _target_frame(windows, name, *, require_ready=True):
if not window['text'].casefold().startswith('expedition pcb') or f'[{name}]'.casefold() not in window['text'].casefold():
continue
mdi = {child['hwnd'] for child in window['children'] if child['class'].casefold() == 'mdiclient'}
if any(child.get('parent') in mdi and child['text'].casefold() == name.casefold()
and child['class'].casefold().startswith('afx:') for child in window['children']):
documents = [child for child in window['children'] if child.get('parent') in mdi
and child['class'].casefold().startswith('afx:')]
if len(documents) == 1 and documents[0]['text'].casefold() == name.casefold():
matches.append(window)
return matches[0] if len(matches) == 1 else None
@@ -408,9 +409,12 @@ def cancelled_startup_step(job, pcb_pid, state, *, closed_frame, deadline, post,
raise
actions = []
def act(hwnd, message):
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')
if read_windows() != windows:
raise RuntimeError('STARTUP_WINDOW_CHANGED: native snapshot changed before action')
if identity_check is not None and not identity_check():
raise RuntimeError('STARTUP_IDENTITY_UNCONFIRMED: registered cleanup binding changed')
if time.monotonic() >= deadline:
raise RuntimeError('STARTUP_CLEANUP_TIMEOUT: original cleanup deadline reached')
post(hwnd, message)
actions.append((hwnd, message))
if message == 0xF5:
+24 -5
View File
@@ -676,7 +676,7 @@ def _close_registered_startup(row, handle, proof, *, stop=None):
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
deadline = time.monotonic()+30 # One diagnostic cleanup intent; ordinary close still uses 3 seconds.
def active_owner():
check_active()
if stop is not None and stop.is_set():
@@ -716,9 +716,15 @@ def _close_registered_startup(row, handle, proof, *, stop=None):
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)
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),
identity_check=confirmed)
except RuntimeError as error:
if not str(error).startswith('STARTUP_WINDOW_CHANGED:'):
raise
# No may remove a modal and enable the target while the next
# snapshot is being read. Revalidate anew inside the same budget.
time.sleep(.1)
except (OSError, pywintypes.error, ValueError, RuntimeError) as error:
return {'release_status':'WAITING','detail':str(error)}
@@ -740,7 +746,20 @@ def _request_close(row, *, stop=None):
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)
owner = _force_ownership(handle,row['pid'])
if (owner.get('force_user_confirmed') is not True
or any(owner.get(k) != row.get(k) for k in ('owner_sid','session_id'))):
return {'release_status':'WAITING','detail':'取消启动会话的用户或 Windows 会话未确认'}
if stop is not None and stop.is_set():
return {'release_status':'CANCELLED','detail':'已停止释放'}
from .session_record import handoff_session
record_path = Path(proof['record_path'])
handoff_session(record_path, evidence_root=record_path.parent, observe_only=False)
from .operation_queue import native_phase
# This confirmed no-write native cleanup has its own single bounded
# budget; metadata inactivity must not abandon it between No and Close.
with native_phase(read_only=True):
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.
+18 -5
View File
@@ -387,15 +387,17 @@ def inspect_session_record(path, *, evidence_root):
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()
read_only = observe_only if callable(observe_only) else lambda: observe_only
observation = Path(path).with_name('observation-' + uuid4().hex + '.json')
with ExitStack() as stack:
handles = {}
while True:
observation_only = read_only()
try:
result = _reconcile(Path(path), Path(evidence_root), handles, stack, release=not observe_only)
result = _reconcile(Path(path), Path(evidence_root), handles, stack, release=not observation_only)
except Exception as error:
result = _result('UNCONFIRMED', str(error))
if (not observe_only and process is not None and process.poll() is not None
if (not observation_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
@@ -405,7 +407,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' and not observe_only:
if result['status'] == 'IDENTITY_CHANGED' and not observation_only:
try:
from .library_lock import release_retained_library
proof = release_retained_library(result['library'], Path(path).parent/'release-proof')
@@ -427,7 +429,7 @@ def observe_retained_session(path, *, evidence_root, stop=None, progress=None, p
except Exception:
logging.getLogger(__name__).warning('Observation callback failed', exc_info=True)
if (result['status'] == 'RELEASED' or stop.is_set()
or observe_only and result['status'] != 'ACTIVE'):
or read_only() and result['status'] != 'ACTIVE'):
return result
if not handles and process is not None and process.poll() is None:
stop.wait(1)
@@ -449,6 +451,9 @@ def handoff_session(path, *, evidence_root, process=None, progress=None, stop=No
aliases = {_library_key(library), _library_key(Path(library).resolve())} if library else set()
with _observer_guard:
if key in _observers:
if (observe_only is False and session.get('operation_id')
and _retained_results.get(key, {}).get('operation_id') == session['operation_id']):
_retained_results[key]['release_operation_id'] = session['operation_id']
return
_retained_libraries[key] = aliases
_retained_results[key] = {'status': 'UNCONFIRMED', 'phase': 'UNCONFIRMED',
@@ -466,11 +471,19 @@ def handoff_session(path, *, evidence_root, process=None, progress=None, stop=No
'block': value.get('block') or previous['block']}
if progress is not None:
progress(value)
def observation_only():
if not observe_only:
return False
with _observer_guard:
value = _retained_results.get(key, {})
return not (session.get('operation_id') and _retained_libraries.get(key) is aliases
and value.get('operation_id') == session.get('operation_id')
and value.get('release_operation_id') == session.get('operation_id'))
def observe():
result = None
try:
result = observe_retained_session(path, evidence_root=evidence_root, progress=notify,
stop=stop, process=process, observe_only=observe_only)
stop=stop, process=process, observe_only=observation_only)
if process is not None and process.poll() is not None:
process.close()
return result
@@ -68,7 +68,7 @@ class ResidualReleaseDialog(QDialog):
self.table.itemSelectionChanged.connect(self._update_prompt)
self.refresh()
def _start(self, action, completed):
def _start(self, action, completed, *, metadata_only=False):
context = BatchTaskContext(str(self.library))
self.context, self.stop = context, context.stop
self.busy = True
@@ -78,7 +78,7 @@ class ResidualReleaseDialog(QDialog):
self.force_button.setEnabled(False)
self.cancel_native_button.setEnabled(False)
self.close_button.setText('停止释放')
self.worker = ServiceWorker(lambda:context.run(action))
self.worker = ServiceWorker(lambda:context.run(action, metadata_only=metadata_only))
worker = self.worker
self._workers.add(worker)
self.worker.signals.succeeded.connect(context.guard_callback(completed, current=lambda:self.context))
@@ -238,7 +238,7 @@ class ResidualReleaseDialog(QDialog):
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)
self._start(inspect, ready, metadata_only=True)
def force_release(self):
if self.busy or not self.plan or not self.plan['sessions']: return
+27 -2
View File
@@ -82,7 +82,29 @@ def test_failed_observer_registration_preserves_original_cancelled_result_and_ha
assert not state['closed']
def test_natural_native_exit_gets_fresh_release_and_admits_waiting_scope_without_click(tmp_path,monkeypatch):
def test_missing_operation_identity_cannot_promote_cold_observation(tmp_path,monkeypatch):
from types import SimpleNamespace
path=tmp_path/'session.json';path.write_text('{invalid')
entered,finish=Event(),Event();modes=[]
def observe(*args,**kwargs):
mode=kwargs['observe_only'];modes.append(mode() if callable(mode) else mode)
entered.set();assert finish.wait(3)
return dict(status='UNCONFIRMED',operation_id=None)
monkeypatch.setattr(session_record,'observe_retained_session',observe)
owner=SimpleNamespace(cbb_library=str(tmp_path/'lib.lmc'),poll=lambda:0,close=lambda:None)
thread=None
try:
session_record.handoff_session(path,evidence_root=tmp_path,process=owner,observe_only=True)
assert entered.wait(2)
thread=session_record._observers[str(path.absolute()).casefold()][0]
assert modes==[True]
finally:
finish.set()
if thread:thread.join(3)
@pytest.mark.parametrize('cold_observer',[False,True])
def test_natural_native_exit_gets_fresh_release_and_admits_waiting_scope_without_click(tmp_path,monkeypatch,cold_observer):
import subprocess,sys,time
from concurrent.futures import ThreadPoolExecutor
from types import SimpleNamespace
@@ -104,11 +126,14 @@ def test_natural_native_exit_gets_fresh_release_and_admits_waiting_scope_without
owner=SimpleNamespace(pid=700,poll=lambda:0,close=lambda:closed.append(native.poll()))
thread=None
try:
session_record.handoff_session(path,evidence_root=evidence,process=owner,stop=stop,
session_record.handoff_session(path,evidence_root=evidence,process=owner,stop=stop,observe_only=cold_observer,
progress=lambda state:active.set() if state['status']=='ACTIVE' else None)
assert active.wait(3) and not closed
key=str(path.absolute()).casefold()
thread=session_record._observers[key][0]
if cold_observer:
session_record.handoff_session(path,evidence_root=evidence,observe_only=False)
assert session_record._observers[key][0] is thread
assert not session_record.library_available(library)
queue=NativeQueue()
def admitted():
+78
View File
@@ -12,6 +12,9 @@ def registered_fixture(tmp_path,monkeypatch,*,closed=False,obstacle=''):
import win32con,win32event
job,records,messages,state=loaded_fixture(tmp_path,monkeypatch)
state.update(tip=False,closing=closed)
state['observer_requests']=[]
monkeypatch.setattr(session_record,'handoff_session',lambda path,**kw:
state['observer_requests'].append((path,list(messages),kw)))
job.update(operation_id='verify-old',operation='verify',library=job['lmc_file'],block='IP101GR',
session_record_path=str(tmp_path/'session.json'),interactive_input=False)
job.pop('diagnostic_log_baseline') # Old builds never persisted this; do not invent it.
@@ -148,3 +151,78 @@ def test_registered_cleanup_cannot_act_from_another_windows_user_session(tmp_pat
dict(owner_sid='current',session_id=1,force_user_confirmed=False))
assert sessions._request_close(row)['release_status']=='WAITING'
assert not messages and records
assert not state['observer_requests']
@pytest.mark.parametrize('obstacle',['','progress','stop','unknown'])
def test_one_legacy_intent_keeps_diagnostic_budget_across_no_ready_and_close(tmp_path,monkeypatch,obstacle):
from threading import Event
job,row,records,messages,state=registered_fixture(tmp_path,monkeypatch)
stop=Event();original=sessions._legacy_diagnostic_windows
def windows(bound):
value=original(bound)
if state['declined']:
if obstacle=='stop' and state['ticks']>=4:stop.set()
if state['ticks']<4 or obstacle=='progress':
value[0]['children'].append(dict(hwnd=123,**{'class':'msctls_progress32'},text='',visible=True))
if obstacle=='unknown':
value.append(dict(hwnd=999,pid=12,**{'class':'#32770'},text='Unknown action',children=[]))
return value
monkeypatch.setattr(sessions,'_legacy_diagnostic_windows',windows)
result=sessions._request_close(row,stop=stop)
assert state['observer_requests'] and state['observer_requests'][0][1]==[]
assert state['observer_requests'][0][2].get('observe_only',False) is False
if not obstacle:
assert result['release_status']=='RELEASED' and not records
assert messages==[(31,245),(100,16)] and 4<=state['ticks']<5
else:
assert result['release_status'] in ('WAITING','CANCELLED') and records
assert messages==[(31,245)]
assert state['ticks']<5 if obstacle=='stop' else 30<=state['ticks']<30.2
def test_known_no_then_changing_ready_snapshot_revalidates_within_same_intent(tmp_path,monkeypatch):
job,row,records,messages,state=registered_fixture(tmp_path,monkeypatch)
original=sessions._legacy_diagnostic_windows;reads=[]
def windows(bound):
value=original(bound)
if state['declined']:
reads.append(1)
if len(reads)==2:value[0]['children'].append(dict(hwnd=124,**{'class':'Afx:tool'},text='settling',parent=100))
return value
monkeypatch.setattr(sessions,'_legacy_diagnostic_windows',windows)
assert sessions._request_close(row)['release_status']=='RELEASED'
assert messages==[(31,245),(100,16)] and not records
def test_proved_native_cleanup_uses_its_budget_instead_of_metadata_inactivity(tmp_path,monkeypatch):
from threading import Event,Timer
from cbb_refresh_verify.operation_queue import BatchTaskContext
job,row,records,messages,state=registered_fixture(tmp_path,monkeypatch)
ready,done=Event(),Event();original=sessions._legacy_diagnostic_windows
def windows(bound):
if state['declined']:assert ready.wait(1)
return original(bound)
monkeypatch.setattr(sessions,'_legacy_diagnostic_windows',windows)
timer=Timer(.25,ready.set);timer.start()
context=BatchTaskContext(str(row['library']))
def cleanup():
try:return sessions._request_close(row)
finally:done.set()
try:
result=context.run(cleanup,timeout_seconds=.08)
assert result['release_status']=='RELEASED' and messages==[(31,245),(100,16)]
finally:
ready.set();timer.join(1);assert done.wait(2)
def test_registered_cleanup_preserves_frame_with_an_additional_mdi_document(tmp_path,monkeypatch):
job,row,records,messages,state=registered_fixture(tmp_path,monkeypatch)
original=sessions._legacy_diagnostic_windows
def windows(bound):
value=original(bound)
value[0]['children'].append(dict(hwnd=888,**{'class':'Afx:document'},text='Other',parent=101))
return value
monkeypatch.setattr(sessions,'_legacy_diagnostic_windows',windows)
assert sessions._request_close(row)['release_status']=='WAITING'
assert records and not messages
@@ -0,0 +1,30 @@
from threading import Event
import pytest
from cbb_refresh_verify.operation_queue import BatchTaskContext,TaskHandoff,hold_native_handoff
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
def test_pure_residual_inspection_remains_available_during_native_finalizer(qtbot,tmp_path,monkeypatch):
library=tmp_path/'lib.lmc';library.touch()
context=BatchTaskContext(str(library),native_policy='external')
entered,finish=Event(),Event();reads=[]
def finalize():
try:hold_native_handoff(None,tmp_path/'session.json')
except TaskHandoff:entered.set();assert finish.wait(5)
monkeypatch.setattr('cbb_refresh_verify.library_lock.inspect_residual_sessions',lambda path:
reads.append(path) or dict(library=str(library),sessions=[],previous_records=[]))
monkeypatch.setattr('cbb_refresh_verify.session_record.discover_sessions',lambda *a,**kw:[])
monkeypatch.setattr('cbb_refresh_verify.session_record.retained_session_states',lambda *a:[])
dialog=None
try:
with pytest.raises(TaskHandoff):context.run(finalize)
assert entered.is_set()
dialog=ResidualReleaseDialog(library,tmp_path/'evidence');qtbot.addWidget(dialog)
qtbot.waitUntil(lambda:not dialog.busy,timeout=3000)
assert reads==[library] and dialog.plan is not None,dialog.message.text()
assert dialog.library==library and dialog.confirm_button.isEnabled()
finally:
finish.set();context.close(timeout_seconds=2)
if dialog is not None:dialog.close()