fix: require a durable boundary before native add submission

This commit is contained in:
阿白叔 committed 2026-11-06 16:41:36 +08:00
1 parent d9a79b6535
commit 051498ba57
4 files changed
+54 -7

No files matched your search

+1 -1
View File
@@ -836,7 +836,7 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None)
observed_failures = {}
_require_add_supervisor(job, root)
from .session_record import update_worker_state
update_worker_state(job, 'NATIVE_CALL')
update_worker_state(job, 'NATIVE_CALL', required=True)
job['_native_add_pending'] = True
win32gui.PostMessage(ok, win32con.BM_CLICK, 0, 0)
success = None
+29 -3
View File
@@ -38,9 +38,11 @@ def register_worker_session(worker, job):
worker.cbb_library = job['library']
def update_worker_state(job, phase, *, identities=(), write_outcome=None):
def update_worker_state(job, phase, *, identities=(), write_outcome=None, required=False):
if not job.get('session_record_path'):
return
if required:
raise ValueError('原生写入缺少会话记录位置,未提交新的调用')
return False
path = Path(job['session_record_path']).with_name('worker-state.json')
try:
state = ({'operation_id': job['operation_id'], 'processes': []} if not path.exists()
@@ -54,9 +56,13 @@ def update_worker_state(job, phase, *, identities=(), write_outcome=None):
if write_outcome is not None:
state['write_outcome'] = write_outcome
write_session_record(path, state)
return True
except Exception:
if required:
raise
# An unavailable journal cannot interrupt an already executing COM call.
logging.getLogger(__name__).warning('Worker session journal unavailable', exc_info=True)
return False
def process_identity(pid):
@@ -317,9 +323,29 @@ def active_write_records(library):
result = []
for path in paths:
try:
session, state, _ = _session(path, path.parent)
session, state, processes = _session(path, path.parent)
if state.get('phase') in ('NATIVE_CALL', 'CLOSING', 'UNCONFIRMED'):
result.append({**session, 'phase': state['phase']})
else:
from .residual_sessions import _process_handle, _handle_identity, _force_ownership
import win32con, win32event
for identity in processes:
if identity.get('role') not in ('worker', 'helper'):
continue
try:
with _process_handle(identity['pid']) as handle:
if win32event.WaitForSingleObject(handle, 0) == win32con.WAIT_OBJECT_0:
continue
actual = {**_handle_identity(handle), **_force_ownership(handle, identity['pid'])}
if any(actual[k] != identity[k] for k in IDENTITY_KEYS if k != 'pid'):
continue
# A retained caller may be inside Close after the last journal write failed.
result.append({**session, 'phase': 'UNCONFIRMED'})
break
except Exception as error:
if getattr(error, 'winerror', None) != 87:
result.append({**session, 'phase': 'UNCONFIRMED'})
break
except (OSError, ValueError):
result.append({'phase': 'UNCONFIRMED'})
return result
+9 -3
View File
@@ -53,7 +53,8 @@ def test_add_timeout_publishes_cancellation_without_killing_native_owner(tmp_pat
@pytest.mark.parametrize('cancel', [True, False])
def test_cancellation_and_phase_at_native_add_submit(tmp_path, monkeypatch, cancel):
@pytest.mark.parametrize('journal_error', [False, True])
def test_cancellation_and_phase_at_native_add_submit(tmp_path, monkeypatch, cancel, journal_error):
import os,sys
from types import SimpleNamespace
import win32gui,win32process
@@ -95,9 +96,14 @@ def test_cancellation_and_phase_at_native_add_submit(tmp_path, monkeypatch, canc
'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'):
if journal_error:
def fail(*a, **kw): raise OSError('phase journal unavailable')
monkeypatch.setattr('cbb_refresh_verify.session_record.write_session_record', fail)
expected = OSError if journal_error and not cancel else RuntimeError
message = 'NATIVE_ADD_CANCELLED' if cancel else 'phase journal unavailable' if journal_error else 'unsafe OK posted'
with pytest.raises(expected, match=message):
native._probe_add_dialog_impl(SimpleNamespace(OnReusableBlocksEditor=lambda:None),job,desktop,{99},root)
assert state['posted']==([110] if cancel else [110,210])
assert state['posted']==([110] if cancel or journal_error else [110,210])
def test_unknown_pending_add_does_not_send_cleanup_dialog_actions(tmp_path, monkeypatch):
+15
View File
@@ -169,3 +169,18 @@ def test_reused_pid_keeps_observing_resources_and_unblocks_only_after_proof(tmp_
assert sessions.library_available(tmp_path/'lib.lmc')
finally:
stop.set()
def test_retained_live_worker_with_stale_postcall_phase_is_still_protected(tmp_path, child):
import threading
path = record(tmp_path, [dict(role='worker', **sessions.process_identity(child.pid))])
sessions.write_session_record(tmp_path/'worker-state.json', dict(operation_id='test-session',
processes=[], phase='POSTCALL'))
stop = threading.Event()
sessions.handoff_session(path, evidence_root=tmp_path, stop=stop)
try:
writes = sessions.active_write_records(tmp_path/'lib.lmc')
assert writes and writes[0]['phase'] == 'UNCONFIRMED'
assert child.poll() is None
finally:
stop.set()