fix: prove prewrite cancellation and bound recovery metadata lifetime

This commit is contained in:
阿白叔 committed 2026-11-17 12:45:59 +08:00
1 parent 32dcd80d1e
commit 906cfc06be
14 files changed
+659 -60

No files matched your search

+41
View File
@@ -0,0 +1,41 @@
"""Real application close while one disposable metadata boundary is held."""
from pathlib import Path
import sys,time
from PySide6.QtCore import QTimer
from PySide6.QtWidgets import QApplication
from cbb_refresh_verify import scoped_manifest as manifest
from cbb_refresh_verify.operation_queue import check_active
from cbb_refresh_verify.ui.main_window import MainWindow
root=Path(sys.argv[1]);mode=sys.argv[2]
source=root/'source';source.mkdir()
(source/('one.log' if mode=='copy' else 'one.dat')).write_bytes(b'isolated fixture')
def held():
(root/'entered').touch()
while not (root/'release').exists():time.sleep(.02)
def hash_file(path):
held()
return manifest.hash_file(path)
if mode=='copy':
original=manifest.shutil.copy2
def copy_file(*args,**kwargs):
held()
return original(*args,**kwargs)
manifest.shutil.copy2=copy_file
def action():
if mode=='hash':manifest.build_manifest(source,hash_function=hash_file)
else:manifest.copy_verified(source,root/'partial-copy',hash_function=hash_file)
check_active()
(root/'late-dispatch').touch()
app=QApplication([])
window=MainWindow(reader=lambda _:None,data_root=root/'data');window.show()
job=window._new_job('management',library=root/'library.lmc')
window._start(action,lambda _:None,queued=False,job=job)
def close_when_entered():
if (root/'entered').exists():window.close()
else:QTimer.singleShot(20,close_when_entered)
QTimer.singleShot(20,close_when_entered)
code=app.exec()
(root/'main-returning').touch()
raise SystemExit(code)
+198
View File
@@ -0,0 +1,198 @@
import json
from pathlib import Path
import pytest
from cbb_refresh_verify import failed_session,session_record,diagnostic_open
from test_cancelled_loaded_startup import loaded_fixture
def ordinary_proof(job,root,baseline,*,worker=None,pid=12):
worker=worker or dict(pid=11,created_handle='worker-created',image='C:/App/python.exe',owner_sid='current',session_id=1)
job.update(diagnostic_only=False,operation='verify',operation_id=job.get('operation_id','verify-ordinary'),
library=job['lmc_file'],session_record_path=str(root/'session.json'),interactive_input=False)
job.pop('diagnostic_log_baseline',None)
session_record.write_session_record(root/'session.json',dict(operation_id=job['operation_id'],operation='verify',
library=job['library'],desktop=job['desktop'],cancel_signal=job['cancel_signal'],processes=[dict(role='worker',**worker)],
resource_scope=dict(scope_state='DECLARED',library=job['library'],operation_id=job['operation_id'],projects=[job['project']])))
binding={k:job[k] for k in ('operation_id','project','pcb','desktop')}
events=[dict(stage='startup_supervisor_no_write',**binding),
dict(stage='startup_prewrite_ready',worker_identity=worker,baseline=baseline,**binding),
dict(stage='pcb_baseline',pids=[]),dict(stage='pcb_worker_started',pcb_pid=pid),
dict(stage='startup_cancelled_prewrite',pcb_pid=pid,identity_verified=False,write_admitted=False,**binding)]
(root/'events.jsonl').write_text(''.join(json.dumps(e)+'\n' for e in events))
return events
@pytest.mark.parametrize('prior_close',[False,True])
def test_proved_ordinary_cancel_finishes_tip_to_loaded_without_annotation_or_second_close(tmp_path,monkeypatch,prior_close):
job,records,messages,state=loaded_fixture(tmp_path,monkeypatch,empty_close_first=prior_close)
ordinary_proof(job,tmp_path,job['diagnostic_log_baseline'])
result=failed_session.close_failed_startup(job,12,timeout_seconds=1)
assert result['status']=='CLOSED' and not records
assert messages==([(100,16),(31,245)] if prior_close else [(201,245),(31,245),(100,16)])
@pytest.mark.parametrize('obstacle',['missing_ready','missing_cancel_phase','supervisor_write','worker_write',
'missing_supervisor','missing_baseline','foreign_worker','foreign_target','save','missing_cancel','interactive','native_lm'])
def test_ordinary_cleanup_requires_positive_bound_no_write_evidence(tmp_path,monkeypatch,obstacle):
job,records,messages,state=loaded_fixture(tmp_path,monkeypatch)
events=ordinary_proof(job,tmp_path,job['diagnostic_log_baseline'])
if obstacle=='missing_ready':events=[e for e in events if e['stage']!='startup_prewrite_ready']
if obstacle=='missing_cancel_phase':events=[e for e in events if e['stage']!='startup_cancelled_prewrite']
if obstacle=='missing_supervisor':events=events[1:]
if obstacle=='supervisor_write':events.append(dict(stage='startup_supervisor_write_possible'))
if obstacle=='worker_write':events.append(dict(stage='startup_write_admitted'))
if obstacle=='missing_baseline':events[1].pop('baseline')
if obstacle=='foreign_worker':events[1]['worker_identity']['created_handle']='other'
if obstacle=='foreign_target':events[-1]['pcb']='C:/foreign.pcb'
if obstacle=='save':(tmp_path/'save.log').write_text('SAVE_ENTERED')
if obstacle=='missing_cancel':Path(job['cancel_signal']).unlink()
if obstacle=='interactive':job['interactive_input']=True
if obstacle=='native_lm':job['native_lm_verify']=True
(tmp_path/'events.jsonl').write_text(''.join(json.dumps(e)+'\n' for e in events))
result=failed_session.close_failed_startup(job,12,timeout_seconds=.3)
assert result['status']=='RETAINED' and records
assert not any(h==31 or m==16 for h,m in messages)
def test_worker_publishes_bound_baseline_before_launch_and_revokes_before_integration(tmp_path,monkeypatch):
from test_verify_worker_stability import exercise_worker
from cbb_refresh_verify import mentor_adapter,integration
job,events,execute=exercise_worker(tmp_path,monkeypatch)
job.update(operation_id='op',operation='verify',library=job['lmc_file'],desktop='CbbVerify_test',
session_record_path=str(Path(job['root'])/'session.json'),diagnostic_only=False)
launch=mentor_adapter.launch_pcb_process
def start(*args):
assert any(e['stage']=='startup_prewrite_ready' and 'baseline' in e for e in events)
return launch(*args)
def write(*args,**kwargs):
assert any(e['stage']=='startup_write_admitted' for e in events)
monkeypatch.setattr(mentor_adapter,'launch_pcb_process',start)
monkeypatch.setattr(integration,'refresh_integration',write)
assert execute()['status']=='PASS'
def test_cancelled_worker_records_positive_prewrite_phase_before_startup_cleanup(tmp_path,monkeypatch):
from test_verify_worker_stability import exercise_worker
from cbb_refresh_verify import pcb_bridge
job,events,execute=exercise_worker(tmp_path,monkeypatch)
job.update(operation_id='op',operation='verify',library=job['lmc_file'],desktop='CbbVerify_test',
session_record_path=str(Path(job['root'])/'session.json'),diagnostic_only=False,
cancel_signal=str(tmp_path/'cancel.signal'))
def cancel(*args,**kwargs):
Path(job['cancel_signal']).touch();raise RuntimeError('VERIFY_CANCELLED')
monkeypatch.setattr(pcb_bridge,'wait_for_target_document',cancel)
observed=[]
def cleanup(*args,**kwargs):observed.extend(events);return {'status':'RETAINED'}
monkeypatch.setattr(failed_session,'close_failed_startup',cleanup)
with pytest.raises(RuntimeError,match='VERIFY_CANCELLED'):execute()
assert any(e['stage']=='startup_cancelled_prewrite' and e['write_admitted'] is False
and e['identity_verified'] is False for e in observed)
@pytest.mark.parametrize('journal_fails',[False,True])
def test_dialog_backend_records_write_revocation_before_action(journal_fails):
from types import SimpleNamespace
from cbb_refresh_verify.dialog_supervisor import Win32DialogBackend,DialogSnapshot,DialogControl
calls=[]
gui=SimpleNamespace(PostMessage=lambda *args:calls.append('native'))
backend=Win32DialogBackend((),win32gui=gui,win32process=object(),win32con=SimpleNamespace(BM_CLICK=245))
def before(snapshot,action):
calls.append('journal')
if journal_fails:raise OSError('cannot record phase')
backend.before_action=before
snapshot=DialogSnapshot(100,12,'Expedition PCB',(DialogControl(101,6,'Button','Yes',True),))
if journal_fails:
with pytest.raises(OSError):backend.perform(snapshot,'confirm_forward_annotation')
assert calls==['journal']
else:
backend.perform(snapshot,'confirm_forward_annotation');assert calls==['journal','native']
def test_positive_ordinary_cancel_phase_yields_after_initial_wait(tmp_path,monkeypatch):
from test_cancelled_session_handoff import worker_fixture
state,stop,run=worker_fixture(tmp_path,monkeypatch)
# The real worker publishes its cancellation fact during the first wait.
from cbb_refresh_verify import desktop_worker
Worker=desktop_worker.DesktopWorker;wait=Worker.wait
def complete_proof(worker,timeout=5):
job=state['job']
baseline={'started_ns':1,'files':{}}
ordinary_proof(job,state['path'].parent,baseline,pid=901,
worker=dict(pid=700,created_handle='worker',image='C:/App/python.exe',owner_sid='current',session_id=1))
return wait(worker,timeout)
monkeypatch.setattr(Worker,'wait',complete_proof)
assert run(False).status=='CANCELLED'
assert state['waits']==[5]
@pytest.mark.parametrize('proof_present',[True,False])
def test_normal_release_of_ordinary_retained_startup_requires_new_complete_prewrite_proof(tmp_path,monkeypatch,proof_present):
from test_registered_startup_release import registered_fixture
from cbb_refresh_verify import residual_sessions
load=diagnostic_open._load_evidence
job,row,records,messages,state=registered_fixture(tmp_path,monkeypatch)
monkeypatch.setattr(diagnostic_open,'_load_evidence',load)
job['diagnostic_only']=False
if proof_present:ordinary_proof(job,tmp_path,state['prelaunch_baseline'])
(tmp_path/'request.json').write_text(json.dumps(job))
result=residual_sessions._request_close(row)
assert result['release_status']==('RELEASED' if proof_present else 'WAITING'),result
assert messages==([(31,245),(100,16)] if proof_present else [])
@pytest.mark.parametrize('obstacle',['unknown','hidden_document','progress','foreign_log_pid','foreign_log_path','revoked'])
def test_ordinary_cleanup_keeps_native_window_write_and_identity_vetoes(tmp_path,monkeypatch,obstacle):
job,records,messages,state=loaded_fixture(tmp_path,monkeypatch,
obstacle=obstacle if obstacle in ('unknown','progress','foreign_log_pid','foreign_log_path') else '')
ordinary_proof(job,tmp_path,job['diagnostic_log_baseline'])
read=diagnostic_open._windows
def windows(pid):
values=read(pid)
if values and obstacle=='hidden_document':
values[0]['children'].append(dict(hwnd=888,**{'class':'Afx:document'},text='Other',parent=101,visible=False))
if state['declined'] and obstacle=='revoked':
with (tmp_path/'events.jsonl').open('a') as stream:stream.write(json.dumps(dict(stage='startup_write_admitted'))+'\n')
return 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 not any(message==16 for _,message in messages)
assert messages==[(201,245)]+([(31,245)] if obstacle in ('progress','revoked') else [])
def test_proved_cancelled_startup_cannot_ack_tip_after_absolute_deadline(tmp_path,monkeypatch):
job,records,messages,state=loaded_fixture(tmp_path,monkeypatch)
ordinary_proof(job,tmp_path,job['diagnostic_log_baseline'])
assert failed_session.close_failed_startup(job,12,timeout_seconds=0)['status']=='RETAINED'
assert not messages and records
def test_agent_backend_cannot_dispatch_before_phase_journal():
from types import SimpleNamespace
from cbb_refresh_verify.dialog_supervisor import AgentDialogBackend
from cbb_refresh_verify.dialog_models import WindowSnapshot,DialogPhase
calls=[]
backend=AgentDialogBackend(SimpleNamespace(perform=lambda **kwargs:calls.append('native')),
before_action=lambda *args:calls.append('journal'))
snapshot=WindowSnapshot(100,12,'ExpeditionPCB.exe','pcb','#32770','Expedition PCB',DialogPhase.PCB_STARTING,())
backend.perform(snapshot,{'action':'confirm_forward_annotation'},DialogPhase.PCB_STARTING)
assert calls==['journal','native']
@pytest.mark.parametrize('action',['tip','empty_close'])
def test_startup_deadline_is_rechecked_after_window_read_before_post(tmp_path,monkeypatch,action):
import win32gui
job,records,messages,state=loaded_fixture(tmp_path,monkeypatch,empty_close_first=action=='empty_close')
ordinary_proof(job,tmp_path,job['diagnostic_log_baseline'])
if action=='tip':
snapshot=failed_session._startup_snapshot
def read(*args):
value=snapshot(*args);state['ticks']=2;return value
monkeypatch.setattr(failed_session,'_startup_snapshot',read)
else:
def children(*args):state['ticks']=2
monkeypatch.setattr(win32gui,'EnumChildWindows',children)
assert failed_session.close_failed_startup(job,12,timeout_seconds=1)['status']=='RETAINED'
assert not messages
+32
View File
@@ -0,0 +1,32 @@
from threading import Event,Thread
from cbb_refresh_verify.operation_queue import QueueCancelled
from test_issue15_ui_integration import window_for
def test_actual_global_stop_button_cancels_running_and_same_app_queued_jobs(qtbot,tmp_path,monkeypatch):
window=window_for(qtbot,tmp_path,monkeypatch)
first=window._new_job('verify',library=tmp_path/'lib.lmc')
second=window._new_job('native_session',library=tmp_path/'lib.lmc')
entered,release,waiting,done=Event(),Event(),Event(),Event();calls=[];errors=[]
def current():
calls.append('first');entered.set();release.wait(3)
def run_first():
try:window.native_queue.run(current,context=first.context,stop=first.context.stop)
except QueueCancelled:pass
def queued():
try:window.native_queue.run(lambda:calls.append('second'),context=second.context,
stop=second.context.stop,waiting=waiting.set)
except QueueCancelled as error:errors.append(error)
finally:done.set()
a=Thread(target=run_first);b=Thread(target=queued)
a.start();assert entered.wait(2);b.start()
try:
qtbot.waitUntil(waiting.is_set);window._update()
assert window.stop_button.isEnabled()
window.stop_button.click()
qtbot.waitUntil(done.is_set)
assert first.context.stop.is_set() and second.context.stop.is_set()
assert calls==['first'] and len(errors)==1
finally:
release.set();a.join(3);b.join(3)
+35
View File
@@ -0,0 +1,35 @@
import os
from pathlib import Path
import subprocess
import sys
import time
import pytest
@pytest.mark.parametrize('mode',['hash','copy','validate'])
def test_actual_app_exits_without_releasing_stalled_manifest_boundary(tmp_path,mode):
script=Path(__file__).parent/'support/manifest_process_exit.py'
env=dict(os.environ,QT_QPA_PLATFORM='offscreen')
child=subprocess.Popen([sys.executable,'-X','utf8',str(script),str(tmp_path),mode],
env=env,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True)
exited=False
try:
deadline=time.monotonic()+8
while not (tmp_path/'main-returning').exists() and child.poll() is None and time.monotonic()<deadline:
time.sleep(.02)
assert (tmp_path/'entered').exists()
assert (tmp_path/'main-returning').exists()
try:
child.wait(timeout=1)
exited=True
except subprocess.TimeoutExpired:
pass
assert not (tmp_path/'late-dispatch').exists()
finally:
(tmp_path/'release').touch() # Failed-version cleanup is cooperative, never termination.
stdout,stderr=child.communicate(timeout=5)
assert child.returncode==0,(stdout,stderr)
assert not (tmp_path/'late-dispatch').exists()
if mode!='hash':assert (tmp_path/'partial-copy').is_dir()
assert exited,'Interpreter waited for nested metadata executor despite the completed UI close'
+143
View File
@@ -0,0 +1,143 @@
from threading import Event
import pytest
from test_backup_recovery import recovery_files
from cbb_refresh_verify import backup_recovery as recovery
from cbb_refresh_verify.library_lock import LibraryLock,LibraryBusy
from cbb_refresh_verify.operation_queue import BatchTaskContext,TaskHandoff,native_channel
from cbb_refresh_verify.verify_runner import VerifyResult
@pytest.mark.parametrize('boundary',['idle','staging','final_manifest'])
@pytest.mark.parametrize('cancel',[False,True])
def test_real_recovery_handoff_preserves_A_lease_without_blocking_B_or_late_install(recovery_files,monkeypatch,boundary,cancel):
request,original,source=recovery_files
entered,release,done=Event(),Event(),Event();calls=[]
context=BatchTaskContext(str(request.lmc_file),native_policy='external')
def hold():
entered.set()
if cancel:context.cancel()
assert release.wait(5)
def idle(*args):
if boundary=='idle' and not entered.is_set():hold()
copier=recovery._copy_verified
def copy(*args,**kwargs):
value=copier(*args,**kwargs)
if boundary=='staging' and not entered.is_set():hold()
return value
monkeypatch.setattr(recovery,'_copy_verified',copy)
manifest=recovery._manifest
def build(root,**kwargs):
value=manifest(root,**kwargs)
if boundary=='final_manifest' and root==request.lmc_file.parent:hold()
return value
monkeypatch.setattr(recovery,'_manifest',build)
def verify(req,**kwargs):
calls.append(req.lmc_file)
return VerifyResult('PASS',library_flag='GREEN')
def action():
try:return recovery.recover_from_backup(request,source,verifier=verify,idle_check=idle)
finally:done.set()
refusal=None
try:
with pytest.raises(TaskHandoff):context.run(action,timeout_seconds=.3)
assert entered.is_set()
with pytest.raises(LibraryBusy):
with LibraryLock(request.lmc_file):pytest.fail('A lease lost during stalled metadata')
def B():
with native_channel():return 'admitted'
try:
result=BatchTaskContext(str(request.lmc_file.parent.parent/'B/library.lmc'),native_policy='external').run(B)
except RuntimeError as error:refusal=str(error)
finally:
release.set();assert done.wait(5);context.close(timeout_seconds=2)
assert (original.parent/'database/icdb.dat').read_bytes()==b'damaged'
assert not list(original.parent.parent.glob('Work.before-restore-*'))
assert len(calls)==(1 if boundary=='final_manifest' else 0)
assert request.lmc_file not in calls
assert refusal is None,refusal
assert result=='admitted'
def test_cancel_during_work_swap_finishes_atomic_pair_without_target_verify(recovery_files,monkeypatch):
from pathlib import Path
request,original,source=recovery_files
context=BatchTaskContext(str(request.lmc_file),native_policy='external');calls=[]
rename=Path.rename
def swap(path,target):
value=rename(path,target)
if path==original.parent:context.cancel()
return value
monkeypatch.setattr(Path,'rename',swap)
def verify(req,**kwargs):
calls.append(req.lmc_file)
return VerifyResult('PASS',library_flag='GREEN')
result=context.run(lambda:recovery.recover_from_backup(request,source,verifier=verify,idle_check=lambda *a:None))
assert result.status!='PASS'
assert (original.parent/'database/icdb.dat').read_bytes()==b'healthy'
retained=list(original.parent.parent.glob('Work.before-restore-*'))
assert len(retained)==1 and (retained[0]/'database/icdb.dat').read_bytes()==b'damaged'
assert len(calls)==1 and request.lmc_file not in calls
def test_shutdown_cannot_abandon_local_work_swap_or_hold_host_channel(recovery_files,monkeypatch):
from pathlib import Path
from threading import Thread
request,original,source=recovery_files
context=BatchTaskContext(str(request.lmc_file),native_policy='external')
entered,release,done=Event(),Event(),Event();calls=[];errors=[]
rename=Path.rename
def swap(path,target):
value=rename(path,target)
if path==original.parent:
entered.set();assert release.wait(5)
return value
monkeypatch.setattr(Path,'rename',swap)
def verify(req,**kwargs):
calls.append(req.lmc_file);return VerifyResult('PASS',library_flag='GREEN')
def run():
try:context.run(lambda:recovery.recover_from_backup(request,source,verifier=verify,idle_check=lambda *a:None))
except Exception as error:errors.append(error)
finally:done.set()
thread=Thread(target=run);thread.start()
try:
assert entered.wait(3)
state=context.shutdown()
assert state['shutdown_handoff'] is False
assert not done.wait(.1)
def B():
with native_channel():return True
assert BatchTaskContext(str(request.lmc_file.parent.parent/'B/library.lmc'),native_policy='external').run(B)
finally:
release.set();thread.join(5)
assert done.is_set() and len(calls)==1
assert (original.parent/'database/icdb.dat').read_bytes()==b'healthy'
def test_cancelled_failed_install_rolls_back_before_releasing_commit(recovery_files,monkeypatch):
from pathlib import Path
request,original,source=recovery_files;calls=[]
context=BatchTaskContext(str(request.lmc_file),native_policy='external');rename=Path.rename
def swap(path,target):
if path.name.startswith('Work.restore-'):
context.cancel();raise OSError('install rename refused')
return rename(path,target)
monkeypatch.setattr(Path,'rename',swap)
def verify(req,**kwargs):
calls.append(req.lmc_file);return VerifyResult('PASS',library_flag='GREEN')
result=context.run(lambda:recovery.recover_from_backup(request,source,verifier=verify,idle_check=lambda *a:None))
assert result.status!='PASS' and 'install rename refused' in result.stderr
assert (original.parent/'database/icdb.dat').read_bytes()==b'damaged'
assert not list(original.parent.parent.glob('Work.before-restore-*'))
assert len(calls)==1
def test_metadata_only_context_cannot_enter_local_commit(tmp_path):
from cbb_refresh_verify.operation_queue import local_commit
mutations=[]
def commit():
with local_commit():mutations.append('rename')
with pytest.raises(RuntimeError,match='Read-only metadata'):
BatchTaskContext(str(tmp_path/'lib.lmc')).run(commit,metadata_only=True)
assert not mutations
+1
View File
@@ -17,6 +17,7 @@ def registered_fixture(tmp_path,monkeypatch,*,closed=False,obstacle=''):
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)
state['prelaunch_baseline']=job['diagnostic_log_baseline']
job.pop('diagnostic_log_baseline') # Old builds never persisted this; do not invent it.
identity=dict(pid=12,created_handle='native-created',image=records[0][1],owner_sid='current',session_id=1)
worker=dict(pid=11,created_handle='worker-created',image='C:/App/CbbRefreshVerify.exe',owner_sid='current',session_id=1)