fix: reconcile reused identities and protect every native dispatch

This commit is contained in:
阿白叔 committed 2026-11-06 16:21:08 +08:00
1 parent cb11624b68
commit d9a79b6535
8 files changed
+159 -13

No files matched your search

+15
View File
@@ -32,6 +32,21 @@ class FakeProjectIntegration:
return True
def test_cancel_during_allowed_getter_prevents_new_integration_call():
from threading import Event
stop = Event()
class Integration(FakeProjectIntegration):
@property
def IsForwardAnnotationAllowed(self):
stop.set()
return True
integration = Integration()
with pytest.raises(IntegrationError, match='VERIFY_CANCELLED'):
refresh_integration(integration, settle_seconds=0,
error_reader=lambda: 'VERIFY_CANCELLED' if stop.is_set() else '')
assert integration.forward_calls == 0
def test_database_restoration_dialog_requires_manual_recovery():
action = choose_dialog_action(
'Database Restoration',
+41 -5
View File
@@ -52,7 +52,8 @@ def test_add_timeout_publishes_cancellation_without_killing_native_owner(tmp_pat
assert len(native._retained_workers)==1
def test_cancellation_during_log_evidence_prevents_native_submit(tmp_path, monkeypatch):
@pytest.mark.parametrize('cancel', [True, False])
def test_cancellation_and_phase_at_native_add_submit(tmp_path, monkeypatch, cancel):
import os,sys
from types import SimpleNamespace
import win32gui,win32process
@@ -78,19 +79,54 @@ def test_cancellation_during_log_evidence_prevents_native_submit(tmp_path, monke
def post(h,*args):
state['posted'].append(h)
if h==110:state['new']=True
if h==210:
from cbb_refresh_verify.session_record import read_session_record
assert read_session_record(root/'worker-state.json', evidence_root=root)['phase'] == 'NATIVE_CALL'
monkeypatch.setattr(win32gui,'PostMessage',post)
original=native._write_json
def write(path,data):
original(path,data)
if path.name=='native-add-log-baseline.json':(root/'cancel-native-add.signal').touch()
if path.name=='native-add-log-baseline.json' and cancel:(root/'cancel-native-add.signal').touch()
monkeypatch.setattr(native,'_write_json',write)
monkeypatch.setattr(failures,'observe_add_failure',lambda *a:(_ for _ in ()).throw(RuntimeError('unsafe OK posted')))
desktop=SimpleNamespace(EnumDesktopWindows=lambda:[100,200] if state['new'] else [100])
job={'operation':'probe_create_add','source':str(source),'library':str(library),
'name':'Block','timeout_seconds':5,'supervisor_pid':os.getpid()}
with pytest.raises(RuntimeError,match='NATIVE_ADD_CANCELLED'):
'name':'Block','timeout_seconds':5,'supervisor_pid':os.getpid(),
'operation_id':'test-add-phase','session_record_path':str(root/'session.json')}
from cbb_refresh_verify.session_record import write_session_record
write_session_record(root/'worker-state.json', {'operation_id': 'test-add-phase', 'phase':'POSTCALL', 'processes':[]})
with pytest.raises(RuntimeError,match='NATIVE_ADD_CANCELLED' if cancel else 'unsafe OK posted'):
native._probe_add_dialog_impl(SimpleNamespace(OnReusableBlocksEditor=lambda:None),job,desktop,{99},root)
assert state['posted']==[110]
assert state['posted']==([110] if cancel else [110,210])
def test_unknown_pending_add_does_not_send_cleanup_dialog_actions(tmp_path, monkeypatch):
from cbb_refresh_verify import native_management as native
def pending(app, job, *a, **kw):
job['_native_add_pending'] = True
raise TimeoutError('native Add pending')
monkeypatch.setattr(native, '_probe_add_dialog_impl', pending)
monkeypatch.setattr(native, '_close_probe_dialogs', lambda *a: pytest.fail('closing a pending Add'))
with pytest.raises(TimeoutError):
native._probe_add_dialog(None, {}, None, set(), tmp_path)
@pytest.mark.parametrize('acknowledged', [False, True])
def test_add_failure_only_allows_cleanup_after_confirmed_native_ack(tmp_path, monkeypatch, acknowledged):
import json
from cbb_refresh_verify import native_management as native
job = {}
def failed(app, job, *a, **kw):
job['_native_add_pending'] = True
(tmp_path/'native-add-output.json').write_text(json.dumps({'failure': {'acknowledged': acknowledged}}))
raise RuntimeError('NATIVE_ADD_FAILED: simulated complete error')
closed = []
monkeypatch.setattr(native, '_probe_add_dialog_impl', failed)
monkeypatch.setattr(native, '_close_probe_dialogs', lambda *a: closed.append(True))
with pytest.raises(RuntimeError, match='NATIVE_ADD_FAILED'):
native._probe_add_dialog(None, job, None, set(), tmp_path)
assert bool(closed) is acknowledged
assert job['_native_add_pending'] is not acknowledged
def test_copy_failure_log_must_be_new_and_match_current_block(tmp_path):
+31
View File
@@ -429,6 +429,37 @@ def test_com_failure_without_owner_identity_cannot_claim_release(tmp_path, monke
assert native._catalog_native({}, tmp_path)['safe_to_continue'] is False
def test_pending_async_add_does_not_close_or_quit_library(tmp_path, monkeypatch):
import cbb_refresh_verify.native_management as native
import cbb_refresh_verify.mentor_adapter as mentor
import win32com.client
library_path = tmp_path/'lib.lmc'
running = []
class Library:
FullName = str(library_path)
FlowType = 1
def Close(self): pytest.fail('Close during pending Add')
class App:
def OpenLibrary(self, path): return Library()
def Quit(self): pytest.fail('Quit during pending Add')
def dispatch(*a): running.append(True); return App()
monkeypatch.setattr(win32com.client, 'DispatchEx', dispatch)
monkeypatch.setattr(native, 'validate_owned_fixture_add', lambda *a: None)
monkeypatch.setattr(native, '_current_desktop', lambda: (SimpleNamespace(EnumDesktopWindows=lambda: []), 'CbbManagement_test'))
monkeypatch.setattr(mentor, '_process_details', lambda _: [
(123, str(tmp_path/'lm/win32/bin/LibraryManager.exe'), '', 0)] if running else [])
def pending(app, job, *a, **kw):
job['_native_add_pending'] = True
raise TimeoutError('native result unknown')
monkeypatch.setattr(native, '_probe_add_dialog', pending)
result = native._catalog_com({'operation': 'add', 'library': str(library_path),
'desktop': 'CbbManagement_test', 'mentor_home': str(tmp_path),
'supervisor_pid': __import__('os').getpid()}, tmp_path)
assert result['success'] is False
assert result['native_pids'] == [123]
assert 'native result unknown' in result['detail']
@pytest.mark.parametrize('registered', [True, False])
def test_shared_add_reopens_exact_catalog_and_reports_identity_mismatch(tmp_path, monkeypatch, registered):
import cbb_refresh_verify.native_management as native
+26
View File
@@ -143,3 +143,29 @@ def test_bad_journal_does_not_drop_in_memory_supervision(tmp_path, child):
assert child.poll() is None
finally:
stop.set()
def test_reused_pid_keeps_observing_resources_and_unblocks_only_after_proof(tmp_path, child, monkeypatch):
import threading
identity = sessions.process_identity(child.pid)
identity['created_handle'] = 'previous-owner'
path = record(tmp_path, [dict(role='worker', **identity)])
released = threading.Event()
stop = threading.Event()
proof = {'status': 'RELEASE_CONFIRMED', 'library': str(tmp_path/'lib.lmc')}
monkeypatch.setattr('cbb_refresh_verify.library_lock.release_retained_library', lambda *a, **kw: proof)
def progress(result):
if result['status'] == 'RELEASED':
released.set()
sessions.handoff_session(path, evidence_root=tmp_path, stop=stop, progress=progress)
try:
assert released.wait(3), 'PID reuse ended observation before independent release'
assert child.poll() is None
# The callback precedes final observer cleanup by a few instructions.
import time
deadline = time.monotonic()+1
while not sessions.library_available(tmp_path/'lib.lmc') and time.monotonic()<deadline:
time.sleep(.01)
assert sessions.library_available(tmp_path/'lib.lmc')
finally:
stop.set()