fix: finish cancelled diagnostic startup after target loading
This commit is contained in:
1 parent
d5d1a3deea
commit
845ae58690
3 files changed
+267
-3
No files matched your search
@@ -365,6 +365,58 @@ 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):
|
||||
"""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)
|
||||
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)
|
||||
frame = current
|
||||
if frame is None and closed_frame is not None:
|
||||
frame = state.get('frame')
|
||||
if frame is None:
|
||||
return closed_frame, False
|
||||
old = state.get('frame')
|
||||
if old is not None and any(frame[k] != old[k] for k in ('hwnd', 'pid', 'class', 'text')):
|
||||
raise RuntimeError('STARTUP_DOCUMENT_CHANGED')
|
||||
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:
|
||||
return closed_frame, False
|
||||
state['frame'] = frame
|
||||
# Validate every window before allowing a known No. An unknown sibling
|
||||
# must not be hidden by the first recognized modal in enumeration order.
|
||||
try:
|
||||
for window in windows:
|
||||
_pending_prompt([window], closing=closed_frame is not None, frame=frame,
|
||||
pcb_name=Path(job['pcb']).name)
|
||||
except RuntimeError as error:
|
||||
if str(error).startswith('DIAGNOSTIC_CLOSE_UNCONFIRMED: unknown native prompt'):
|
||||
return closed_frame, False
|
||||
raise
|
||||
actions = []
|
||||
def act(hwnd, message):
|
||||
if _windows(pcb_pid) != windows or time.monotonic() >= deadline:
|
||||
raise RuntimeError('STARTUP_ACTION_UNCONFIRMED: native state or deadline changed')
|
||||
post(hwnd, message)
|
||||
actions.append((hwnd, message))
|
||||
if message == 0xF5:
|
||||
emit(stage='startup_prompt_no', pcb_pid=pcb_pid, hwnd=hwnd, control_id=7)
|
||||
pending = _pending_prompt(windows, closing=closed_frame is not None, frame=frame,
|
||||
session=SimpleNamespace(post=act), clicked=state['clicked'], pcb_name=Path(job['pcb']).name)
|
||||
if (closed_frame is None and not pending
|
||||
and _target_frame(windows, Path(job['pcb']).stem) is not None):
|
||||
act(frame['hwnd'], 0x10)
|
||||
closed_frame = frame['hwnd']
|
||||
return closed_frame, bool(actions)
|
||||
|
||||
|
||||
def check_target_window(job, pcb_pid, *, emit, error_reader, launcher_process=None) -> dict:
|
||||
"""Prove this launch opened its native document, close it, and prove exit.
|
||||
|
||||
|
||||
@@ -63,7 +63,7 @@ def _tip_target(snapshot):
|
||||
|
||||
|
||||
def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event: None,
|
||||
timeout_seconds=20, launcher_process=None):
|
||||
timeout_seconds=None, launcher_process=None):
|
||||
"""Normally close our empty PCB after a diagnosed database startup failure.
|
||||
|
||||
No COM attach: the global ROT can name another session. Only the exact
|
||||
@@ -90,6 +90,15 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
if not pcb_pid or pcb_pid in baseline_pids:
|
||||
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
|
||||
expected = os.path.normcase(os.path.abspath(job['pcb']))
|
||||
cancelled_diagnostic = (job.get('diagnostic_only') is True
|
||||
and bool(job.get('cancel_signal')) and Path(job['cancel_signal']).exists()
|
||||
and isinstance(job.get('diagnostic_log_baseline'), dict)
|
||||
and {'started_ns', 'files'} <= job['diagnostic_log_baseline'].keys()
|
||||
and not (root/'save.log').exists())
|
||||
# Diagnostic close already owns a 30-second cleanup budget. Start it
|
||||
# once here; the empty-to-loaded transition never resets that deadline.
|
||||
if timeout_seconds is None:
|
||||
timeout_seconds = 30 if cancelled_diagnostic else 20
|
||||
deadline = time.monotonic() + max(0, timeout_seconds)
|
||||
sent = False
|
||||
declined_hwnd = None
|
||||
@@ -99,6 +108,14 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
close_handle = None
|
||||
close_identity = None
|
||||
close_frame = None
|
||||
diagnostic_state = {'clicked': set()}
|
||||
def cleanup_post(hwnd, message):
|
||||
if (time.monotonic() >= deadline or _current_desktop_name() != desktop
|
||||
or win32event.WaitForSingleObject(close_handle, 0) != win32con.WAIT_TIMEOUT
|
||||
or residual_sessions._handle_identity(close_handle) != close_identity
|
||||
or win32process.GetWindowThreadProcessId(hwnd)[1] != pcb_pid):
|
||||
raise ValueError('STARTUP_ACTION_UNCONFIRMED')
|
||||
win32gui.PostMessage(hwnd, message, 0, 0)
|
||||
while True:
|
||||
records = [r for r in _process_details('ExpeditionPCB.exe') if r[0] == pcb_pid]
|
||||
if not records:
|
||||
@@ -133,6 +150,22 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
or '-reusablecircuit' not in [a.casefold() for a in args]
|
||||
or expected not in [os.path.normcase(os.path.abspath(a)) for a in args[1:]]):
|
||||
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
|
||||
if cancelled_diagnostic and time.monotonic() < deadline:
|
||||
if close_handle is None:
|
||||
close_handle = handles.enter_context(residual_sessions._process_handle(pcb_pid))
|
||||
close_identity = residual_sessions._handle_identity(close_handle)
|
||||
if Path(close_identity['image']).name.casefold() != 'expeditionpcb.exe':
|
||||
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
|
||||
from .diagnostic_open import cancelled_startup_step
|
||||
closed, acted = cancelled_startup_step(job, pcb_pid, diagnostic_state,
|
||||
closed_frame=close_frame, deadline=deadline, post=cleanup_post, emit=emit)
|
||||
if closed is not None and not sent:
|
||||
sent, close_frame = True, closed
|
||||
emit(stage='startup_close_requested', pcb_pid=pcb_pid, hwnd=closed,
|
||||
document_identity='native_path_pid_logs', cleanup='cancelled_diagnostic')
|
||||
if acted:
|
||||
continue
|
||||
if not sent:
|
||||
windows = []
|
||||
def observe(hwnd, _):
|
||||
if (win32process.GetWindowThreadProcessId(hwnd)[1] == pcb_pid
|
||||
@@ -213,8 +246,9 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
win32gui.EnumChildWindows(main[0], child, None)
|
||||
addresses = unreleased_addresses(job['lmc_file'], job['project'], job['pcb'])
|
||||
if len(main) == 1 and not unknown and not documents and (cancelled_open or not addresses):
|
||||
close_handle = handles.enter_context(residual_sessions._process_handle(pcb_pid))
|
||||
close_identity = residual_sessions._handle_identity(close_handle)
|
||||
if close_handle is None:
|
||||
close_handle = handles.enter_context(residual_sessions._process_handle(pcb_pid))
|
||||
close_identity = residual_sessions._handle_identity(close_handle)
|
||||
if Path(close_identity['image']).name.casefold() != 'expeditionpcb.exe':
|
||||
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
|
||||
win32gui.PostMessage(main[0], win32con.WM_CLOSE, 0, 0)
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
"""Cancellation may race native loading after COM/document admission stopped."""
|
||||
from copy import deepcopy
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from cbb_refresh_verify import diagnostic_open, failed_session, residual_sessions
|
||||
from cbb_refresh_verify.dialog_models import ControlSnapshot, DialogPhase, WindowSnapshot
|
||||
from test_failed_startup import startup_fixture
|
||||
from test_diagnostic_open import write_logs
|
||||
|
||||
|
||||
def loaded_fixture(tmp_path, monkeypatch, *, empty_close_first=False, obstacle=''):
|
||||
import win32con, win32gui
|
||||
job, records, messages = startup_fixture(tmp_path, monkeypatch)
|
||||
job.update(project=str(tmp_path/'IP101GR/IP101GR.prj'), pcb=str(tmp_path/'IP101GR/PCB/IP101GR.pcb'),
|
||||
diagnostic_only=True, cancel_signal=str(tmp_path/'cancel.signal'))
|
||||
Path(job['pcb']).parent.mkdir(parents=True)
|
||||
Path(job['pcb']).touch(); Path(job['cancel_signal']).touch()
|
||||
records[0] = (12, records[0][1], f'ExpeditionPCB.exe "{job["pcb"]}" -ReusableCircuit', 11)
|
||||
job['diagnostic_log_baseline'] = diagnostic_open.snapshot_diagnostic_logs(job)
|
||||
write_logs(job, pid=99 if obstacle == 'foreign_log_pid' else 12, foreign=obstacle == 'foreign_log_path')
|
||||
if obstacle == 'stale_logs': job['diagnostic_log_baseline'] = diagnostic_open.snapshot_diagnostic_logs(job)
|
||||
if obstacle == 'write': (tmp_path/'save.log').write_text('save entered')
|
||||
if obstacle == 'ordinary': job['diagnostic_only'] = False
|
||||
if obstacle == 'not_cancelled': Path(job['cancel_signal']).unlink()
|
||||
state = dict(ticks=0., tip=not empty_close_first, declined=False, closing=False)
|
||||
clock = SimpleNamespace(monotonic=lambda:state['ticks'],
|
||||
sleep=lambda seconds:state.__setitem__('ticks', state['ticks']+seconds))
|
||||
monkeypatch.setattr(failed_session, 'time', clock)
|
||||
monkeypatch.setattr(diagnostic_open, 'time', clock)
|
||||
target = dict(hwnd=100, pid=12, **{'class':'Afx:main'},
|
||||
text='Expedition PCB - Reusable Block - [IP101GR]', enabled=False,
|
||||
children=[dict(hwnd=101, **{'class':'MDIClient'}, text='', parent=100),
|
||||
dict(hwnd=102, **{'class':'Afx:document'}, text='IP101GR', parent=101)])
|
||||
if obstacle == 'foreign_mdi': target['children'][1]['text'] = 'Other'
|
||||
forward = dict(hwnd=200, pid=12, **{'class':'#32770'}, text='Expedition PCB', owner=100,
|
||||
children=[dict(hwnd=30, **{'class':'Static'}, id=6172,
|
||||
text='New changes are ready for Forward Annotation. Do you want to Forward Annotate now?'),
|
||||
dict(hwnd=31, **{'class':'Button'}, id=7, text='&No', enabled=True),
|
||||
dict(hwnd=32, **{'class':'Button'}, id=6, text='&Yes', enabled=True)])
|
||||
if obstacle == 'foreign_prompt': forward['owner'] = 999
|
||||
if obstacle == 'unknown': forward['text'] = 'Unknown action'
|
||||
def windows(pid):
|
||||
if state['tip'] or empty_close_first and not state['closing']: return []
|
||||
frame = deepcopy(target)
|
||||
frame['enabled'] = state['declined']
|
||||
if not state['declined'] or obstacle == 'progress':
|
||||
frame['children'].append(dict(hwnd=103, **{'class':'msctls_progress32'}, text='', visible=True))
|
||||
return [frame] + ([] if state['declined'] else [deepcopy(forward)])
|
||||
monkeypatch.setattr(diagnostic_open, '_windows', windows)
|
||||
monkeypatch.setattr(diagnostic_open, '_request_close_handoff', lambda *a, **kw:
|
||||
pytest.fail('cancelled supervisor must not be asked for a normal admission ack'))
|
||||
monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn,arg:
|
||||
[fn(h,arg) for h in ((200,) if state['tip'] else (100,200))])
|
||||
monkeypatch.setattr(win32gui, 'GetClassName', lambda h:'#32770' if h == 200 else 'Afx:main')
|
||||
monkeypatch.setattr(win32gui, 'GetWindowText', lambda h:
|
||||
'Expedition PCB' if empty_close_first and not state['closing'] else target['text'])
|
||||
monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda h: h != 200 or state['tip'] or not empty_close_first)
|
||||
tip = WindowSnapshot(200,12,'ExpeditionPCB.exe','pcb','#32770','Tip of the Day',
|
||||
DialogPhase.PCB_STARTING,(ControlSnapshot(201,1,'Button','OK',enabled=True),))
|
||||
unknown = WindowSnapshot(200,12,'ExpeditionPCB.exe','pcb','#32770','Expedition PCB',
|
||||
DialogPhase.PCB_STARTING,())
|
||||
monkeypatch.setattr(failed_session, '_startup_snapshot', lambda *a:tip if state['tip'] else unknown)
|
||||
def post(hwnd, message, *_):
|
||||
messages.append((hwnd,message))
|
||||
if hwnd == 201: state['tip'] = False
|
||||
elif hwnd == 31:
|
||||
state['declined'] = True
|
||||
if state['closing']: records.clear()
|
||||
elif hwnd == 100 and message == win32con.WM_CLOSE:
|
||||
state['closing'] = True
|
||||
if state['declined']: records.clear()
|
||||
monkeypatch.setattr(win32gui, 'PostMessage', post)
|
||||
return job, records, messages, state
|
||||
|
||||
|
||||
@pytest.mark.parametrize('empty_close_first', [False, True])
|
||||
def test_cancelled_diagnostic_tip_to_loaded_forward_no_closes_once_without_ack(tmp_path, monkeypatch, empty_close_first):
|
||||
job, records, messages, state = loaded_fixture(tmp_path, monkeypatch, empty_close_first=empty_close_first)
|
||||
events = []
|
||||
result = failed_session.close_failed_startup(job,12,timeout_seconds=1,
|
||||
emit=lambda **event:events.append(event))
|
||||
assert result['status'] == 'CLOSED' and result['release']['safe_to_continue']
|
||||
assert messages == ([(100,16),(31,245)] if empty_close_first else [(201,245),(31,245),(100,16)])
|
||||
assert not records and Path(job['cancel_signal']).exists()
|
||||
assert not any(e.get('stage') in ('diagnostic_complete','diagnostic_native_open_confirmed','save_start') for e in events)
|
||||
assert sum(e['stage']=='startup_close_requested' for e in events)==1
|
||||
|
||||
|
||||
@pytest.mark.parametrize('obstacle', ['foreign_log_pid','foreign_log_path','stale_logs','foreign_mdi',
|
||||
'foreign_prompt','unknown','progress','write','ordinary','not_cancelled'])
|
||||
def test_cancelled_loaded_cleanup_cannot_override_identity_write_or_unknown_guards(tmp_path, monkeypatch, obstacle):
|
||||
job, records, messages, state = loaded_fixture(tmp_path, monkeypatch, obstacle=obstacle)
|
||||
result = failed_session.close_failed_startup(job,12,timeout_seconds=.5)
|
||||
assert result['status']=='RETAINED' and records
|
||||
assert messages == ([(201,245),(31,245)] if obstacle=='progress' else [(201,245)])
|
||||
|
||||
|
||||
def test_cancelled_diagnostic_keeps_one_thirty_second_cleanup_budget(tmp_path, monkeypatch):
|
||||
job, records, messages, state = loaded_fixture(tmp_path,monkeypatch,obstacle='progress')
|
||||
result = failed_session.close_failed_startup(job,12)
|
||||
assert result['status']=='RETAINED' and records
|
||||
assert 30 <= state['ticks'] <= 30.2
|
||||
assert messages==[(201,245),(31,245)]
|
||||
|
||||
|
||||
def test_unknown_sibling_vetoes_known_forward_no(tmp_path,monkeypatch):
|
||||
job,records,messages,state=loaded_fixture(tmp_path,monkeypatch)
|
||||
original=diagnostic_open._windows
|
||||
def windows(pid):
|
||||
values=original(pid)
|
||||
return values+[dict(hwnd=999,pid=12,**{'class':'#32770'},text='Unknown action',children=[])] if values else values
|
||||
monkeypatch.setattr(diagnostic_open,'_windows',windows)
|
||||
result=failed_session.close_failed_startup(job,12,timeout_seconds=.5)
|
||||
assert result['status']=='RETAINED' and records
|
||||
assert messages==[(201,245)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('filename',['IP101GR.pcb','Foreign.pcb'])
|
||||
def test_cancelled_loaded_close_only_declines_exact_owned_save_question(tmp_path,monkeypatch,filename):
|
||||
import win32gui
|
||||
job,records,messages,state=loaded_fixture(tmp_path,monkeypatch)
|
||||
original_windows=diagnostic_open._windows
|
||||
def windows(pid):
|
||||
if not state['closing']:return original_windows(pid)
|
||||
return [dict(hwnd=400,pid=12,**{'class':'#32770'},text='Expedition PCB',owner=100,
|
||||
children=[dict(hwnd=40,**{'class':'Static'},text=f'Save changes to {filename}?'),
|
||||
dict(hwnd=41,**{'class':'Button'},id=7,text='No',enabled=True),
|
||||
dict(hwnd=42,**{'class':'Button'},id=6,text='Yes',enabled=True),
|
||||
dict(hwnd=43,**{'class':'Button'},id=2,text='Cancel',enabled=True)])]
|
||||
monkeypatch.setattr(diagnostic_open,'_windows',windows)
|
||||
original_post=win32gui.PostMessage
|
||||
def post(hwnd,message,*args):
|
||||
if hwnd==100:
|
||||
messages.append((hwnd,message));state['closing']=True
|
||||
elif hwnd==41:
|
||||
messages.append((hwnd,message));records.clear()
|
||||
else:original_post(hwnd,message,*args)
|
||||
monkeypatch.setattr(win32gui,'PostMessage',post)
|
||||
result=failed_session.close_failed_startup(job,12,timeout_seconds=1)
|
||||
assert result['status']==('CLOSED' if filename=='IP101GR.pcb' else 'RETAINED')
|
||||
assert messages==[(201,245),(31,245),(100,16)]+([(41,245)] if filename=='IP101GR.pcb' else [])
|
||||
|
||||
|
||||
def test_supervisor_finishes_inflight_poll_before_signalling_cleanup_and_never_polls_again(tmp_path,monkeypatch):
|
||||
import json
|
||||
from threading import Event
|
||||
from cbb_refresh_verify import desktop_worker
|
||||
from cbb_refresh_verify.verify_runner import run_verify
|
||||
from cbb_refresh_verify.dialog_supervisor import DialogPollResult
|
||||
from test_verify_runner import fixture, request, PORTS_OK
|
||||
fixture(tmp_path); stop=Event(); state={'polling':False,'polls':0,'cleanup':False}
|
||||
class Worker:
|
||||
desktop=None;pid=700;companion_pids=[];returncode=None
|
||||
def __init__(self,command,name):
|
||||
self.name=name
|
||||
state['path']=Path(command[-1]);state['job']=json.loads(state['path'].read_text())
|
||||
state['path'].with_name('events.jsonl').write_text(json.dumps(dict(stage='pcb_worker_started',pcb_pid=901))+'\n')
|
||||
def poll(self):return self.returncode
|
||||
def request_stop(self):
|
||||
assert not state['polling'] and state['polls']==1
|
||||
Path(state['job']['cancel_signal']).touch()
|
||||
def wait(self,timeout=5):
|
||||
assert Path(state['job']['cancel_signal']).exists() and not state['polling']
|
||||
state['cleanup']=True;self.returncode=1;return 1
|
||||
def close(self):pass
|
||||
class Supervisor:
|
||||
def poll(self,*args):
|
||||
assert not state['cleanup'] and not Path(state['job']['cancel_signal']).exists()
|
||||
state['polling']=True;state['polls']+=1;stop.set();state['polling']=False
|
||||
return DialogPollResult()
|
||||
monkeypatch.setattr(desktop_worker,'DesktopWorker',Worker)
|
||||
result=run_verify(request(tmp_path,diagnostic_only=True),port_check=PORTS_OK,stop=stop,
|
||||
dialog_supervisor_factory=lambda **kw:Supervisor())
|
||||
assert result.status=='CANCELLED' and state['cleanup'] and state['polls']==1
|
||||
assert not state['path'].with_name('diagnostic-close-ack.json').exists()
|
||||
Reference in new issue
Block a user