"""Finish a proved owned idle client, then prove resources independently.""" from contextlib import nullcontext from dataclasses import replace import json from pathlib import Path from threading import Event import pytest from cbb_refresh_verify import residual_sessions as residual, session_record as sessions from cbb_refresh_verify import operation_lifecycle as lifecycle from cbb_refresh_verify.verify_runner import VerifyResult def owned_fixture(tmp_path, monkeypatch, kind='startup'): import win32con, win32event library=tmp_path/'library/lib.lmc';library.parent.mkdir();library.touch() root=tmp_path/'evidence';root.mkdir() operation='catalog' if kind=='catalog' else 'verify' desktop=('CbbManagement_' if kind=='catalog' else 'CbbVerify_')+'owned' job=dict(operation_id='owned',operation=operation,library=str(library),lmc_file=str(library), block='Bad',root=str(root),desktop=desktop,interactive_input=False, project=str(library.parent/'ReusableBlocksLP/Bad/Work/Bad.prj'), pcb=str(library.parent/'ReusableBlocksLP/Bad/Work/PCB/Bad.pcb'), session_record_path=str(root/'session.json')) if kind=='catalog':job['worker_role']='catalog_readonly' worker=dict(role='worker',pid=11,created_handle='worker-created',image='C:/Python/python.exe', owner_sid='owner',session_id=1) native=dict(role='native',pid=12,created_handle='native-created', image='D:/Mentor/LibraryManager.exe' if kind=='catalog' else 'D:/Mentor/ExpeditionPCB.exe', owner_sid='owner',session_id=1) sessions.write_session_record(root/'session.json',dict(operation_id='owned',operation=operation, library=str(library),block='Bad',desktop=desktop,processes=[worker])) sessions.write_session_record(root/'worker-state.json',dict(operation_id='owned',phase='UNCONFIRMED',processes=[native])) result=dict(status='FAIL',safe_to_continue=False,error_stage='PCB_STARTING', error_category='MENTOR_DATABASE_LOAD_FAILED',block_name='Bad',evidence_path=str(root/'result.json')) if kind=='saved': result.update(error_stage='library_flag',error_category='MENTOR_VERIFY_NOT_COMMITTED', write_outcome=dict(save_state='COMMITTED',close_state='CLOSED',helper_state='EXITED',interrupted=False)) if kind=='catalog':result=dict(success=False,safe_to_continue=False,detail='catalog close failed') (root/'request.json').write_text(json.dumps(job)) (root/'result.json').write_text(json.dumps(result)) windows=[dict(hwnd=100,**{'class':'Afx:main'},title='Library Manager' if kind=='catalog' else 'Expedition PCB', desktop=desktop,enabled=True,documents=[],children=[])] state=dict(worker_alive=False,native_alive=True,identity_changed=False,posts=[]) monkeypatch.setattr(residual,'_process_handle',lambda pid,**kw:nullcontext(pid)) monkeypatch.setattr(residual,'_handle_identity',lambda handle: {k:(('replacement' if state['identity_changed'] else v) if k=='created_handle' else v) for k,v in (worker if handle==11 else native).items() if k in ('created_handle','image')}) monkeypatch.setattr(residual,'_force_ownership',lambda *a:dict(force_user_confirmed=True,owner_sid='owner',session_id=1)) monkeypatch.setattr(residual,'_process_windows',lambda *a,**kw:{12:windows}) monkeypatch.setattr(sessions,'active_write_records',lambda library:[]) wait=win32event.WaitForSingleObject monkeypatch.setattr(win32event,'WaitForSingleObject',lambda handle,ms: (win32con.WAIT_TIMEOUT if state['worker_alive' if handle==11 else 'native_alive'] else win32con.WAIT_OBJECT_0) if handle in (11,12) else wait(handle,ms)) def post(window, hwnd, pid, message): record=sessions.read_session_record(root/'session.json',evidence_root=root) assert record.get('owned_idle_cleanup'), 'intent must be durable before native action' state['posts'].append((hwnd,pid,message)) state['native_alive']=False monkeypatch.setattr(residual,'_post_window_message',post) return root,job,result,windows,state @pytest.mark.parametrize('kind',['startup','saved','catalog']) def test_owned_idle_client_is_closed_once_without_changing_business_result(tmp_path,monkeypatch,kind): root,job,result,windows,state=owned_fixture(tmp_path,monkeypatch,kind) before=(root/'result.json').read_bytes() assert residual.finish_owned_idle_session(root/'session.json') assert state['posts']==[(100,12,16)] and not state['native_alive'] residual.finish_owned_idle_session(root/'session.json') assert state['posts']==[(100,12,16)] assert (root/'result.json').read_bytes()==before @pytest.mark.parametrize('obstacle',['worker_alive','identity_changed','documents','hidden_document','unknown', 'progress','desktop','request_identity','save_unknown','other_write','stopped','claim_io','window_race']) def test_unproved_or_writing_client_is_never_automatically_closed(tmp_path,monkeypatch,obstacle): root,job,result,windows,state=owned_fixture(tmp_path,monkeypatch) stop=Event() if obstacle in ('worker_alive','identity_changed'):state[obstacle]=True if obstacle=='documents':windows[0]['documents']=[55] if obstacle=='hidden_document':windows[0]['children'].append(dict(hwnd=55,**{'class':'Afx:document'},visible=False)) if obstacle=='unknown':windows.append(dict(hwnd=200,**{'class':'#32770'},title='Unknown',enabled=True,desktop=job['desktop'],documents=[],children=[])) if obstacle=='progress':windows[0]['children'].append(dict(hwnd=60,**{'class':'msctls_progress32'})) if obstacle=='desktop':windows[0]['desktop']='Default' if obstacle=='request_identity': job['operation_id']='other';(root/'request.json').write_text(json.dumps(job)) if obstacle=='save_unknown':(root/'save.log').write_text('SAVE_START\n') if obstacle=='other_write':monkeypatch.setattr(sessions,'active_write_records',lambda _: [dict(operation_id='other')]) if obstacle=='stopped':stop.set() if obstacle=='claim_io': monkeypatch.setattr(sessions,'write_session_record',lambda *a,**kw: (_ for _ in ()).throw(OSError('journal unavailable'))) if obstacle=='window_race': original=sessions.write_session_record def write(path,value): original(path,value) if value.get('owned_idle_cleanup'):windows[0]['documents']=[55] monkeypatch.setattr(sessions,'write_session_record',write) residual.finish_owned_idle_session(root/'session.json',stop=stop) assert not state['posts'] and state['native_alive'] def test_late_release_actively_finishes_owned_idle_client_then_proves_shared_files(tmp_path,monkeypatch): root,job,result,windows,state=owned_fixture(tmp_path,monkeypatch) monkeypatch.setattr(sessions,'inspect_session_record',lambda *a,**kw: dict(status='ACTIVE' if state['native_alive'] else 'UNCONFIRMED')) def release(library,evidence,**kw): assert not state['native_alive'], 'resource proof must follow native cleanup' return dict(status='RELEASE_CONFIRMED',lease_state='RELEASED',library=library, blocked_resources=[],resource_scope=dict(scope_state='OBSERVED')) monkeypatch.setattr('cbb_refresh_verify.library_lock.release_retained_library',release) failed=VerifyResult('FAIL',stderr='database load failed',safe_to_continue=False, evidence_path=root/'result.json') updated=lifecycle.recheck_failed_release(job['library'],'Bad',failed) assert updated.status=='FAIL' and updated.safe_to_continue assert state['posts']==[(100,12,16)] def test_closed_client_does_not_imply_shared_database_released(tmp_path,monkeypatch): root,job,result,windows,state=owned_fixture(tmp_path,monkeypatch) monkeypatch.setattr(sessions,'inspect_session_record',lambda *a,**kw: dict(status='ACTIVE' if state['native_alive'] else 'UNCONFIRMED')) from cbb_refresh_verify.library_lock import LibraryBusy def release(*a,**kw):raise LibraryBusy('shared database still held by another client') monkeypatch.setattr('cbb_refresh_verify.library_lock.release_retained_library',release) failed=VerifyResult('FAIL',safe_to_continue=False,evidence_path=root/'result.json') updated=lifecycle.recheck_failed_release(job['library'],'Bad',failed) assert not updated.safe_to_continue and updated.status=='FAIL' assert state['posts']==[(100,12,16)] attempt=json.loads((root/'late-release-attempt.json').read_text()) assert 'shared database' in attempt['detail'] def test_retained_verify_lease_does_not_expand_one_target_to_every_cbb(tmp_path,monkeypatch): from cbb_refresh_verify import verify_runner as runner, library_lock as locks library=tmp_path/'library/lib.lmc';library.parent.mkdir();library.touch() other=library.parent/'ReusableBlocksLP/Other/Work/database/cdbsvr/sAddress.adr' other.parent.mkdir(parents=True);other.write_text('unrelated occupied engineering database') evidence=tmp_path/'evidence/result.json';evidence.parent.mkdir() evidence.write_text('{}') monkeypatch.setattr(runner,'_run_verify_serialized',lambda *a,**kw: VerifyResult('FAIL',safe_to_continue=False,evidence_path=evidence)) monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners',lambda *_:[]) result=runner._run_verify_task(runner.VerifyRequest(library,'Bad',evidence.parent)) assert not result.safe_to_continue try: proof=locks.release_retained_library(library,tmp_path/'release',block_name='Bad') assert proof['proof_scope']=='BLOCK' and proof['proof_block_name']=='Bad' assert other.read_text()=='unrelated occupied engineering database' finally: with locks._guard: owner=locks._owners.pop(locks.LibraryLock(library).key,None) if owner:owner['handle'].Close() @pytest.mark.parametrize('read_only',[False,True]) def test_background_observer_finishes_owned_idle_client_but_cold_observation_stays_read_only(tmp_path,monkeypatch,read_only): root,job,result,windows,state=owned_fixture(tmp_path,monkeypatch) def reconcile(*a,**kw): return dict(status='ACTIVE' if state['native_alive'] else 'RELEASED',operation_id='owned', library=job['library'],block='Bad',release_proof=None) monkeypatch.setattr(sessions,'_reconcile',reconcile) stop=Event() outcome=sessions.observe_retained_session(root/'session.json',evidence_root=root, observe_only=read_only,stop=stop,progress=lambda value:stop.set()) assert outcome['status']==('ACTIVE' if read_only else 'RELEASED') assert state['posts']==([] if read_only else [(100,12,16)]) def test_real_shared_database_handle_still_prevents_release_after_own_client_exits(tmp_path,monkeypatch): import win32con,win32file root,job,result,windows,state=owned_fixture(tmp_path,monkeypatch) library=Path(job['library']) shared=library.parent/'SymbolLibs/__ReusableBlocksSymb/icdb.dat' shared.parent.mkdir(parents=True);shared.write_bytes(b'actual shared database fixture') monkeypatch.setattr(sessions,'inspect_session_record',lambda *a,**kw: dict(status='ACTIVE' if state['native_alive'] else 'UNCONFIRMED')) monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners',lambda *_:[]) held=win32file.CreateFile(str(shared),win32con.GENERIC_READ,0,None,win32con.OPEN_EXISTING,0,None) try: failed=VerifyResult('FAIL',safe_to_continue=False,evidence_path=root/'result.json') updated=lifecycle.recheck_failed_release(library,'Bad',failed) assert state['posts']==[(100,12,16)] and not updated.safe_to_continue attempt=json.loads((root/'late-release-attempt.json').read_text()) assert 'icdb.dat' in attempt['detail'] assert attempt['status']=='IN_USE' and attempt['blocked_resources']==[str(shared)] finally: held.Close() @pytest.mark.parametrize('malformed',['request','result','write_outcome']) def test_malformed_record_never_authorizes_or_crashes_cleanup(tmp_path,monkeypatch,malformed): root,job,result,windows,state=owned_fixture(tmp_path,monkeypatch,'saved') if malformed=='write_outcome': result['write_outcome']=['not facts'];(root/'result.json').write_text(json.dumps(result)) else: (root/(malformed+'.json')).write_text('[]') assert not residual.finish_owned_idle_session(root/'session.json') assert not state['posts'] @pytest.mark.parametrize('changed',['result_block','result_path','state_after_claim']) def test_wrong_result_or_changed_state_cannot_authorize_normal_close(tmp_path,monkeypatch,changed): root,job,result,windows,state=owned_fixture(tmp_path,monkeypatch,'saved') if changed=='result_block':result['block_name']='Other' if changed=='result_path':result['evidence_path']=str(tmp_path/'other/result.json') (root/'result.json').write_text(json.dumps(result)) if changed=='state_after_claim': write=sessions.write_session_record def changed_state(path,record): write(path,record) if record.get('owned_idle_cleanup'): previous=sessions.read_session_record(root/'worker-state.json',evidence_root=root) write(root/'worker-state.json',{**previous,'phase':'NATIVE_CALL'}) monkeypatch.setattr(sessions,'write_session_record',changed_state) assert not residual.finish_owned_idle_session(root/'session.json') assert not state['posts']