File size: 19,423 Bytes
29078f2 eeb144a 29078f2 ee872c7 eeb144a 63e3e38 156e872 9bec131 e6e90f2 8c7f11a 929f779 262c3c2 7ffc398 262c3c2 ee872c7 cb3668d 156e872 63e3e38 169f8e1 9bec131 8c7f11a 262c3c2 9bec131 cb3668d 63e3e38 eeb144a 8c62083 e6e90f2 156e872 eeb144a 29078f2 eeb144a 29078f2 eeb144a 8c7f11a 262c3c2 dead914 262c3c2 eeb144a 8c7f11a 262c3c2 8c7f11a eeb144a dead914 9bec131 29078f2 e1833b0 eeb144a dead914 8c7f11a 63e3e38 9bec131 8c7f11a 262c3c2 9bec131 262c3c2 8c7f11a dead914 262c3c2 eeb144a dead914 262c3c2 dead914 eeb144a 169f8e1 8c7f11a 169f8e1 eeb144a dead914 eeb144a dead914 eeb144a dead914 eeb144a dead914 eeb144a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 | """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
|