fix: centralize native dispatch and itemize retained session release

This commit is contained in:
阿白叔 committed 2026-11-09 14:03:07 +08:00
1 parent 60101b7195
commit 306aa5c544
4 files changed
+149 -29

No files matched your search

+8 -2
View File
@@ -528,7 +528,8 @@ def release_retained_library(library, evidence_dir, *, block_name=None):
"""
import win32con, win32event, win32file
library = Path(library).resolve(strict=True)
from .session_record import retained_session_snapshot, acknowledge_library_release
from .session_record import (retained_session_snapshot, acknowledge_library_release,
reconciled_retained_sessions)
retained = retained_session_snapshot(library)
evidence = Path(evidence_dir).resolve()
if evidence.is_relative_to(library.parent) or library.parent.is_relative_to(evidence):
@@ -581,10 +582,15 @@ def release_retained_library(library, evidence_dir, *, block_name=None):
raise LibraryBusy('释放检查期间协调检查点变化,保留原文件。')
root = evidence/('release-' + uuid4().hex)
root.mkdir(parents=True, exist_ok=False)
reconciled_sessions = reconciled_retained_sessions(retained, block_name=scoped)
reconciled_blocks = sorted({item['block_name'] for item in (*reconciled, *reconciled_sessions)
if item.get('block_name')})
record = {'library': str(library), 'status': 'RELEASE_CONFIRMED', **proof,
'requested_block_name': block_name, 'proof_scope': 'BLOCK' if scoped else 'LIBRARY',
'proof_block_name': scoped, 'reconciled_checkpoints': reconciled,
'reconciled_foreign_blockers': foreign,
'reconciled_foreign_blockers': sorted(set(foreign) | {
block for block in reconciled_blocks if block_name and block != block_name}),
'reconciled_blocks': reconciled_blocks, 'reconciled_sessions': reconciled_sessions,
'unknown_checkpoint_archived': unknown,
'data_recovery_confirmed': False, 'evidence_path': str(root/'release.json')}
(root/'release.json').write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
+20 -23
View File
@@ -835,10 +835,11 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None)
_write_json(root/'native-add-log-baseline.json', log_baseline)
observed_failures = {}
_require_add_supervisor(job, root)
from .session_record import update_worker_state
update_worker_state(job, 'NATIVE_CALL', required=True)
job['_native_add_pending'] = True
win32gui.PostMessage(ok, win32con.BM_CLICK, 0, 0)
from .session_record import dispatch_native, update_worker_state
def submit_add():
job['_native_add_pending'] = True
win32gui.PostMessage(ok, win32con.BM_CLICK, 0, 0)
dispatch_native(job, submit_add, asynchronous=True, required=True)
success = None
while time.monotonic() < deadline:
pythoncom.PumpWaitingMessages()
@@ -1106,9 +1107,10 @@ def _catalog_com(job, root):
watcher = None
try:
_require_management_continuation(job, root)
from .session_record import update_worker_state
update_worker_state(job, 'NATIVE_CALL')
app = win32com.client.DispatchEx('LibraryManager.Application')
from .session_record import dispatch_native, update_worker_state
# Keep the launch pending until its exact native identity is recorded.
app = dispatch_native(job, lambda: win32com.client.DispatchEx('LibraryManager.Application'),
asynchronous=True)
app.Visible = True
processes = _process_details('LibraryManager.exe')
owned_pids.update(int(p[0]) for p in processes)
@@ -1124,15 +1126,14 @@ def _catalog_com(job, root):
if job['operation'] in ('probe_create_add', 'probe_create'):
target = prepare_probe_library(job, root)
_require_management_continuation(job, root)
update_worker_state(job, 'NATIVE_CALL')
library = app.CreateLibrary(str(target), 1)
library = dispatch_native(job, lambda: app.CreateLibrary(str(target), 1), asynchronous=True)
_write_json(root.parent/'probe-owner.json', {'library': str(target), 'token': job['probe_token']})
else:
if job['operation'] == 'probe_readd':
validate_probe_readd(job, root)
_require_management_continuation(job, root)
update_worker_state(job, 'NATIVE_CALL')
library = app.OpenLibrary(str(absolute_preserving_drive(job['library'])))
library = dispatch_native(job, lambda: app.OpenLibrary(str(absolute_preserving_drive(job['library']))),
asynchronous=True)
update_worker_state(job, 'POSTCALL')
if refused:
raise RuntimeError('目录读取需要升级中心库或选择流程;已拒绝,目标未获准自动升级。')
@@ -1142,12 +1143,10 @@ def _catalog_com(job, root):
if int(library.FlowType) != 1:
raise RuntimeError('Native Add requires the DxDesigner Logical-Physical library flow.')
_probe_add_dialog(app, job, desktop, owned_pids, root, library=library)
update_worker_state(job, 'CLOSING')
library.Close()
dispatch_native(job, lambda: library.Close(), phase='CLOSING')
library = None
_require_management_continuation(job, root)
update_worker_state(job, 'NATIVE_CALL')
library = app.OpenLibrary(str(absolute_preserving_drive(job['library'])))
library = dispatch_native(job, lambda: app.OpenLibrary(str(absolute_preserving_drive(job['library']))))
if (library is None or Path(str(library.FullName)).resolve() != Path(job['library']).resolve()
or int(library.FlowType) != 1):
raise RuntimeError('Native Add reopen did not confirm the exact library and flow.')
@@ -1189,16 +1188,14 @@ def _catalog_com(job, root):
finally:
if library is not None and not job.get('_native_add_pending'):
try:
update_worker_state(job, 'CLOSING')
library.Close()
dispatch_native(job, lambda: library.Close(), phase='CLOSING')
except Exception as error:
result['close_detail'] = str(error)
result['close_exception'] = _exception_details(error)
library = None
if app is not None and not job.get('_native_add_pending'):
try:
update_worker_state(job, 'CLOSING')
app.Quit()
dispatch_native(job, lambda: app.Quit(), phase='CLOSING')
except Exception as error:
result['quit_detail'] = str(error)
result['quit_exception'] = _exception_details(error)
@@ -1266,12 +1263,11 @@ def management_worker_main(request_path):
_write_json(root/'command.json', command)
with (root/'native-output.txt').open('wb') as output:
_require_management_continuation(job, root)
from .session_record import update_worker_state
update_worker_state(job, 'NATIVE_CALL')
from .session_record import dispatch_native, update_worker_state
result['safe_to_continue'] = False
try:
process = subprocess.Popen(command, stdout=output, stderr=subprocess.STDOUT,
creationflags=subprocess.CREATE_NO_WINDOW)
process = dispatch_native(job, lambda: subprocess.Popen(command, stdout=output,
stderr=subprocess.STDOUT, creationflags=subprocess.CREATE_NO_WINDOW), asynchronous=True)
except (FileNotFoundError, PermissionError):
result['safe_to_continue'] = True
raise
@@ -1292,6 +1288,7 @@ def management_worker_main(request_path):
except subprocess.TimeoutExpired:
continue
result['wait_exceeded'] = True
update_worker_state(job, 'POSTCALL')
result.update(safe_to_continue=True, exit_code=code)
text = (root/'native-output.txt').read_bytes().decode('mbcs', errors='replace')
result.update(success=removal_output_ok(code, text, job['name'], job['partition']),
+30 -4
View File
@@ -32,24 +32,36 @@ def library_available(library):
def retained_session_snapshot(library):
key = _library_key(library)
with _observer_guard:
return {path: (aliases, _retained_results.get(path, {}).get('block'))
return {path: (aliases, _retained_results.get(path, {}).get('block'),
_retained_results.get(path, {}).get('operation_id'))
for path, aliases in _retained_libraries.items() if key in aliases}
def reconciled_retained_sessions(snapshot, *, block_name=None):
with _observer_guard:
return [{'path': path, 'block_name': block, 'operation_id': operation_id}
for path, (aliases, block, operation_id) in snapshot.items()
if _retained_libraries.get(path) is aliases
and _retained_results.get(path, {}).get('operation_id') == operation_id
and (block_name is None or block == block_name)]
def acknowledge_library_release(proof, snapshot, *, block_name=None):
"""Called under fresh proof handles; never clear a newer handoff."""
if proof.get('status') != 'RELEASE_CONFIRMED':
return
key = _library_key(proof['library'])
with _observer_guard:
records = [dict(_retained_results.get(path, {}), path=path)
for path, (aliases, block) in snapshot.items()
records = [dict(path=path, operation_id=operation_id)
for path, (aliases, block, operation_id) in snapshot.items()
if key in aliases and _retained_libraries.get(path) is aliases
and _retained_results.get(path, {}).get('operation_id') == operation_id
and (block_name is None or block == block_name)]
record_session_release(proof, records)
with _observer_guard:
for path, (aliases, block) in snapshot.items():
for path, (aliases, block, operation_id) in snapshot.items():
if (key in aliases and _retained_libraries.get(path) is aliases
and _retained_results.get(path, {}).get('operation_id') == operation_id
and (block_name is None or block == block_name)):
_retained_libraries.pop(path, None)
_retained_results.pop(path, None)
@@ -95,6 +107,7 @@ def register_worker_session(worker, job):
def update_worker_state(job, phase, *, identities=(), write_outcome=None, required=False):
"""required controls journal I/O; a supervisor-loss dispatch veto always raises."""
if not job.get('session_record_path'):
if required:
raise ValueError('原生写入缺少会话记录位置,未提交新的调用')
@@ -123,6 +136,19 @@ def update_worker_state(job, phase, *, identities=(), write_outcome=None, requir
return False
def dispatch_native(job, call, *, phase='NATIVE_CALL', asynchronous=False, required=False):
"""Reserve the native call before dispatch; asynchronous results require an explicit acknowledgment."""
update_worker_state(job, phase, required=required)
try:
result = call()
except BaseException:
update_worker_state(job, 'UNCONFIRMED')
raise
if not asynchronous:
update_worker_state(job, 'POSTCALL')
return result
def process_identity(pid):
from .residual_sessions import _process_handle, _handle_identity, _force_ownership
with _process_handle(pid) as handle:
@@ -0,0 +1,91 @@
from contextlib import contextmanager
import json
from pathlib import Path
from threading import Event
import pytest
from cbb_refresh_verify import desktop_worker as desktop, session_record as sessions
@pytest.mark.parametrize('asynchronous,expected', [(False, 'POSTCALL'), (True, 'NATIVE_CALL')])
@pytest.mark.parametrize('phase', ['NATIVE_CALL', 'CLOSING'])
def test_dispatch_records_pending_before_call_and_waits_for_async_ack(tmp_path, asynchronous, expected, phase):
job = dict(operation_id='dispatch-test', session_record_path=str(tmp_path/'session.json'))
def native_call():
value = sessions.read_session_record(tmp_path/'worker-state.json', evidence_root=tmp_path)
assert value['phase'] == phase
assert desktop._native_phases[job['operation_id']] == phase
return 'native-result'
assert sessions.dispatch_native(job, native_call, phase=phase, asynchronous=asynchronous, required=True) == 'native-result'
assert sessions.read_session_record(tmp_path/'worker-state.json', evidence_root=tmp_path)['phase'] == (
phase if asynchronous else expected)
def test_dispatch_veto_is_not_swallowed_by_optional_journal_mode(tmp_path, monkeypatch):
job = dict(operation_id='veto-test', session_record_path=str(tmp_path/'session.json'))
lost = Event()
monkeypatch.setattr(desktop, '_supervisor_lost', lost)
sessions.update_worker_state(job, 'PRECALL')
lost.set()
with pytest.raises(RuntimeError, match='WORKER_CANCELLED'):
sessions.dispatch_native(job, lambda: pytest.fail('native call after supervisor loss'), required=False)
assert sessions.read_session_record(tmp_path/'worker-state.json', evidence_root=tmp_path)['phase'] == 'PRECALL'
def test_dispatch_refuses_new_call_if_required_journal_cannot_be_written(tmp_path, monkeypatch):
job = dict(operation_id='disk-test', session_record_path=str(tmp_path/'session.json'))
def unavailable(*args, **kwargs):
raise OSError('disk unavailable')
monkeypatch.setattr(sessions, 'write_session_record', unavailable)
with pytest.raises(OSError, match='disk unavailable'):
sessions.dispatch_native(job, lambda: pytest.fail('unrecorded dispatch'), required=True)
def test_failed_native_return_stays_unconfirmed(tmp_path):
job = dict(operation_id='unknown-test', session_record_path=str(tmp_path/'session.json'))
def interrupted():
raise TimeoutError('COM transport result unknown')
with pytest.raises(TimeoutError):
sessions.dispatch_native(job, interrupted)
assert sessions.read_session_record(tmp_path/'worker-state.json', evidence_root=tmp_path)['phase'] == 'UNCONFIRMED'
def test_whole_library_release_names_every_reconciled_retained_block(tmp_path, monkeypatch):
from cbb_refresh_verify import library_lock as locks
monkeypatch.setattr(sessions, '_retained_libraries', {})
monkeypatch.setattr(sessions, '_retained_results', {})
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
for block in ('BlockA', 'BlockB'):
path = tmp_path/block/'session.json'; path.parent.mkdir()
op = 'operation-'+block
sessions.write_session_record(path, dict(operation_id=op, library=str(library), block=block, processes=[]))
key = str(path.absolute()).casefold()
sessions._retained_libraries[key] = {sessions._library_key(library)}
sessions._retained_results[key] = dict(block=block, library=str(library), operation_id=op)
locks._persist_blocker(library, lease_id='b'*32, block_name='BlockB')
@contextmanager
def proof(*args, **kwargs):
yield dict(native_owners=[], addresses=[], exclusive_files=[str(library)])
monkeypatch.setattr(locks, '_prove_library_released', proof)
result = locks.release_retained_library(library, tmp_path/'proof', block_name='BlockA')
assert result['reconciled_blocks'] == ['BlockA', 'BlockB']
assert {r['operation_id'] for r in result['reconciled_sessions']} == {'operation-BlockA', 'operation-BlockB'}
assert result['reconciled_foreign_blockers'] == ['BlockB']
assert sessions.library_available(library)
for block in ('BlockA', 'BlockB'):
receipt = json.loads(next((tmp_path/block).glob('observation-release-*.json')).read_text('utf-8'))
assert receipt['release_proof']['reconciled_blocks'] == ['BlockA', 'BlockB']
def test_release_snapshot_cannot_ack_a_replaced_operation(tmp_path, monkeypatch):
library = tmp_path/'lib.lmc'
key = str(tmp_path/'session.json')
aliases = {sessions._library_key(library)}
monkeypatch.setattr(sessions, '_retained_libraries', {key: aliases})
monkeypatch.setattr(sessions, '_retained_results', {key: dict(block='A', operation_id='before')})
snapshot = sessions.retained_session_snapshot(library)
sessions._retained_results[key]['operation_id'] = 'after'
sessions.acknowledge_library_release(dict(status='RELEASE_CONFIRMED', library=str(library)), snapshot)
assert not sessions.library_available(library)
assert sessions.reconciled_retained_sessions(snapshot) == []