fix: resume CBB batches after verified native release

This commit is contained in:
阿白叔 committed 2026-11-25 09:28:05 +08:00
1 parent c76b755f13
commit 5bab125122
18 files changed
+642 -60

No files matched your search

+1 -1
View File
@@ -416,7 +416,7 @@ def test_residual_refresh_details_confirm_and_close(residual, qtbot):
qtbot.waitUntil(lambda: not d.busy)
assert len(residual.releases) == 1 and residual.releases[0]['force'] is False
assert d.table.item(0, 6).text() == '允许'
assert d.table.item(0, 7).text() == '未释放'
assert d.table.item(0, 7).text() == '未退出'
press(qtbot, d.close_button)
assert not d.isVisible()
+73
View File
@@ -111,6 +111,79 @@ def test_smoke_arguments_exit_zero_and_write_lifecycle_log(tmp_path: Path):
assert "gui_smoke_window_created" in text
def test_desktop_duplicate_activates_original_and_recovers_after_exit(tmp_path):
import os
import subprocess
import sys
import time
harness = r'''
import os, sys
from PySide6.QtWidgets import QWidget
from cbb_refresh_verify import application
from cbb_refresh_verify.ui import main_window
class Window(QWidget):
def __init__(self, *, logging_context):
super().__init__()
self.directory = logging_context.root
def show(self):
self.showMinimized()
(self.directory / f'{os.getpid()}.started').touch()
def activateWindow(self):
assert not self.isMinimized()
(self.directory / f'{os.getpid()}.activated').touch()
super().activateWindow()
main_window.MainWindow = Window
raise SystemExit(application.main(sys.argv[1:]))
'''
data = tmp_path / 'data'
independent = tmp_path / 'other'
processes = []
def start(directory):
process = subprocess.Popen([sys.executable, '-c', harness, '--data-root', str(directory)],
env={**os.environ, 'QT_QPA_PLATFORM': 'offscreen'})
processes.append(process)
return process
def wait_for_file(path):
deadline = time.monotonic() + 12
while not path.exists() and time.monotonic() < deadline:
time.sleep(.03)
assert path.is_file(), path
try:
initial = start(data)
wait_for_file(data / f'{initial.pid}.started')
duplicate = start(data / '..' / data.name.upper())
assert duplicate.wait(timeout=8) == 0
assert {path.stem for path in data.glob('*.started')} == {str(initial.pid)}
assert (data / f'{initial.pid}.activated').is_file()
other = start(independent)
wait_for_file(independent / f'{other.pid}.started')
initial.kill()
initial.wait(timeout=5)
contenders = [start(data), start(data)]
deadline = time.monotonic() + 12
while not any(process.poll() is not None for process in contenders) and time.monotonic() < deadline:
time.sleep(.03)
assert sorted((process.poll() for process in contenders), key=lambda value: value is None) == [0, None]
surviving = next(process for process in contenders if process.poll() is None)
assert {path.stem for path in data.glob('*.started')} == {str(initial.pid), str(surviving.pid)}
assert (data / f'{surviving.pid}.activated').is_file()
finally:
for process in processes:
if process.poll() is None:
process.kill()
process.wait(timeout=5)
def test_module_entrypoint_propagates_main_exit_code():
import subprocess, sys
code = (
+29
View File
@@ -0,0 +1,29 @@
import pytest
from cbb_refresh_verify.library_lock import LibraryBusy
from cbb_refresh_verify.operation_queue import BatchTaskContext, QueueUnavailable
from cbb_refresh_verify.verify_runner import VerifyRequest
def test_batch_admission_rechecks_once_before_dispatch(tmp_path, monkeypatch):
from cbb_refresh_verify import verify_runner
library = tmp_path/'library.lmc'
library.touch()
request = VerifyRequest(library, 'Next', tmp_path/'evidence')
calls = []
monkeypatch.setattr('cbb_refresh_verify.library_lock.recheck_previous_release',
lambda lib, *args, **kwargs: calls.append((lib, kwargs['infer_scope'])))
verify_runner.wait_for_batch_release(request, BatchTaskContext(str(library)))
assert calls == [(library, True)]
def test_batch_admission_reports_resource_at_entry(tmp_path, monkeypatch):
from cbb_refresh_verify import verify_runner
library = tmp_path/'library.lmc'
library.touch()
request = VerifyRequest(library, 'Next', tmp_path/'evidence')
def busy(*args, **kwargs):
raise LibraryBusy('共享符号库 icdb.dat 仍在使用')
monkeypatch.setattr('cbb_refresh_verify.library_lock.recheck_previous_release', busy)
with pytest.raises(QueueUnavailable, match='共享符号库 icdb.dat 仍在使用'):
verify_runner.wait_for_batch_release(request, BatchTaskContext(str(library)), timeout_seconds=0)
+45 -8
View File
@@ -23,9 +23,10 @@ def test_status_scan_delivers_progress_after_each_record(tmp_path):
assert snapshots == [(1, 2, 1), (2, 2, 2)]
@pytest.mark.parametrize('include_identity', [False, True])
def test_catalog_registration_only_skips_project_identities(tmp_path, monkeypatch, include_identity):
@pytest.mark.parametrize(('include_identity', 'unknown_foreign'), [(False, False), (True, False), (False, True)])
def test_catalog_registration_only_skips_project_identities(tmp_path, monkeypatch, include_identity, unknown_foreign):
import win32com.client
import win32process
from cbb_refresh_verify import mentor_adapter
lmc = tmp_path / 'lib.lmc'
@@ -42,15 +43,26 @@ def test_catalog_registration_only_skips_project_identities(tmp_path, monkeypatc
Partitions=lambda _: SimpleNamespace(Count=1, Item=lambda _: partition))
app = SimpleNamespace(OpenLibrary=lambda _: library, Quit=lambda: None)
exe = tmp_path / 'lm/win32/bin/LibraryManager.exe'
no_owners = iter([[], [(123, str(exe), '', 0)]])
monkeypatch.setattr(mentor_adapter, '_process_details', lambda _: next(no_owners))
previous = [(321, str(exe), '', 0)] if unknown_foreign else []
snapshots = iter([previous, [*previous, (123, str(exe), '', 0)]])
monkeypatch.setattr(mentor_adapter, '_process_details', lambda _: next(snapshots))
if unknown_foreign:
exe.parent.mkdir(parents=True)
exe.write_bytes(b'library manager')
monkeypatch.setitem(native._BINARY_PROOF, 'lm/win32/bin/LibraryManager.exe', native.hash_file(exe))
monkeypatch.setattr(native, '_open_catalog_manager_library', lambda _: None)
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda _: (456, 123))
monkeypatch.setattr(native, '_current_desktop',
lambda: (SimpleNamespace(EnumDesktopWindows=lambda: []), 'CbbManagement_test'))
lambda: (SimpleNamespace(EnumDesktopWindows=lambda: [42] if unknown_foreign else []),
'CbbManagement_test'))
monkeypatch.setattr(win32com.client, 'DispatchEx', lambda _: app)
result = native._catalog_com({'operation': 'catalog', 'worker_role': 'catalog_readonly',
'include_engineering_identity': include_identity, 'library': str(lmc),
'desktop': 'CbbManagement_test', 'mentor_home': str(tmp_path), 'supervisor_pid': __import__('os').getpid()}, tmp_path)
assert result['success']
assert result['native_pids'] == [123]
if unknown_foreign:
assert result['existing_manager_libraries'] == {321: None}
assert hashed == ([project] if include_identity else [])
@@ -77,14 +89,15 @@ def test_catalog_distinguishes_foreign_and_conflicting_manager(tmp_path, monkeyp
def held(library):
raise OSError('shared database handle is occupied')
monkeypatch.setattr(native, '_probe_catalog_files', held)
if scope == 'foreign':
if scope in {'foreign', 'unknown'}:
native._check_catalog_owners(target, owners)
else:
with pytest.raises(RuntimeError, match='LIBRARY_MANAGER_BUSY.*123'):
native._check_catalog_owners(target, owners)
def test_catalog_rejects_reused_foreign_com_proxy_without_mutating_it(tmp_path, monkeypatch):
@pytest.mark.parametrize('title_resolved', [True, False])
def test_catalog_rejects_reused_foreign_com_proxy_without_mutating_it(tmp_path, monkeypatch, title_resolved):
import win32com.client
from cbb_refresh_verify import mentor_adapter
@@ -99,7 +112,7 @@ def test_catalog_rejects_reused_foreign_com_proxy_without_mutating_it(tmp_path,
monkeypatch.setitem(native._BINARY_PROOF, 'lm/win32/bin/LibraryManager.exe', native.hash_file(exe))
before = [(123, 'LibraryManager.exe', f'LibraryManager.exe "{other}"', 0)]
monkeypatch.setattr(mentor_adapter, '_process_details', lambda _: before)
monkeypatch.setattr(native, '_open_catalog_manager_library', lambda _: other, raising=False)
monkeypatch.setattr(native, '_open_catalog_manager_library', lambda _: other if title_resolved else None)
monkeypatch.setattr(native, '_current_desktop',
lambda: (SimpleNamespace(EnumDesktopWindows=lambda: []), 'CbbManagement_test'))
@@ -119,6 +132,30 @@ def test_catalog_rejects_reused_foreign_com_proxy_without_mutating_it(tmp_path,
assert result['native_pids'] == []
assert result['no_new_manager'] is True
assert 'LIBRARY_MANAGER_BUSY' in result['detail']
@pytest.mark.parametrize('resource', ['library', 'shared_symbols'])
def test_catalog_checks_target_sharing_when_manager_title_lacks_a_path(tmp_path, monkeypatch, resource):
import win32con
import win32file
from cbb_refresh_verify.icdb_ownership import shared_symbol_database
library = tmp_path/'target.lmc'
library.touch()
shared = shared_symbol_database(library)/'icdb.dat'
shared.parent.mkdir(parents=True)
shared.touch()
locked = library if resource == 'library' else shared
monkeypatch.setattr(native, '_open_catalog_manager_library', lambda _: None)
handle = win32file.CreateFile(str(locked), win32con.GENERIC_READ, 0, None, win32con.OPEN_EXISTING, 0, None)
try:
with pytest.raises(native.NativeOperationError) as raised:
native._check_catalog_owners(library, [(123, 'LibraryManager.exe', '', 0)])
assert raised.value.blocking_manager_pids == (123,)
assert str(locked) in str(raised.value)
finally:
handle.Close()
native._check_catalog_owners(library, [(123, 'LibraryManager.exe', '', 0)])
+110
View File
@@ -177,3 +177,113 @@ def test_cancelled_prewrite_can_dismiss_exact_late_load_failure(qtbot, tmp_path,
assert residual_sessions.finish_owned_idle_session(root/'session.json') is proved
assert state['posts'] == ([(201, 12, 245), (100, 12, 16)] if proved else [])
assert (root/'result.json').read_bytes() == original
@pytest.mark.parametrize('obstacle', [None, 'tip', 'read_write', 'unknown_prompt', 'save',
'uncertain_phase', 'live_supervisor', 'live_worker',
'wrong_pcb', 'possible_write'])
def test_restarted_verify_closes_exact_prewrite_orphan(tmp_path, monkeypatch, obstacle):
import json
from contextlib import nullcontext
from types import SimpleNamespace
from test_owned_idle_cleanup import owned_fixture
from cbb_refresh_verify import failed_session, residual_sessions
root, job, _, windows, state = owned_fixture(tmp_path, monkeypatch)
path = root/'session.json'
session = session_record.read_session_record(path, evidence_root=root)
supervisor = dict(pid=10, image='C:/App/CbbRefreshVerify.exe', created_handle='supervisor-created',
owner_sid='owner', session_id=1)
job.update(supervisor_identity=supervisor, supervisor_pid=10, diagnostic_only=False,
cancel_signal=str(root/'cancel.signal'))
session.update(supervisor_identity=supervisor, cancel_signal=job['cancel_signal'],
resource_scope=dict(scope_state='DECLARED', library=job['library'],
operation_id='owned', projects=[job['project']]))
session_record.write_session_record(path, session)
(root/'request.json').write_text(json.dumps(job), encoding='utf-8')
(root/'result.json').unlink()
Path(job['cancel_signal']).touch()
session_record.write_session_record(root/'supervisor-lost.json',
{'operation_id': 'owned', 'phase': 'SUPERVISOR_LOST'})
worker_state = session_record.read_session_record(root/'worker-state.json', evidence_root=root)
if obstacle == 'uncertain_phase':
worker_state['phase'] = 'NATIVE_CALL'
session_record.write_session_record(root/'worker-state.json', worker_state)
binding = {key: job[key] for key in ('operation_id', 'project', 'pcb', 'desktop')}
command = f'"D:/Mentor/ExpeditionPCB.exe" "{job["pcb"]}" -ReusableCircuit'
if obstacle == 'wrong_pcb':
command = command.replace(job['pcb'], job['pcb'] + '.wrong')
rows = [dict(stage='startup_supervisor_no_write', **binding),
dict(stage='startup_prewrite_ready', worker_identity=session['processes'][0],
baseline=dict(started_ns=42, files={}), **binding),
dict(stage='pcb_baseline', pids=[]),
dict(stage='pcb_worker_started', pcb_pid=12, command=command)]
if obstacle == 'possible_write':
rows.append(dict(stage='startup_supervisor_write_possible', **binding))
(root/'events.jsonl').write_text(''.join(json.dumps(row)+'\n' for row in rows), encoding='utf-8')
if obstacle == 'save':
(root/'save.log').write_text('SAVE_START\n', encoding='utf-8')
state['worker_alive'] = obstacle == 'live_worker'
monkeypatch.setattr(residual_sessions, '_recorded_process_exited',
lambda identity: obstacle != 'live_supervisor' and identity == supervisor)
if obstacle in ('tip', 'read_write', 'unknown_prompt'):
frame = windows[0]
frame['enabled'] = False
windows.append(dict(hwnd=200, title='Tip of the Day' if obstacle == 'tip' else 'Expedition PCB',
desktop=job['desktop'], children=[], enabled=True, **{'class': '#32770'}))
def post(window, hwnd, pid, message):
observed = session_record.read_session_record(path, evidence_root=root)
assert observed['owned_idle_cleanup']['pid'] == pid
state['posts'].append((hwnd, pid, message))
if hwnd == 201:
windows.pop()
frame['enabled'] = True
else:
state['native_alive'] = False
def dismiss_tip(row, handle, windows, **options):
post(windows[1], 201, row['pid'], 245)
return 200
monkeypatch.setattr(residual_sessions, '_dismiss_startup_tip', dismiss_tip)
monkeypatch.setattr(residual_sessions, '_post_window_message', post)
monkeypatch.setattr(residual_sessions, '_window_desktop', lambda *_: nullcontext())
monkeypatch.setattr(failed_session, '_startup_snapshot', lambda *_: 'exact shutdown prompt')
monkeypatch.setattr(failed_session, '_tip_target', lambda _: SimpleNamespace(handle=201))
monkeypatch.setattr(failed_session, '_cancel_target', lambda _: ('read_write_access',
SimpleNamespace(handle=201)) if obstacle == 'read_write' else None)
recovered = residual_sessions.finish_owned_idle_session(path)
assert recovered is (obstacle in (None, 'tip', 'read_write'))
expected_posts = [(201, 12, 245)] if obstacle in ('tip', 'read_write') else []
if recovered:
expected_posts.append((100, 12, 16))
assert state['posts'] == expected_posts
if recovered:
receipt = session_record.read_session_record(root/'owned-idle-cleanup-result.json', evidence_root=root)
assert receipt['status'] == 'CLIENT_EXITED'
assert receipt['resource_release_confirmed'] is False
def test_verify_registers_ordinary_pcb_before_any_write_phase(tmp_path, monkeypatch):
import json
from cbb_refresh_verify import mentor_adapter
bound_phases = []
request = tmp_path/'request.json'
request.write_text(json.dumps(dict(root=str(tmp_path), block_name='Bad', diagnostic_only=False,
desktop='CbbVerify_owned', operation_id='owned', session_record_path=str(tmp_path/'session.json'))),
encoding='utf-8')
monkeypatch.setattr(session_record, 'update_worker_state',
lambda job, phase, **options: bound_phases.append((phase, options['identities'])))
def execute(job, emit):
emit(stage='pcb_worker_started', pcb_pid=12)
emit(stage='integration_action', action='UpdateNets')
return {'status': 'PASS'}
monkeypatch.setattr(mentor_adapter, 'execute_job', execute)
assert mentor_adapter.worker_main(request) == 0
assert bound_phases == [('PRECALL', [('native', 12)]), ('NATIVE_CALL', [])]
+36
View File
@@ -307,3 +307,39 @@ def test_arbitrary_guard_filename_is_preserved_and_primary(tmp_path, monkeypatch
with pytest.raises(locks.LibraryBusy):
locks.release_retained_library(library, tmp_path/'release')
assert marker.read_bytes() == b'{not a guard record'
def test_recovery_scope_uses_interrupted_block_instead_of_new_selection(tmp_path, monkeypatch):
from cbb_refresh_verify import library_lock as locks
library = tmp_path/'lib/lib.lmc'
library.parent.mkdir()
library.touch()
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
locks._persist_blocker(library, lease_id='a'*32, block_name='Interrupted')
proof = locks.release_retained_library(library, tmp_path/'evidence',
block_name='NewSelection', infer_scope=True)
assert proof['proof_scope'] == 'BLOCK'
assert proof['proof_block_names'] == ['Interrupted']
assert proof['reconciled_foreign_blockers'] == ['Interrupted']
def test_probe_timeout_reports_last_io_phase_and_path(tmp_path, monkeypatch):
from cbb_refresh_verify import file_probe
import sys
script = tmp_path/'slow_probe.py'
library = tmp_path/'lib.lmc'
script.write_text(
"import json, sys, time\n"
"from pathlib import Path\n"
"job = Path(sys.argv[-1])\n"
"job.with_name('progress.json').write_text(json.dumps("
"{'stage': 'open_exclusive', 'path': 'SymbolLibs/icdb.dat'}))\n"
"time.sleep(30)\n",
encoding='utf-8')
start = file_probe.subprocess.Popen
monkeypatch.setattr(file_probe.subprocess, 'Popen',
lambda command, **kwargs: start([sys.executable, str(script), command[-1]], **kwargs))
with pytest.raises(TimeoutError, match=r'FILE_PROBE_TIMEOUT.*open_exclusive.*SymbolLibs/icdb.dat'):
with file_probe.hold_release_files(library, timeout_seconds=.7):
pytest.fail('a timed-out probe cannot prove release')
+2 -1
View File
@@ -59,7 +59,8 @@ def test_confirm_releases_full_plan_and_only_emits_actual_library_proof(qtbot, t
qtbot.waitUntil(lambda: not dialog.busy)
assert len(calls) == 1 and calls[0]['sessions'] == plan['sessions']
assert calls[0]['library'] == plan['library'] and released == [proof]
assert '已释放 2' in dialog.message.text()
assert '库已释放' in dialog.message.text()
assert '2 个客户端退出' in dialog.message.text()
assert not dialog.confirm_button.isEnabled()