Reconcile all83 observed Semrush URLs and make complete CI verification independent of PyPI
Rebuild V2 candidate verification / candidate (push) Failing after 1m27s
Rebuild V2 candidate verification / candidate (push) Failing after 1m27s
This commit is contained in:
1 parent
44c5797144
commit
e8cef39175
89 files changed
+110413
-1374
No files matched your search
@@ -14,6 +14,7 @@ from collections import Counter, defaultdict
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
@@ -22,9 +23,17 @@ from urllib.parse import unquote, urldefrag, urljoin, urlsplit, urlunsplit
|
||||
|
||||
try:
|
||||
from bs4 import BeautifulSoup
|
||||
from PIL import Image
|
||||
except ImportError:
|
||||
raise SystemExit("Use .local-run/recovery-env/bin/python; requirements are pinned in scripts/rebuild-v2/requirements.txt")
|
||||
raise SystemExit("Use the pinned recovery Python, or set PYTHONPATH=scripts/rebuild-v2/vendor for offline verification")
|
||||
|
||||
RASTER_DECODER = os.environ.get("VIDEOREG_RASTER_DECODER", "pillow")
|
||||
if RASTER_DECODER not in ("pillow", "sharp"):
|
||||
raise SystemExit("VIDEOREG_RASTER_DECODER must be pillow or sharp; raster validation cannot be disabled")
|
||||
if RASTER_DECODER == "pillow":
|
||||
try:
|
||||
from PIL import Image, ImageSequence
|
||||
except ImportError:
|
||||
raise SystemExit("Pillow is required for the default local decoder; use explicit VIDEOREG_RASTER_DECODER=sharp in offline CI")
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
INTERNAL_HOSTS = {"videoreg.ru", "www.videoreg.ru"}
|
||||
@@ -286,6 +295,34 @@ def main():
|
||||
inventory = read_json(args.inventory, [])
|
||||
legacy = read_json(ROOT / "deploy/legacy-routes.json", {})
|
||||
errors = [{"kind": "export-file-outside-root", "file": x} for x in unsafe_files]
|
||||
repository_git = subprocess.run(["git", "rev-parse", "HEAD"], cwd=ROOT, capture_output=True, text=True)
|
||||
repository_head = repository_git.stdout.strip()
|
||||
built_health = {}
|
||||
try:
|
||||
built_health_path = confined(out / "health/ready", out)
|
||||
if built_health_path is not None:
|
||||
built_health = read_json(built_health_path, {})
|
||||
except (ValueError, OSError) as exc:
|
||||
errors.append(dict(kind="invalid-built-health-metadata", error=str(exc)))
|
||||
metadata = built_health.get("metadata", {}) if isinstance(built_health, dict) else {}
|
||||
built_revision = metadata.get("commitSha") if isinstance(metadata, dict) else None
|
||||
built_source_files = []
|
||||
built_source_manifest = None
|
||||
if not isinstance(built_revision, str) or not re.fullmatch(r"[0-9a-f]{40}", built_revision):
|
||||
errors.append(dict(kind="missing-built-source-revision", value=built_revision))
|
||||
else:
|
||||
# A later docs/tooling commit is not the source revision of an already
|
||||
# built candidate. Compare actual active sources to that Git snapshot.
|
||||
for source in source_before:
|
||||
result = subprocess.run(["git", "show", built_revision + ":" + source["path"]], cwd=ROOT, capture_output=True)
|
||||
if result.returncode:
|
||||
errors.append(dict(kind="built-source-unavailable-in-git", revision=built_revision, file=source["path"]))
|
||||
else:
|
||||
built_source_files.append(dict(path=source["path"], sha256=sha(result.stdout)))
|
||||
if len(built_source_files) == len(source_before):
|
||||
built_source_manifest = manifest_hash(built_source_files)
|
||||
if built_source_manifest != manifest_hash(source_before):
|
||||
errors.append(dict(kind="current-app-source-differs-from-built-revision", builtRevision=built_revision, builtSourceManifestSha256=built_source_manifest, actualSourceManifestSha256=manifest_hash(source_before)))
|
||||
warnings = []
|
||||
responses = {}
|
||||
http_checks = []
|
||||
@@ -329,6 +366,15 @@ def main():
|
||||
http_checks.append(dict(url=url, method=method, status=status, curlReturncode=result.returncode, bytes=len(content), location=headers.get("location"), contentType=headers.get("content-type")))
|
||||
return value
|
||||
|
||||
live_health_response = request("/health/ready")
|
||||
live_health = None
|
||||
try:
|
||||
live_health = json.loads(live_health_response["body"])
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
if live_health_response["status"] != 200 or live_health != built_health:
|
||||
errors.append(dict(kind="live-built-health-identity-mismatch", status=live_health_response["status"], expected=built_health, actual=live_health))
|
||||
|
||||
pages = []
|
||||
occurrences = []
|
||||
script_constants = []
|
||||
@@ -361,19 +407,42 @@ def main():
|
||||
errors.append(dict(kind="empty-export-no-html"))
|
||||
|
||||
# Decode every exported raster asset, including unlinked public files.
|
||||
# Files are confined above; PIL verification never executes image content.
|
||||
for entry in before:
|
||||
path = out / entry["path"]
|
||||
if path.suffix.lower() in (".png", ".jpg", ".jpeg", ".gif", ".webp", ".ico"):
|
||||
# Both explicit decoders fail closed; there is no "skip images" fallback.
|
||||
raster_entries = [entry for entry in before if Path(entry["path"]).suffix.lower() in (".png", ".jpg", ".jpeg", ".gif", ".webp", ".ico")]
|
||||
if RASTER_DECODER == "sharp":
|
||||
result = subprocess.run(["node", str(ROOT / "scripts/rebuild-v2/decode-raster-sharp.mjs")], cwd=ROOT,
|
||||
input=json.dumps(dict(root=str(out), files=[e["path"] for e in raster_entries])).encode(), capture_output=True)
|
||||
try:
|
||||
decoded = json.loads(result.stdout)
|
||||
decoded_rows = decoded["results"]
|
||||
if [item.get("file") for item in decoded_rows] != [e["path"] for e in raster_entries]:
|
||||
raise ValueError("Sharp did not return every requested raster in order")
|
||||
for entry, item in zip(raster_entries, decoded_rows):
|
||||
item["sha256"] = entry["sha256"]
|
||||
asset_checks.append(item)
|
||||
if not item.get("valid"):
|
||||
errors.append(dict(kind="invalid-raster-image", file=entry["path"], error=item.get("error"), decoder="sharp"))
|
||||
if result.returncode and not any(not item.get("valid") for item in decoded_rows):
|
||||
errors.append(dict(kind="raster-decoder-process-failed", decoder="sharp", returncode=result.returncode, error=result.stderr.decode(errors="replace")[:2000]))
|
||||
except (ValueError, KeyError, TypeError) as exc:
|
||||
errors.append(dict(kind="raster-decoder-failed", decoder="sharp", error=str(exc), stderr=result.stderr.decode(errors="replace")[:2000]))
|
||||
else:
|
||||
for entry in raster_entries:
|
||||
path = out / entry["path"]
|
||||
try:
|
||||
with Image.open(path) as image:
|
||||
width, height = image.size
|
||||
image.verify()
|
||||
asset_checks.append(dict(file=entry["path"], type="raster", valid=True, width=width, height=height, sha256=entry["sha256"]))
|
||||
with Image.open(path) as image:
|
||||
for frame in ImageSequence.Iterator(image):
|
||||
frame.load()
|
||||
asset_checks.append(dict(file=entry["path"], type="raster", valid=True, width=width, height=height, sha256=entry["sha256"], decoder="pillow-verify-and-full-load"))
|
||||
except Exception as exc:
|
||||
asset_checks.append(dict(file=entry["path"], type="raster", valid=False, error=str(exc)))
|
||||
asset_checks.append(dict(file=entry["path"], type="raster", valid=False, error=str(exc), decoder="pillow"))
|
||||
errors.append(dict(kind="invalid-raster-image", file=entry["path"], error=str(exc)))
|
||||
elif path.suffix.lower() == ".pdf":
|
||||
for entry in before:
|
||||
path = out / entry["path"]
|
||||
if path.suffix.lower() == ".pdf":
|
||||
data = path.read_bytes()
|
||||
valid = b"%PDF-" in data[:1024] and b"%%EOF" in data[-2048:]
|
||||
asset_checks.append(dict(file=entry["path"], type="pdf-signature-and-eof", valid=valid, sha256=entry["sha256"]))
|
||||
@@ -546,8 +615,7 @@ def main():
|
||||
errors.append(dict(kind="build-mutated-during-check"))
|
||||
if source_before != source_after:
|
||||
errors.append(dict(kind="source-mutated-during-check"))
|
||||
git = subprocess.run(["git", "rev-parse", "HEAD"], cwd=ROOT, capture_output=True, text=True)
|
||||
report = dict(schemaVersion=1, domain="videoreg.ru", generatedAt=datetime.now(timezone.utc).isoformat(), sourceCommit=git.stdout.strip(), sourceManifestSha256=manifest_hash(source_before), sourceFiles=source_before, exportManifestSha256=manifest_hash(before), exportFileCount=len(before), base=base, origin=args.origin, tlsVerified=False if args.insecure_origin else (True if base.startswith("https://") and all(x["curlReturncode"] == 0 for x in http_checks) else None), browserDOMInspection="not performed by this script; use separate exact-candidate browser evidence", summary=dict(technicalStatus="failed" if errors else "passed", restorationStatus="blocked-unresolved-inventory" if unresolved else "reconciled", acceptance="blocked" if errors or unresolved else "mechanical-checks-only-not-role-approval", htmlFiles=len(pages), contentPages=sum(not p["errorDocument"] for p in pages), HTTPRequests=len(http_checks), localReferences=len(local_refs), emittedExternalOccurrences=len(outbound), activeSourceFiles=len(source_files), inventoryItems=len(inventory), unresolvedInventoryItems=len(unresolved), suspiciousPages=len(warnings), errors=len(errors), decodedRasterAssets=sum(x["type"] == "raster" for x in asset_checks)), pages=pages, assetChecks=asset_checks, duplicateBodies=duplicates, suspiciousCandidates=warnings, errors=errors, localReferences=local_refs, outboundOccurrences=outbound, inertScriptConstants=script_constants, activeSourceReferences=active_occurrences, HTTPChecks=http_checks, legacyRoutes=legacy_results, sourcePublications=source_publications, behavior=behavior, coverage=dict(statusCounts=dict(Counter(x["status"] for x in inventory_results)), items=inventory_results, unresolved=unresolved), limitations=["No external page is fetched by this checker; approvals must contain independent editorial verification.", "HTML/CSS/script-string extraction detects static references. Live JavaScript interactions, crops and browser DOM are checked separately.", "Suspicious thin/spam/error flags require per-page editorial assessment; they are not automatically treated as spam exclusions.", "A reconciled inventory does not establish that the external discovery denominator is complete."])
|
||||
report = dict(schemaVersion=1, domain="videoreg.ru", generatedAt=datetime.now(timezone.utc).isoformat(), sourceCommit=built_revision, repositoryHead=repository_head, builtHealthMetadata=built_health, builtSourceManifestSha256=built_source_manifest, rasterDecoder=RASTER_DECODER, sourceManifestSha256=manifest_hash(source_before), sourceFiles=source_before, exportManifestSha256=manifest_hash(before), exportFileCount=len(before), base=base, origin=args.origin, tlsVerified=False if args.insecure_origin else (True if base.startswith("https://") and all(x["curlReturncode"] == 0 for x in http_checks) else None), browserDOMInspection="not performed by this script; use separate exact-candidate browser evidence", summary=dict(technicalStatus="failed" if errors else "passed", restorationStatus="blocked-unresolved-inventory" if unresolved else "reconciled", acceptance="blocked" if errors or unresolved else "mechanical-checks-only-not-role-approval", htmlFiles=len(pages), contentPages=sum(not p["errorDocument"] for p in pages), HTTPRequests=len(http_checks), localReferences=len(local_refs), emittedExternalOccurrences=len(outbound), activeSourceFiles=len(source_files), inventoryItems=len(inventory), unresolvedInventoryItems=len(unresolved), suspiciousPages=len(warnings), errors=len(errors), decodedRasterAssets=sum(x["type"] == "raster" for x in asset_checks)), pages=pages, assetChecks=asset_checks, duplicateBodies=duplicates, suspiciousCandidates=warnings, errors=errors, localReferences=local_refs, outboundOccurrences=outbound, inertScriptConstants=script_constants, activeSourceReferences=active_occurrences, HTTPChecks=http_checks, legacyRoutes=legacy_results, sourcePublications=source_publications, behavior=behavior, coverage=dict(statusCounts=dict(Counter(x["status"] for x in inventory_results)), items=inventory_results, unresolved=unresolved), limitations=["No external page is fetched by this checker; approvals must contain independent editorial verification.", "HTML/CSS/script-string extraction detects static references. Live JavaScript interactions, crops and browser DOM are checked separately.", "Suspicious thin/spam/error flags require per-page editorial assessment; they are not automatically treated as spam exclusions.", "A reconciled inventory does not establish that the external discovery denominator is complete."])
|
||||
args.report.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.report.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
||||
print(json.dumps(dict(report=str(args.report.relative_to(ROOT) if args.report.is_relative_to(ROOT) else args.report), **report["summary"]), ensure_ascii=False))
|
||||
|
||||
Reference in new issue
Block a user