fix: reconcile reused identities and protect every native dispatch
This commit is contained in:
1 parent
cb11624b68
commit
d9a79b6535
8 files changed
+159
-13
No files matched your search
@@ -109,6 +109,7 @@ def refresh_integration(pi, *, emit=lambda **event: None, settle_seconds=5, time
|
|||||||
emit(stage='integration_action_unavailable', action=method,
|
emit(stage='integration_action_unavailable', action=method,
|
||||||
initial_status=state[name], reason='mentor_not_allowed')
|
initial_status=state[name], reason='mentor_not_allowed')
|
||||||
raise IntegrationError(f'{name}: required but not allowed')
|
raise IntegrationError(f'{name}: required but not allowed')
|
||||||
|
check_error() # The permission getter itself can block past cancellation.
|
||||||
emit(stage='integration_action', action=method, initial_status=state[name],
|
emit(stage='integration_action', action=method, initial_status=state[name],
|
||||||
reason='required_verification' if name not in executed else 'resynchronize')
|
reason='required_verification' if name not in executed else 'resynchronize')
|
||||||
started = clock()
|
started = clock()
|
||||||
|
|||||||
@@ -717,10 +717,22 @@ def _set_probe_field(hwnd, control_id, expected, root):
|
|||||||
def _probe_add_dialog(app, job, desktop, owned_pids, root, *, library=None):
|
def _probe_add_dialog(app, job, desktop, owned_pids, root, *, library=None):
|
||||||
try:
|
try:
|
||||||
return _probe_add_dialog_impl(app, job, desktop, owned_pids, root, library=library)
|
return _probe_add_dialog_impl(app, job, desktop, owned_pids, root, library=library)
|
||||||
|
except Exception as error:
|
||||||
|
if job.get('_native_add_pending') and str(error).startswith('NATIVE_ADD_FAILED:'):
|
||||||
|
try:
|
||||||
|
failure = json.loads((Path(root)/'native-add-output.json').read_text('utf-8')).get('failure', {})
|
||||||
|
if failure.get('acknowledged') is True:
|
||||||
|
job['_native_add_pending'] = False
|
||||||
|
from .session_record import update_worker_state
|
||||||
|
update_worker_state(job, 'POSTCALL')
|
||||||
|
except (OSError, ValueError, AttributeError):
|
||||||
|
pass
|
||||||
|
raise
|
||||||
finally:
|
finally:
|
||||||
import gc
|
import gc
|
||||||
gc.collect() # Release UIA wrappers before closing native child dialogs.
|
gc.collect() # Release UIA wrappers before closing native child dialogs.
|
||||||
_close_probe_dialogs(desktop, owned_pids)
|
if not job.get('_native_add_pending'):
|
||||||
|
_close_probe_dialogs(desktop, owned_pids)
|
||||||
|
|
||||||
|
|
||||||
def _require_management_continuation(job, root):
|
def _require_management_continuation(job, root):
|
||||||
@@ -823,6 +835,9 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None)
|
|||||||
_write_json(root/'native-add-log-baseline.json', log_baseline)
|
_write_json(root/'native-add-log-baseline.json', log_baseline)
|
||||||
observed_failures = {}
|
observed_failures = {}
|
||||||
_require_add_supervisor(job, root)
|
_require_add_supervisor(job, root)
|
||||||
|
from .session_record import update_worker_state
|
||||||
|
update_worker_state(job, 'NATIVE_CALL')
|
||||||
|
job['_native_add_pending'] = True
|
||||||
win32gui.PostMessage(ok, win32con.BM_CLICK, 0, 0)
|
win32gui.PostMessage(ok, win32con.BM_CLICK, 0, 0)
|
||||||
success = None
|
success = None
|
||||||
while time.monotonic() < deadline:
|
while time.monotonic() < deadline:
|
||||||
@@ -853,6 +868,8 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None)
|
|||||||
break
|
break
|
||||||
if not success:
|
if not success:
|
||||||
raise TimeoutError('未取得原生新增成功消息;保留副本与私有桌面证据。')
|
raise TimeoutError('未取得原生新增成功消息;保留副本与私有桌面证据。')
|
||||||
|
job['_native_add_pending'] = False
|
||||||
|
update_worker_state(job, 'POSTCALL')
|
||||||
|
|
||||||
|
|
||||||
def run_isolated_probe(source, root, name, *, mentor_home=None, replacement_source=None):
|
def run_isolated_probe(source, root, name, *, mentor_home=None, replacement_source=None):
|
||||||
@@ -1125,6 +1142,7 @@ def _catalog_com(job, root):
|
|||||||
if int(library.FlowType) != 1:
|
if int(library.FlowType) != 1:
|
||||||
raise RuntimeError('Native Add requires the DxDesigner Logical-Physical library flow.')
|
raise RuntimeError('Native Add requires the DxDesigner Logical-Physical library flow.')
|
||||||
_probe_add_dialog(app, job, desktop, owned_pids, root, library=library)
|
_probe_add_dialog(app, job, desktop, owned_pids, root, library=library)
|
||||||
|
update_worker_state(job, 'CLOSING')
|
||||||
library.Close()
|
library.Close()
|
||||||
library = None
|
library = None
|
||||||
_require_management_continuation(job, root)
|
_require_management_continuation(job, root)
|
||||||
@@ -1169,14 +1187,18 @@ def _catalog_com(job, root):
|
|||||||
result['detail'] = str(error)
|
result['detail'] = str(error)
|
||||||
result['exception'] = _exception_details(error)
|
result['exception'] = _exception_details(error)
|
||||||
finally:
|
finally:
|
||||||
if library is not None:
|
if library is not None and not job.get('_native_add_pending'):
|
||||||
try: library.Close()
|
try:
|
||||||
|
update_worker_state(job, 'CLOSING')
|
||||||
|
library.Close()
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
result['close_detail'] = str(error)
|
result['close_detail'] = str(error)
|
||||||
result['close_exception'] = _exception_details(error)
|
result['close_exception'] = _exception_details(error)
|
||||||
library = None
|
library = None
|
||||||
if app is not None:
|
if app is not None and not job.get('_native_add_pending'):
|
||||||
try: app.Quit()
|
try:
|
||||||
|
update_worker_state(job, 'CLOSING')
|
||||||
|
app.Quit()
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
result['quit_detail'] = str(error)
|
result['quit_detail'] = str(error)
|
||||||
result['quit_exception'] = _exception_details(error)
|
result['quit_exception'] = _exception_details(error)
|
||||||
|
|||||||
@@ -142,6 +142,9 @@ def _reconcile(path, root, handles, stack):
|
|||||||
if identity.get('role') == 'supervisor':
|
if identity.get('role') == 'supervisor':
|
||||||
continue
|
continue
|
||||||
key = tuple(identity[k] for k in IDENTITY_KEYS)
|
key = tuple(identity[k] for k in IDENTITY_KEYS)
|
||||||
|
changed_key = ('identity_changed', *key)
|
||||||
|
if changed_key in handles:
|
||||||
|
return _result('IDENTITY_CHANGED', '记录中的进程身份已变化,仅供观察', session=session, state=state)
|
||||||
if key not in handles:
|
if key not in handles:
|
||||||
try:
|
try:
|
||||||
handle = win32api.OpenProcess(win32con.SYNCHRONIZE | 0x1000, False, identity['pid'])
|
handle = win32api.OpenProcess(win32con.SYNCHRONIZE | 0x1000, False, identity['pid'])
|
||||||
@@ -157,6 +160,8 @@ def _reconcile(path, root, handles, stack):
|
|||||||
actual = {'pid': identity['pid'], **_handle_identity(handle),
|
actual = {'pid': identity['pid'], **_handle_identity(handle),
|
||||||
**_force_ownership(handle, identity['pid'])}
|
**_force_ownership(handle, identity['pid'])}
|
||||||
if any(actual[k] != identity[k] for k in IDENTITY_KEYS):
|
if any(actual[k] != identity[k] for k in IDENTITY_KEYS):
|
||||||
|
handles[key] = handle
|
||||||
|
handles[changed_key] = True
|
||||||
return _result('IDENTITY_CHANGED', '记录中的进程身份已变化,仅供观察',
|
return _result('IDENTITY_CHANGED', '记录中的进程身份已变化,仅供观察',
|
||||||
session=session, state=state)
|
session=session, state=state)
|
||||||
handles[key] = handle
|
handles[key] = handle
|
||||||
@@ -205,6 +210,14 @@ def observe_retained_session(path, *, evidence_root, stop=None, progress=None, p
|
|||||||
session={'library': str(process.cbb_library)}, proof=proof)
|
session={'library': str(process.cbb_library)}, proof=proof)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
if result['status'] == 'IDENTITY_CHANGED':
|
||||||
|
try:
|
||||||
|
from .library_lock import release_retained_library
|
||||||
|
proof = release_retained_library(result['library'], Path(path).parent/'release-proof')
|
||||||
|
if proof.get('status') == 'RELEASE_CONFIRMED':
|
||||||
|
result = {**result, 'status': 'RELEASED', 'identity_changed': True, 'release_proof': proof}
|
||||||
|
except Exception as error:
|
||||||
|
result['detail'] += f';资源释放待确认:{error}'
|
||||||
try:
|
try:
|
||||||
write_session_record(observation, {**result, 'operation_id': result['operation_id'] or 'unknown'})
|
write_session_record(observation, {**result, 'operation_id': result['operation_id'] or 'unknown'})
|
||||||
except (OSError, ValueError):
|
except (OSError, ValueError):
|
||||||
@@ -214,14 +227,14 @@ def observe_retained_session(path, *, evidence_root, stop=None, progress=None, p
|
|||||||
progress(result)
|
progress(result)
|
||||||
except Exception:
|
except Exception:
|
||||||
logging.getLogger(__name__).warning('Observation callback failed', exc_info=True)
|
logging.getLogger(__name__).warning('Observation callback failed', exc_info=True)
|
||||||
if result['status'] in ('RELEASED', 'IDENTITY_CHANGED') or stop.is_set():
|
if result['status'] == 'RELEASED' or stop.is_set():
|
||||||
return result
|
return result
|
||||||
if not handles and process is not None and process.poll() is None:
|
if not handles and process is not None and process.poll() is None:
|
||||||
stop.wait(1)
|
stop.wait(1)
|
||||||
continue # The exact owned handle survives a failed journal.
|
continue # The exact owned handle survives a failed journal.
|
||||||
if not handles and process is None:
|
if not handles and process is None:
|
||||||
return result
|
return result
|
||||||
stop.wait(5 if result['status'] == 'UNCONFIRMED' else 1)
|
stop.wait(5 if result['status'] in ('UNCONFIRMED', 'IDENTITY_CHANGED') else 1)
|
||||||
|
|
||||||
|
|
||||||
def handoff_session(path, *, evidence_root, process=None, progress=None, stop=None):
|
def handoff_session(path, *, evidence_root, process=None, progress=None, stop=None):
|
||||||
|
|||||||
@@ -475,8 +475,10 @@ class MainWindow(QWidget):
|
|||||||
f'{item.get("stage", "")}\n{item["evidence_path"]}')
|
f'{item.get("stage", "")}\n{item["evidence_path"]}')
|
||||||
for session in sessions:
|
for session in sessions:
|
||||||
if session['status'] != 'RELEASED':
|
if session['status'] != 'RELEASED':
|
||||||
|
phase = {'NATIVE_CALL': '原生操作进行中', 'CLOSING': '正在关闭', 'POSTCALL': '原生调用已返回',
|
||||||
|
'PRECALL': '尚未开始', 'UNCONFIRMED': '当前状态无法确认'}.get(session.get('phase'), '待核对')
|
||||||
self.output.append(f'未完成会话:{session.get("block") or ""} · '
|
self.output.append(f'未完成会话:{session.get("block") or ""} · '
|
||||||
f'{session.get("phase", "")} · {session.get("detail", "")}\n{session["path"]}')
|
f'{phase} · {session.get("detail", "")}\n{session["path"]}')
|
||||||
|
|
||||||
def check_library_release(self):
|
def check_library_release(self):
|
||||||
if self.busy or not self.lmc_edit.text().strip():
|
if self.busy or not self.lmc_edit.text().strip():
|
||||||
|
|||||||
@@ -32,6 +32,21 @@ class FakeProjectIntegration:
|
|||||||
return True
|
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():
|
def test_database_restoration_dialog_requires_manual_recovery():
|
||||||
action = choose_dialog_action(
|
action = choose_dialog_action(
|
||||||
'Database Restoration',
|
'Database Restoration',
|
||||||
|
|||||||
@@ -52,7 +52,8 @@ def test_add_timeout_publishes_cancellation_without_killing_native_owner(tmp_pat
|
|||||||
assert len(native._retained_workers)==1
|
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
|
import os,sys
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
import win32gui,win32process
|
import win32gui,win32process
|
||||||
@@ -78,19 +79,54 @@ def test_cancellation_during_log_evidence_prevents_native_submit(tmp_path, monke
|
|||||||
def post(h,*args):
|
def post(h,*args):
|
||||||
state['posted'].append(h)
|
state['posted'].append(h)
|
||||||
if h==110:state['new']=True
|
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)
|
monkeypatch.setattr(win32gui,'PostMessage',post)
|
||||||
original=native._write_json
|
original=native._write_json
|
||||||
def write(path,data):
|
def write(path,data):
|
||||||
original(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(native,'_write_json',write)
|
||||||
monkeypatch.setattr(failures,'observe_add_failure',lambda *a:(_ for _ in ()).throw(RuntimeError('unsafe OK posted')))
|
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])
|
desktop=SimpleNamespace(EnumDesktopWindows=lambda:[100,200] if state['new'] else [100])
|
||||||
job={'operation':'probe_create_add','source':str(source),'library':str(library),
|
job={'operation':'probe_create_add','source':str(source),'library':str(library),
|
||||||
'name':'Block','timeout_seconds':5,'supervisor_pid':os.getpid()}
|
'name':'Block','timeout_seconds':5,'supervisor_pid':os.getpid(),
|
||||||
with pytest.raises(RuntimeError,match='NATIVE_ADD_CANCELLED'):
|
'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)
|
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):
|
def test_copy_failure_log_must_be_new_and_match_current_block(tmp_path):
|
||||||
|
|||||||
@@ -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
|
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])
|
@pytest.mark.parametrize('registered', [True, False])
|
||||||
def test_shared_add_reopens_exact_catalog_and_reports_identity_mismatch(tmp_path, monkeypatch, registered):
|
def test_shared_add_reopens_exact_catalog_and_reports_identity_mismatch(tmp_path, monkeypatch, registered):
|
||||||
import cbb_refresh_verify.native_management as native
|
import cbb_refresh_verify.native_management as native
|
||||||
|
|||||||
@@ -143,3 +143,29 @@ def test_bad_journal_does_not_drop_in_memory_supervision(tmp_path, child):
|
|||||||
assert child.poll() is None
|
assert child.poll() is None
|
||||||
finally:
|
finally:
|
||||||
stop.set()
|
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()
|
||||||
Reference in new issue
Block a user