fix: prevent iCDB disconnects and recover failed projects

This commit is contained in:
阿白叔 committed 2026-10-27 17:51:53 +08:00
1 parent 8a517d6f38
commit 2490067b2d
19 files changed
+1117 -60

No files matched your search

+291
View File
@@ -0,0 +1,291 @@
import json
import os
from pathlib import Path
import subprocess
import sys
import time
import pytest
from cbb_refresh_verify import verify_runner as runner
def test_content_timeout_preserves_importer_and_native_like_child(tmp_path):
import win32api, win32con, win32process
script = tmp_path/'importer.py'
pids = tmp_path/'pids.json'
script.write_text(
'import subprocess,sys,time,os,json\nfrom pathlib import Path\n'
'child=subprocess.Popen([sys.executable,"-c","import time;time.sleep(30)"],'
'stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)\n'
f'Path({str(pids)!r}).write_text(json.dumps([os.getpid(),child.pid]))\n'
'time.sleep(30)\n', encoding='utf-8')
handles = []
try:
result = runner._run_process([sys.executable, str(script)], 2, tmp_path)
assert result[3] is True
assert pids.is_file()
for pid in json.loads(pids.read_text()):
try:
handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION |
win32con.PROCESS_TERMINATE, False, pid)
except Exception:
pytest.fail(f'Timeout terminated database-related process {pid}')
handles.append(handle)
assert win32process.GetExitCodeProcess(handle) == 259
finally:
for handle in handles:
win32process.TerminateProcess(handle, 0)
handle.Close()
def test_content_timeout_stops_remaining_batch(tmp_path, monkeypatch):
from test_verify_runner import fixture, request
fixture(tmp_path)
monkeypatch.setattr(runner, 'resolve_importer', lambda *_: Path('ReuseBlockImporter.exe'))
calls = []
def timeout(*args):
calls.append(args)
return None, '', 'content check still running', True
req = request(tmp_path, libspec='EE', dms_login_config='login')
results = runner.run_batch([req, req], verifier=lambda item: runner.run_verify(item,
process_runner=timeout, port_check=lambda: pytest.fail('PCB must not start')))
assert len(calls) == 1
assert results[0].status == 'TIMEOUT'
assert results[0].safe_to_continue is False
assert results[1].status == 'SKIPPED'
@pytest.mark.parametrize('identity,close_ok,other_document,expected_code', [
(True, True, False, 0), (False, True, False, 2), (True, False, False, 4), (True, True, True, 5)])
def test_failed_document_close_uses_native_discard_and_rejects_wrong_identity(
tmp_path, identity, close_ok, other_document, expected_code):
source = Path('src/cbb_refresh_verify/close_failed_block.vbs').read_text('utf-8')
classes = r'''
Dim nativeClosed
nativeClosed = False
Class FakePi
Public ProjectFile
Private Sub Class_Initialize
ProjectFile = PROJECT_VALUE
End Sub
End Class
Class FakeDoc
Public Name
Private Sub Class_Initialize
Name = "CBB.pcb"
End Sub
Public Property Get ProjectIntegration
Set ProjectIntegration = New FakePi
End Property
Public Function Validate(value)
Validate = 17
End Function
Public Function Close(saveChanges)
If saveChanges Then WScript.Quit 90
WScript.Echo "NATIVE_DISCARD_CLOSE"
nativeClosed = CLOSE_RETURN
Close = CLOSE_RETURN
End Function
End Class
Class FakeApp
Public Property Get ActiveDocument
If nativeClosed And Not OTHER_DOCUMENT Then
Set ActiveDocument = Nothing
Else
Set ActiveDocument = New FakeDoc
End If
End Property
Public Sub Quit()
WScript.Echo "NATIVE_QUIT"
End Sub
End Class
Class FakeLic
Public Function GetToken(value)
GetToken = value
End Function
End Class
'''.replace('PROJECT_VALUE', 'WScript.Arguments(0)' if identity else '"OTHER.prj"')
classes = classes.replace('CLOSE_RETURN', str(close_ok))
classes = classes.replace('OTHER_DOCUMENT', str(other_document))
source = source.replace('Option Explicit', 'Option Explicit\n'+classes)
source = source.replace('GetObject(, "MGCPCB.Application")', 'New FakeApp')
source = source.replace('CreateObject("MGCPCBAutomationLicensing.Application")', 'New FakeLic')
harness = tmp_path/'close.vbs'
harness.write_text(source, encoding='ascii')
outcome = subprocess.run([str(Path(os.environ['WINDIR'])/'SysWOW64/cscript.exe'),
'//nologo', str(harness), 'expected.prj', 'CBB.pcb'], capture_output=True, text=True, timeout=10)
assert outcome.returncode == expected_code, outcome.stderr
assert ('NATIVE_DISCARD_CLOSE' in outcome.stdout) is identity
assert ('NATIVE_QUIT' in outcome.stdout) is (identity and close_ok and not other_document)
def test_cancel_after_native_save_returns_stops_later_native_operations(tmp_path):
source = Path('src/cbb_refresh_verify/save_verified_block.vbs').read_text('utf-8')
classes = r'''
Class FakePi
Public ProjectFile, ForwardAnnotationStatus, SynchCESStatus, LoadCESStatus, BackAnnotationStatus
Private Sub Class_Initialize
ProjectFile = WScript.Arguments(0)
ForwardAnnotationStatus = 2
SynchCESStatus = 2
LoadCESStatus = 2
BackAnnotationStatus = 2
End Sub
End Class
Class FakeDoc
Public Name
Private Sub Class_Initialize
Name = "CBB.pcb"
End Sub
Public Property Get ProjectIntegration
Set ProjectIntegration = New FakePi
End Property
Public Function Validate(token)
Validate = 17
End Function
Public Function Save()
Dim fso, flag
Set fso = CreateObject("Scripting.FileSystemObject")
Set flag = fso.CreateTextFile(WScript.Arguments(2), True)
flag.Close
WScript.Sleep 120
WScript.Echo "NATIVE_SAVE_RETURNED"
Save = True
End Function
Public Function IsSaved()
IsSaved = True
End Function
Public Function Close(saveChanges)
Close = True
End Function
End Class
Class FakeApp
Public Property Get ActiveDocument
Set ActiveDocument = New FakeDoc
End Property
Public Sub Quit()
End Sub
End Class
Class FakeLic
Public Function GetToken(value)
GetToken = value
End Function
End Class
'''
source = source.replace('Option Explicit', 'Option Explicit\n'+classes)
source = source.replace('GetObject(, "MGCPCB.Application")', 'New FakeApp')
source = source.replace('CreateObject("MGCPCBAutomationLicensing.Application")', 'New FakeLic')
harness = tmp_path/'save-cancel.vbs'
harness.write_text(source, encoding='ascii')
outcome = subprocess.run([str(Path(os.environ['WINDIR'])/'SysWOW64/cscript.exe'),
'//nologo', str(harness), 'expected.prj', 'CBB.pcb', str(tmp_path/'cancel.signal')],
capture_output=True, text=True, timeout=10)
assert 'NATIVE_SAVE_RETURNED' in outcome.stdout
assert outcome.returncode == 9, outcome.stderr
assert 'VERIFY_CANCELLED' in outcome.stdout
assert 'CLOSE_OK' not in outcome.stdout
def test_worker_attempts_normal_close_after_idle_integration_failure(tmp_path, monkeypatch):
from test_verify_worker_stability import exercise_worker
from cbb_refresh_verify import mentor_adapter as adapter
job, events, execute = exercise_worker(tmp_path, monkeypatch, integration_error='packaging rejected')
closes = []
monkeypatch.setattr('cbb_refresh_verify.failed_session.close_failed_document',
lambda value, **kwargs: closes.append(value) or {'status': 'CLOSED'})
with pytest.raises(RuntimeError, match='packaging rejected'):
execute()
assert closes == [job]
assert not any(event['stage'] == 'save_start' for event in events)
def test_stop_requests_cooperative_cancel_without_terminating_busy_client(tmp_path):
calls = []
class BusyWorker:
def request_stop(self): calls.append('cancel')
def wait(self, timeout): raise TimeoutError('native Save still running')
def kill(self): calls.append('kill')
runner._stop_worker(BusyWorker(), timeout=0)
assert calls == ['cancel']
def test_status_server_close_allows_eof_cleanup_before_termination(tmp_path):
from cbb_refresh_verify.status_bridge import StatusBridgeServer
script = tmp_path/'reader.py'
marker = tmp_path/'released.txt'
script.write_text('import sys,time\nfrom pathlib import Path\n'
'for line in sys.stdin: pass\n'
'time.sleep(.1)\n'
f'Path({str(marker)!r}).write_text("native handles released")\n', encoding='utf-8')
server = StatusBridgeServer(script)
server.start()
time.sleep(.2)
server.close()
assert marker.is_file()
def test_shared_symbol_database_owner_blocks_content_check_and_pcb(tmp_path, monkeypatch):
from test_verify_runner import fixture, request
fixture(tmp_path)
address = tmp_path/'SymbolLibs/__ReusableBlocksSymb/cdbsvr/sAddress.adr'
address.parent.mkdir(parents=True)
address.write_bytes(b'unknown native owner')
req = request(tmp_path, libspec='EE', dms_login_config='login')
outcome = runner.run_verify(req, process_runner=lambda *args: pytest.fail('must not launch importer'))
assert outcome.status == 'BLOCKED'
assert outcome.safe_to_continue is False
assert '__ReusableBlocksSymb' in outcome.stderr
assert address.read_bytes() == b'unknown native owner'
def test_shared_symbol_database_must_be_released_before_pass(tmp_path, monkeypatch):
from test_verify_worker_stability import exercise_worker
from cbb_refresh_verify import mentor_adapter as adapter
job, events, execute = exercise_worker(tmp_path, monkeypatch)
original = adapter.subprocess.Popen
def helper(*args, **kwargs):
address = Path(job['lmc_file']).parent/'SymbolLibs/__ReusableBlocksSymb/cdbsvr/sAddress.adr'
address.parent.mkdir(parents=True)
address.write_bytes(b'shared owner retained')
return original(*args, **kwargs)
monkeypatch.setattr(adapter.subprocess, 'Popen', helper)
with pytest.raises(RuntimeError, match='ICDB_RELEASE_UNCONFIRMED'):
execute()
assert not any(event['stage'] == 'complete' for event in events)
def test_cooperative_supervisor_loss_keeps_pending_save_helper_alive(tmp_path):
import win32api, win32con, win32process
supervisor = subprocess.Popen([sys.executable, '-c', 'import time;time.sleep(30)'])
script, ready, cancel = tmp_path/'worker.py', tmp_path/'ready.json', tmp_path/'cancel.signal'
script.write_text('import subprocess,sys,time,json\nfrom pathlib import Path\n'
'from cbb_refresh_verify.desktop_worker import start_supervisor_watchdog,launch_save_helper\n'
f'start_supervisor_watchdog({supervisor.pid},cancel_path={str(cancel)!r})\n'
'helper=launch_save_helper([sys.executable,"-c","import time;time.sleep(30)"])\n'
f'Path({str(ready)!r}).write_text(json.dumps(helper.pid))\n'
'time.sleep(30)\n', encoding='utf-8')
worker = subprocess.Popen([sys.executable, str(script)])
handle = None
try:
deadline = time.monotonic()+5
while not ready.exists() and time.monotonic()<deadline:
time.sleep(.05)
assert ready.exists()
handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_TERMINATE,
False, json.loads(ready.read_text()))
supervisor.terminate()
supervisor.wait(3)
deadline = time.monotonic()+3
while not cancel.exists() and time.monotonic()<deadline:
time.sleep(.05)
assert cancel.exists()
assert worker.poll() is None
assert win32process.GetExitCodeProcess(handle) == 259
finally:
for process in (worker, supervisor):
if process.poll() is None: process.terminate()
process.wait(3)
if handle:
win32process.TerminateProcess(handle, 0)
handle.Close()
+142
View File
@@ -0,0 +1,142 @@
import json
from pathlib import Path
import pytest
def target_fixture(tmp_path):
from test_verify_runner import fixture, request
from cbb_refresh_verify.native_repair import select_repair_target
work = fixture(tmp_path)
database = work/'database'
database.mkdir()
(database/'icdb.dat').write_bytes(b'original damaged database')
diagnosis = {'error_code': 'ICDB_REPAIR_REQUIRED', 'machine': 'OLD-PC',
'database_path': str(database), 'session': '2026-10-24 08.22.29-10308', 'scope': 'project'}
return request(tmp_path), diagnosis, select_repair_target(request(tmp_path), diagnosis)
def test_repair_target_matches_actual_database_not_guessed_cbb_name(tmp_path):
request, record, target = target_fixture(tmp_path)
assert target.project.name == 'CBB1.prj'
assert target.database == target.project.parent/'database'
@pytest.mark.parametrize('change', ['foreign', 'shared', 'missing_session'])
def test_repair_target_rejects_unresolved_or_shared_database(tmp_path, change):
from cbb_refresh_verify.native_repair import select_repair_target
request, record, target = target_fixture(tmp_path)
if change == 'foreign': record['database_path'] = str(tmp_path/'foreign/database')
if change == 'shared':
record.update(scope='central_library', database_path=str(tmp_path/'SymbolLibs/__ReusableBlocksSymb'))
if change == 'missing_session': record['session'] = ''
with pytest.raises(ValueError):
select_repair_target(request, record)
def test_repair_backup_contains_database_locks_backups_and_original_files(tmp_path):
from cbb_refresh_verify.native_repair import backup_project
request, record, target = target_fixture(tmp_path)
for relative in ('database/cdbsvr/sAddress.adr', 'ProjectBackup/backups/old.zip',
'PCB/copy.lock', 'Log Files/ProjectBackupLog.txt'):
path = target.project.parent/relative
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(b'original '+relative.encode())
destination = tmp_path/'repair-backup'
manifest = backup_project(target, destination)
assert manifest['complete'] is True
assert (destination/'database/icdb.dat').read_bytes() == b'original damaged database'
assert (destination/'database/cdbsvr/sAddress.adr').read_bytes().startswith(b'original')
assert (destination/'ProjectBackup/backups/old.zip').is_file()
assert (destination/'PCB/copy.lock').is_file()
def test_repair_backup_refuses_database_open_by_another_client(tmp_path):
import win32file, win32con
from cbb_refresh_verify.native_repair import backup_project
request, record, target = target_fixture(tmp_path)
handle = win32file.CreateFile(str(target.database/'icdb.dat'), win32con.GENERIC_READ,
win32con.FILE_SHARE_READ, None, win32con.OPEN_EXISTING, 0, None)
try:
with pytest.raises(OSError):
backup_project(target, tmp_path/'backup')
finally:
handle.Close()
assert not (tmp_path/'backup/backup-manifest.json').exists()
def test_repair_backup_rejects_reparse_directory(tmp_path):
import _winapi
from cbb_refresh_verify.native_repair import backup_project
request, record, target = target_fixture(tmp_path)
outside = tmp_path/'outside'
outside.mkdir()
_winapi.CreateJunction(str(outside), str(target.project.parent/'linked'))
with pytest.raises(ValueError):
backup_project(target, tmp_path/'backup')
def test_native_confirmation_requires_exact_target_and_known_repair_prompt():
from cbb_refresh_verify.native_repair_ui import confirmation_allowed
assert confirmation_allowed('iCDB Project Backup - C:\\exact.prj', r'C:\exact.prj',
'The project content will be validated and repaired if necessary.\n'
'A project backup will be created before any action take place.\n'
'You will be able to revert all changes using that backup.')
assert not confirmation_allowed('iCDB Project Backup - C:\\OTHER.prj', r'C:\exact.prj',
'The project content will be validated and repaired if necessary.')
assert not confirmation_allowed('iCDB Project Backup - C:\\exact.prj', r'C:\exact.prj',
'Confirm no other clients are connected. Continue anyway?')
def test_native_diagnostics_finish_alone_does_not_prove_repair_success():
from cbb_refresh_verify.native_repair_ui import repair_completed
assert not repair_completed('Diagnostic: FINISH', 'IC: Closing project', native_backup=False)
assert not repair_completed('ERROR: invalid database\nDiagnostic: FINISH',
'iCDBProjectBackupRepair\nIC: Closing project', native_backup=True)
assert repair_completed('Diagnostic: START\nDiagnostic: FINISH',
'iCDBProjectBackupRepair\nIC: Closing project', native_backup=True)
def test_automatic_repair_retries_only_once_and_preserves_original_failure(tmp_path, monkeypatch):
from dataclasses import replace
from cbb_refresh_verify import verify_runner as runner
from cbb_refresh_verify import native_repair
request, record, target = target_fixture(tmp_path)
evidence = tmp_path/'first/result.json'
evidence.parent.mkdir()
(evidence.parent/'diagnostics').mkdir()
(evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps(record))
original = runner.VerifyResult('FAIL', stderr='native lost session',
safe_to_continue=False, error_category='ICDB_REPAIR_REQUIRED', evidence_path=evidence)
calls = []
def verify(req, **kwargs):
calls.append(req)
return original
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: {'status':'REPAIRED'})
outcome = runner.run_verify(request)
assert len(calls) == 2
assert outcome.status == 'FAIL'
assert outcome.stderr == 'native lost session'
assert outcome.recovery_attempts[0]['original_error'] == 'native lost session'
def test_automatic_repair_does_not_retry_busy_or_unsupported_target(tmp_path, monkeypatch):
from cbb_refresh_verify import verify_runner as runner
from cbb_refresh_verify import native_repair
request, record, target = target_fixture(tmp_path)
evidence = tmp_path/'first/result.json'
evidence.parent.mkdir()
(evidence.parent/'diagnostics').mkdir()
(evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps(record))
calls = []
def verify(req, **kwargs):
calls.append(req)
return runner.VerifyResult('FAIL', stderr='native lost session',
error_category='ICDB_REPAIR_REQUIRED', safe_to_continue=False, evidence_path=evidence)
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: {'status':'BLOCKED'})
outcome = runner.run_verify(request)
assert len(calls) == 1
assert outcome.safe_to_continue is False
assert outcome.recovery_attempts[0]['status'] == 'BLOCKED'
-1
View File
@@ -24,7 +24,6 @@ FORBIDDEN_APIS = (
'AttachThreadInput',
'WM_MOUSEMOVE',
'WM_CONTEXTMENU',
'WM_COMMAND',
'VK_APPS',
'TVM_SELECTITEM',
'EndMenu',