"""Issue 15 recovery entry regressions. Native boundaries never launch Mentor.""" from contextlib import contextmanager import json import os from pathlib import Path from types import SimpleNamespace import pytest @pytest.fixture(autouse=True) def no_real_owner_probe(monkeypatch): monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda names: []) def test_ordinary_worker_aligns_both_bound_projects_and_retains_each_original(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) main = Path(job['project']); aux = Path(job['pcb']).parent/'pcb.prj' original_main = b'KEY CentralLibrary "old-main.lmc"\r\n#\x81\x40\r\n' original_aux = b'\xff\xfe'+ 'KEY CentralLibrary "old-pcb.lmc"\r\n'.encode('utf-16-le') main.write_bytes(original_main); aux.write_bytes(original_aux) assert execute()['status'] == 'PASS' from cbb_refresh_verify.backup_recovery import _project_text for path in (main, aux): import re reference = re.search(r'KEY CentralLibrary "([^"]+)"', _project_text(path))[1] assert (path.parent/reference).resolve() == Path(job['lmc_file']).resolve() saved = [p.read_bytes() for p in (Path(job['root'])/'diagnostics').rglob('*.before-central-library')] assert original_main in saved and original_aux in saved def test_ordinary_legacy_binding_never_rewrites_template(tmp_path, monkeypatch): from test_verify_worker_stability import exercise_worker job, _, execute = exercise_worker(tmp_path, monkeypatch) main = Path(job['project']); pcb = Path(job['pcb']) main.write_text('KEY CentralLibrary "old.lmc"\n') pcb.write_text('KEY ProjectFile "../CBB.prj"\n') template = pcb.parent/'template.prj'; template.write_text('KEY CentralLibrary "do-not-touch.lmc"\n') original = template.read_bytes() assert execute()['status'] == 'PASS' assert template.read_bytes() == original assert 'old.lmc' not in main.read_text() def inconsistency(database): return (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.") def test_current_inconsistency_has_structured_database_and_old_error_is_not_reused(tmp_path): from cbb_refresh_verify import icdb_recovery as recovery, mentor_adapter as adapter source = tmp_path/'LogFiles/PCBLogFile.txt'; source.parent.mkdir() db = tmp_path/'database'; message = inconsistency(db) source.write_text(message+'\n') baseline = recovery.snapshot_log(source) assert recovery.read_log_failure(source, baseline)[1] is None source.write_text('new header\n'+message+'\n') assert recovery.read_log_failure(source, baseline)[1] is None baseline = recovery.snapshot_log(source) with source.open('a') as stream: stream.write(message+'\n') text, record = recovery.read_log_failure(source, baseline) assert record['database_path'] == str(db) and record['scope'] == 'project' assert record['kind'] == 'database_inconsistent' detail = adapter.pcb_log_reports_missing_server(tmp_path/'CBB.pcb', offset=baseline) assert 'ICDB_REPAIR_REQUIRED' in detail and str(db) in detail and '未修复' in detail def test_manual_repair_selects_diagnosed_bound_database_without_layout_or_healthy_header(tmp_path): from test_native_backup import project_fixture from cbb_refresh_verify import native_backup as native request, main = project_fixture(tmp_path) pcb = main.parent/'PCB/Block.pcb'; pcb.parent.mkdir() pcb.write_text('KEY ProjectFile "../Block.prj"\n') aux = pcb.parent/'pcb.prj'; aux.write_text('KEY iCDBDir "database"\n') for prj in (main, aux): (prj.parent/'database').mkdir(); (prj.parent/'database/icdb.dat').write_bytes(b'not-a-healthy-header') assert native.native_backup_target(request, mode='repair')[0] == main assert native.native_backup_target(request, mode='repair', target_database=aux.parent/'database')[0] == aux with pytest.raises(ValueError, match='TARGET'): native.native_backup_target(request, mode='repair', target_database=tmp_path/'foreign') def test_versions_launcher_rechecks_parent_retained_lease_and_persists_before_gate(tmp_path, monkeypatch): import subprocess, sys from test_native_backup import project_fixture from cbb_refresh_verify import native_backup as native, library_lock, session_record request, project = project_fixture(tmp_path) monkeypatch.setattr(native, 'native_backup_executable', lambda *_: tmp_path/'native.exe') calls = [] monkeypatch.setattr(library_lock, 'recheck_previous_release', lambda *a, **k: calls.append('recheck')) monkeypatch.setattr(session_record, 'process_identity', lambda pid: dict(pid=pid, created='now', executable='python', owner='test')) child = subprocess.Popen([sys.executable,'-c','input()'],stdin=subprocess.PIPE,text=True) def spawn(command, **kw): job = json.loads(Path(command[-1]).read_text()) assert calls == ['recheck'] and not Path(job['start_gate']).exists() calls.append('spawn') return child monkeypatch.setattr(native.subprocess, 'Popen', spawn) try: session = native.launch_native_backup(request, mode='repair') finally: child.communicate('\n',timeout=5) record = json.loads(session.job.read_text()) assert Path(record['start_gate']).is_file() assert Path(record['session_record_path']).is_file() assert session.mode == 'repair' and session.database == project.parent/'database' assert session.operation_id == record['operation_id'] assert record['automatic_repair'] is False @pytest.mark.parametrize('failure', ['spawn', 'registration']) def test_backup_failure_leaves_start_gate_closed(tmp_path, monkeypatch, failure): from test_native_backup import project_fixture from cbb_refresh_verify import native_backup as native, session_record request, _ = project_fixture(tmp_path) monkeypatch.setattr(native, 'native_backup_executable', lambda *_: tmp_path/'native.exe') def spawn(*a, **k): if failure == 'spawn': raise OSError('start failed') return SimpleNamespace(pid=123, poll=lambda: None) monkeypatch.setattr(native.subprocess, 'Popen', spawn) monkeypatch.setattr(session_record, 'register_worker_session', lambda *a: (_ for _ in ()).throw(OSError('register failed'))) with pytest.raises(OSError): native.launch_native_backup(request) job = next(request.evidence_dir.glob('native-backup-*/request.json')) record = json.loads(job.read_text()) assert not Path(record['start_gate']).exists() assert Path(record['cancel_signal']).exists() def test_changed_prj_bytes_refused_before_recovery_tool_dispatch(tmp_path, monkeypatch): import hashlib from test_native_backup import project_fixture from cbb_refresh_verify import native_backup as native request, project = project_fixture(tmp_path) job = tmp_path/'request.json' record = dict(library=str(request.lmc_file), block=request.block_name, project=str(project), project_sha256=hashlib.sha256(project.read_bytes()).hexdigest()) job.write_text(json.dumps(record)) project.write_text(project.read_text()+'# changed identity\n') monkeypatch.setattr(native, 'native_backup_executable', lambda *_: tmp_path/'native.exe') assert native.native_backup_worker_main(job, process_factory=lambda *a: pytest.fail('changed PRJ dispatched')) == 1 assert '身份' in json.loads(job.with_name('result.json').read_text('utf-8'))['detail'] def test_real_parent_retained_sidecar_is_reconciled_before_child_acquires_it_and_reopens(tmp_path, monkeypatch): import subprocess, sys from test_native_backup import project_fixture from cbb_refresh_verify import native_backup as native, library_lock as locks from cbb_refresh_verify.file_probe import hold_release_files request, _ = project_fixture(tmp_path) with locks.LibraryLock(request.lmc_file, safe_to_release=lambda: False, block_name='Block') as retained: pass @contextmanager def proof(library, **kwargs): with hold_release_files(library, (library.parent/'ReusableBlocksLP/Block/Work',)) as files: yield {**files, 'native_owners': []} monkeypatch.setattr(locks, '_prove_library_released', proof) monkeypatch.setattr(native, 'native_backup_executable', lambda *_: tmp_path/'not-launched.exe') popen = subprocess.Popen script = ( 'import json,sys\nfrom pathlib import Path\n' 'from cbb_refresh_verify.desktop_worker import run_native_worker\n' 'from cbb_refresh_verify.library_lock import LibraryLock\n' 'def action(path):\n' ' j=json.loads(Path(path).read_text())\n' ' with LibraryLock(j["library"],checkpoint=False):\n' ' Path(path).with_name("child-acquired").write_text("owned")\n' ' return 0\n' 'raise SystemExit(run_native_worker(action,sys.argv[1]))\n') def spawn(command, **kwargs): if '--native-backup-worker' in command: assert not locks.has_retained_library(request.lmc_file) return popen([sys.executable, '-c', script, command[-1]], **kwargs) return popen(command, **kwargs) monkeypatch.setattr(native.subprocess, 'Popen', spawn) try: for mode in ('versions', 'repair'): session = native.launch_native_backup(request, mode=mode) assert session.process.wait(10) == 0 assert session.job.with_name('child-acquired').read_text() == 'owned' assert retained.path.is_file() finally: owner = locks._owners.pop(retained.key, None) if owner: owner['handle'].Close() def test_native_registration_failure_never_resumes_suspended_child(tmp_path): import sys from cbb_refresh_verify.native_backup import _NativeBackupProcess marker = tmp_path/'must-not-run' def refuse(process): raise OSError('required identity journal failed') with pytest.raises(OSError, match='journal'): _NativeBackupProcess([sys.executable, '-c', f'from pathlib import Path;Path({str(marker)!r}).touch()'], tmp_path, before_resume=refuse) assert not marker.exists() def test_independent_backup_job_registration_retains_descendants_after_caller_handles_close(tmp_path): import sys, time from cbb_refresh_verify.native_backup import _NativeBackupProcess, _BackupJobWriter script = tmp_path/'parent.py'; marker = tmp_path/'child.pid' script.write_text('import subprocess,sys,time\nfrom pathlib import Path\n' 'p=subprocess.Popen([sys.executable,"-c","import time;time.sleep(1)"])\n' f'Path({str(marker)!r}).write_text(str(p.pid))\ntime.sleep(.1)\n') process = _NativeBackupProcess([sys.executable, str(script)], tmp_path) registered = _BackupJobWriter(process.job) try: deadline = time.monotonic()+5 while process.poll() is None and time.monotonic()