Files
cbb-refresh-verify-795/tests/test_observer_startup_cleanup.py
T

164 lines
8.7 KiB
Python

import json
from pathlib import Path
import threading
import pytest
from cbb_refresh_verify import diagnostic_open, residual_sessions, session_record
from test_registered_startup_release import registered_fixture
from test_cancelled_ordinary_startup import ordinary_proof
def fixture(tmp_path, monkeypatch, *, obstacle='', closed=False):
load=diagnostic_open._load_evidence
job,row,records,messages,state=registered_fixture(tmp_path,monkeypatch,obstacle=obstacle,closed=closed)
monkeypatch.setattr(diagnostic_open,'_load_evidence',load)
events=ordinary_proof(job,tmp_path,state['prelaunch_baseline'])
if closed:events.append(dict(stage='startup_close_requested',pcb_pid=12,hwnd=100))
(tmp_path/'events.jsonl').write_text(''.join(json.dumps(e)+'\n' for e in events))
(tmp_path/'request.json').write_text(json.dumps(job))
monkeypatch.setattr(residual_sessions,'inspect_residual_sessions',lambda *a,**k:dict(sessions=[row]))
return job,row,records,messages,state
@pytest.mark.parametrize('closed',[False,True])
def test_registered_observer_finishes_late_loaded_ordinary_startup_once(tmp_path,monkeypatch,closed):
job,row,records,messages,state=fixture(tmp_path,monkeypatch,closed=closed)
original=(tmp_path/'result.json').read_bytes()
states=[]
def reconcile(*a,**kw):
states.append(1)
return dict(status='ACTIVE' if records else 'RELEASED',operation_id=job['operation_id'],
release_proof=None if records else dict(status='RELEASE_CONFIRMED'))
monkeypatch.setattr(session_record,'_reconcile',reconcile)
stop=threading.Event()
def progress(value):
if len(states)>2:stop.set()
result=session_record.observe_retained_session(tmp_path/'session.json',evidence_root=tmp_path,stop=stop,progress=progress)
assert result['status']=='RELEASED'
assert messages==([(31,245)] if closed else [(31,245),(100,16)])
assert (tmp_path/'result.json').read_bytes()==original
claim=json.loads((tmp_path/'session.json').read_text())['retained_startup_cleanup']
assert claim['operation_id']==job['operation_id'] and claim['pcb_pid']==12
@pytest.mark.parametrize('obstacle',['live_worker','other_write','save','foreign_identity','missing_cancel'])
def test_automatic_observer_does_not_consume_intent_or_act_without_positive_proof(tmp_path,monkeypatch,obstacle):
job,row,records,messages,state=fixture(tmp_path,monkeypatch,obstacle=obstacle)
residual_sessions.resume_cancelled_startup(tmp_path/'session.json')
assert not messages and records
assert 'retained_startup_cleanup' not in json.loads((tmp_path/'session.json').read_text())
def test_timed_out_retained_phase_is_not_restarted_by_observer_or_explicit_release(tmp_path,monkeypatch):
job,row,records,messages,state=fixture(tmp_path,monkeypatch)
read=residual_sessions._legacy_diagnostic_windows
def progress(bound):
values=read(bound)
if state['declined']:values[0]['children'].append(dict(hwnd=123,**{'class':'msctls_progress32'},visible=True))
return values
monkeypatch.setattr(residual_sessions,'_legacy_diagnostic_windows',progress)
residual_sessions.resume_cancelled_startup(tmp_path/'session.json')
first=state['ticks']
assert 30<=first<30.2 and messages==[(31,245)]
residual_sessions.resume_cancelled_startup(tmp_path/'session.json')
assert residual_sessions._request_close(row)['release_status']=='WAITING'
assert state['ticks']==first and messages==[(31,245)] and records
def test_claim_is_persisted_before_any_native_action_and_failure_prevents_action(tmp_path,monkeypatch):
job,row,records,messages,state=fixture(tmp_path,monkeypatch)
def denied(*a,**kw):raise OSError('journal unavailable')
monkeypatch.setattr(session_record,'write_session_record',denied)
residual_sessions.resume_cancelled_startup(tmp_path/'session.json')
assert not messages and records
def test_retained_phase_never_repeats_worker_no_on_still_visible_prompt(tmp_path,monkeypatch):
job,row,records,messages,state=fixture(tmp_path,monkeypatch)
with (tmp_path/'events.jsonl').open('a') as stream:
stream.write(json.dumps(dict(stage='startup_prompt_no',pcb_pid=12,hwnd=31,control_id=7))+'\n')
residual_sessions.resume_cancelled_startup(tmp_path/'session.json')
assert not messages and records and 30<=state['ticks']<30.2
@pytest.mark.parametrize('obstacle',['unknown','hidden_document','revoked'])
def test_late_observer_preserves_unknown_or_changed_loaded_state_before_claim(tmp_path,monkeypatch,obstacle):
job,row,records,messages,state=fixture(tmp_path,monkeypatch)
read=residual_sessions._legacy_diagnostic_windows
def windows(bound):
values=read(bound)
if obstacle=='unknown':values.append(dict(hwnd=999,pid=12,**{'class':'#32770'},text='Unknown',children=[]))
if obstacle=='hidden_document':values[0]['children'].append(dict(hwnd=888,**{'class':'Afx:document'},text='Other',parent=101,visible=False))
if obstacle=='revoked':
with (tmp_path/'events.jsonl').open('a') as stream:stream.write('{"stage":"startup_write_admitted"}\n')
return values
monkeypatch.setattr(residual_sessions,'_legacy_diagnostic_windows',windows)
residual_sessions.resume_cancelled_startup(tmp_path/'session.json')
assert not messages and records
assert 'retained_startup_cleanup' not in json.loads((tmp_path/'session.json').read_text())
def test_duplicate_observer_explicit_release_and_process_restart_share_persisted_claim(tmp_path):
"""Real process/mutex/file race; only native evidence and action boundary are stubs."""
import os,subprocess,sys,time
path=tmp_path/'session.json'
session_record.write_session_record(path,dict(operation_id='one',block='B',library=str(tmp_path/'lib.lmc')))
(tmp_path/'request.json').write_text(json.dumps(dict(diagnostic_only=False)))
script=tmp_path/'race.py'
script.write_text('''
import json,sys,time
from pathlib import Path
from contextlib import nullcontext
import win32api
from cbb_refresh_verify import session_record as s,residual_sessions as r,diagnostic_open as d,failed_session as f
root=Path(sys.argv[1]);mode=sys.argv[2];tag=sys.argv[3];path=root/'session.json'
job=dict(diagnostic_only=False,desktop='CbbVerify_test',pcb=str(root/'B.pcb'))
row=dict(pid=1,name='ExpeditionPCB.exe',created_handle='bound',image='ExpeditionPCB.exe',owner_sid='owner',session_id=1)
proof=dict(job=job,record_path=str(path),operation_id='one',closed_frame=None)
r._process_handle=lambda *a,**k:nullcontext(win32api.GetCurrentProcess())
r._handle_identity=lambda h:dict(created_handle='bound',image='ExpeditionPCB.exe')
r._force_ownership=lambda *a:dict(force_user_confirmed=True,owner_sid='owner',session_id=1)
r._process_windows=lambda *a:{}
r._cancelled_diagnostic_record=lambda *a:proof
r._legacy_diagnostic_windows=lambda *a:[dict(hwnd=100,pid=1)]
d._target_frame=lambda *a,**k:dict(hwnd=100,pid=1)
d._pending_prompt=lambda *a,**k:False
f.cancelled_prewrite_startup=lambda *a:{}
r.inspect_residual_sessions=lambda *a,**k:dict(sessions=[row])
s._session=lambda *a:(s.read_session_record(path,evidence_root=root),{},[dict(role='native',pid=1,image='ExpeditionPCB.exe')])
def close(*a,**k):
assert 'retained_startup_cleanup' in json.loads(path.read_text())
(root/('action-'+tag)).write_text('one native phase')
until=time.monotonic()+8
while not (root/'release').exists() and time.monotonic()<until:time.sleep(.01)
return dict(release_status='WAITING')
r._close_registered_startup=close
(root/('ready-'+tag)).touch()
until=time.monotonic()+8
while not (root/'go').exists() and time.monotonic()<until:time.sleep(.01)
result=r.resume_cancelled_startup(path) if mode=='observer' else r._request_close(row)
(root/('result-'+tag)).write_text(json.dumps(result))
''',encoding='utf-8')
env=dict(os.environ,PYTHONPATH=str(Path(session_record.__file__).parents[1]))
children=[]
def start(mode,tag):
child=subprocess.Popen([sys.executable,str(script),str(tmp_path),mode,tag],env=env)
children.append(child);return child
try:
start('observer','a');start('explicit','b')
end=time.monotonic()+5
while len(list(tmp_path.glob('ready-*')))<2 and time.monotonic()<end:time.sleep(.01)
assert len(list(tmp_path.glob('ready-*')))==2
(tmp_path/'go').touch()
end=time.monotonic()+5
while not list(tmp_path.glob('action-*')) and time.monotonic()<end:time.sleep(.01)
assert len(list(tmp_path.glob('action-*')))==1
(tmp_path/'release').touch()
for child in children:assert child.wait(5)==0
assert start('observer','restart').wait(5)==0
assert len(list(tmp_path.glob('action-*')))==1
finally:
(tmp_path/'go').touch();(tmp_path/'release').touch()
for child in children:child.wait(10)