"""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()