fix: classify ICDB repair outcomes and gate released recovery

This commit is contained in:
阿白叔 committed 2026-11-02 18:14:38 +08:00
1 parent 44b808b8e2
commit aa760c2839
12 files changed
+751 -27

No files matched your search

+30
View File
@@ -0,0 +1,30 @@
{
"source": "Issue 2 data.zip, verify-86f90ffba911; selected fields only; paths and process identities sanitized",
"limitations": "Logs only. No field database, executable fault reproduction or recovery claim.",
"block": "1GPHY_8211",
"diagnosis": {
"error_code": "ICDB_REPAIR_REQUIRED",
"scope": "project",
"machine": "FIELD-PC",
"session": "2026-10-20 14.03.54-18212",
"database_relative": "Work/database"
},
"native_error": "The last server session on different server machine lost the connection to the database. Please use iCDB Project Backup 'Repair project' functionality to fix this issue. (Machine:[FIELD-PC] Path:[<library>/ReusableBlocksLP/1GPHY_8211/Work/database] session:[2026-10-20 14.03.54-18212])",
"observed_events": [
{"stage": "pcb_launch", "strategy": "reusable_circuit_direct"},
{"stage": "pcb_launcher_started", "launcher_pid": 11},
{"stage": "pcb_worker_started", "pcb_pid": 12, "binding": "commandline"},
{"stage": "native_failure_logs"},
{"stage": "process_retained", "safe_to_continue": false},
{"stage": "failed", "error": "VERIFY_CANCELLED: stop and normally close target document"}
],
"dialog": {
"pid": 12,
"phase": "PCB_STARTING",
"action": "acknowledge_fatal",
"error_code": "MENTOR_DATABASE_LOAD_FAILED",
"text": "Problem encountered while opening one of the database files. See PCBLogFile.txt for details. Loading of the job has failed. Do you wish to view the log file now?"
},
"original_result": {"status": "FAIL", "error_category": "ICDB_REPAIR_REQUIRED", "error_stage": "PCB_STARTING"},
"original_repair": {"status": "BLOCKED", "detail": "REPAIR_DATABASE_IN_USE"}
}
+30
View File
@@ -156,3 +156,33 @@ def test_failed_startup_rejects_unrelated_failure_dialog(tmp_path, monkeypatch,
'pid': pid, 'phase': phase, 'error_code': 'MENTOR_DATABASE_LOAD_FAILED'})+'\n')
assert failed_session.close_failed_startup(job, 12, timeout_seconds=0)['status'] == 'RETAINED'
assert not messages
@pytest.mark.parametrize('exits', [True, False])
def test_startup_close_waits_for_launcher_after_empty_pcb_exit(tmp_path, monkeypatch, exits):
from types import SimpleNamespace
job, records, messages = startup_fixture(tmp_path, monkeypatch)
ticks = [0.0]
launcher = SimpleNamespace(pid=11, poll=lambda: 0 if exits and ticks[0] >= .4 else None)
monkeypatch.setattr(failed_session, 'time', SimpleNamespace(
monotonic=lambda: ticks[0], sleep=lambda seconds: ticks.__setitem__(0, ticks[0]+seconds)))
result = failed_session.close_failed_startup(job, 12, launcher_process=launcher, timeout_seconds=1)
assert ticks[0] >= .4
assert result['status'] == ('CLOSED' if exits else 'RETAINED')
assert result['release']['launcher_exited'] is exits
assert result['release']['pcb_exited'] is True
assert len(messages) == 1
def test_startup_exit_does_not_hide_late_database_address(tmp_path, monkeypatch):
import win32gui
job, records, messages = startup_fixture(tmp_path, monkeypatch)
def close(*args):
records.clear()
address = tmp_path/'database/cdbsvr/sAddress.adr'
address.parent.mkdir(parents=True)
address.write_text('still owned')
monkeypatch.setattr(win32gui, 'PostMessage', close)
result = failed_session.close_failed_startup(job, 12, timeout_seconds=0)
assert result['status'] == 'RETAINED'
assert result['release']['addresses']
+387 -2
View File
@@ -22,7 +22,7 @@ def test_repair_target_matches_actual_database_not_guessed_cbb_name(tmp_path):
assert target.database == target.project.parent/'database'
@pytest.mark.parametrize('change', ['foreign', 'shared', 'missing_session'])
@pytest.mark.parametrize('change', ['foreign', 'shared', 'missing_session', 'unknown_scope'])
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)
@@ -30,6 +30,7 @@ def test_repair_target_rejects_unresolved_or_shared_database(tmp_path, change):
if change == 'shared':
record.update(scope='central_library', database_path=str(tmp_path/'SymbolLibs/__ReusableBlocksSymb'))
if change == 'missing_session': record['session'] = ''
if change == 'unknown_scope': record['scope'] = 'unknown'
with pytest.raises(ValueError):
select_repair_target(request, record)
@@ -134,12 +135,41 @@ def test_automatic_repair_retries_only_once_and_preserves_original_failure(tmp_p
calls.append(req)
return original
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: {'status':'REPAIRED'})
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw:
{'status':'REPAIRED', 'release': {'safe_to_continue': True}})
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'
assert outcome.recovery_attempts[0]['status'] == 'REPAIR_VALIDATION_FAILED'
assert outcome.recovery_attempts[0]['native_status'] == 'REPAIRED'
@pytest.mark.parametrize('text,expected,terminal', [
('There is no backup of iCDB.\nRepair project error [Cannot repair the project - there is no backup of missing iCDB].',
'MISSING_HEALTHY_BACKUP', True),
('Repair project error [Database validation failed].', 'NATIVE_REPAIR_FAILED', True),
('Project is in use. Full functionality is unavailable.', 'DATABASE_BUSY', False),
('Repairing the project. Diagnostic: START', 'UNCONFIRMED', False),
])
def test_current_native_output_classifies_failure_and_terminal_evidence(text, expected, terminal):
from cbb_refresh_verify.native_repair_ui import classify_repair_evidence
result = classify_repair_evidence('', '', '', text)
assert result['outcome'] == expected
assert result['failure_complete'] is terminal
def test_historical_no_backup_output_replay_is_conclusive_failure():
from cbb_refresh_verify.native_repair_ui import classify_repair_evidence
# Sanitized actual native Output from the 2026-10-28 no-history fixture.
text = ('Repairing the project [<project>/CBB.prj].\n'
'Repair backup [repair.zip] created successfully.\n'
'The iCDB database is corrupted.\nThere is no backup of iCDB.\n'
'Repair project error [Cannot repair the project - there is no backup of missing iCDB].\n'
'The project is probably in inconsistent state. Please restore the project from one of previous backups.')
result = classify_repair_evidence('', '', '', text)
assert result == {'outcome': 'MISSING_HEALTHY_BACKUP', 'failure_complete': True}
@pytest.mark.parametrize('repair_status', ['BLOCKED', 'RESTORED_REVIEW_REQUIRED'])
@@ -264,3 +294,358 @@ def test_backup_detects_a_file_added_during_the_copy(tmp_path, monkeypatch):
monkeypatch.setattr(native_repair.shutil, 'copy2', changed)
with pytest.raises(OSError, match='REPAIR_BACKUP_CHANGED'):
native_repair.backup_project(target, tmp_path/'backup')
def repair_worker_fixture(tmp_path, monkeypatch, scenario):
"""Replay native window/log transitions without launching a native client."""
from types import SimpleNamespace
import win32con, win32gui
from cbb_refresh_verify import native_repair_ui as ui, native_repair, mentor_adapter
request, diagnosis, target = target_fixture(tmp_path)
root = tmp_path/'worker'
root.mkdir()
job = root/'request.json'
job.write_text(json.dumps({'project': str(target.project), 'database': str(target.database),
'root': str(root), 'cancel_signal': str(root/'cancel.signal'), 'timeout': 1,
'supervisor_pid': 123, 'desktop': 'CbbRepair_test'}))
ticks = [0.0]
state = {'requested': False, 'confirmed': False, 'closed': False}
actions = []
monkeypatch.setattr(ui, 'time', SimpleNamespace(monotonic=lambda: ticks[0], time_ns=lambda: 0,
sleep=lambda seconds: ticks.__setitem__(0, ticks[0]+seconds)))
monkeypatch.setattr(ui, '_current_desktop_name', lambda: 'CbbRepair_test')
monkeypatch.setattr(ui, '_repair_command', lambda *_: 32924)
monkeypatch.setattr(ui, 'discover_sdd_home', lambda *_: tmp_path, raising=False)
monkeypatch.setattr('cbb_refresh_verify.mentor_paths.discover_sdd_home', lambda *_: tmp_path)
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.start_supervisor_watchdog', lambda *a, **kw: None)
monkeypatch.setattr(native_repair, 'backup_project', lambda *a: {})
monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: [])
monkeypatch.setattr(mentor_adapter, '_process_details', lambda *_: [])
monkeypatch.setattr(ui.subprocess, 'Popen', lambda *a, **kw: SimpleNamespace(
pid=777, poll=lambda: 0 if state['closed'] and ticks[0] >= .6 else None))
terminal = 'Repair project error [Cannot repair the project - there is no backup of missing iCDB].'
def output(_):
if scenario == 'busy_before': return 'Project is in use. Full functionality is unavailable.'
if scenario == 'stale': return terminal
if not state['confirmed']: return ''
if scenario == 'busy': return 'Repair project error [Project is in use].'
if scenario == 'active': return 'Repairing the project. Please wait.'
if scenario in {'success', 'restore'}: return 'Repair project finished.'
return terminal
monkeypatch.setattr(ui, '_native_output', output, raising=False)
def windows(_):
main = {'hwnd': 100, 'class': 'Afx:main', 'title': 'iCDB Project Backup - '+str(target.project),
'enabled': True, 'children': []}
if state['confirmed'] and scenario in {'unknown', 'custom_prompt'}:
return [main, {'hwnd': 300, 'class': 'CustomDialog' if scenario == 'custom_prompt' else '#32770', 'title': 'Unexpected',
'enabled': True, 'children': [{'text': 'Overwrite design?', 'class': 'Button',
'id': 1, 'hwnd': 301, 'enabled': True}]}]
if state['requested'] and not state['confirmed']:
return [main, {'hwnd': 200, 'class': '#32770', 'title': '', 'enabled': True,
'children': [{'hwnd': 201, 'class': 'Button', 'id': 1, 'enabled': True,
'text': '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.'}]}]
return [main]
monkeypatch.setattr(ui, '_windows', windows)
def post(hwnd, message, *args):
actions.append((hwnd, message))
if message == win32con.WM_COMMAND: state['requested'] = True
if message == win32con.BM_CLICK:
state['confirmed'] = True
if scenario in {'success', 'restore'}:
import zipfile
log = target.project.parent/'Log Files/ProjectBackupLog.txt'
log.parent.mkdir(parents=True)
log.write_text('Successfully created [Project Repair] backup [repair.zip]')
archive = target.project.parent/'ProjectBackup/backups/repair.zip'
archive.parent.mkdir(parents=True)
with zipfile.ZipFile(archive, 'w') as zipped: zipped.writestr('database/icdb.dat', b'backup')
logs = {'dbcheck': 'Diagnostic: START\nDiagnostic: FINISH',
'log': f'{target.database}\niCDBProjectBackupRepair\nIC: Closing project'}
if scenario == 'restore':
logs['dbrestore'] = 'iCDB database restored from backup: old.zip\n[0] DONE'
for folder, text in logs.items():
path = target.database/'cdbsvr'/folder/'new-777/log.txt'
path.parent.mkdir(parents=True)
path.write_text(text)
if scenario == 'address':
address = target.database/'cdbsvr/sAddress.adr'
address.parent.mkdir(parents=True)
address.write_text('owner')
if message == win32con.WM_CLOSE: state['closed'] = True
monkeypatch.setattr(win32gui, 'PostMessage', post)
return ui, root, job, actions
@pytest.mark.parametrize('scenario,expected,closed', [
('failed', 'MISSING_HEALTHY_BACKUP', True), ('busy', 'DATABASE_BUSY', True),
('unknown', 'UNKNOWN_DIALOG', False), ('custom_prompt', 'UNKNOWN_DIALOG', False),
('active', 'TIMEOUT_UNRELEASED', False),
('stale', 'TIMEOUT_UNRELEASED', False), ('address', 'MISSING_HEALTHY_BACKUP', False),
])
def test_native_worker_closes_only_conclusively_failed_idle_tool(tmp_path, monkeypatch, scenario, expected, closed):
import win32con
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, scenario)
assert ui.repair_worker_main(job) == 1
result = json.loads((root/'repair-result.json').read_text('utf-8'))
assert result['status'] == expected
assert result['release']['safe_to_continue'] is closed
assert ((100, win32con.WM_CLOSE) in actions) is closed
assert actions[:2] == [(100, win32con.WM_COMMAND), (201, win32con.BM_CLICK)]
assert bool(result['evidence']['output_tail']) is (scenario != 'stale')
if scenario == 'unknown': assert result['unknown_dialogs'][0]['title'] == 'Unexpected'
@pytest.mark.parametrize('scenario,expected', [('success', 'REPAIRED'), ('restore', 'RESTORED_REVIEW_REQUIRED')])
def test_native_worker_preserves_success_and_historical_restore_distinction(tmp_path, monkeypatch, scenario, expected):
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, scenario)
assert ui.repair_worker_main(job) == (0 if scenario == 'success' else 1)
result = json.loads((root/'repair-result.json').read_text('utf-8'))
assert result['status'] == expected
assert result['release']['safe_to_continue'] is True
assert result['evidence']['native_backup'] is True
assert result['evidence']['confirmed'] is (scenario == 'success')
assert (root/'native-logs/dbcheck/new-777/log.txt').exists()
def test_native_busy_project_on_load_never_invokes_repair(tmp_path, monkeypatch):
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'busy_before')
assert ui.repair_worker_main(job) == 1
result = json.loads((root/'repair-result.json').read_text('utf-8'))
assert result['status'] == 'DATABASE_BUSY'
assert actions == []
assert not result['release']['safe_to_continue']
@pytest.mark.parametrize('status,released,scope,expected', [
('MISSING_HEALTHY_BACKUP', True, 'project', True),
('NATIVE_REPAIR_FAILED', True, 'project', True),
('MISSING_HEALTHY_BACKUP', False, 'project', False),
('MISSING_HEALTHY_BACKUP', True, 'central_library', False),
('MISSING_HEALTHY_BACKUP', True, 'unknown', False),
('UNKNOWN_DIALOG', True, 'project', False), ('TIMEOUT_UNRELEASED', True, 'project', False),
])
def test_failed_repair_continues_only_released_project_local_items(
tmp_path, monkeypatch, status, released, scope, expected):
from cbb_refresh_verify import verify_runner as runner, native_repair
request, diagnosis, target = target_fixture(tmp_path)
diagnosis['scope'] = scope
evidence = tmp_path/'first/result.json'
evidence.parent.mkdir()
(evidence.parent/'diagnostics').mkdir()
(evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps(diagnosis))
original = runner.VerifyResult('FAIL', stderr='original session lost', safe_to_continue=False,
error_category='ICDB_REPAIR_REQUIRED', error_stage='PCB_STARTING', evidence_path=evidence)
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **kw: original)
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: {
'status': status, 'release': {'safe_to_continue': released},
'evidence': {'failure_complete': True}, 'project': str(target.project),
'database': str(target.database)})
result = runner.run_verify(request)
assert result.safe_to_continue is expected
assert result.status == 'FAIL'
assert result.error_stage == 'PCB_STARTING'
assert result.stderr.startswith('original session lost')
assert status in result.stderr
assert result.recovery_attempts[0]['original_stage'] == 'PCB_STARTING'
@pytest.mark.parametrize('validation_status,flag,expected', [
('PASS', 'GREEN', True), ('PASS', 'UNKNOWN', False), ('FAIL', 'GREEN', False),
])
def test_maintenance_counts_require_native_success_then_verify_green(
tmp_path, monkeypatch, validation_status, flag, expected):
from cbb_refresh_verify import verify_runner as runner, native_repair
from cbb_refresh_verify.icdb_maintenance import maintenance_counts
request, diagnosis, 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(diagnosis))
original = runner.VerifyResult('FAIL', stderr='original lost session', safe_to_continue=False,
error_category='ICDB_REPAIR_REQUIRED', evidence_path=evidence)
evidence.write_text(json.dumps({'stderr': original.stderr}))
validated = runner.VerifyResult(validation_status, library_flag=flag,
evidence_path=tmp_path/'second.json', safe_to_continue=True)
calls = []
def verify(req, **kwargs):
calls.append(req)
return original if len(calls) == 1 else validated
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw:
{'status': 'REPAIRED', 'release': {'safe_to_continue': True}})
result = runner.run_verify(request)
assert len(calls) == 2 and calls[1].auto_repair is False
assert result.recovery_attempts[0]['validation_passed'] is expected
assert maintenance_counts([result])['repaired'] == int(expected)
assert original.evidence_path.exists(), 'Original result evidence must remain available'
assert json.loads(original.evidence_path.read_text('utf-8'))['stderr'] == 'original lost session'
def test_native_success_without_release_does_not_reopen(tmp_path, monkeypatch):
from cbb_refresh_verify import verify_runner as runner, native_repair
request, diagnosis, 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(diagnosis))
calls = []
def verify(*args, **kwargs):
calls.append('open')
return runner.VerifyResult('FAIL', 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': 'REPAIRED'})
result = runner.run_verify(request)
assert calls == ['open']
assert not result.safe_to_continue
assert result.recovery_attempts[0]['status'] == 'REPAIR_RELEASE_UNCONFIRMED'
@pytest.mark.parametrize('obstacle', ['none', 'launcher', 'repair_tool', 'importer', 'address', 'handle', 'shared_handle', 'probe'])
def test_repair_release_requires_process_address_and_database_handle_release(tmp_path, monkeypatch, obstacle):
import win32con, win32file
from cbb_refresh_verify import native_repair, mentor_adapter
request, diagnosis, target = target_fixture(tmp_path)
monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda:
[(123, 'ExpeditionPCB.exe', 'launcher')] if obstacle == 'launcher' else [])
def processes(name):
if obstacle == 'probe': raise OSError('process observation unavailable')
if ((obstacle == 'repair_tool' and name == 'iCDBProjectBackup.exe')
or (obstacle == 'importer' and name == 'ReuseBlockImporter.exe')):
return [(456, name, 'unconfirmed owner', 0)]
return []
monkeypatch.setattr(mentor_adapter, '_process_details', processes)
if obstacle == 'address':
address = target.database/'cdbsvr/sAddress.adr'
address.parent.mkdir(parents=True)
address.touch()
handle = None
try:
if obstacle in {'handle', 'shared_handle'}:
database_file = target.database/'icdb.dat'
if obstacle == 'shared_handle':
database_file = request.lmc_file.parent/'SymbolLibs/__ReusableBlocksSymb/icdb.dat'
database_file.parent.mkdir(parents=True)
database_file.touch()
handle = win32file.CreateFile(str(database_file), win32con.GENERIC_READ,
0, None, win32con.OPEN_EXISTING, 0, None)
result = native_repair.repair_release_state(request, target,
{'release': {'safe_to_continue': True}})
assert result['safe_to_continue'] is (obstacle == 'none')
finally:
if handle: handle.Close()
def test_attempt_persists_distinct_native_failure_and_release_result(tmp_path, monkeypatch):
from cbb_refresh_verify import native_repair, mentor_adapter
request, diagnosis, target = target_fixture(tmp_path)
evidence = tmp_path/'evidence'
evidence.mkdir()
monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: [])
monkeypatch.setattr(mentor_adapter, '_process_details', lambda *_: [])
monkeypatch.setattr(native_repair, 'run_native_repair', lambda *a, **kw: {
'status': 'MISSING_HEALTHY_BACKUP', 'project': str(target.project),
'database': str(target.database), 'release': {'safe_to_continue': True},
'evidence': {'failure_complete': True, 'output_tail': 'no backup'}})
result = native_repair.attempt_recovery(request, diagnosis, evidence)
assert result['status'] == 'MISSING_HEALTHY_BACKUP'
assert result['release']['database_exclusive'] is True
assert result['release']['safe_to_continue'] is True
assert isinstance(result['evidence'], dict)
assert result['evidence_path'] == str(evidence/'native-repair')
assert json.loads((evidence/'native-repair/attempt.json').read_text('utf-8')) == result
def test_retry_exception_keeps_original_error_and_native_repair_evidence(tmp_path, monkeypatch):
from cbb_refresh_verify import verify_runner as runner, native_repair
request, diagnosis, 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(diagnosis))
calls = []
def verify(*a, **kw):
calls.append('open')
if len(calls) > 1: raise OSError('retry infrastructure failure')
return runner.VerifyResult('FAIL', stderr='original native error', safe_to_continue=False,
error_category='ICDB_REPAIR_REQUIRED', evidence_path=evidence)
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: {
'status': 'REPAIRED', 'release': {'safe_to_continue': True},
'evidence': {'confirmed': True, 'diagnostic_tail': 'original repair evidence'}})
result = runner.run_verify(request)
assert not result.safe_to_continue
assert 'original native error' in result.stderr
assert 'retry infrastructure failure' in result.stderr
assert result.recovery_attempts[0]['evidence']['diagnostic_tail'] == 'original repair evidence'
assert result.recovery_attempts[0]['status'] == 'REPAIR_VALIDATION_FAILED'
assert json.loads(evidence.read_text('utf-8'))['recovery_attempts']
def test_sanitized_field_open_failure_replay_closes_launcher_then_repairs_once(tmp_path, monkeypatch):
from types import SimpleNamespace
from dataclasses import replace
from test_failed_startup import startup_fixture
from cbb_refresh_verify import verify_runner as runner, native_repair, failed_session, mentor_adapter
from cbb_refresh_verify.pcb_bridge import wait_for_target_document, PcbBridgeError
replay = json.loads((Path(__file__).parent/'fixtures/issue2-lost-session-sanitized.json').read_text('utf-8'))
request, diagnosis, target = target_fixture(tmp_path)
# Retain a different PRJ name: the field CBB name never authorizes guessing it.
block_root = target.project.parent.parent
block_root.rename(block_root.with_name(replay['block']))
request = replace(request, block_name=replay['block'])
project, pcb = runner.preflight(request)
diagnosis['database_path'] = str(project.parent/'database')
target = native_repair.select_repair_target(request, diagnosis)
job, records, messages = startup_fixture(tmp_path, monkeypatch)
job.update(project=str(project), pcb=str(pcb), lmc_file=str(request.lmc_file))
records[0] = (12, records[0][1], f'ExpeditionPCB.exe "{pcb}" -ReusableCircuit', 11)
diagnosis.update(session=replay['diagnosis']['session'], machine='FIELD-PC')
(tmp_path/'diagnostics/icdb-recovery.json').write_text(json.dumps(diagnosis))
(tmp_path/'dialogs.jsonl').write_text(json.dumps(replay['dialog'])+'\n')
ticks = [0.0]
monkeypatch.setattr(failed_session, 'time', SimpleNamespace(monotonic=lambda: ticks[0],
sleep=lambda seconds: ticks.__setitem__(0, ticks[0]+seconds)))
launcher = SimpleNamespace(pid=11, poll=lambda: 0 if ticks[0] >= .4 else None)
monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: [])
trace = []
evidence = tmp_path/'result.json'
original = runner.VerifyResult('FAIL', stderr=replay['native_error'], safe_to_continue=False,
error_category=replay['original_result']['error_category'],
error_stage=replay['original_result']['error_stage'], evidence_path=evidence)
assert runner.classify_failure_category(original.stderr) == original.error_category
assert runner.phase_for_event(replay['observed_events'][2]).value == original.error_stage
opens = []
def verify(req, **kwargs):
opens.append(req)
trace.append('open')
if len(opens) == 1:
errors = iter(('', replay['native_error']))
with pytest.raises(PcbBridgeError, match='Repair project'):
wait_for_target_document(job, lambda: SimpleNamespace(ActiveDocument=None),
process_alive=lambda: True, error_reader=lambda: next(errors),
emit=lambda **e: trace.append(e['stage']), sleep=lambda _: None)
closed = failed_session.close_failed_startup(job, 12, launcher_process=launcher,
emit=lambda **e: trace.append(e['stage']), timeout_seconds=1)
assert closed['status'] == 'CLOSED'
trace.append('launcher_exited')
return original # Repeated field error after one repair must not loop.
def repair(actual, root, **kwargs):
assert actual == target
assert trace[-1] == 'launcher_exited'
assert not records and launcher.poll() == 0
trace.append('native_repair')
return {'status': 'REPAIRED', 'project': str(actual.project), 'database': str(actual.database),
'release': {'safe_to_continue': True}, 'evidence': {'confirmed': True}}
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
monkeypatch.setattr(native_repair, 'run_native_repair', repair)
result = runner.run_verify(request)
assert trace == ['open', 'pcb_document_wait', 'startup_close_requested', 'startup_close_result',
'launcher_exited', 'native_repair', 'open']
assert len(opens) == 2 and opens[1].auto_repair is False
assert result.error_stage == 'PCB_STARTING'
assert result.recovery_attempts[0]['status'] == 'REPAIR_VALIDATION_FAILED'
assert result.recovery_attempts[0]['original_error'] == replay['native_error']
assert json.loads((tmp_path/'pre-repair-result.json').read_text('utf-8'))['stderr'] == replay['native_error']
+12
View File
@@ -89,3 +89,15 @@ def test_success_requires_save_and_pcb_exit():
assert execution_outcome(save_complete=True, pcb_exited=True)['status'] == 'PASS'
assert execution_outcome(save_complete=False, pcb_exited=True)['status'] == 'FAIL'
assert execution_outcome(save_complete=True, pcb_exited=False)['status'] == 'FAIL'
def test_connected_com_without_document_remains_startup_and_checks_native_failure(tmp_path):
errors = iter(('', 'ICDB_REPAIR_REQUIRED: original lost session'))
events = []
with pytest.raises(PcbBridgeError) as raised:
wait_for_target_document(job(tmp_path), lambda: Application(None), process_alive=lambda: True,
error_reader=lambda: next(errors), emit=lambda **e: events.append(e), sleep=lambda _: None)
assert raised.value.error_code == 'PCB_STARTUP_FAILED'
assert 'original lost session' in str(raised.value)
assert [e['stage'] for e in events] == ['pcb_document_wait']
assert events[0]['error_code'] == 'PCB_DOCUMENT_NOT_READY'