"""Pinned source reconstruction for canonical backend coverage coordinates. Frozen historical anchors remain unchanged. Reverse explicitly reviewed patches before the path-only import migration. Reconstructed bytes are historical proof inputs, not current runtime behavior. Refactor23 destinations carry no debt; line shifts there still require full coverage of the actual current code. """ import hashlib import json from pathlib import Path MAP_FILE = 'quality/backend-path-migration.json' MAP_SHA = 'de3275d169af9795a92185609797178a282802309f43c1f2628e65b75f0b6e76' TRANSITION_FILE = 'quality/reviewed-functional-source-transition.json' TRANSITION_SHA = '3b284323fdf226820b69b074473f7933f563bf41f3d011bdbb9273be0efeb97b' AUDIT_TRANSITION_FILE = 'quality/reviewed-audit-source-transition.json' AUDIT_TRANSITION_SHA = '39d78b6869791ec1169ba20d1520a0f4d3094c46f2a48eb5b9a0e8d022439799' SEARCH_PERF_TRANSITION_FILE = 'quality/reviewed-wildcard-scope-transition.json' SEARCH_PERF_TRANSITION_SHA = '2724f1070802276af8d6b0cc348e7a58f058dcfdc8a7e28cd7c05b3727222013' READER_RESOURCE_RETIREMENT_FILE = 'quality/reviewed-reader-resource-retirement.json' READER_RESOURCE_RETIREMENT_SHA = '9b7f7810ce0b95b9e70737517669072073213001bf60ad3c52967cae5eabe698' RETIRED_READER_RESOURCE_MODULES = frozenset({ 'backend/reader/archive/application/archives.py', 'backend/reader/archive/domain/content.py', 'backend/reader/archive/http/routes.py', }) # These files have exact Refactor23 hashes but no import-relocation entries. TRANSITION_ONLY = {'backend/search/application/execution.py', 'backend/search/application/requests.py', 'backend/search/http/schemas.py'} CATALOG_TARGET = 'backend/reader/catalog/infrastructure/v3.py' STREAMS_TARGET = 'backend/shared/transport/streams.py' def reviewed_transition(root: Path) -> dict: path = root / TRANSITION_FILE if not path.exists(): return {} # Historical source fixtures still run the original proof. raw = path.read_bytes() if hashlib.sha256(raw).hexdigest() != TRANSITION_SHA: raise ValueError('backend source transition requires exact reviewed mapping') return json.loads(raw)['sources'] def recover_reviewed_parent(name: str, data: bytes, sources: dict) -> bytes: entry = sources.get(name) if entry is None: return data if hashlib.sha256(data).hexdigest() != entry['current_sha256']: raise ValueError('backend source transition requires exact current source: ' + name) lines = data.decode().splitlines(keepends=True) for start, current, previous in reversed(entry['hunks']): span = current.splitlines(keepends=True) if lines[start:start + len(span)] != span: raise ValueError('backend source transition does not match reviewed hunk: ' + name) lines[start:start + len(span)] = previous.splitlines(keepends=True) parent = ''.join(lines).encode() if hashlib.sha256(parent).hexdigest() != entry['parent_sha256']: raise ValueError('backend source transition did not recover exact parent: ' + name) return parent def replay_reviewed_current(name: str, parent: bytes, sources: dict) -> bytes: """Prove the other direction using the same current-coordinate hunks.""" entry = sources[name] if hashlib.sha256(parent).hexdigest() != entry['parent_sha256']: raise ValueError('backend source transition requires exact reviewed parent: ' + name) lines = parent.decode().splitlines(keepends=True) for start, current, previous in entry['hunks']: span = previous.splitlines(keepends=True) if lines[start:start + len(span)] != span: raise ValueError('backend source transition does not match reviewed parent hunk: ' + name) lines[start:start + len(span)] = current.splitlines(keepends=True) data = ''.join(lines).encode() if hashlib.sha256(data).hexdigest() != entry['current_sha256']: raise ValueError('backend source transition did not replay exact current source: ' + name) return data def audit_transition(root: Path) -> dict: path = root / AUDIT_TRANSITION_FILE if not path.exists(): raise ValueError('backend audit source transition mapping is missing') raw = path.read_bytes() if hashlib.sha256(raw).hexdigest() != AUDIT_TRANSITION_SHA: raise ValueError('backend audit source transition requires exact reviewed mapping') return json.loads(raw)['sources'] def search_perf_transition(root: Path) -> dict: path = root / SEARCH_PERF_TRANSITION_FILE if not path.exists(): raise ValueError('wildcard scope source transition mapping is missing') raw = path.read_bytes() if hashlib.sha256(raw).hexdigest() != SEARCH_PERF_TRANSITION_SHA: raise ValueError('wildcard scope source transition requires exact reviewed mapping') return json.loads(raw)['sources'] def reader_resource_retirement(root: Path) -> dict: path = root / READER_RESOURCE_RETIREMENT_FILE if not path.exists(): return {} # Historical trees must still supply the old live destinations. raw = path.read_bytes() if hashlib.sha256(raw).hexdigest() != READER_RESOURCE_RETIREMENT_SHA: raise ValueError('reader resource retirement requires exact reviewed mapping') for name in sorted(RETIRED_READER_RESOURCE_MODULES): retired = root / name if retired.exists() or retired.is_symlink(): raise ValueError('retired reader resource module is still present: ' + name) return json.loads(raw)['sources'] def require_audit_seo_full_coverage(root: Path, baseline: dict) -> dict: """The changed SEO module had no debt; enforce full current coverage instead. This is stronger than carrying historical coordinates across rewritten control flow: the ordinary gate requires every live statement and branch, including all newly added ones. Never discard a baseline with missing requirements. """ target = 'backend/site/application/seo.py' if target not in baseline or target not in audit_transition(root): return baseline entry = baseline[target] if entry['missing_lines'] or entry['missing_arcs']: raise ValueError('audit SEO transition cannot transfer coverage debt') return {name: value for name, value in baseline.items() if name != target} def carry_catalog_coverage(root: Path, baseline: dict) -> dict: """Carry every prior requirement onto the exact pinned Catalog v3 patch.""" if CATALOG_TARGET not in baseline or CATALOG_TARGET not in reviewed_transition(root): return baseline entry = dict(baseline[CATALOG_TARGET]) if entry['missing_lines'] or entry['missing_arcs']: raise ValueError('catalog source transition cannot transfer missing coverage debt') def translate(n: int) -> int: # The new load signature/docstring adds two lines after the def; # the pin callback adds three after validate_base_ref. The rewritten # pin guard still has to exercise both validation and the skip path. line = abs(n) if line >= 147: line += 5 elif line >= 106: line += 2 return line if n >= 0 else -line entry['lines'] = sorted(translate(n) for n in entry['lines']) entry['arcs'] = sorted([translate(a), translate(b)] for a, b in entry['arcs']) return {**baseline, CATALOG_TARGET: entry} def carry_upstream_coverage(root: Path, baseline: dict) -> dict: """Translate old coordinates only; retain requirements for both rewritten validators.""" target = 'backend/shared/transport/upstream.py' if target not in baseline or target not in reviewed_transition(root): return baseline # The verified patch adds one comment line before each of two rewritten # call sites. Those statements and their existing arcs are still required. def translate(n: int) -> int: line = abs(n) if line >= 154: line += 2 elif line >= 125: line += 1 return line if n >= 0 else -line entry = dict(baseline[target]) for key in ('lines', 'missing_lines'): entry[key] = sorted(translate(n) for n in entry[key]) for key in ('arcs', 'missing_arcs'): entry[key] = sorted([translate(a), translate(b)] for a, b in entry[key]) return {**baseline, target: entry} def require_audit_upstream_full_coverage(root: Path, baseline: dict) -> dict: """Replace the deleted unreachable retry tail's debt with full live coverage.""" target = 'backend/shared/transport/upstream.py' if target not in baseline or target not in audit_transition(root): return baseline entry = baseline[target] if entry['missing_lines'] != [331] or entry['missing_arcs'] != [[284, 331]]: raise ValueError('upstream audit must retain exact historical retry debt') return {name: value for name, value in baseline.items() if name != target} def require_audit_reader_assets_full_coverage(root: Path, baseline: dict) -> dict: """Require full live coverage after deleting the unreachable second bucket check.""" target = 'backend/reader/catalog/domain/assets.py' if target not in baseline or target not in audit_transition(root): return baseline entry = baseline[target] if entry['missing_lines'] != [126] or entry['missing_arcs'] != [[125, 126]]: raise ValueError('reader assets audit must retain exact historical bucket-check debt') return {name: value for name, value in baseline.items() if name != target} def carry_stream_override_coverage(root: Path, baseline: dict) -> dict: """Translate coordinates after the pinned import and decorator insertions.""" if STREAMS_TARGET not in baseline or STREAMS_TARGET not in reviewed_transition(root): return baseline def translate(n: int) -> int: # Old __call__ starts at 20. Its new code object starts at the decorator # (21), while the old definition/statement itself moved to line 22. line = abs(n) line += (line >= 11) + (line > 20 or n == 20) return line if n >= 0 else -line entry = dict(baseline[STREAMS_TARGET]) for key in ('lines', 'missing_lines'): entry[key] = sorted(translate(n) for n in entry[key]) for key in ('arcs', 'missing_arcs'): entry[key] = sorted([translate(a), translate(b)] for a, b in entry[key]) return {**baseline, STREAMS_TARGET: entry} def migration(root: Path) -> dict: raw = (root / MAP_FILE).read_bytes() if hashlib.sha256(raw).hexdigest() != MAP_SHA: raise ValueError('backend path migration requires exact reviewed mapping') return json.loads(raw) def has_migration(root: Path) -> bool: if (root / MAP_FILE).is_file(): return True # Historical fixture trees restore the original implementations. A live # migrated tree must never fall back to hashing compatibility imports. if any('sys.modules[__name__] = _implementation' in path.read_text() for path in (root / 'backend').glob('*.py')): raise ValueError('backend path migration mapping is missing') return False def canonical_path(root: Path, name: str) -> Path: if not has_migration(root): return root / name return root / migration(root)['moves'].get(name, name) def reverse_matching_cache_patch(name: str, data: bytes) -> bytes: """Reverse only the exact reviewed 512 -> 4096 cache-capacity change. Retention and eviction timing change; matching results and coverage line/arc coordinates do not. Current execution still has to pass the coverage gate. This adapter does not authorize any other source or algorithm change. """ if name != 'backend/search_matching.py': return data before_sha = 'f90a1fe6d6f690125b5148810f8c1429b4a47dd4cfe85913da66b47cb45c17c6' after_sha = 'fc472396b9ac7c17e19068490b52bee3d4b2440575455f7c48e653662cfa4e93' digest = hashlib.sha256(data).hexdigest() if digest == before_sha: return data # Original historical fixture, still checked by the mapping. if digest != after_sha: raise ValueError('matching cache patch requires exact reviewed source') before = b' if len(masks) >= 512:\n' after = b' if len(masks) >= 4096:\n' if data.count(after) != 1: raise ValueError('matching cache patch requires one exact constant change') restored = data.replace(after, before, 1) if hashlib.sha256(restored).hexdigest() != before_sha: raise ValueError('matching cache patch failed historical reconstruction') return restored def reviewed_source(root: Path, name: str) -> bytes: """Validate reviewed patches, then reconstruct pre-move import text.""" if not has_migration(root): return (root / name).read_bytes() return _reviewed_source(root, name, migration(root), reviewed_transition(root), audit_transition(root), search_perf_transition(root), reader_resource_retirement(root)) def _reviewed_source(root: Path, name: str, manifest: dict, transition: dict, audit: dict, perf: dict, retirement: dict) -> bytes: entry = manifest['sources'].get(name) target = entry['target'] if entry else name if retirement and entry is not None and target in RETIRED_READER_RESOURCE_MODULES: # Only the already pinned, pre-move content rules are needed by the # standalone path proof. Deleted code is never read as a live source. from scripts.check_refactor_coverage import SNAPSHOT_DIR data = (root / SNAPSHOT_DIR / (name + '.snapshot')).read_bytes() if hashlib.sha256(data).hexdigest() != entry['before_sha256']: raise ValueError('backend path migration requires exact reviewed before source: ' + name) return data data = recover_reviewed_parent(target, (root / target).read_bytes(), retirement) data = recover_reviewed_parent(target, data, perf) data = recover_reviewed_parent(target, data, audit) if entry is None: return recover_reviewed_parent(name, data, transition) if name in TRANSITION_ONLY else data data = recover_reviewed_parent(target, data, transition) data = reverse_matching_cache_patch(name, data) # Reconstruct only the reviewed native TIFF allowlist change for historical # coordinates. Runtime and mutation tests still use the actual source. if name == 'backend/app.py' and hashlib.sha256(data).hexdigest() == ( '1e39ffc449a8270470d44e6893608b487bf36c91bdcd1a91aa299cba1caf2214'): data = data.replace(b'"bmp", "webp", "mp3"', b'"bmp", "tif", "tiff", "webp", "mp3"', 1) if hashlib.sha256(data).hexdigest() != entry['after_sha256']: raise ValueError('backend path migration requires exact canonical source: ' + entry['target']) lines = data.decode().splitlines(keepends=True) for number, before, after in entry['imports']: if lines[number - 1] != after or not before.lstrip().startswith('from ') or not after.lstrip().startswith('from '): raise ValueError('backend path migration permits only reviewed import lines') lines[number - 1] = before if 'logger_identity' in entry: expected = [12, 'logger = logging.getLogger(__name__)\n', 'logger = logging.getLogger("backend.search_execution")\n'] if name != 'backend/search_execution.py' or entry['logger_identity'] != expected or lines[11] != expected[2]: raise ValueError('backend path migration requires preserved executor logger identity') lines[11] = expected[1] restored = ''.join(lines).encode() if hashlib.sha256(restored).hexdigest() != entry['before_sha256']: raise ValueError('backend path migration failed source reconstruction: ' + name) return restored def validate_migration(root: Path, *, refactor_before: dict[str, bytes] | None = None) -> None: """Check live sources except overlaps already verified by the no-debt Refactor23 proof.""" _validated_migration_sources(root, migration(root), refactor_before=refactor_before) def _validated_migration_sources(root: Path, manifest: dict, *, refactor_before: dict[str, bytes] | None = None) -> dict[str, bytes]: # Read each checked manifest once per proof; never cache across proofs. sources = reviewed_transition(root) audit = audit_transition(root) perf = search_perf_transition(root) retirement = reader_resource_retirement(root) # Frozen Refactor23 destinations must still validate their live successor. for name in audit.keys() | perf.keys() | retirement.keys(): parent = recover_reviewed_parent(name, (root / name).read_bytes(), retirement) parent = recover_reviewed_parent(name, parent, perf) recover_reviewed_parent(name, parent, audit) before = refactor_before if refactor_before is not None else {} historical = {} for name in sorted(TRANSITION_ONLY & sources.keys()): if name in before: if hashlib.sha256(before[name]).hexdigest() != sources[name]['parent_sha256']: raise ValueError('backend source transition requires exact reviewed parent: ' + name) historical[name] = before[name] else: historical[name] = _reviewed_source(root, name, manifest, sources, audit, perf, retirement) for name, entry in manifest['sources'].items(): if name not in before: historical[name] = _reviewed_source(root, name, manifest, sources, audit, perf, retirement) elif hashlib.sha256(before[name]).hexdigest() != entry['before_sha256']: raise ValueError('backend path migration requires exact reviewed before source: ' + name) else: historical[name] = before[name] if 'compatibility_sha256' in entry: # Here name is the live shim path, not the canonical implementation # reconstructed by _reviewed_source. Preserve the frozen shim hash. compatibility = recover_reviewed_parent(name, (root / name).read_bytes(), perf) compatibility = recover_reviewed_parent(name, compatibility, audit) if hashlib.sha256(compatibility).hexdigest() != entry['compatibility_sha256']: raise ValueError('backend path migration requires exact compatibility import: ' + name) return historical def historical_migration_sources(root: Path, *, refactor_before: dict[str, bytes]) -> dict[str, bytes]: """Validate once and return the reconstructed bytes for a historical fixture.""" return _validated_migration_sources(root, migration(root), refactor_before=refactor_before) def migrate_paths(root: Path, baseline: dict, *, refactor_before: dict[str, bytes] | None = None) -> dict: """Rename debt entries only; every covered/missing line, arc and count survives.""" if not has_migration(root): return baseline manifest = migration(root) _validated_migration_sources(root, manifest, refactor_before=refactor_before) moves = manifest['moves'] result = {} for name, entry in baseline.items(): target = moves.get(name, name) if target in result: raise ValueError('duplicate backend coverage destination: ' + target) result[target] = dict(entry) return result