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

@@ -0,0 +1,187 @@
# Task 3 report: scoped primary manifests and complete verified backups
Status: implementation and verification complete. Started on b90a9bb; paused at
the RED checkpoint for the coordinator's native startup-window repair fix and
resumed on 877e3b4. No native UI/process/live-library actions were performed by
this implementer. Original untracked review.diff was preserved and not staged.
## Result and scope
Complete backup trees are still copied and retained. SHA256 and semantic
before/after comparisons now cover only primary design/project/database/
constraint files and required central-library dependencies. Runtime changes
after a successful snapshot do not stop install. Primary content changes,
additions and deletions do stop install, with copies retained as evidence.
The validate-copy -> conflict checks -> retain original Work -> install ->
reopen/native verification flow is preserved. Source equality now runs after
incoming Work preparation, immediately before target equality, closing the old
late-source-change window. Source idle/address ownership is rechecked there as
well: excluding address bytes from semantic hashes does not bypass idle checks.
Scoped production files: backup_recovery.py and new scoped_manifest.py. Scoped
tests: test_backup_recovery.py and new test_scoped_manifest.py. No Verify public
types, Task 2 helpers/READY logic, native repair classifiers/process whitelist,
or library binary contents were changed.
## Exact classification rules
Project scope retains every unclassified file as primary. This includes PRJ,
PCB, DXP, icdb.dat, Layout databases, schematic/logic/symbol assets, CES/config,
unknown binary/engineering formats, and text files outside explicit excluded
categories. Rules are case-insensitive; manifests preserve relative path case.
Explicit semantic exclusions, still copied and metadata-validated:
- Directory components: log, logs, temp, tmp, __pycache__, backup, backups,
output, outputs, report, reports, gerber, gerbers, odb++, and historical
Work.before-restore-* directory components.
- File suffixes: .log, .tmp, .temp, .lck, .lock, .bak, .backup, .pdf.
- File names: sAddress.adr and editor files starting with ~$.
The uploader-compatible .<stem>.cbb-upload.lock falls under .lock, so it is
runtime and never primary. It is **not** silently removed from complete copies.
Central-library scope includes only target ReusableBlocksLP/<block>/Work and
Cert, root configuration files (the selected .lmc, other root config files),
and shared/configuration dependency directories outside ReusableBlocksLP. Known
examples include SymbolLibs/__ReusableBlocksSymb, CellDB and PartDB; new unknown
dependency directory names remain primary conservatively. Other root .lmc files,
other ReusableBlocksLP CBBs, target historical/non-Work/non-Cert trees and the
explicit runtime/generated categories above do not enter semantic equality.
Those unrelated files still enter the complete copy and its metadata checks.
Later semantic scans prune ignored/runtime/unrelated CBB directories before
entering them, so transient/unavailable runtime or unrelated trees cannot
interfere with the post-snapshot content check.
## Reusable API contract for Task 4
Import from cbb_refresh_verify.scoped_manifest:
```python
scope = ManifestScope.library(block_name, selected_lmc.name)
before = copy_verified(library_root, private_backup, scope=scope, progress=callback)
current = build_manifest(library_root, scope=scope, exclude=private_incoming)
if current != before:
# stop install; retain evidence
...
```
- `ManifestScope()` is project scope. `ManifestScope.library(block_name,
library_name)` requires nonempty single-component names; no path traversal.
- `build_manifest(root, *, scope=None, exclude=None, progress=None,
hash_function=hash_file)` returns a semantic manifest. `exclude` is an optional
private incoming subtree, **not** a copy exclusion. Hash injection is a test
hook; normal callers use the default.
- `copy_verified(source, destination, *, scope=None, progress=None,
hash_function=hash_file)` requires a fresh destination outside source. Copies
all files/directories, returns the same semantic schema, retains partial
destination on failure, and raises ValueError/OSError for unsafe/changed data.
- `scan_tree(root)` scans complete membership and refuses links/junctions and
special files. Its optional scope/exclude is used by semantic scans only;
complete copies always scan without filters.
- `hash_file(path)` streams SHA256 in 1 MiB chunks. Files are processed with up
to eight workers, retaining the existing concurrency bound.
- Progress callback accepts **one dict**, not the old private `(count,total)`
pair: `stage` (`copy` or `hash`), `hashed_files`, `hashed_bytes`, `total_files`,
plus `copied_files` for copy. Hash counts/bytes count unique primary snapshot
files/logical bytes, not aggregate disk IO. `total_files` counts all files for
copies and primary files for standalone manifest generation. Initial zero and
each 256/final-file event are emitted. Recovery keeps existing public progress
stage/message keys and adds `manifest_stage` and these counters.
Version 1 JSON-compatible output (relative paths are POSIX, no machine-specific
absolute paths or mtimes in equality):
```json
{
"version": 1,
"scope": {"kind": "library", "block_name": "A", "library_name": "target.lmc"},
"files": {
"ReusableBlocksLP/A/Work/A.prj": {
"size": 123, "sha256": "<sha256>", "scope": "target_work"
}
}
}
```
Entry scope labels are project, target_work, target_cert, library_config and
shared_dependency. Default project's descriptor uses empty block/library names.
Recovery persists both library-before-manifest.json and
source-before-manifest.json. The shape changed only for private backup helpers;
VerifyRequest/VerifyResult contracts are unchanged. There is no old-manifest
loader or destructive migration: existing historical evidence remains intact.
## Copy integrity and old strict equality compatibility
Copy validation remains strict for the **entire** snapshot: before/after source
file/directory membership, file type, size and nanosecond mtime must agree;
destination membership/type/size/mtime must match too. Primary regular source
files are SHA256 read before copy and again for validation; destination hashes
must match. All native icdb.dat and .lmc files retain exclusive read handles
during copying. For scoped primary native files, the expected digest is built
from the source ReadFile stream independently of destination SHA256. Identical
size/mtime destination corruption is therefore rejected, including locked DBs.
Unrelated native DBs are still locked/copied; their bytes are not SHA256 hashed.
The old final `_manifest(source) == complete_copy_record` was an all-file hash
comparison that rehashed every runtime and unrelated project file. It is
replaced by full-tree copy metadata validation and primary byte verification at
snapshot time. Later equality compares version/scope and primary relative
path/size/hash/scope only. Thus log-only additions/changes/deletions after a
successful copy are accepted, while primary keyset/content changes remain real
conflicts. No conflict tests were weakened or deleted; additional source,
target, Cert, shared dependency, late-source and active-address regressions were
added. Empty directory metadata is intentionally not part of semantic equality.
## RED/GREEN and verification evidence
1. Initial RED, before production edits:
`python -m pytest tests/test_scoped_manifest.py tests/test_backup_recovery.py -q`
-> **29 failed, 26 passed in 7.89s**. Failures demonstrated missing versioned
manifest/schema/progress and post-snapshot runtime/unrelated tolerance.
Copy/conflict protections already present continued passing.
2. Initial GREEN -> **55 passed in 11.93s**.
3. Additional RED for semantic traversal of an unavailable ignored/unrelated
tree -> **1 failed, 36 passed in 2.79s**; fixed by pruning semantic scans.
4. Additional RED for source mutation during incoming Work preparation and
source address reappearance -> **2 failed, 20 deselected in 1.56s**; both had
incorrectly installed before the final-source-check changes.
5. Final focused:
`python -m pytest tests/test_scoped_manifest.py tests/test_backup_recovery.py tests/test_backup_recovery_dialog.py -q`
-> **64 passed in 9.93s**.
6. Coordinator was notified **before** the full suite and explicitly confirmed
no native owner/mutex and paused all native probes. Exactly one final suite:
`python -m pytest -q` -> **693 passed, 1 warning in 47.99s**. Warning:
pywinauto's existing "Revert to STA COM threading mode" warning in
test_library_reader.py::test_status_log_records_unseen_id_inference.
7. `git diff --check` passed. Review confirmed no unrelated/native-helper edits.
Coverage includes every primary category, unknown engineering formats,
runtime/history/generated exclusions with complete-copy retention, hash-path
scope, relocatability, source changed/deleted/added during copy/validation,
target changes/deletions/additions, Cert/shared-library conflicts, unrelated
CBB tolerance, copied corruption with preserved metadata, locked stream bytes,
source content changes with preserved metadata, complete copy membership and
nonprimary size consistency, idle/address rechecks, retained copies on failure,
and unchanged native reopen/retained-Work recovery behavior.
## Limitations / follow-up boundary
- No real field lost-session reproduction, native GUI success reproduction, or
Windows 10 run was performed for this task; file-based tests do not substitute
for those required native/field validations.
- Task 4 must adapt complete-copy access to a live uploader lock **only when the
operation actually owns that coordination lock**. The current helper copies
readable locks and fails closed on unreadable/live exclusively owned files;
it does not delete locks or broadly drop engineering data.
- Native idle guards and later coordination locks remain necessary. Final
equality and filesystem rename are not one cross-process atomic transaction
against arbitrary noncooperating external writers.
- Nonprimary byte hashes are intentionally absent. Their copy integrity uses
complete membership and size/mtime checks, as specified; same-size,
timestamp-preserving nonprimary corruption is outside the semantic guarantee.
- All snapshots must be stable while copied, including runtime files. This
deliberately differs from post-snapshot semantic checks, which tolerate
runtime changes. Original and partial recovery evidence is retained on failure.
+30 -105
View File
@@ -3,12 +3,8 @@
This restores project data for an existing library entry. It is not a native
cross-library import and does not delete library records or shared symbols.
"""
from contextlib import ExitStack
from concurrent.futures import ThreadPoolExecutor
from dataclasses import asdict, replace
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
@@ -16,105 +12,22 @@ import stat
from uuid import uuid4
from .verify_runner import VerifyResult, preflight
from .scoped_manifest import (ManifestScope, build_manifest, copy_verified,
hash_file as _hash, scan_tree as _scan)
def _hash(path):
digest = hashlib.sha256()
with path.open('rb') as stream:
for data in iter(lambda: stream.read(1024 * 1024), b''):
digest.update(data)
return digest.hexdigest()
def _manifest(root, *, scope=None, exclude=None, progress=None):
return build_manifest(root, scope=scope, exclude=exclude, progress=progress, hash_function=_hash)
def _scan(root):
if root.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
raise ValueError(f'不支持通过目录链接恢复:{root}')
entries = {}
folders = [root]
while folders:
with os.scandir(folders.pop()) as scanned:
for entry in scanned:
metadata = entry.stat(follow_symlinks=False)
if metadata.st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
raise ValueError(f'目录含文件或目录链接,停止恢复:{entry.path}')
path = Path(entry.path)
entries[path] = metadata
if stat.S_ISDIR(metadata.st_mode):
folders.append(path)
return dict(sorted(entries.items()))
def _copy_verified(source, destination, *, scope=None, progress=None):
return copy_verified(source, destination, scope=scope, progress=progress, hash_function=_hash)
def _paths(root):
return list(_scan(root))
def _manifest(root, *, exclude=None):
entries = _scan(root)
paths = [path for path in entries
if exclude is None or not path.is_relative_to(exclude)]
def entry(path):
return str(path.relative_to(root)), _hash(path) if stat.S_ISREG(entries[path].st_mode) else None
with ThreadPoolExecutor(max_workers=8) as pool:
return dict(pool.map(entry, paths))
def _copy_verified(source, destination, *, progress=None):
"""Copy every file, refusing links and changed files; lock native databases."""
import win32con, win32file
entries = _scan(source)
paths = list(entries)
destination.mkdir(parents=True, exist_ok=False)
record = {}
with ExitStack() as stack:
locks = {}
for path in paths:
if stat.S_ISREG(entries[path].st_mode) and (path.name.casefold() == 'icdb.dat' or path.suffix.casefold() == '.lmc'):
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
stack.callback(handle.Close)
locks[path] = handle
files = []
for path in paths:
relative = str(path.relative_to(source))
copied = destination / relative
if stat.S_ISDIR(entries[path].st_mode):
copied.mkdir(parents=True, exist_ok=True)
record[relative] = None
continue
files.append(path)
def copy_file(path):
relative = str(path.relative_to(source))
copied = destination / relative
before = entries[path]
copied.parent.mkdir(parents=True, exist_ok=True)
if path in locks:
with copied.open('wb') as stream:
while True:
_, data = win32file.ReadFile(locks[path], 1024 * 1024)
if not data:
break
stream.write(data)
shutil.copystat(path, copied)
digest = _hash(copied)
else:
digest = _hash(path)
shutil.copy2(path, copied)
if _hash(copied) != digest:
raise OSError(f'副本校验失败:{path}')
after = path.stat()
if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
raise OSError(f'复制期间文件变化:{path}')
return relative, digest
with ThreadPoolExecutor(max_workers=8) as pool:
for count, (relative, digest) in enumerate(pool.map(copy_file, files), 1):
record[relative] = digest
if progress and (count % 256 == 0 or count == len(files)):
progress(count, len(files))
if _manifest(source) != record:
raise OSError(f'复制期间目录内容变化:{source}')
return record
def _idle_check(library, project, pcb):
from .mentor_adapter import pcb_processes, _process_details
from .icdb_ownership import unreleased_addresses
@@ -213,9 +126,15 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
record = {'operation': 'same_cbb_complete_project_restore', 'source': str(source),
'library': str(library), 'block': request.block_name, 'installed': False,
'validation_library': str(validation_dir/library.name)}
def emit(stage, message):
def emit(stage, message, **details):
if progress:
progress({'stage': stage, 'block': request.block_name, 'message': message})
progress({'stage': stage, 'block': request.block_name, 'message': message, **details})
def copy_progress(stage, message):
def report(event):
details = {key: value for key, value in event.items() if key != 'stage'}
emit(stage, f'{message} {event["copied_files"]} / {event["total_files"]}',
manifest_stage=event['stage'], **details)
return report
def save(result):
record.update({'installed': installed, 'result': asdict(result)})
root.mkdir(parents=True, exist_ok=True)
@@ -245,13 +164,16 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
raise ValueError('磁盘空间不足:需要容纳中心库回退副本和验证副本。')
(root/'recovery-request.json').write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
emit('backup', '正在保留完整中心库副本…')
original_manifest = _copy_verified(library_root, root/'library-before', progress=lambda n, total:
emit('backup', f'正在保留中心库副本:{n} / {total} 个文件…'))
library_scope = ManifestScope.library(request.block_name, library.name)
original_manifest = _copy_verified(library_root, root/'library-before', scope=library_scope,
progress=copy_progress('backup', '正在保留中心库副本:'))
(root/'library-before-manifest.json').write_text(json.dumps(original_manifest, indent=2), encoding='utf-8')
emit('prepare_source', '正在准备备份验证副本…')
source_manifest = _copy_verified(source.parent, root/'source-before')
_copy_verified(root/'library-before', validation_dir, progress=lambda n, total:
emit('prepare_source', f'正在准备验证库:{n} / {total} 个文件…'))
source_manifest = _copy_verified(source.parent, root/'source-before',
progress=copy_progress('prepare_source', '正在保留备份工程副本:'))
(root/'source-before-manifest.json').write_text(json.dumps(source_manifest, indent=2), encoding='utf-8')
_copy_verified(root/'library-before', validation_dir, scope=library_scope,
progress=copy_progress('prepare_source', '正在准备验证库:'))
staged_library = validation_dir/library.name
staged_work = staged_library.parent/'ReusableBlocksLP'/request.block_name/'Work'
# Both paths are newly created private copies; originals are retained.
@@ -259,7 +181,8 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
if not resolved_work.is_relative_to(validation_dir.resolve()):
raise ValueError('验证副本工程路径越界。')
shutil.rmtree(resolved_work)
_copy_verified(root/'source-before', staged_work)
_copy_verified(root/'source-before', staged_work,
progress=copy_progress('prepare_source', '正在准备备份验证工程:'))
staged_project = staged_work/source.name
staged_pcb = staged_work/source_pcb.relative_to(source.parent)
_align_library(staged_project, staged_pcb, staged_library)
@@ -277,15 +200,17 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
'备份校验未通过,目标未更改。\n' + (source_result.stderr or source_result.library_flag_detail)))
idle_check(library, project, pcb)
idle_check(staged_library, staged_project, staged_pcb)
if _manifest(source.parent) != source_manifest:
raise ValueError('备份来源在验证期间发生变化,目标未更改。')
token = root.name.removeprefix('backup-restore-')
work = project.parent.resolve()
incoming = work.with_name('Work.restore-' + token)
retained = work.with_name('Work.before-restore-' + token)
_copy_verified(staged_work, incoming)
_copy_verified(staged_work, incoming,
progress=copy_progress('prepare_source', '正在准备恢复工程:'))
_align_library(incoming/source.name, incoming/source_pcb.relative_to(source.parent), library)
if _manifest(library_root, exclude=incoming.resolve()) != original_manifest:
idle_check(library, source, source_pcb)
if _manifest(source.parent) != source_manifest:
raise ValueError('备份来源在验证期间发生变化,目标未更改。')
if _manifest(library_root, scope=library_scope, exclude=incoming.resolve()) != original_manifest:
raise ValueError('目标中心库在验证期间发生变化,停止恢复。')
emit('install', '备份已通过验证,正在保留原工程并恢复…')
work.rename(retained)
+265
View File
@@ -0,0 +1,265 @@
"""Complete, metadata-verified snapshots with scoped semantic SHA256 manifests.
Unknown engineering files are primary. Only explicit runtime, history and
generated categories are ignored by semantic comparisons; they are still copied
and their membership/size/mtime must remain stable throughout the snapshot.
"""
from concurrent.futures import ThreadPoolExecutor
from contextlib import ExitStack
from dataclasses import asdict, dataclass
import hashlib
import os
from pathlib import Path
import shutil
import stat
MANIFEST_VERSION = 1
_NONPRIMARY_DIRECTORIES = frozenset({
'log', 'logs', 'temp', 'tmp', '__pycache__', 'backup', 'backups',
'output', 'outputs', 'report', 'reports', 'gerber', 'gerbers', 'odb++',
})
_NONPRIMARY_SUFFIXES = frozenset({
'.log', '.tmp', '.temp', '.lck', '.lock', '.bak', '.backup', '.pdf',
})
@dataclass(frozen=True)
class ManifestScope:
"""Project root by default; library selects one CBB and shared dependencies."""
kind: str = 'project'
block_name: str = ''
library_name: str = ''
def __post_init__(self):
if self.kind not in ('project', 'library'):
raise ValueError('Unknown manifest scope')
if self.kind == 'library':
for value in (self.block_name, self.library_name):
if not value or value in ('.', '..') or any(c in value for c in '/\\:'):
raise ValueError('Library scope requires single-component block/library names')
@classmethod
def library(cls, block_name, library_name):
return cls('library', block_name, library_name)
def includes_directory(self, relative):
parts = tuple(part.casefold() for part in Path(relative).parts)
if any(part in _NONPRIMARY_DIRECTORIES or part.startswith('work.before-restore-')
for part in parts):
return False
if self.kind == 'project' or parts[0] != 'reusableblockslp':
return True
return ((len(parts) < 2 or parts[1] == self.block_name.casefold())
and (len(parts) < 3 or parts[2] in ('work', 'cert')))
def classify(self, relative):
"""Return a semantic scope label or None; paths are relative to the root."""
parts = tuple(part.casefold() for part in Path(relative).parts)
if (any(part in _NONPRIMARY_DIRECTORIES or part.startswith('work.before-restore-')
for part in parts[:-1])
or Path(parts[-1]).suffix in _NONPRIMARY_SUFFIXES
or parts[-1] == 'saddress.adr' or parts[-1].startswith('~$')):
return None
if self.kind == 'project':
return 'project'
if parts[0] == 'reusableblockslp':
if len(parts) < 4 or parts[1] != self.block_name.casefold():
return None
return {'work': 'target_work', 'cert': 'target_cert'}.get(parts[2])
if len(parts) == 1:
if Path(parts[0]).suffix == '.lmc' and parts[0] != self.library_name.casefold():
return None
return 'library_config'
# Shared DB/config/dependency trees are conservative: new dependency
# directory names remain primary without adding them to an allowlist.
return 'shared_dependency'
def hash_file(path):
digest = hashlib.sha256()
with Path(path).open('rb') as stream:
for data in iter(lambda: stream.read(1024 * 1024), b''):
digest.update(data)
return digest.hexdigest()
def scan_tree(root, *, scope=None, exclude=None):
"""Refuse links/special files; optionally prune trees outside semantic scope.
Copies always call this without a scope, validating complete membership.
Later semantic scans avoid entering runtime or unrelated CBB directories.
"""
root = Path(root)
if root.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
raise ValueError(f'不支持通过目录链接恢复:{root}')
entries = {}
folders = [root]
while folders:
with os.scandir(folders.pop()) as scanned:
for entry in scanned:
path = Path(entry.path)
if exclude is not None and path.is_relative_to(exclude):
continue
if scope is not None:
relative = path.relative_to(root)
if entry.is_dir(follow_symlinks=False):
if not scope.includes_directory(relative):
continue
elif scope.classify(relative) is None:
continue
metadata = entry.stat(follow_symlinks=False)
if metadata.st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
raise ValueError(f'目录含文件或目录链接,停止恢复:{entry.path}')
if not (stat.S_ISDIR(metadata.st_mode) or stat.S_ISREG(metadata.st_mode)):
raise ValueError(f'不支持的特殊文件:{entry.path}')
entries[path] = metadata
if stat.S_ISDIR(metadata.st_mode):
folders.append(path)
return dict(sorted(entries.items()))
def _metadata_record(root, entries):
return {path.relative_to(root).as_posix():
('file', info.st_size, info.st_mtime_ns) if stat.S_ISREG(info.st_mode) else ('dir',)
for path, info in entries.items()}
def _manifest(scope, files):
return {'version': MANIFEST_VERSION, 'scope': asdict(scope), 'files': dict(sorted(files.items()))}
def _emit(progress, stage, hashed_files, hashed_bytes, **extra):
if progress:
progress({'stage': stage, 'hashed_files': hashed_files, 'hashed_bytes': hashed_bytes, **extra})
def build_manifest(root, *, scope=None, exclude=None, progress=None, hash_function=hash_file):
"""Hash primary files only. Excluded subtrees are for private incoming Work.
The returned dict is versioned, JSON-compatible and relocatable. Equality
compares primary path membership, size, hash and scope, never runtime mtimes.
"""
root = Path(root)
scope = scope or ManifestScope()
entries = scan_tree(root, scope=scope, exclude=exclude)
selected = {path: scope.classify(path.relative_to(root)) for path, info in entries.items()
if stat.S_ISREG(info.st_mode)}
selected = {path: label for path, label in selected.items() if label is not None}
def hashed(path):
digest = hash_function(path)
after = path.stat()
before = entries[path]
if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
raise OSError(f'计算哈希期间文件变化:{path}')
return path.relative_to(root).as_posix(), {
'size': before.st_size, 'sha256': digest, 'scope': selected[path]}
files = {}
hashed_bytes = 0
_emit(progress, 'hash', 0, 0, total_files=len(selected))
with ThreadPoolExecutor(max_workers=8) as pool:
for count, (relative, item) in enumerate(pool.map(hashed, selected), 1):
files[relative] = item
hashed_bytes += item['size']
if count % 256 == 0 or count == len(selected):
_emit(progress, 'hash', count, hashed_bytes, total_files=len(selected))
# Check primary membership and metadata again after every hash completed.
# Runtime files can change/add/disappear without a semantic conflict.
after = scan_tree(root, scope=scope, exclude=exclude)
before_primary = {p: entries[p] for p in selected}
after_primary = {p: info for p, info in after.items() if stat.S_ISREG(info.st_mode)
and (exclude is None or not p.is_relative_to(exclude))
and scope.classify(p.relative_to(root)) is not None}
if _metadata_record(root, before_primary) != _metadata_record(root, after_primary):
raise OSError(f'计算哈希期间主要文件变化:{root}')
return _manifest(scope, files)
def copy_verified(source, destination, *, scope=None, progress=None, hash_function=hash_file):
"""Copy the whole tree, validate all metadata, SHA256 only scoped primary files.
Native icdb.dat/LMC files are held with exclusive read handles for the copy.
Their expected SHA256 comes from the source read stream, independently of
hashing destination bytes. Failures retain the partial destination evidence.
Progress receives one dict with stage, hashed_files/bytes and copied_files.
"""
import win32con
import win32file
source, destination = Path(source), Path(destination)
scope = scope or ManifestScope()
if destination.resolve().is_relative_to(source.resolve()):
raise ValueError('复制目标不能位于源目录内。')
entries = scan_tree(source)
expected_metadata = _metadata_record(source, entries)
destination.mkdir(parents=True, exist_ok=False)
files = [path for path, info in entries.items() if stat.S_ISREG(info.st_mode)]
record = {}
hashed_count = hashed_bytes = 0
_emit(progress, 'copy', 0, 0, copied_files=0, total_files=len(files))
with ExitStack() as stack:
locks = {}
for path in files:
if path.name.casefold() == 'icdb.dat' or path.suffix.casefold() == '.lmc':
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
stack.callback(handle.Close)
locks[path] = handle
for path, info in entries.items():
if stat.S_ISDIR(info.st_mode):
(destination/path.relative_to(source)).mkdir(parents=True, exist_ok=True)
def copy_file(path):
relative = path.relative_to(source)
copied = destination/relative
copied.parent.mkdir(parents=True, exist_ok=True)
label = scope.classify(relative)
digest = None
if path in locks:
stream_hash = hashlib.sha256() if label is not None else None
with copied.open('wb') as stream:
while True:
_, data = win32file.ReadFile(locks[path], 1024 * 1024)
if not data:
break
if stream_hash is not None:
stream_hash.update(data)
stream.write(data)
shutil.copystat(path, copied)
if stream_hash is not None:
digest = stream_hash.hexdigest()
else:
if label is not None:
digest = hash_function(path)
shutil.copy2(path, copied)
before, after = entries[path], path.stat()
if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
raise OSError(f'复制期间文件变化:{path}')
return relative.as_posix(), digest, label
with ThreadPoolExecutor(max_workers=8) as pool:
for count, (relative, digest, label) in enumerate(pool.map(copy_file, files), 1):
if label is not None:
size = entries[source/relative].st_size
record[relative] = {'size': size, 'sha256': digest, 'scope': label}
hashed_count += 1
hashed_bytes += size
if count % 256 == 0 or count == len(files):
_emit(progress, 'copy', hashed_count, hashed_bytes,
copied_files=count, total_files=len(files))
def validate_bytes(relative):
item = record[relative]
path = source/relative
if path not in locks and hash_function(path) != item['sha256']:
raise OSError(f'复制期间主要文件内容变化:{path}')
if hash_function(destination/relative) != item['sha256']:
raise OSError(f'复制内容校验失败:{path}')
with ThreadPoolExecutor(max_workers=8) as pool:
list(pool.map(validate_bytes, record))
if _metadata_record(source, scan_tree(source)) != expected_metadata:
raise OSError(f'复制期间目录内容变化:{source}')
if _metadata_record(destination, scan_tree(destination)) != expected_metadata:
raise OSError(f'复制目标目录或文件元数据不一致:{destination}')
return _manifest(scope, record)
+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