fix: reconcile native save release and resume affected CBB batches
This commit is contained in:
1 parent
443668aa4b
commit
c76b755f13
16 files changed
+655
-36
No files matched your search
@@ -28,3 +28,33 @@ def test_batch_rechecks_owned_failure_before_skipping_next_item(tmp_path,monkeyp
|
||||
assert results[0].status=='FAIL' and results[0].stderr=='original failure'
|
||||
assert results[0].safe_to_continue is released
|
||||
assert calls==(['A','B'] if released else ['A'])
|
||||
|
||||
|
||||
def test_batch_rechecks_admission_after_timeout_and_real_release(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import session_record
|
||||
from cbb_refresh_verify.operation_queue import QueueUnavailable
|
||||
|
||||
library = tmp_path/'first/lib.lmc'
|
||||
independent = tmp_path/'second/lib.lmc'
|
||||
occupied = True
|
||||
admission_calls = []
|
||||
|
||||
def available(path):
|
||||
return Path(path) != library or not occupied
|
||||
|
||||
def admit(request, action):
|
||||
nonlocal occupied
|
||||
admission_calls.append(request.block_name)
|
||||
if not available(request.lmc_file):
|
||||
raise QueueUnavailable(request.lmc_file, timed_out=True)
|
||||
if request.block_name == 'B':
|
||||
occupied = False
|
||||
return action()
|
||||
|
||||
monkeypatch.setattr(session_record, '_live_library_available', available)
|
||||
requests = [VerifyRequest(lmc, name, tmp_path/'evidence')
|
||||
for name, lmc in [('A', library), ('A2', library), ('B', independent), ('C', library)]]
|
||||
results = run_batch(requests, verifier=lambda _: VerifyResult('PASS'), item_executor=admit)
|
||||
assert admission_calls == ['A', 'B', 'C']
|
||||
assert [result.status for result in results] == ['SKIPPED', 'SKIPPED', 'PASS', 'PASS']
|
||||
assert results[0].error_category == 'NATIVE_SESSION_PENDING'
|
||||
@@ -40,3 +40,35 @@ def test_cancelled_paused_ticket_does_not_hold_later_work():
|
||||
assert outcome==['cancelled','next']
|
||||
finally:
|
||||
stop.set();queue.wake();thread.join(2)
|
||||
|
||||
def test_saved_database_wait_yields_only_to_other_library_roots(tmp_path):
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from threading import Event
|
||||
from cbb_refresh_verify.operation_queue import BatchTaskContext, allow_other_libraries
|
||||
|
||||
queue = NativeQueue()
|
||||
waiting, released = Event(), Event()
|
||||
same_directory_started = Event()
|
||||
current = BatchTaskContext(str(tmp_path/'first/a.lmc'))
|
||||
same_directory = BatchTaskContext(str(tmp_path/'first/b.lmc'))
|
||||
independent = BatchTaskContext(str(tmp_path/'second/c.lmc'))
|
||||
|
||||
def saved():
|
||||
with allow_other_libraries():
|
||||
waiting.set()
|
||||
assert released.wait(4)
|
||||
return 'confirmed'
|
||||
|
||||
with ThreadPoolExecutor(max_workers=3) as threads:
|
||||
first = threads.submit(queue.run, saved, context=current)
|
||||
assert waiting.wait(2)
|
||||
second = threads.submit(queue.run, same_directory_started.set, context=same_directory)
|
||||
try:
|
||||
third = threads.submit(queue.run, lambda: 'independent', context=independent)
|
||||
assert third.result(timeout=2) == 'independent'
|
||||
assert not same_directory_started.is_set()
|
||||
finally:
|
||||
released.set()
|
||||
assert first.result(timeout=2) == 'confirmed'
|
||||
second.result(timeout=2)
|
||||
assert same_directory_started.is_set()
|
||||
@@ -363,3 +363,65 @@ def test_shared_address_is_bound_to_shared_database_without_a_project_prj(tmp_pa
|
||||
}]
|
||||
assert str(address) in proof['binding_files']
|
||||
assert str(database / 'icdb.dat') in proof['exclusive_files']
|
||||
|
||||
|
||||
def test_shared_address_with_matching_native_shutdown_allows_release_and_open(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import library_lock, owner_probe, pcb_open_consent
|
||||
|
||||
library = tmp_path/'library/lib.lmc'
|
||||
work = library.parent/'ReusableBlocksLP/A/Work'
|
||||
project, pcb = work/'A.prj', work/'PCB/A.pcb'
|
||||
shared = library.parent/'SymbolLibs/__ReusableBlocksSymb'
|
||||
database = shared/'icdb.dat'
|
||||
address = shared/'cdbsvr/sAddress.adr'
|
||||
log = address.parent/'log/2026-11-24 10.51.10-16972/2026.11.24.txt'
|
||||
for path in (library, work/'database/icdb.dat', pcb.parent/'Layout/LayoutDB.lyt', database, log):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(b'fixture')
|
||||
project.write_text('KEY PCBDesignPath "PCB/A.pcb"\nKEY iCDBDir "database"\n')
|
||||
pcb.write_text('KEY ProjectFile "../A.prj"\n')
|
||||
guid = 'e3f4-cafd-6e7f-6e1b-f9bf-40b5-abf4-0b60-117c-d02d-bff6-3645'
|
||||
adr = f'{guid}\n127.0.0.1\n10000\n1094\n2026-11-24 10.51.10-16972\n.\n'
|
||||
address.write_text(adr)
|
||||
lines = [
|
||||
'iCDB Server ver.1.094, build:535943',
|
||||
'Machine [LOCAL] User [operator] PID [16972]',
|
||||
f'S: Project path [{shared}] on file system [NTFS]',
|
||||
f'S: Server GUID [{guid}]',
|
||||
'S: Wrote data to server address file',
|
||||
'iCDB Server PI: Database closed',
|
||||
f'Single file [{database}] closed with size [7 (0 kB)]',
|
||||
f'AT: ERROR: Could not remove server address file [{address}]',
|
||||
'S: STOP',
|
||||
]
|
||||
def write_log(events):
|
||||
log.write_text('\n'.join(f'[2026.11.24 10:51:22] [0000m.11s.465ms] [0] {event}'
|
||||
for event in events) + '\n')
|
||||
write_log(lines)
|
||||
monkeypatch.setattr(owner_probe, 'query_process_snapshot', lambda: [])
|
||||
monkeypatch.setattr(owner_probe, 'query_owners', lambda *_: [])
|
||||
release = library_lock.release_retained_library(library, tmp_path/'recovery', block_name='A')
|
||||
assert release['status'] == 'RELEASE_CONFIRMED'
|
||||
assert release['shared_shutdowns'][str(address)]['server_guid'] == guid
|
||||
evidence = tmp_path/'open'
|
||||
evidence.mkdir()
|
||||
job = dict(root=str(evidence), lmc_file=str(library), block_name='A', project=str(project), pcb=str(pcb))
|
||||
with pcb_open_consent.resource_guard(job, set(), require_complete_proof=True):
|
||||
pass
|
||||
proof = json.loads((evidence/'pcb-open-resource-proof.json').read_text('utf-8'))
|
||||
assert proof['shared_shutdowns'] == release['shared_shutdowns']
|
||||
assert address.read_text() == adr
|
||||
assert database.read_bytes() == b'fixture'
|
||||
|
||||
import os
|
||||
modified = log.stat().st_mtime_ns + 2_000_000_000
|
||||
os.utime(database, ns=(modified, modified))
|
||||
with pytest.raises(ValueError, match='SHARED_ICDB_INSPECTION_UNAVAILABLE'):
|
||||
with pcb_open_consent.resource_guard(job, set(), require_complete_proof=True):
|
||||
pytest.fail('an older server shutdown was accepted after a database change')
|
||||
os.utime(database, ns=(modified, modified - 3_000_000_000))
|
||||
|
||||
write_log(lines[:-1]) # Database closed, but server shutdown is incomplete.
|
||||
with pytest.raises(ValueError, match='SHARED_ICDB_INSPECTION_UNAVAILABLE'):
|
||||
with pcb_open_consent.resource_guard(job, set(), require_complete_proof=True):
|
||||
pytest.fail('incomplete native shutdown allowed read/write open')
|
||||
@@ -158,3 +158,55 @@ def test_released_batch_can_resume_only_its_unexecuted_items(qtbot, tmp_path, mo
|
||||
monkeypatch.setattr(window, '_run', lambda names, **kw: calls.append((names, kw)))
|
||||
action.click()
|
||||
assert calls == [(['Gamma'], {'maintenance': False, 'request_snapshot': original_remaining})]
|
||||
|
||||
|
||||
def test_orphaned_inflight_save_confirms_only_bound_prompt_after_three_seconds(tmp_path, monkeypatch):
|
||||
from types import SimpleNamespace
|
||||
from cbb_refresh_verify import desktop_worker, residual_sessions, session_record
|
||||
|
||||
desktop = 'CbbVerify_fixture'
|
||||
job = {'interactive_input': False, 'desktop': desktop,
|
||||
'operation_id': 'verify-fixture', 'session_record_path': str(tmp_path/'session.json')}
|
||||
identity = {'role': 'native', 'pid': 75, 'created_handle': 'original',
|
||||
'image': 'ExpeditionPCB.exe', 'owner_sid': 'sid', 'session_id': 1}
|
||||
state = {'operation_id': job['operation_id'], 'phase': 'NATIVE_CALL', 'processes': [identity]}
|
||||
actual = dict(identity)
|
||||
known = {'hwnd': 1, 'title': 'Expedition PCB', 'desktop': desktop, 'class': '#32770',
|
||||
'enabled': True, 'children': [
|
||||
{'class': 'Static', 'text': 'Do you want to save the Reusable Block cell?'},
|
||||
{'class': 'Button', 'id': 6, 'hwnd': 2, 'enabled': True},
|
||||
{'class': 'Button', 'id': 7, 'hwnd': 3, 'enabled': True}]}
|
||||
unrelated = {**known, 'hwnd': 9, 'desktop': 'Default'}
|
||||
snapshots = SimpleNamespace(incomplete={})
|
||||
snapshots.get = lambda *_: [unrelated, known]
|
||||
clicks, events = [], []
|
||||
monkeypatch.setattr(session_record, 'read_session_record', lambda *a, **k: state)
|
||||
monkeypatch.setattr(session_record, 'process_identity', lambda pid: actual)
|
||||
monkeypatch.setattr(residual_sessions, '_process_windows', lambda *_: snapshots)
|
||||
monkeypatch.setattr(residual_sessions, '_post_window_message', lambda *args: clicks.append(args))
|
||||
lost = False
|
||||
monkeypatch.setattr(desktop_worker, 'supervisor_has_exited', lambda: lost, raising=False)
|
||||
now = 10.0
|
||||
prompt = residual_sessions.OrphanedVerifySavePrompt(job, 75, lambda **event: events.append(event),
|
||||
clock=lambda: now)
|
||||
prompt.poll(('SAVE_START',))
|
||||
assert clicks == []
|
||||
lost = True
|
||||
prompt.poll(())
|
||||
assert clicks == []
|
||||
prompt.poll(('SAVE_START',))
|
||||
now = 12.9
|
||||
prompt.poll(('SAVE_START',))
|
||||
assert clicks == []
|
||||
now = 13.0
|
||||
actual['created_handle'] = 'reused'
|
||||
prompt.poll(('SAVE_START',))
|
||||
assert clicks == []
|
||||
actual['created_handle'] = 'original'
|
||||
now = 14.0
|
||||
prompt.poll(('SAVE_START',))
|
||||
now = 17.0
|
||||
prompt.poll(('SAVE_START',))
|
||||
prompt.poll(('SAVE_START',))
|
||||
assert [(args[0]['hwnd'], args[1], args[2]) for args in clicks] == [(1, 2, 75)]
|
||||
assert events[0]['stage'] == 'orphaned_save_confirmed'
|
||||
@@ -183,3 +183,23 @@ def test_window_close_tolerates_fake_and_deleted_dialog_pools(qtbot, tmp_path, m
|
||||
window.show()
|
||||
window.close()
|
||||
qtbot.waitUntil(lambda: not window.isVisible())
|
||||
|
||||
|
||||
def test_late_job_retains_mapping_after_window_destruction(qtbot, tmp_path):
|
||||
import shiboken6
|
||||
from cbb_refresh_verify.ui.main_window import MainWindow
|
||||
|
||||
window = MainWindow(reader=lambda _: None, data_root=tmp_path, authoritative_status=False)
|
||||
lease, entered, release, closed, calls = slow_lease(get_ident())
|
||||
job = window._new_job('verify', lease=lease)
|
||||
window._shutdown_leases[id(lease)] = lease
|
||||
window.library_lease = None
|
||||
|
||||
try:
|
||||
shiboken6.delete(window)
|
||||
window._finish_job(job)
|
||||
qtbot.waitUntil(entered.is_set)
|
||||
assert calls == ['retain']
|
||||
assert not closed.is_set()
|
||||
finally:
|
||||
release.set()
|
||||
@@ -1036,6 +1036,76 @@ def test_saved_closed_without_cert_uses_bridge_and_never_reexecutes_verify(
|
||||
assert ordering[-1] == 'failure_logs'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('config_name', ['CBB1.prj', 'PCB/pcb.prj'])
|
||||
def test_native_save_waits_for_scoped_database_sharing_violation(tmp_path, monkeypatch, config_name):
|
||||
from cbb_refresh_verify import file_probe
|
||||
import win32con
|
||||
import win32file
|
||||
|
||||
work = fixture(tmp_path)
|
||||
config_path = work/config_name
|
||||
database = config_path.parent/'ActualDatabase/icdb.dat'
|
||||
if config_path.exists():
|
||||
with config_path.open('a', encoding='utf-8') as config:
|
||||
config.write('\nKEY iCDBDir "ActualDatabase"\n')
|
||||
else:
|
||||
config_path.write_text('KEY iCDBDir "ActualDatabase"\n', encoding='utf-8-sig')
|
||||
database.parent.mkdir()
|
||||
database.touch()
|
||||
shared = tmp_path/'SymbolLibs/__ReusableBlocksSymb/icdb.dat'
|
||||
shared.parent.mkdir(parents=True)
|
||||
shared.touch()
|
||||
locked = win32file.CreateFile(str(database), win32con.GENERIC_READ, 0, None,
|
||||
win32con.OPEN_EXISTING, 0, None)
|
||||
progress = []
|
||||
released = False
|
||||
|
||||
class FinishedWorker:
|
||||
desktop = None
|
||||
returncode = 0
|
||||
|
||||
def __init__(self, command, *_args, **kwargs):
|
||||
root = Path(command[-1]).parent
|
||||
(root/'outcome.json').write_text('{"status":"PASS"}', encoding='utf-8')
|
||||
(root/'save.log').write_text(
|
||||
'SAVE_START\nSAVE_OK\nIS_SAVED\nCLOSE_OK\nQUIT_OK\n', encoding='utf-8')
|
||||
|
||||
def poll(self):
|
||||
return 0
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
def observe(event):
|
||||
nonlocal released
|
||||
progress.append(event)
|
||||
if event['stage'] == 'post_save_release_pending':
|
||||
# Model the original case: PCB is gone, the database is still held.
|
||||
assert event['blocked_resources'] == [str(database)]
|
||||
locked.Close()
|
||||
released = True
|
||||
|
||||
def read_status(*_args):
|
||||
assert released, 'Native status read started before iCDB released the database'
|
||||
return BridgeResult('READY', 'IsVerifiedReuseBlock', 1)
|
||||
|
||||
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', FinishedWorker)
|
||||
monkeypatch.setattr('cbb_refresh_verify.verify_runner._cleanup_session_processes',
|
||||
lambda *a, **kw: {'safe_to_continue': True, 'remaining_pids': []})
|
||||
# Source-mode subprocess uses the same import root as the current test run.
|
||||
monkeypatch.setenv('PYTHONPATH', str(Path(file_probe.__file__).parents[1]))
|
||||
try:
|
||||
result = run_verify(request(tmp_path), port_check=PORTS_OK, flag_reader=read_status, progress=observe)
|
||||
finally:
|
||||
if not released:
|
||||
locked.Close()
|
||||
assert result.status == 'PASS'
|
||||
assert result.safe_to_continue
|
||||
release = json.loads(result.evidence_path.with_name('session-release.json').read_text('utf-8'))
|
||||
assert {str(shared), str(database)} <= set(release['database_release']['exclusive_files'])
|
||||
assert sum(event['stage'] == 'post_save_release_pending' for event in progress) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize('detail, category', [
|
||||
('PROJECT_INTEGRATION_FAILED: There were errors during packaging', 'MENTOR_PROJECT_INTEGRATION'),
|
||||
('DATABASE_LOAD_FAILED: DataBase Load is being terminated with 2 errors', 'MENTOR_DATABASE_LOAD_FAILED'),
|
||||
|
||||
Reference in new issue
Block a user