fix: preserve engineering identity in scoped runtime exclusions

This commit is contained in:
阿白叔 committed 2026-11-02 19:50:26 +08:00
1 parent 29c154d2ca
commit 3415e010ff
4 files changed
+288 -12

No files matched your search

@@ -0,0 +1,251 @@
# Scoped recovery manifests and complete verified backups
Status: implemented; review finding P1 addressed with focused validation. 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.
Initial implementation: 29c154d. The review correction is described below.
Durable documentation lives here; an ignored review copy remains at
.superpowers/sdd/2026-11-02-issue-2-management/task-3-report.md.
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:
- Runtime/history child directories **at a project workspace root**, its PCB
workspace root, a selected Work/Cert root, or the library root: log, logs,
temp, tmp, __pycache__, backup, backups, output, outputs, report, reports,
gerber, gerbers, odb++, Log Files, LogFiles, and Work.before-restore-*.
- ProjectBackup/backups only at those workspace roots. Other ProjectBackup
content remains conservative primary data.
- Known native runtime below database/cdbsvr and PCB/database/cdbsvr: log,
dbcheck and dbrestore subtrees. In shared library databases, those same
subtrees below SymbolLibs/<partition>/cdbsvr or <shared-root>/cdbsvr. Other
unknown files below cdbsvr remain primary; the directory is not dropped.
- File suffixes: .log, .tmp, .temp, .lck, .lock, .bak, .backup, .pdf.
- File names: sAddress.adr and editor files starting with ~$.
Directory exclusions are contextual rather than arbitrary ancestor matching.
ReusableBlocksLP/<selected-block>/Work and Cert are structural identity
components, never runtime labels. CBB names Logs, Temp, Backup, Output, Report,
Log Files, ProjectBackup and Work.before-restore-engineering remain valid and
their primary files are hashed in both semantic manifests and complete-copy
validation. Case variants have the same protection.
Shared dependency partitions and nested engineering folders keep their names:
SymbolLibs/temp/icdb.dat, SymbolLibs/Temp_a/device.sym,
SymbolLibs/Backup/device.sym, hdl/Logs/design.v and hdl/Backup/design.v are
primary. Runtime directory labels apply at the known roots above, not inside
arbitrary engineering/dependency hierarchies. File suffix/name exclusions are
applied to files, not to engineering directories with matching suffixes.
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
The original full-suite evidence below belongs to initial commit 29c154d. The
P1 review correction has fresh focused validation, and has **not** rerun the
full suite; the coordinator requested focused tests only for this fix.
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.
## Review correction: contextual runtime directory classification
Review found that the initial unconditional directory ancestor rules could
classify valid selected CBB names (Logs/Temp/Backup) or real SymbolLibs/temp
engineering partitions as runtime. That removed primary paths from both the
baseline manifest and later conflict comparison, and from copy byte checks.
The classifier now resolves the structural role first and only applies the
runtime directory rules at documented workspace/native DB locations. Semantic
directory traversal and complete-copy byte classification share that rule.
Complete tree copy/metadata validation remains unchanged. This also protects
nested engineering folders with names Logs/Backup, and avoids broad dropping
of unknown cdbsvr files.
Independent regressions cover Work and Cert under 11 colliding CBB names/case
variants, real SymbolLibs/temp and Temp_a partitions, arbitrary nested
engineering folders, source and destination corruption with unchanged size/
mtime, independent locked database destination corruption, and end-to-end
recovery conflicts that previously overwrote concurrent target/shared edits.
Known native Log Files, ProjectBackup/backups and DB server log/dbcheck/
dbrestore data remain semantically ignored and completely copied.
Review-fix RED:
`python -m pytest tests/test_scoped_manifest.py tests/test_backup_recovery.py -q --tb=short`
-> **47 failed, 74 passed in 18.41s**, before production changes. The failures
included silently accepted primary corruption and installs over concurrent
target/shared edits. Additional conservative-boundary regressions prevented
reintroducing the same bug through Log Files/ProjectBackup/retained-Work names
or broad cdbsvr directory exclusion.
Final review-fix focused GREEN:
`python -m pytest tests/test_scoped_manifest.py tests/test_backup_recovery.py tests/test_backup_recovery_dialog.py -q --tb=short`
-> **141 passed in 18.28s**. No native UI/process actions, live-library mutation,
or full-suite run was performed during this fix round.
## 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.