fix: retain native save completion through cancellation and restart

This commit is contained in:
阿白叔 committed 2026-11-24 08:48:33 +08:00
1 parent 18349413c5
commit 443668aa4b
11 files changed
+220 -45

No files matched your search

+4 -1
View File
@@ -256,6 +256,7 @@ def main(argv: Sequence[str] | None = None) -> int:
try:
from .operation_queue import BatchTaskContext, NativeQueue, request_library_keys
from .session_record import discover_sessions, handoff_session
from .residual_sessions import recoverable_orphan_session
aliases = tuple(request_library_keys(requests[0]))
task = BatchTaskContext(str(mentor_path), aliases=aliases,
@@ -267,7 +268,9 @@ def main(argv: Sequence[str] | None = None) -> int:
continue
old_request = VerifyRequest(Path(old_session['library']), names[0], context.root)
if request_library_keys(old_request).intersection(aliases):
handoff_session(old_session['path'], evidence_root=context.root, observe_only=True)
path = old_session['path']
handoff_session(path, evidence_root=context.root,
observe_only=lambda path=path: not recoverable_orphan_session(path))
def admit(_request, action):
return queue.run(action, stop=task.stop, context=task,
+4 -1
View File
@@ -373,6 +373,9 @@ def _owner_matches_scope(item, library, roots):
return None
candidates = []
worker_flags = {'--verify-worker', '--repair-worker', '--management-worker', '--native-backup-worker'}
path_flags = {'-icdb', '-project', '-p'}
if ntpath.basename(str(item.get('name') or args[0])).casefold() == 'icdbnetserver.exe':
path_flags.add('-db')
for index, arg in enumerate(args[1:], 1):
if arg.casefold() in worker_flags and index + 1 < len(args):
try:
@@ -388,7 +391,7 @@ def _owner_matches_scope(item, library, roots):
value = arg.split('=', 1)[1] if arg.startswith('-') and '=' in arg else arg
if (ntpath.isabs(value) and (ntpath.splitext(value)[1].casefold() in ('.prj', '.pcb', '.lmc')
or arg.casefold().startswith(('-project=', '-icdb='))
or args[index - 1].casefold() in ('-icdb', '-project', '-p'))):
or args[index - 1].casefold() in path_flags)):
candidates.append(value)
normalized_roots = [ntpath.normcase(ntpath.normpath(str(root))) for root in roots]
expected_library = ntpath.normcase(ntpath.normpath(str(library)))
+13 -5
View File
@@ -865,7 +865,7 @@ def execute_job(job, emit):
code = helper.returncode
save_log = (root/'save.log').read_bytes().decode('utf-8', errors='replace')
from .runtime_timing import parse_save_progress
emit(stage='save_progress', helper_exited=True, **parse_save_progress(save_log))
emit(stage='save_progress', helper_exited=True, helper_exit_code=code, **parse_save_progress(save_log))
markers = set(save_log.splitlines())
from .operation_lifecycle import classify_save_state
write_facts = classify_save_state(save_log.splitlines(), helper_exited=True, native_released=None)
@@ -1022,17 +1022,25 @@ def worker_main(request_path):
'integration_action_complete': 'POSTCALL', 'saved_and_closed': 'RELEASE_CHECK',
'complete': 'FINISHED', 'failed': 'UNCONFIRMED'}.get(event.get('stage'))
identities = [(role, event.get(key)) for role, key in
(('native', 'pcb_pid'), ('native', 'lm_pid'), ('helper', 'helper_pid'))
(('native', 'pcb_pid'), ('native', 'lm_pid'))
if event.get(key)]
facts = None
continuing_save = False
if event.get('stage') == 'save_progress':
from .operation_lifecycle import classify_save_state
facts = classify_save_state(event.get('markers', ()),
helper_exited=event.get('helper_exited'), native_released=None)
phase = ('POSTCALL' if event.get('helper_exited') is True else
'CLOSING' if 'CLOSE_START' in event.get('markers', ()) else 'NATIVE_CALL')
facts['save_close_confirmed'] = (
event.get('helper_exited') is True and event.get('helper_exit_code') == 0
and facts['interrupted'] is False
and save_log_has_core_markers('\n'.join(event.get('markers', ())))
)
# Save and Close run in one already admitted helper.
continuing_save = event.get('helper_exited') is not True
phase = 'NATIVE_CALL' if continuing_save else 'POSTCALL'
if phase or identities:
update_worker_state(job, phase or 'UNCONFIRMED', identities=identities, write_outcome=facts)
update_worker_state(job, phase or 'UNCONFIRMED', identities=identities,
write_outcome=facts, continuation=continuing_save)
event.update(time=time.strftime('%Y-%m-%d %H:%M:%S'), block=job['block_name'],
monotonic_seconds=time.monotonic())
with (root/'events.jsonl').open('a', encoding='utf-8') as stream:
+62 -27
View File
@@ -832,15 +832,36 @@ def _recorded_process_exited(identity):
return error.winerror == 87
def orphaned_catalog_session(path):
from .session_record import IDENTITY_KEYS, MAX_BYTES, read_session_record
def _saved_and_closed(facts):
return (isinstance(facts, dict) and facts.get('interrupted') is False
and all(facts.get(key) == value for key, value in (
('save_state', 'COMMITTED'), ('close_state', 'CLOSED'), ('helper_state', 'EXITED'))))
def _worker_save_facts(state, identities):
if (state.get('phase') in ('POSTCALL', 'RELEASE_CHECK', 'FINISHED', 'UNCONFIRMED')
and any(p.get('role') == 'helper' for p in identities)):
facts = state.get('write_outcome')
if isinstance(facts, dict) and facts.get('save_close_confirmed') is True:
return facts
return None
def recoverable_orphan_session(path):
from .session_record import IDENTITY_KEYS, MAX_BYTES, read_session_record, _session
import stat
path = Path(path)
try:
session = read_session_record(path, evidence_root=path.parent)
if (session.get('operation') != 'catalog' or session.get('worker_role') != 'catalog_readonly'
or not str(session.get('desktop', '')).startswith('CbbManagement_')):
operation = session.get('operation')
desktop = str(session.get('desktop', ''))
if operation == 'verify' and desktop.startswith('CbbVerify_'):
_, state, identities = _session(path, path.parent)
if not _saved_and_closed(_worker_save_facts(state, identities)):
return False
elif (operation != 'catalog' or session.get('worker_role') != 'catalog_readonly'
or not desktop.startswith('CbbManagement_')):
return False
request = path.with_name('request.json')
if request.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
@@ -854,13 +875,17 @@ def orphaned_catalog_session(path):
('operation_id', 'operation', 'library', 'desktop', 'worker_role'))
or Path(job['session_record_path']).resolve() != path.resolve()):
return False
if operation == 'verify' and (job.get('interactive_input') is not False
or job.get('block') != session.get('block') or job.get('lmc_file') != session['library']
or Path(job.get('root', '')).resolve() != path.parent.resolve()):
return False
identity = job['supervisor_identity']
if (not isinstance(identity, dict) or any(identity.get(key) is None for key in IDENTITY_KEYS)
or type(identity['pid']) is not int or identity['pid'] <= 0
or identity['pid'] != job.get('supervisor_pid')):
return False
if session.get('supervisor_identity') != identity:
if session.get('supervisor_identity') is not None:
if operation != 'catalog' or session.get('supervisor_identity') is not None:
return False
lost = read_session_record(path.with_name('supervisor-lost.json'), evidence_root=path.parent)
if lost.get('operation_id') != session['operation_id'] or lost.get('phase') != 'SUPERVISOR_LOST':
@@ -907,32 +932,37 @@ def finish_owned_idle_session(path, *, stop=None):
result = read_result()
if result is None:
if (state.get('phase') not in ('PRECALL', 'POSTCALL', 'RELEASE_CHECK', 'FINISHED', 'UNCONFIRMED')
or not orphaned_catalog_session(path)):
or not recoverable_orphan_session(path)):
return False
elif not isinstance(result, dict) or result.get('safe_to_continue') is not False:
return False
cancelled_before_write = None
if operation == 'verify':
if result is None:
return False
facts = result.get('write_outcome') or {}
failed_open = (result.get('error_stage') == 'PCB_STARTING'
and result.get('error_category') in ('MENTOR_DATABASE_LOAD_FAILED','ICDB_REPAIR_REQUIRED')
and not path.with_name('save.log').exists())
if (result.get('status') == 'CANCELLED' and result.get('error_stage') == 'PCB_STARTING'
and state.get('phase') == 'UNCONFIRMED'):
from .failed_session import cancelled_prewrite_startup
cancelled_before_write = cancelled_prewrite_startup(job)
saved_closed = (isinstance(facts, dict) and facts.get('interrupted') is False
and all(facts.get(k) == v for k,v in (
('save_state','COMMITTED'),('close_state','CLOSED'),('helper_state','EXITED'))))
if (not desktop.startswith('CbbVerify_') or job.get('interactive_input') is not False
or result.get('status') not in ('FAIL','BLOCKED','TIMEOUT','CANCELLED')
or result.get('block_name') != job['block']
or Path(result.get('evidence_path','')).resolve() != path.with_name('result.json').resolve()
or Path(job.get('root','')).resolve() != path.parent.resolve()
or job.get('lmc_file') != job['library']
or not (failed_open or saved_closed or cancelled_before_write is not None)): return False
or Path(job.get('root', '')).resolve() != path.parent.resolve()
or job.get('lmc_file') != job['library']):
return False
if result is not None:
if (result.get('status') not in ('FAIL', 'BLOCKED', 'TIMEOUT', 'CANCELLED')
or result.get('block_name') != job['block']
or Path(result.get('evidence_path', '')).resolve() != path.with_name('result.json').resolve()):
return False
facts = result.get('write_outcome')
worker_facts = _worker_save_facts(state, identities)
provisional = (isinstance(facts, dict) and facts.get('helper_state') in ('RUNNING', 'UNKNOWN')
and facts.get('interrupted') is False and facts.get('save_state') != 'REJECTED'
and facts.get('close_state') != 'FAILED')
if facts is None or provisional or (session.get('supervisor_identity') and _saved_and_closed(facts)):
facts = worker_facts
failed_open = (result.get('error_stage') == 'PCB_STARTING'
and result.get('error_category') in ('MENTOR_DATABASE_LOAD_FAILED', 'ICDB_REPAIR_REQUIRED')
and not path.with_name('save.log').exists())
if (result.get('status') == 'CANCELLED' and result.get('error_stage') == 'PCB_STARTING'
and state.get('phase') == 'UNCONFIRMED'):
from .failed_session import cancelled_prewrite_startup
cancelled_before_write = cancelled_prewrite_startup(job)
if not (failed_open or _saved_and_closed(facts) or cancelled_before_write is not None):
return False
client_name = 'expeditionpcb.exe'
elif operation == 'catalog' and job.get('worker_role') == 'catalog_readonly' and desktop.startswith('CbbManagement_'):
client_name = 'librarymanager.exe'
@@ -1008,8 +1038,13 @@ def finish_owned_idle_session(path, *, stop=None):
or (empty_target() != target if failure is None else load_failure_button() != failure)
or (cancelled_before_write is not None
and cancelled_prewrite_startup(job, client['pid']) != cancelled_before_write)
or read_result() != result or result is None and not orphaned_catalog_session(path)
or stop is not None and stop.is_set()): return False
or read_result() != result or result is None and not recoverable_orphan_session(path)
or stop is not None and stop.is_set()):
# Nothing was sent. The still-matching claim can be retried.
if latest.get('owned_idle_cleanup') == claim:
latest.pop('owned_idle_cleanup')
write_session_record(path, latest)
return False
with native_phase(read_only=True):
if failure is not None:
_post_window_message({'desktop': desktop}, failure[1], client['pid'], win32con.BM_CLICK)
+2 -2
View File
@@ -164,7 +164,7 @@ def register_worker_session(worker, job):
'lease_state': 'ACTIVE', 'resource_scope': session_resource_scope(job),
'worker_protection': protection, 'task_operation_id': context.operation_id if context else None,
'blocked_resources': [], 'data_recovery_required': None})
if protection == 'catalog_readonly' and job.get('supervisor_identity'):
if (protection == 'catalog_readonly' or job.get('operation') == 'verify') and job.get('supervisor_identity'):
record['supervisor_identity'] = job['supervisor_identity']
if job.get('start_gate_protocol') == 'event-v1':
import win32api, win32con, win32event
@@ -484,7 +484,7 @@ def handoff_session(path, *, evidence_root, process=None, progress=None, stop=No
if progress is not None:
progress(value)
def observation_only():
if not observe_only:
if not (observe_only() if callable(observe_only) else observe_only):
return False
with _observer_guard:
value = _retained_results.get(key, {})
+4 -4
View File
@@ -605,7 +605,7 @@ class MainWindow(QWidget):
def _show_unfinished_management(self):
from cbb_refresh_verify.management import unfinished_operations
from cbb_refresh_verify.session_record import discover_sessions, handoff_session
from cbb_refresh_verify.residual_sessions import orphaned_catalog_session
from cbb_refresh_verify.residual_sessions import recoverable_orphan_session
root = self.data_root
revision, owner = self._view_revision, self._current_job
context = BatchTaskContext(str(root))
@@ -619,9 +619,9 @@ class MainWindow(QWidget):
sessions = discover_sessions(root)
for session in sessions:
if session['status'] == 'ACTIVE':
recover_catalog = orphaned_catalog_session(session['path'])
handoff_session(session['path'], evidence_root=root,
observe_only=not recover_catalog,
path = session['path']
handoff_session(path, evidence_root=root,
observe_only=lambda path=path: not recoverable_orphan_session(path),
progress=lambda value: notify({'stage': 'session_observation', **value}))
return unfinished, sessions
worker = ServiceWorker(lambda:context.run(inspect))
+16 -2
View File
@@ -1472,10 +1472,24 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
from .operation_lifecycle import classify_save_state
save_lines = ((root/'save.log').read_text('utf-8', errors='replace').splitlines()
if (root/'save.log').is_file() else [])
_write_optional_evidence(root/'write-outcome.json', classify_save_state(save_lines,
facts = classify_save_state(save_lines,
helper_exited=(False if automation_release.get('remaining_pids') else
True if worker_exited and automation_release.get('safe_to_continue') else None),
native_released=release_result.get('safe_to_continue') is True))
native_released=release_result.get('safe_to_continue') is True)
if 'SAVE_START' in save_lines and getattr(process, 'session_record_path', None):
from .session_record import read_session_record
try:
state = read_session_record(root/'worker-state.json', evidence_root=root)
except (OSError, ValueError):
state = {}
receipt = state.get('write_outcome')
confirmed = (state.get('operation_id') == job['operation_id']
and isinstance(receipt, dict) and receipt.get('save_close_confirmed') is True)
facts['save_close_confirmed'] = confirmed
if facts['helper_state'] == 'EXITED' and not confirmed:
facts['interrupted'] = True
facts['detail'] = '缺少保存助手正常退出的完整记录'
_write_optional_evidence(root/'write-outcome.json', facts)
(root/'session-release.json').write_text(json.dumps({
**(release_result or {}), 'block': request.block_name,
'library': str(request.lmc_file), 'worker_exited': worker_exited,
+37
View File
@@ -110,3 +110,40 @@ def test_supervisor_crash_preserves_registered_save_caller_and_native(tmp_path):
if win32process.GetExitCodeProcess(handle) == 259:
win32process.TerminateProcess(handle, 0)
handle.Close()
def test_registered_save_records_completion_after_supervisor_loss(tmp_path, monkeypatch):
from threading import Event
from cbb_refresh_verify import desktop_worker, session_record
root = tmp_path
state_path = root/'worker-state.json'
job = {'root': str(root), 'block_name': 'CBB', 'operation_id': 'save-orphan',
'session_record_path': str(root/'session.json')}
request = root/'request.json'
request.write_text(json.dumps(job), encoding='utf-8')
lost = Event()
monkeypatch.setattr(desktop_worker, '_supervisor_lost', lost)
monkeypatch.setattr(desktop_worker, '_native_phases', {})
def execute(job, emit):
emit(stage='save_start')
emit(stage='save_helper', helper_pid=987)
lost.set()
emit(stage='save_progress', markers=['SAVE_START', 'SAVE_OK', 'CLOSE_START'],
helper_exited=False)
state = session_record.read_session_record(state_path, evidence_root=root)
assert state['phase'] == 'NATIVE_CALL'
emit(stage='save_progress', markers=['SAVE_START', *FULL_SAVE.splitlines()],
helper_exited=True, helper_exit_code=0)
with pytest.raises(RuntimeError, match='WORKER_CANCELLED'):
emit(stage='integration_action')
return {'status': 'FAIL', 'stderr': 'supervisor interrupted'}
monkeypatch.setattr(adapter, 'execute_job', execute)
assert adapter.worker_main(request) == 1
state = session_record.read_session_record(state_path, evidence_root=root)
assert state['phase'] == 'POSTCALL'
facts = state['write_outcome']
assert facts['save_close_confirmed'] is True
assert (facts['save_state'], facts['close_state'], facts['helper_state']) == (
'COMMITTED', 'CLOSED', 'EXITED')
+3 -3
View File
@@ -66,10 +66,10 @@ def test_catalog_recovery_only_adopts_an_exact_exited_supervisor(tmp_path, monke
job = dict(record, supervisor_pid=55, session_record_path=str(path))
(tmp_path/'request.json').write_text(json.dumps(job), encoding='utf-8')
monkeypatch.setattr(residual_sessions, '_recorded_process_exited', lambda found: found == identity)
assert residual_sessions.orphaned_catalog_session(path)
assert residual_sessions.recoverable_orphan_session(path)
job['supervisor_identity'] = {**identity, 'pid': 56}
(tmp_path/'request.json').write_text(json.dumps(job), encoding='utf-8')
assert not residual_sessions.orphaned_catalog_session(path)
assert not residual_sessions.recoverable_orphan_session(path)
def test_idle_orphan_catalog_can_close_without_final_result(tmp_path, monkeypatch):
@@ -78,7 +78,7 @@ def test_idle_orphan_catalog_can_close_without_final_result(tmp_path, monkeypatc
root, job, _, _, state = owned_fixture(tmp_path, monkeypatch, 'catalog')
(root/'result.json').unlink()
monkeypatch.setattr(residual_sessions, 'orphaned_catalog_session', lambda _: True, raising=False)
monkeypatch.setattr(residual_sessions, 'recoverable_orphan_session', lambda _: True, raising=False)
session_record.write_session_record(root/'worker-state.json',
dict(operation_id='owned', phase='NATIVE_CALL', processes=[dict(role='native', pid=12,
created_handle='native-created', image='D:/Mentor/LibraryManager.exe', owner_sid='owner', session_id=1)]))
+12
View File
@@ -593,3 +593,15 @@ def test_same_target_recovery_gate_preserves_release_and_batch_continues(setup,
adapter=adapter, idle_check=lambda *_: None)
assert [result.status for result in results] == ['BLOCKED', 'UPLOADED']
assert all(result.safe_to_continue for result in results)
@pytest.mark.parametrize('same_library', [True, False])
def test_release_scope_binds_native_shared_database_argument(tmp_path, same_library):
from cbb_refresh_verify.icdb_ownership import shared_symbol_database
from cbb_refresh_verify.library_lock import _owner_matches_scope
library = tmp_path/'Target/lib.lmc'
target = shared_symbol_database(library)
database = target if same_library else shared_symbol_database(tmp_path/'Foreign/lib.lmc')
owner = {'name': 'iCDBNetServer.exe', 'command': f'iCDBNetServer.exe -db "{database}"'}
assert _owner_matches_scope(owner, library, (target,)) is same_library
+63
View File
@@ -217,3 +217,66 @@ def test_wrong_result_or_changed_state_cannot_authorize_normal_close(tmp_path,mo
monkeypatch.setattr(sessions,'write_session_record',changed_state)
assert not residual.finish_owned_idle_session(root/'session.json')
assert not state['posts']
@pytest.mark.parametrize('terminal', [True, False])
def test_save_handoff_uses_terminal_worker_receipt(tmp_path, monkeypatch, terminal):
root, _, result, _, state = owned_fixture(tmp_path, monkeypatch, 'saved')
facts = result['write_outcome']
result['write_outcome'] = dict(save_state='UNKNOWN', close_state='UNKNOWN',
helper_state='RUNNING', interrupted=False)
facts['save_close_confirmed'] = terminal
if not terminal:
facts['save_state'] = 'UNKNOWN'
state_path = root/'worker-state.json'
state_record = sessions.read_session_record(state_path, evidence_root=root)
state_record['processes'].append(dict(role='helper', pid=13, image='C:/Windows/cscript.exe',
created_handle='helper-created', owner_sid='owner', session_id=1))
sessions.write_session_record(state_path, {**state_record, 'phase': 'POSTCALL', 'write_outcome': facts})
import pywintypes
def open_process(pid, **kwargs):
if pid == 13:
raise pywintypes.error(87, 'OpenProcess', 'exited')
return nullcontext(pid)
monkeypatch.setattr(residual, '_process_handle', open_process)
result['status'] = 'CANCELLED'
(root/'result.json').write_text(json.dumps(result))
before = (root/'result.json').read_bytes()
assert residual.finish_owned_idle_session(root/'session.json') is terminal
assert bool(state['posts']) is terminal
assert (root/'result.json').read_bytes() == before
def test_crash_after_returned_save_can_close_only_with_matching_supervisor(tmp_path, monkeypatch):
import pywintypes
root, job, result, _, state = owned_fixture(tmp_path, monkeypatch, 'saved')
(root/'result.json').unlink()
journal = root/'session.json'
supervisor = dict(pid=14, image='C:/app/CbbRefreshVerify.exe', created_handle='parent-created',
owner_sid='owner', session_id=1)
session = sessions.read_session_record(journal, evidence_root=root)
sessions.write_session_record(journal, {**session, 'supervisor_identity': supervisor})
state_path = root/'worker-state.json'
journal_state = sessions.read_session_record(state_path, evidence_root=root)
helper = dict(role='helper', pid=13, image='C:/Windows/cscript.exe', created_handle='helper-created',
owner_sid='owner', session_id=1)
sessions.write_session_record(state_path, {**journal_state, 'phase': 'UNCONFIRMED',
'processes': [*journal_state['processes'], helper],
'write_outcome': {**result['write_outcome'], 'save_close_confirmed': True}})
def open_process(pid, **kwargs):
if pid in (13, 14):
raise pywintypes.error(87, 'OpenProcess', 'exited')
return nullcontext(pid)
monkeypatch.setattr(residual, '_process_handle', open_process)
request = root/'request.json'
job.update(supervisor_pid=14, supervisor_identity={**supervisor, 'created_handle': 'other'})
request.write_text(json.dumps(job), encoding='utf-8')
assert not residual.finish_owned_idle_session(journal)
job['supervisor_identity'] = supervisor
request.write_text(json.dumps(job), encoding='utf-8')
assert residual.finish_owned_idle_session(journal)
assert state['posts'] == [(100, 12, 16)]
assert not (root/'result.json').exists()