fix: inspect native ICDB occupancy before bounded repair
This commit is contained in:
1 parent
cb1326688b
commit
e14a864b37
17 files changed
+617
-153
No files matched your search
@@ -1,81 +1,75 @@
|
||||
"""Exercise the production diagnosis gate; do not spoof callback names."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
"""Native occupancy must precede repair even when old addresses remain."""
|
||||
import pytest
|
||||
from test_maintenance_entry import case, no_native_launch
|
||||
from test_native_occupancy import output
|
||||
|
||||
|
||||
def diagnostic_result(req, *, error='', database=None):
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
root = req.evidence_dir/'probe'; root.mkdir(parents=True, exist_ok=True)
|
||||
result = VerifyResult('FAIL' if error else 'PASS', error_category=error,
|
||||
evidence_path=root/'result.json', safe_to_continue=not error)
|
||||
result.evidence_path.write_text('{}', encoding='utf-8')
|
||||
if error == 'ICDB_REPAIR_REQUIRED':
|
||||
record = {'error_code': error, 'scope': 'project', 'session': 'test-session',
|
||||
'database_path': str(database)}
|
||||
(root/'diagnostics').mkdir(exist_ok=True)
|
||||
(root/'diagnostics/icdb-recovery.json').write_text(json.dumps(record), encoding='utf-8')
|
||||
return result
|
||||
def inspection(target, *, fault=False):
|
||||
return {'inspection_only': True, 'repair_requested': False, 'native_pid': 777,
|
||||
'native_exit_code': 0, 'project': str(target.project), 'database': str(target.database),
|
||||
'output': output(target.project, target.database, fault=fault),
|
||||
'status': 'NOT_IN_USE', 'repair_required': fault, 'release': {'native_exited': True}}
|
||||
|
||||
|
||||
def test_diagnosis_holds_library_lock_and_healthy_never_repair(case, monkeypatch):
|
||||
@pytest.mark.parametrize('old_address', [False, True])
|
||||
def test_native_inspection_holds_lock_without_opening_pcb(case, monkeypatch, old_address):
|
||||
from cbb_refresh_verify import verify_runner as runner, native_repair, library_lock
|
||||
request, project, address = case
|
||||
address.unlink()
|
||||
def worker(req, **kw):
|
||||
key = library_lock.LibraryLock(req.lmc_file).key
|
||||
assert key in library_lock._owners
|
||||
if not old_address: address.unlink()
|
||||
def native(target, root, **kw):
|
||||
key = library_lock.LibraryLock(request.lmc_file).key
|
||||
assert library_lock._owners[key]['depth'] > 0
|
||||
assert req.diagnostic_only and not req.auto_repair and not req.maintenance
|
||||
assert not req.native_lm_verify and not req.libspec
|
||||
return diagnostic_result(req)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', worker)
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', lambda *a, **k: pytest.fail('healthy repair'))
|
||||
assert kw['inspection_only'] is True
|
||||
assert kw['timeout_seconds'] <= 30
|
||||
return inspection(target)
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', native)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k: pytest.fail('inspection opened PCB'))
|
||||
result = runner.run_verify(request)
|
||||
assert result.status == 'PASS' and result.recovery_attempts == ()
|
||||
assert result.status == 'CHECKED' and result.recovery_attempts == ()
|
||||
assert result.library_flag == 'UNKNOWN'
|
||||
assert not library_lock.has_blocker(request.lmc_file)
|
||||
assert result.safe_to_continue is (not old_address)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fault', ['missing', 'generic', 'assertion', 'wrong_database', 'outside_evidence'])
|
||||
def test_unconfirmed_diagnosis_never_repairs(case, monkeypatch, fault):
|
||||
@pytest.mark.parametrize('fault', ['missing', 'generic', 'assertion', 'wrong_database', 'stale_verdict', 'not_exited'])
|
||||
def test_unconfirmed_native_inspection_never_repairs(case, monkeypatch, fault):
|
||||
from cbb_refresh_verify import verify_runner as runner, native_repair
|
||||
request, project, address = case
|
||||
address.unlink()
|
||||
def worker(req, **kw):
|
||||
if fault == 'assertion': raise AssertionError('diagnostic failure')
|
||||
if fault == 'missing': return runner.VerifyResult('PASS')
|
||||
if fault == 'generic': return diagnostic_result(req, error='DATABASE_SAFETY_STOP')
|
||||
if fault == 'outside_evidence':
|
||||
from dataclasses import replace
|
||||
req = replace(req, evidence_dir=request.evidence_dir/'old-run')
|
||||
return diagnostic_result(req, error='ICDB_REPAIR_REQUIRED',
|
||||
database=project.parent/('wrong' if fault == 'wrong_database' else 'database'))
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', worker)
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', lambda *a, **k: pytest.fail('unconfirmed repair'))
|
||||
def native(target, root, **kw):
|
||||
assert kw['inspection_only'] is True
|
||||
if fault == 'assertion': raise AssertionError('probe failed')
|
||||
if fault == 'missing': return {}
|
||||
record = inspection(target, fault=True)
|
||||
if fault == 'generic': record['output'] = 'DATABASE_SAFETY_STOP'
|
||||
if fault == 'wrong_database': record['database'] = str(project.parent/'other')
|
||||
if fault == 'stale_verdict': record['output'] += 'Checking if project is in use.'
|
||||
if fault == 'not_exited': record['release']['native_exited'] = False
|
||||
return record
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', native)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k: pytest.fail('unconfirmed reopened PCB'))
|
||||
result = runner.run_verify(request)
|
||||
assert result.status != 'PASS' and result.recovery_attempts == ()
|
||||
assert result.status == 'BLOCKED' and not result.recovery_attempts
|
||||
|
||||
|
||||
def test_diagnostic_fault_repairs_once_then_full_verification(case, monkeypatch):
|
||||
def test_native_fault_repairs_once_then_full_verification_with_old_address(case, monkeypatch):
|
||||
from cbb_refresh_verify import verify_runner as runner, native_repair
|
||||
from test_native_repair import complete_native_success
|
||||
request, project, address = case
|
||||
address.unlink()
|
||||
calls = []
|
||||
def worker(req, **kw):
|
||||
calls.append('diagnose' if req.diagnostic_only else 'verify')
|
||||
if req.diagnostic_only:
|
||||
return diagnostic_result(req, error='ICDB_REPAIR_REQUIRED', database=project.parent/'database')
|
||||
assert req.post_repair_proof is not None and not req.auto_repair
|
||||
return runner.VerifyResult('PASS', library_flag='GREEN')
|
||||
def repair(target, *a, **kw):
|
||||
def native(target, root, **kw):
|
||||
if kw.get('inspection_only'):
|
||||
assert address.exists()
|
||||
calls.append('inspect')
|
||||
return inspection(target, fault=True)
|
||||
calls.append('repair')
|
||||
address.unlink() # Simulated native repair release only.
|
||||
return complete_native_success(target)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', worker)
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', repair)
|
||||
def verify(req, **kw):
|
||||
assert req.post_repair_proof is not None and not req.diagnostic_only and not req.auto_repair
|
||||
calls.append('verify')
|
||||
return runner.VerifyResult('PASS', library_flag='GREEN')
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', native)
|
||||
monkeypatch.setattr(native_repair, 'repair_release_state', lambda req, target, result: result['release'])
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
|
||||
result = runner.run_verify(request)
|
||||
assert calls == ['diagnose', 'repair', 'verify']
|
||||
assert calls == ['inspect', 'repair', 'verify']
|
||||
assert result.status == 'PASS' and len(result.recovery_attempts) == 1
|
||||
@@ -48,20 +48,19 @@ def case(tmp_path, monkeypatch):
|
||||
|
||||
|
||||
def patch_verification_after_fault(monkeypatch, runner, verify):
|
||||
"""Inject native startup evidence, then exercise the production repair gate."""
|
||||
def worker(req, **kwargs):
|
||||
if not req.diagnostic_only:
|
||||
return verify(req, **kwargs)
|
||||
project, pcb = runner.preflight(req)
|
||||
root = req.evidence_dir/'native-startup'; root.mkdir(parents=True, exist_ok=True)
|
||||
(root/'diagnostics').mkdir(exist_ok=True)
|
||||
(root/'diagnostics/icdb-recovery.json').write_text(json.dumps({
|
||||
'error_code': 'ICDB_REPAIR_REQUIRED', 'scope': 'project', 'session': 'fixture',
|
||||
'database_path': str(project.parent/'database')}), encoding='utf-8')
|
||||
evidence = root/'result.json'; evidence.write_text('{}', encoding='utf-8')
|
||||
return runner.VerifyResult('FAIL', error_category='ICDB_REPAIR_REQUIRED',
|
||||
safe_to_continue=False, evidence_path=evidence)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', worker)
|
||||
"""Inject only native process boundaries; production interprets the Output."""
|
||||
from cbb_refresh_verify import native_repair
|
||||
from test_native_occupancy import output
|
||||
repair = native_repair.run_native_repair
|
||||
def native(target, root, **kw):
|
||||
if not kw.get('inspection_only'):
|
||||
return repair(target, root, **kw)
|
||||
return {'inspection_only': True, 'repair_requested': False, 'native_pid': 777,
|
||||
'native_exit_code': 0, 'project': str(target.project), 'database': str(target.database),
|
||||
'output': output(target.project, target.database, fault=True),
|
||||
'status': 'NOT_IN_USE', 'repair_required': True, 'release': {'native_exited': True}}
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', native)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('pcb_config', ['standard', 'legacy_template'])
|
||||
|
||||
@@ -88,12 +88,11 @@ def test_restarted_export_copy_can_release_only_after_fresh_proof(export_case, t
|
||||
|
||||
|
||||
def test_maintenance_idle_guard_recognizes_new_exporter_names(monkeypatch):
|
||||
import win32com.client
|
||||
from cbb_refresh_verify.maintenance_entry import assert_native_idle
|
||||
def query(sql):
|
||||
assert 'icdb2ascii.exe' in sql.casefold() and 'icdbnetserver.exe' in sql.casefold()
|
||||
return [SimpleNamespace(ProcessId=123456, Name='icdb2ascii.exe', CommandLine='export')]
|
||||
monkeypatch.setattr(win32com.client, 'GetObject', lambda *_: SimpleNamespace(ExecQuery=query))
|
||||
def query(names):
|
||||
assert 'icdb2ascii.exe' in [n.casefold() for n in names] and 'icdbnetserver.exe' in [n.casefold() for n in names]
|
||||
return [{'pid': 123456, 'name': 'icdb2ascii.exe', 'command': 'export'}]
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', query)
|
||||
with pytest.raises(ValueError, match='MAINTENANCE_OWNER_ACTIVE'): assert_native_idle()
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
|
||||
|
||||
def output(project, database, *, fault=False, busy=False):
|
||||
text = f'Loading project file [{project}].\nChecking if project is in use.\n'
|
||||
if fault:
|
||||
text += (f'Project database [{database}] is inconsistent. It has been manually copied while the iCDB Server was running. '
|
||||
"Please use iCDB Project Backup 'Repair project' functionality to fix this issue.\n")
|
||||
return text + ('Project is in use.\n' if busy else
|
||||
"Project is not in use. Full iCDB Project Backup's functionality is available.\nBackup information loaded correctly.\n")
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fault,busy,status,repair', [
|
||||
(False, False, 'NOT_IN_USE', False), (True, False, 'NOT_IN_USE', True),
|
||||
(True, True, 'IN_USE', False), (False, True, 'IN_USE', False)])
|
||||
def test_native_ownership_and_repair_need_are_separate(tmp_path, fault, busy, status, repair):
|
||||
from cbb_refresh_verify.native_occupancy import classify_inspection
|
||||
project, database = tmp_path/'A.prj', tmp_path/'database'
|
||||
result = classify_inspection(project, database, output(project, database, fault=fault, busy=busy))
|
||||
assert result['status'] == status
|
||||
assert result['repair_required'] is repair
|
||||
|
||||
|
||||
@pytest.mark.parametrize('case', ['progress', 'wrong_project', 'wrong_database', 'stale_verdict', 'generic_repair'])
|
||||
def test_incomplete_or_foreign_output_cannot_authorize_repair(tmp_path, case):
|
||||
from cbb_refresh_verify.native_occupancy import classify_inspection
|
||||
project, database = tmp_path/'A.prj', tmp_path/'database'
|
||||
text = output(project, database, fault=True)
|
||||
if case == 'progress': text = f'Loading project file [{project}].\nChecking if project is in use.'
|
||||
if case == 'wrong_project': text = output(tmp_path/'Other.prj', database, fault=True)
|
||||
if case == 'wrong_database': text = output(project, tmp_path/'other', fault=True)
|
||||
if case == 'stale_verdict': text += 'Checking if project is in use.\n'
|
||||
if case == 'generic_repair': text = output(project, database) + 'Please try to repair the project!'
|
||||
assert classify_inspection(project, database, text)['repair_required'] is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fault,busy', [(False, False), (True, False), (False, True)])
|
||||
def test_inspection_mode_only_observes_and_closes_its_tool(tmp_path, monkeypatch, fault, busy):
|
||||
import win32con
|
||||
from test_native_repair import repair_worker_fixture
|
||||
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
|
||||
data = json.loads(job.read_text('utf-8')); data['inspection_only'] = True
|
||||
job.write_text(json.dumps(data), encoding='utf-8')
|
||||
monkeypatch.setattr(ui, '_repair_command', lambda *a: pytest.fail('inspection resolved Repair command'))
|
||||
monkeypatch.setattr(ui, '_native_output', lambda *_: output(data['project'], data['database'], fault=fault, busy=busy))
|
||||
assert ui.repair_worker_main(job) == 0
|
||||
result = json.loads((root/'repair-result.json').read_text('utf-8'))
|
||||
assert result['status'] == ('IN_USE' if busy else 'NOT_IN_USE')
|
||||
assert result['release']['native_exited'] is True
|
||||
assert result['repair_required'] is (fault and not busy)
|
||||
assert actions == [(100, win32con.WM_CLOSE)]
|
||||
|
||||
|
||||
def test_only_check_never_counts_as_repair_success():
|
||||
from cbb_refresh_verify.icdb_maintenance import maintenance_counts
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
counts = maintenance_counts([VerifyResult('CHECKED', safe_to_continue=True)])
|
||||
assert counts['passed'] == counts['repaired'] == 0
|
||||
assert counts['checked_without_repair'] == 1
|
||||
|
||||
|
||||
def test_cancelled_probe_returns_within_grace_without_killing_native(tmp_path, monkeypatch):
|
||||
from threading import Event
|
||||
from types import SimpleNamespace
|
||||
from cbb_refresh_verify import native_repair as native
|
||||
from cbb_refresh_verify.native_repair import RepairTarget
|
||||
stop = Event(); ticks = [0.0]; actions = []
|
||||
def sleep(seconds):
|
||||
ticks[0] += seconds
|
||||
stop.set()
|
||||
monkeypatch.setattr(native, 'time', SimpleNamespace(monotonic=lambda: ticks[0], sleep=sleep))
|
||||
class Worker:
|
||||
pid = 123
|
||||
def __init__(self, *a): pass
|
||||
def bind_cancellation(self, p): pass
|
||||
def poll(self): return None
|
||||
def request_stop(self): actions.append('cancel')
|
||||
def close(self): actions.append('close_handles')
|
||||
def kill(self): pytest.fail('native owner must not be killed')
|
||||
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker)
|
||||
result = native.run_native_repair(RepairTarget(tmp_path/'A.prj', tmp_path/'database'),
|
||||
tmp_path/'evidence', timeout_seconds=600, inspection_only=True, stop=stop)
|
||||
assert ticks[0] < 6
|
||||
assert result['status'] == 'CANCELLED_UNRELEASED'
|
||||
assert result['release']['safe_to_continue'] is False
|
||||
assert actions[-1] == 'close_handles'
|
||||
|
||||
|
||||
def test_ui_keeps_processing_events_and_passes_cancel_to_native_task(qtbot, tmp_path, monkeypatch):
|
||||
from threading import Event
|
||||
from PySide6.QtCore import QTimer
|
||||
from test_ui_filters import load_window
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
entered = Event(); cancelled = Event(); ticks = []
|
||||
def verify(req, *, stop, **kw):
|
||||
entered.set()
|
||||
if stop.wait(3): cancelled.set()
|
||||
return VerifyResult('CANCELLED')
|
||||
monkeypatch.setattr('cbb_refresh_verify.verify_runner.run_verify', verify)
|
||||
window = load_window(qtbot, tmp_path, monkeypatch,
|
||||
status_refresher=lambda names, _: {name: 'PENDING' for name in names})
|
||||
window.search_edit.setText('Beta')
|
||||
timer = QTimer(window); timer.setInterval(10); timer.timeout.connect(lambda: ticks.append(True)); timer.start()
|
||||
window.repair_icdb_all()
|
||||
qtbot.waitUntil(entered.is_set)
|
||||
qtbot.waitUntil(lambda: len(ticks) >= 3)
|
||||
assert window.busy and window.stop_button.isEnabled()
|
||||
window.stop_button.click()
|
||||
qtbot.waitUntil(lambda: not window.busy)
|
||||
assert cancelled.is_set()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('extra', ['foreign_session', 'extra_error'])
|
||||
def test_foreign_or_additional_fault_is_never_a_clean_inspection(tmp_path, extra):
|
||||
from cbb_refresh_verify.native_occupancy import classify_inspection
|
||||
project, database = tmp_path/'A.prj', tmp_path/'database'
|
||||
text = output(project, database, fault=extra == 'extra_error')
|
||||
if extra == 'foreign_session':
|
||||
text += ('The last server session on different server machine lost the connection to the database. '
|
||||
'Machine:[SERVER] Path:[C:/Other/Work/database] session:[old]')
|
||||
else:
|
||||
text += 'ERROR: shared symbol database unavailable'
|
||||
assert classify_inspection(project, database, text)['status'] == 'UNCONFIRMED'
|
||||
|
||||
|
||||
def test_unconfirmed_inspection_closes_known_main_at_timeout(tmp_path, monkeypatch):
|
||||
import win32con
|
||||
from test_native_repair import repair_worker_fixture
|
||||
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
|
||||
data = json.loads(job.read_text('utf-8')); data['inspection_only'] = True
|
||||
job.write_text(json.dumps(data), encoding='utf-8')
|
||||
monkeypatch.setattr(ui, '_native_output', lambda *_: 'Unrecognized response')
|
||||
assert ui.repair_worker_main(job) == 1
|
||||
result = json.loads((root/'repair-result.json').read_text('utf-8'))
|
||||
assert result['status'] == 'UNCONFIRMED'
|
||||
assert result['release']['native_exited'] is True
|
||||
assert actions == [(100, win32con.WM_CLOSE)]
|
||||
|
||||
|
||||
def test_directory_scan_honors_cancel_between_entries(tmp_path):
|
||||
from cbb_refresh_verify.scoped_manifest import scan_tree
|
||||
for i in range(10): (tmp_path/f'{i}.dat').touch()
|
||||
calls = []
|
||||
def cancel():
|
||||
calls.append(True)
|
||||
if len(calls) == 3: raise RuntimeError('CANCELLED')
|
||||
with pytest.raises(RuntimeError, match='CANCELLED'):
|
||||
scan_tree(tmp_path, check=cancel)
|
||||
assert len(calls) == 3
|
||||
|
||||
|
||||
def test_cancel_during_final_guard_cannot_launch_native_tool(tmp_path, monkeypatch):
|
||||
from contextlib import contextmanager
|
||||
from test_native_repair import repair_worker_fixture
|
||||
from cbb_refresh_verify.native_repair import RepairTarget
|
||||
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
|
||||
data = json.loads(job.read_text('utf-8'))
|
||||
data['maintenance_context'] = {'library': str(tmp_path/'lib.lmc'), 'block': 'CBB1'}
|
||||
job.write_text(json.dumps(data), encoding='utf-8')
|
||||
calls = []
|
||||
@contextmanager
|
||||
def guard(*a, **kw):
|
||||
calls.append(True)
|
||||
yield {'target': RepairTarget(Path(data['project']), Path(data['database']))}
|
||||
if len(calls) == 2: Path(data['cancel_signal']).touch()
|
||||
monkeypatch.setattr('cbb_refresh_verify.maintenance_entry.maintenance_target_guard', guard)
|
||||
monkeypatch.setattr(ui.subprocess, 'Popen', lambda *a, **kw: pytest.fail('late native launch'))
|
||||
assert ui.repair_worker_main(job) == 1
|
||||
assert len(calls) == 2 and not actions
|
||||
|
||||
|
||||
def test_verified_cbb_refusal_is_not_hidden_by_secondary_release_failure():
|
||||
from cbb_refresh_verify.verify_runner import classify_failure_category
|
||||
detail = ('BackAnnotate: Back Annotation is not allowed on verified (or once verified) Reusable Blocks.'
|
||||
'\nPCB_RELEASE_UNCONFIRMED: not released')
|
||||
assert classify_failure_category(detail) == 'CBB_REIMPORT_REQUIRED'
|
||||
@@ -0,0 +1,23 @@
|
||||
import subprocess
|
||||
import pytest
|
||||
|
||||
|
||||
def test_wmi_timeout_is_unknown_not_idle(monkeypatch):
|
||||
from cbb_refresh_verify.owner_probe import query_owners
|
||||
def hang(command, **kw):
|
||||
assert 0 < kw['timeout'] <= 10
|
||||
raise subprocess.TimeoutExpired(command, kw['timeout'])
|
||||
monkeypatch.setattr(subprocess, 'run', hang)
|
||||
with pytest.raises(RuntimeError, match='OWNER_QUERY_TIMEOUT'):
|
||||
query_owners(['ExpeditionPCB.exe'])
|
||||
|
||||
|
||||
def test_malformed_wmi_response_is_not_empty_owner_list(monkeypatch):
|
||||
from cbb_refresh_verify.owner_probe import query_owners
|
||||
from pathlib import Path
|
||||
def run(command, **kw):
|
||||
Path(command[-1]).with_name('result.json').write_text('{}')
|
||||
return subprocess.CompletedProcess(command, 0)
|
||||
monkeypatch.setattr(subprocess, 'run', run)
|
||||
with pytest.raises(RuntimeError, match='OWNER_QUERY_UNCONFIRMED'):
|
||||
query_owners(['ExpeditionPCB.exe'])
|
||||
Reference in new issue
Block a user