feat: scope recovery manifests while verifying complete backups

This commit is contained in:
阿白叔 committed 2026-11-02 19:32:07 +08:00
1 parent 877e3b4c76
commit 29c154d2ca
5 files changed
+789 -105

No files matched your search

+92
View File
@@ -188,3 +188,95 @@ def test_equivalent_library_reference_preserves_native_project_bytes_and_date(re
before = original.read_bytes(), original.stat().st_mtime_ns
_align_library(original, original.parent/'PCB/A.pcb', request.lmc_file)
assert (original.read_bytes(), original.stat().st_mtime_ns) == before
def test_logs_and_unrelated_cbb_changes_after_snapshot_do_not_block_install(recovery_files):
from cbb_refresh_verify.backup_recovery import recover_from_backup
request, original, source = recovery_files
(source.parent/'session.log').write_bytes(b'snapshot log')
other = project(request.lmc_file.parent/'ReusableBlocksLP/B/Work', 'B', b'unrelated')
calls = []
def verify(req, **kwargs):
calls.append(req)
if len(calls) == 1:
(source.parent/'session.log').write_bytes(b'updated source log')
(original.parent/'new.log').write_bytes(b'new target log')
(other.parent/'database/icdb.dat').write_bytes(b'unrelated update')
return VerifyResult('PASS', library_flag='GREEN')
result = recover_from_backup(request, source, verifier=verify, idle_check=lambda *_: None)
assert result.status == 'PASS'
assert len(calls) == 2
assert (original.parent/'database/icdb.dat').read_bytes() == b'healthy'
assert (other.parent/'database/icdb.dat').read_bytes() == b'unrelated update'
assert list(request.evidence_dir.rglob('source-before/session.log'))[0].read_bytes() == b'snapshot log'
@pytest.mark.parametrize('location,change', [
('source', 'edit'), ('source', 'delete'), ('source', 'add'),
('target', 'delete'), ('target', 'add'), ('cert', 'edit'), ('shared', 'edit'),
])
def test_primary_conflicts_preserve_target_and_complete_recovery_copies(recovery_files, location, change):
from cbb_refresh_verify.backup_recovery import recover_from_backup
request, original, source = recovery_files
if location == 'source':
conflict = source.parent/'database/icdb.dat'
elif location == 'target':
conflict = original.parent/'PCB/Layout/LayoutDB.lyt'
elif location == 'cert':
conflict = original.parent.parent/'Cert/A.prj'
else:
conflict = request.lmc_file.parent/'SymbolLibs/__ReusableBlocksSymb/icdb.dat'
conflict.parent.mkdir(parents=True, exist_ok=True)
if location in ('cert', 'shared'):
conflict.write_bytes(b'before')
calls = []
def verify(*args, **kwargs):
calls.append(args)
if change == 'delete':
conflict.unlink()
elif change == 'add':
(conflict.parent/'new-engineering.bin').write_bytes(b'new')
else:
conflict.write_bytes(b'concurrent edit')
return VerifyResult('PASS', library_flag='GREEN')
result = recover_from_backup(request, source, verifier=verify, idle_check=lambda *_: None)
assert result.status == 'BLOCKED'
assert len(calls) == 1
assert (original.parent/'database/icdb.dat').read_bytes() == b'damaged'
assert not list(original.parent.parent.glob('Work.before-restore-*'))
assert list(request.evidence_dir.rglob('library-before/target.lmc'))
assert list(request.evidence_dir.rglob('source-before/database/icdb.dat'))
def test_source_conflict_while_preparing_incoming_work_blocks_install(recovery_files, monkeypatch):
from cbb_refresh_verify import backup_recovery as recovery
request, original, source = recovery_files
copy = recovery._copy_verified
def copy_then_change_source(src, dst, **kwargs):
result = copy(src, dst, **kwargs)
if dst.name.startswith('Work.restore-'):
(source.parent/'database/icdb.dat').write_bytes(b'late concurrent change')
return result
monkeypatch.setattr(recovery, '_copy_verified', copy_then_change_source)
result = recovery.recover_from_backup(request, source,
verifier=lambda *a, **k: VerifyResult('PASS', library_flag='GREEN'), idle_check=lambda *_: None)
assert result.status == 'BLOCKED'
assert (original.parent/'database/icdb.dat').read_bytes() == b'damaged'
def test_source_address_record_is_rechecked_after_validation(recovery_files):
from cbb_refresh_verify.backup_recovery import recover_from_backup
request, original, source = recovery_files
address = source.parent/'database/cdbsvr/sAddress.adr'
def idle(library, project, pcb):
if project == source and address.exists():
raise ValueError('Source database ownership is still active')
def verify(*args, **kwargs):
address.parent.mkdir(parents=True, exist_ok=True)
address.write_bytes(b'live owner')
return VerifyResult('PASS', library_flag='GREEN')
result = recover_from_backup(request, source, verifier=verify, idle_check=idle)
assert result.status == 'BLOCKED'
assert 'ownership' in result.stderr
assert address.read_bytes() == b'live owner'
assert (original.parent/'database/icdb.dat').read_bytes() == b'damaged'
+215
View File
@@ -0,0 +1,215 @@
"""File-level regressions: complete snapshots, scoped semantic conflicts."""
import hashlib
import os
from pathlib import Path
import shutil
import pytest
from cbb_refresh_verify import backup_recovery as recovery
def put(root, relative, data=b'engineering'):
path = root / relative
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
return path
@pytest.mark.parametrize('relative', [
'A.prj', 'PCB/A.pcb', 'PCB/A.dxp', 'database/icdb.dat',
'PCB/Layout/LayoutDB.lyt', 'schematic/sheet.1', 'logic/block.1',
'symbols/device.sym', 'CES/constraints.ces', 'config/native.cfg',
'unknown/new-engineering-format.bin', 'notes.txt',
])
def test_primary_edits_additions_and_deletions_change_semantics(tmp_path, relative):
path = put(tmp_path, relative)
before = recovery._manifest(tmp_path)
assert before['version'] == 1
entry = before['files'][relative]
assert entry == {'size': len(b'engineering'),
'sha256': hashlib.sha256(b'engineering').hexdigest(), 'scope': 'project'}
path.write_bytes(b'changed')
assert recovery._manifest(tmp_path) != before
path.unlink()
assert recovery._manifest(tmp_path) != before
put(tmp_path, relative, b'engineering')
put(tmp_path, 'additional.dat')
assert recovery._manifest(tmp_path) != before
@pytest.mark.parametrize('relative', [
'logs/session.txt', 'log/native.log', 'session.log', 'temp/native.bin',
'tmp/native.bin', 'session.tmp', 'database/icdb.lck',
'database/cdbsvr/sAddress.adr', '.target.cbb-upload.lock',
'backups/old/A.prj', 'backup/old/icdb.dat', 'A.prj.bak',
'drawing.pdf', 'output/netlist.txt', 'reports/check.txt',
])
def test_runtime_history_and_generated_content_is_copied_but_not_hashed(tmp_path, relative):
source = tmp_path/'source'
put(source, 'A.prj')
runtime = put(source, relative, b'old')
destination = tmp_path/'copy'
progress = []
manifest = recovery._copy_verified(source, destination, progress=progress.append)
assert (destination/relative).read_bytes() == b'old'
assert manifest['version'] == 1
assert set(manifest['files']) == {'A.prj'}
assert progress[-1]['hashed_files'] == 1
assert progress[-1]['hashed_bytes'] == len(b'engineering')
assert progress[-1]['stage'] == 'copy'
runtime.write_bytes(b'new runtime content')
put(source, 'logs/new-session.log')
assert recovery._manifest(source) == manifest
runtime.unlink()
assert recovery._manifest(source) == manifest
def test_central_scope_hashes_target_work_cert_root_config_and_shared_dependencies(tmp_path):
from cbb_refresh_verify.scoped_manifest import ManifestScope
scope = ManifestScope.library('A', 'target.lmc')
expected = {
'target.lmc': 'library_config',
'library.xml': 'library_config',
'ReusableBlocksLP/A/Work/A.prj': 'target_work',
'ReusableBlocksLP/A/Cert/A.prj': 'target_cert',
'SymbolLibs/__ReusableBlocksSymb/icdb.dat': 'shared_dependency',
'CellDB/custom.cell': 'shared_dependency',
'PartDB/parts.pdb': 'shared_dependency',
'NewRequiredDependency/native.bin': 'shared_dependency',
}
for relative in expected:
put(tmp_path, relative)
unrelated = put(tmp_path, 'ReusableBlocksLP/B/Work/B.prj')
put(tmp_path, 'ReusableBlocksLP/A/Backups/old.prj')
put(tmp_path, 'other.lmc')
before = recovery._manifest(tmp_path, scope=scope)
assert before['scope'] == {'kind': 'library', 'block_name': 'A', 'library_name': 'target.lmc'}
assert {p: e['scope'] for p, e in before['files'].items()} == expected
unrelated.write_bytes(b'other project changed')
put(tmp_path, 'ReusableBlocksLP/C/Work/C.prj')
assert recovery._manifest(tmp_path, scope=scope) == before
for relative in expected:
path = tmp_path/relative
path.write_bytes(b'changed')
assert recovery._manifest(tmp_path, scope=scope) != before
path.write_bytes(b'engineering')
destination = tmp_path.parent/(tmp_path.name + '-copy')
assert recovery._copy_verified(tmp_path, destination, scope=scope) == before
assert (destination/'ReusableBlocksLP/B/Work/B.prj').read_bytes() == b'other project changed'
@pytest.mark.parametrize('relative', ['A.prj', 'database/icdb.dat', 'target.lmc'])
def test_corrupted_destination_bytes_are_rejected_and_evidence_is_preserved(tmp_path, monkeypatch, relative):
source = tmp_path/'source'
put(source, relative)
destination = tmp_path/'destination'
real_hash = recovery._hash
def corrupt_then_hash(path):
if path == destination/relative:
metadata = path.stat()
path.write_bytes(b'X' * metadata.st_size)
os.utime(path, ns=(metadata.st_atime_ns, metadata.st_mtime_ns))
return real_hash(path)
monkeypatch.setattr(recovery, '_hash', corrupt_then_hash)
with pytest.raises(OSError):
recovery._copy_verified(source, destination)
assert (source/relative).read_bytes() == b'engineering'
assert (destination/relative).exists()
def test_source_byte_changes_with_preserved_metadata_are_rejected(tmp_path, monkeypatch):
source, destination = tmp_path/'source', tmp_path/'destination'
primary = put(source, 'A.prj')
real_copy = shutil.copy2
def copy_then_change_source(src, dst, *args, **kwargs):
result = real_copy(src, dst, *args, **kwargs)
metadata = primary.stat()
primary.write_bytes(b'X' * metadata.st_size)
os.utime(primary, ns=(metadata.st_atime_ns, metadata.st_mtime_ns))
return result
monkeypatch.setattr(shutil, 'copy2', copy_then_change_source)
with pytest.raises(OSError):
recovery._copy_verified(source, destination)
assert (destination/'A.prj').read_bytes() == b'engineering'
@pytest.mark.parametrize('change', ['changed', 'deleted', 'added'])
def test_complete_tree_metadata_must_stay_stable_during_copy(tmp_path, monkeypatch, change):
source = tmp_path/'source'
put(source, 'A.prj')
runtime = put(source, 'logs/session.log')
destination = tmp_path/'destination'
real_copy = shutil.copy2
def copy_then_mutate(src, dst, *args, **kwargs):
result = real_copy(src, dst, *args, **kwargs)
if Path(src).name == 'A.prj':
if change == 'changed':
runtime.write_bytes(b'changed while copying')
elif change == 'deleted':
runtime.unlink()
else:
put(source, 'logs/added.log')
return result
monkeypatch.setattr(shutil, 'copy2', copy_then_mutate)
with pytest.raises(OSError):
recovery._copy_verified(source, destination)
assert destination.exists()
def test_destination_nonprimary_membership_and_size_are_validated(tmp_path, monkeypatch):
source = tmp_path/'source'
put(source, 'logs/session.log')
destination = tmp_path/'destination'
real_copy = shutil.copy2
def truncated(src, dst, *args, **kwargs):
result = real_copy(src, dst, *args, **kwargs)
Path(dst).write_bytes(b'x')
return result
monkeypatch.setattr(shutil, 'copy2', truncated)
with pytest.raises(OSError):
recovery._copy_verified(source, destination)
def test_semantic_scan_does_not_visit_runtime_or_unrelated_cbb_trees(tmp_path, monkeypatch):
from cbb_refresh_verify.scoped_manifest import ManifestScope
scope = ManifestScope.library('A', 'target.lmc')
put(tmp_path, 'target.lmc')
put(tmp_path, 'ReusableBlocksLP/A/Work/A.prj')
put(tmp_path, 'ReusableBlocksLP/B/Work/B.prj')
put(tmp_path, 'logs/transient.log')
before = recovery._manifest(tmp_path, scope=scope)
real_scan = os.scandir
def runtime_unavailable(path):
# These trees may be actively changing after the successful snapshot.
if Path(path) in (tmp_path/'logs', tmp_path/'ReusableBlocksLP/B'):
raise OSError('transient runtime/unrelated tree is unavailable')
return real_scan(path)
monkeypatch.setattr(os, 'scandir', runtime_unavailable)
assert recovery._manifest(tmp_path, scope=scope) == before
def test_only_primary_paths_are_read_for_sha256_and_manifest_is_relocatable(tmp_path, monkeypatch):
from cbb_refresh_verify.scoped_manifest import ManifestScope
scope = ManifestScope.library('A', 'target.lmc')
source, destination = tmp_path/'source', tmp_path/'destination'
primary = {'target.lmc', 'ReusableBlocksLP/A/Work/A.prj',
'SymbolLibs/shared/icdb.dat', 'config.xml'}
excluded = {'ReusableBlocksLP/B/Work/B.prj', 'logs/native.log', 'export.pdf',
'.target.cbb-upload.lock', 'backup/old/icdb.dat'}
for relative in primary | excluded:
put(source, relative)
real_hash = recovery._hash
hashed = []
def record_hash(path):
root = source if path.is_relative_to(source) else destination
relative = path.relative_to(root).as_posix()
assert relative in primary, f'Nonprimary content hashed: {relative}'
hashed.append(relative)
return real_hash(path)
monkeypatch.setattr(recovery, '_hash', record_hash)
manifest = recovery._copy_verified(source, destination, scope=scope)
assert set(hashed) == primary
assert recovery._manifest(source, scope=scope) == manifest
assert recovery._manifest(destination, scope=scope) == manifest
assert {p.relative_to(destination).as_posix() for p in destination.rglob('*') if p.is_file()} == primary | excluded