compatibility.py

cdk-rsx/tools/compatibility.py

compatibility.py466 lines← SDK documentation
1"""Exact build-time compatibility payloads and actual-Wasm inventory checks.23These helpers never qualify an implementation or authorize a runtime catalog.4The approved registry contains immutable, reviewed qualification references.5"""6import hashlib7import json8import os9from pathlib import Path10import re11import tarfile12import tomllib131415ALIASES_FORMAT = "cdk-rsx-compat-aliases-v1"16INVENTORY_FORMAT = "cdk-rsx-policy-inputs-v1"17REGISTRY_FORMAT = "cdk-rsx-compat-registry-v1"18APPROVAL_FORMAT = "cdk-rsx-compat-approval-v1"19MAX_ENTRIES = 16_38420MAX_DOCUMENT_BYTES = 8 * 1024 * 102421TARGETS = ("wasm32-unknown-unknown", "wasm64-unknown-unknown")22HEX = re.compile(r"[0-9a-f]{64}\Z")23FIELDS = {"context", "scope", "raw", "identity"}24PACKAGE_ROOTS_ENV = "CDK_RSX_COMPAT_PACKAGE_ROOTS"25CRATES_IO = {"registry+https://github.com/rust-lang/crates.io-index",26             "sparse+https://index.crates.io/"}27PACKAGE_RECIPES = {"cdk-rsx-engine-hylix-derive", "cdk-rsx-engine-nyxus-derive",28                   "cdk-rsx-store-derive", "cdk-rsx-wire"}293031def canonical_bytes(document):32    return (json.dumps(document, sort_keys=True, separators=(",", ":"), ensure_ascii=True) + "\n").encode()333435def sha256_file(path):36    with Path(path).open("rb") as stream:37        return hashlib.file_digest(stream, "sha256").hexdigest()383940def verify_package_source(directory, archive):41    """Bind the exact source Cargo selected to the checksum-verified archive."""42    inputs = set()43    with tarfile.open(archive, "r:gz") as bundle:44        for member in bundle:45            parts = member.name.split("/")46            if (parts[0] != archive.stem or any(part in ("", ".", "..") for part in parts)47                    or not (member.isfile() or member.isdir())):48                raise ValueError(f"invalid SDK package archive entry: {member.name}")49            if member.isdir():50                continue51            if len(parts) == 1:52                raise ValueError(f"invalid SDK package archive file: {member.name}")53            path = directory.joinpath(*parts[1:])54            if path in inputs or path.resolve(strict=True) != path or not path.is_file():55                raise ValueError(f"invalid SDK package source file: {path}")56            with bundle.extractfile(member) as source:57                expected = hashlib.file_digest(source, "sha256").hexdigest()58            if sha256_file(path) != expected:59                raise ValueError(f"SDK package source differs from its locked archive: {path}")60            inputs.add(path)61    if directory / "Cargo.toml" not in inputs:62        raise ValueError(f"SDK package archive lacks Cargo.toml: {archive}")63    actual = set()64    for current, children, names in os.walk(directory):65        current = Path(current)66        for child in [*children, *names]:67            path = current / child68            if path.is_symlink():69                raise ValueError(f"SDK package source contains a symlink: {path}")70        actual.update(current / name for name in names)71    actual.difference_update({directory / ".cargo-ok", directory / ".cargo-checksum.json"})72    if actual != inputs:73        raise ValueError(f"SDK package files differ from its locked archive: {directory}")74    return inputs757677def verified_sdk_packages(metadata, tool_metadata, sdk, cargo_home, archives=None):78    """Find Cargo's SDK package owners; path and foreign registry sources are ineligible."""79    sdk = Path(sdk).resolve()80    members = set(tool_metadata.get("workspace_members", ()))81    names = {}82    for package in tool_metadata["packages"]:83        if package["id"] not in members or package.get("source") is not None:84            continue85        directory = Path(package["manifest_path"]).resolve().parent86        if directory.is_relative_to(sdk / "crates") and package.get("repository"):87            names[package["name"]] = (package["repository"], directory.relative_to(sdk).as_posix())88    lock = Path(metadata["workspace_root"]) / "Cargo.lock"89    checksums = {(package["name"], package["version"], package.get("source")): package.get("checksum")90                 for package in tomllib.loads(lock.read_text()).get("package", [])}91    resolved = {node["id"] for node in metadata["resolve"]["nodes"]}92    roots, records, inputs = {}, [], set()93    for package in metadata["packages"]:94        name, version, source = package["name"], package["version"], package.get("source")95        if (package["id"] not in resolved or source not in CRATES_IO or name not in names96                or package.get("repository") != names[name][0]):97            continue98        checksum = _hash(checksums.get((name, version, source)), "locked SDK package checksum")99        filename = f"{name}-{version}.crate"100        if archives is not None:101            candidates = [archives / filename]102            if not candidates[0].is_file():103                raise ValueError(f"locked SDK package archive is missing: {candidates[0]}")104        else:105            candidates = sorted((Path(cargo_home) / "registry/cache").glob(f"*/{filename}"))106        archive = next((path for path in candidates if path.is_file() and sha256_file(path) == checksum), None)107        if archive is None:108            if candidates:109                raise ValueError(f"SDK package archive checksum differs from Cargo.lock: {candidates[0]}")110            # A source replacement can support ordinary builds without an111            # archive. Its leaves remain raw until the archive is supplied.112            continue113        manifest = Path(package["manifest_path"])114        directory = manifest.resolve(strict=True).parent115        if manifest != directory / "Cargo.toml":116            raise ValueError(f"SDK package manifest is not canonical: {manifest}. "117                             "Use a physical copy of the verified archive sources for the Cargo directory source.")118        owned = verify_package_source(directory, archive.resolve())119        scope = names[name][1]120        roots[str(directory)] = scope121        inputs.add(archive.resolve())122        inputs.update(owned)123        archive_record = {"path": str(archive.resolve()), "bytes": archive.stat().st_size, "sha256": checksum}124        records.append({"name": name, "version": version, "source": source,125                        "archive": archive_record, "root": str(directory), "scope": scope})126    return roots, sorted(records, key=canonical_bytes), sorted(inputs)127128129def _pairs(pairs):130    result = {}131    for key, value in pairs:132        if key in result:133            raise ValueError(f"duplicate JSON field: {key}")134        result[key] = value135    return result136137138def load_document(path):139    raw = Path(path).read_bytes()140    if len(raw) > MAX_DOCUMENT_BYTES:141        raise ValueError(f"compatibility document exceeds byte bound: {path}")142    def invalid_constant(value):143        raise ValueError(f"non-JSON numeric constant: {value}")144    return json.loads(raw, object_pairs_hook=_pairs, parse_constant=invalid_constant)145146147def _fields(document, expected, label):148    if not isinstance(document, dict) or set(document) != set(expected):149        raise ValueError(f"invalid {label} fields")150151152def _hash(value, label):153    if not isinstance(value, str) or not HEX.fullmatch(value):154        raise ValueError(f"invalid {label}: expected lowercase SHA-256 hex")155    return value156157158def eligible_scope(scope):159    if not isinstance(scope, str) or len(scope.encode()) > 2048:160        return False161    if scope == "recipe/cdk-rsx-source-policy":162        return True163    if scope.startswith("recipe/package/") and scope.removeprefix("recipe/package/") in PACKAGE_RECIPES:164        return True165    if scope in {f"compiler/{target}" for target in TARGETS}:166        return True167    if not scope.startswith("sdk/crates/") or ":" not in scope:168        return False169    caller, names = scope.removeprefix("sdk/").split(":", 1)170    parts = caller.split("/")171    if (len(parts) < 4 or any(part in ("", ".", "..") for part in parts)172            or not caller.endswith(".rs")173            or not (parts[1] == "cdk-rsx" or parts[1].startswith("cdk-rsx-"))174            or not re.fullmatch(r"[A-Za-z0-9_./-]+", caller)):175        return False176    return bool(names and re.fullmatch(r"[A-Za-z0-9_./,-]+", names)177                and all(name and not name.startswith("/") for name in names.split(",")))178179180def _entries(document, format):181    _fields(document, ("format", "entries"), format)182    if document["format"] != format or not isinstance(document["entries"], list):183        raise ValueError(f"invalid {format} document")184    if len(document["entries"]) > MAX_ENTRIES:185        raise ValueError("compatibility entry bound exceeded")186    found = {}187    for row in document["entries"]:188        _fields(row, FIELDS, "compatibility entry")189        if not eligible_scope(row["scope"]):190            raise ValueError(f"ineligible compatibility scope: {row['scope']}")191        for key in ("context", "raw", "identity"):192            _hash(row[key], key)193        key = (row["context"], row["scope"], row["raw"])194        if key in found and found[key] != row:195            raise ValueError(f"conflicting compatibility identity: {key}")196        found[key] = dict(row)197    return [found[key] for key in sorted(found)]198199200def validate_aliases(document):201    rows = _entries(document, ALIASES_FORMAT)202    by_key = {(row["context"], row["scope"], row["raw"]): row["identity"] for row in rows}203    for row in rows:204        if row["context"] == "0" * 64:205            raise ValueError("alias context cannot be the unqualified zero sentinel")206        target = (row["context"], row["scope"], row["identity"])207        if target in by_key and by_key[target] != row["identity"]:208            raise ValueError("compatibility aliases cannot form chains or cycles")209    return {"format": ALIASES_FORMAT, "entries": rows}210211212def merge_aliases(*documents):213    rows = []214    for document in documents:215        rows.extend(validate_aliases(document)["entries"])216    return validate_aliases({"format": ALIASES_FORMAT, "entries": rows})217218219def validate_inventory(document, aliases, *, context=None, target=None):220    rows = _entries(document, INVENTORY_FORMAT)221    approved = validate_aliases(aliases)222    mapping = {(row["context"], row["scope"], row["raw"]): row["identity"]223               for row in approved["entries"]}224    if context is not None:225        _hash(context, "inventory context")226        if context == "0" * 64 or any(row["context"] != context for row in rows):227            raise ValueError("actual Wasm compatibility context differs from canonical build")228    for row in rows:229        expected = mapping.get((row["context"], row["scope"], row["raw"]), row["raw"])230        if row["identity"] != expected:231            raise ValueError(f"actual Wasm identity differs from exact alias payload: {row['scope']}")232    if target is not None:233        if target not in TARGETS:234            raise ValueError(f"unsupported compatibility target: {target}")235        scopes = {row["scope"] for row in rows}236        if f"compiler/{target}" not in scopes or "recipe/cdk-rsx-source-policy" not in scopes:237            raise ValueError("rooted artifact lacks compiler or source-policy producer inventory")238        if any(scope.startswith("compiler/") and scope != f"compiler/{target}" for scope in scopes):239            raise ValueError("actual Wasm inventory contains a different compiler target")240    return {"format": INVENTORY_FORMAT, "entries": rows}241242243def _relative_file(base, value):244    if not isinstance(value, str) or not value or Path(value).is_absolute():245        raise ValueError("registry record paths must be relative")246    path = (base / value).resolve(strict=True)247    if not path.is_relative_to(base.resolve()):248        raise ValueError("registry record escapes its directory")249    return path250251252def _checked_file(path, expected, inputs):253    _hash(expected, "referenced file hash")254    if sha256_file(path) != expected:255        raise ValueError(f"compatibility evidence hash differs: {path}")256    inputs.add(Path(path).resolve())257    return load_document(path)258259260def _evidence(record, base, inputs):261    if not isinstance(record, dict) or not {"path", "sha256"} <= record.keys():262        raise ValueError("invalid compatibility evidence reference")263    path = _relative_file(base, record["path"])264    document = _checked_file(path, record["sha256"], inputs)265    if "bytes" in record and record["bytes"] != path.stat().st_size:266        raise ValueError(f"compatibility evidence size differs: {path}")267    return document268269270def load_registry(path):271    """Return the merged semantic payload and compact original tracked inputs.272273    Approval pins are checked here; qualification execution/review belongs to274    qualify-compat.py. Large evidence binaries are not copied into build sources.275    """276    path = Path(path).resolve(strict=True)277    registry = load_document(path)278    _fields(registry, ("format", "qualifications"), "compatibility registry")279    if registry["format"] != REGISTRY_FORMAT or not isinstance(registry["qualifications"], list):280        raise ValueError("invalid compatibility registry")281    if len(registry["qualifications"]) > MAX_ENTRIES:282        raise ValueError("compatibility qualification bound exceeded")283    inputs, documents = {path}, []284    for row in registry["qualifications"]:285        _fields(row, ("aliases", "sha256", "approval", "approval_sha256"), "registry row")286        aliases_path = _relative_file(path.parent, row["aliases"])287        aliases = _checked_file(aliases_path, row["sha256"], inputs)288        validate_aliases(aliases)289        approval_path = _relative_file(path.parent, row["approval"])290        approval = _checked_file(approval_path, row["approval_sha256"], inputs)291        required = {"format", "status", "aliases_sha256", "qualification", "review", "artifacts", "evidence"}292        if (not isinstance(approval, dict) or not required <= approval.keys()293                or approval["format"] != APPROVAL_FORMAT or approval["status"] != "approved"294                or approval["aliases_sha256"] != row["sha256"]):295            raise ValueError(f"unapproved or mismatched compatibility qualification: {approval_path}")296        pins = approval["artifacts"]297        if not isinstance(pins, dict) or pins.get("target") not in TARGETS:298            raise ValueError("invalid compatibility artifact target pins")299        for name in ("baseline_sha256", "candidate_sha256"):300            _hash(pins.get(name), name)301        if not isinstance(approval["evidence"], list) or not approval["evidence"]:302            raise ValueError("compatibility approval lacks evidence references")303        report = _evidence(approval["qualification"], approval_path.parent, inputs)304        review = _evidence(approval["review"], approval_path.parent, inputs)305        if (not isinstance(report, dict) or report.get("format") != "cdk-rsx-compat-qualification-v1"306                or report.get("status") != "passed"307                or not isinstance(report.get("aliases"), dict)308                or report["aliases"].get("sha256") != row["sha256"]):309            raise ValueError("compatibility qualification report did not pass")310        changes = report.get("changes")311        changed = validate_aliases({"format": ALIASES_FORMAT, "entries": changes})["entries"]312        allowed = {canonical_bytes(entry) for entry in aliases["entries"]}313        if any(canonical_bytes(entry) not in allowed for entry in changed):314            raise ValueError("qualification changes differ from approved aliases")315        artifacts = report.get("artifacts", {})316        if (any(not isinstance(artifacts.get(role), dict)317                or artifacts[role].get("sha256") != pins[role + "_sha256"]318                for role in ("baseline", "candidate"))319                or report.get("candidate", {}).get("configuration", {}).get("target") != pins["target"]):320            raise ValueError("qualification artifact pins differ from approval")321        if (not isinstance(review, dict) or review.get("format") != "cdk-rsx-compat-review-v1"322                or not isinstance(review.get("reviewer"), str) or not review["reviewer"].strip()323                or review.get("common_class_invariant") is not True324                or not isinstance(review.get("scopes"), list) or len(review["scopes"]) != len(changes)):325            raise ValueError("compatibility approval lacks explicit interpretation review")326        for reviewed, entry in zip(review["scopes"], changes):327            if (not isinstance(reviewed, dict) or any(reviewed.get(key) != value for key, value in entry.items())328                    or any(not isinstance(reviewed.get(key), str) or not reviewed[key].strip()329                           for key in ("unchanged_read_interpretation", "unchanged_write_interpretation"))):330                raise ValueError("compatibility interpretation review scope differs")331        documents.append(aliases)332    return merge_aliases(*documents), sorted(inputs)333334335def build_context(metadata, target, rustflags, compiler, tooling):336    """Hash target, effective flags/compiler facts and resolved feature closure.337338    Cargo package IDs resolve nodes only; physical paths/IDs never enter the339    context. Keep the complete (unfiltered) metadata closure conservative.340    """341    if target not in TARGETS:342        raise ValueError(f"unsupported compatibility target: {target}")343    _hash(tooling, "tooling fingerprint")344    packages = {package["id"]: package for package in metadata["packages"]}345    if not isinstance(metadata.get("resolve"), dict) or "nodes" not in metadata["resolve"]:346        raise ValueError("compatibility context requires resolved Cargo feature metadata")347    closure = []348    for node in metadata["resolve"]["nodes"]:349        package = packages[node["id"]]350        closure.append({"name": package["name"], "version": package["version"],351                        "features": sorted(node["features"])})352    # A remap's physical origin is deliberately absent from this portable353    # context; its logical destination and all other effective flags remain.354    flags = ["--remap-path-prefix=<source>=" + flag.rsplit("=", 1)[1]355             if flag.startswith("--remap-path-prefix=") else flag for flag in rustflags]356    facts = {"format": "cdk-rsx-compat-context-v1", "target": target,357             "rustflags": flags, "compiler": compiler, "tooling": tooling,358             "packages": sorted(closure, key=canonical_bytes)}359    return hashlib.sha256(canonical_bytes(facts)).hexdigest(), facts360361362def tooling_fingerprint(documents, sdk, *, excluded=()):363    """Conservative producer/build/startup closure, independent of alias data.364365    Registry packages retain lock checksums/source/features/dependency edges.366    Local proc macros and SDK ABI/startup tools retain exact production file367    bytes and their local helper closure. No application implementation or its368    local feature list, registry approval data or output path enters this hash.369    """370    sdk = Path(sdk).resolve()371    excluded = [Path(path).resolve() for path in372                (*excluded, sdk / "target", sdk / "tmp", sdk / ".rustup", sdk / ".cargo-home")]373    inputs, lock_packages = set(), {}374    for document in documents:375        lock = Path(document["workspace_root"]) / "Cargo.lock"376        inputs.add(lock.resolve(strict=True))377        for package in tomllib.loads(lock.read_text()).get("package", []):378            if "source" in package:379                key = (package["name"], package["version"], package["source"])380                checksum = package.get("checksum")381                if key in lock_packages and lock_packages[key] != checksum:382                    raise ValueError(f"conflicting locked tooling dependency: {key}")383                lock_packages[key] = checksum384385    registry, local_files, local_edges, local_packages = {}, {}, set(), {}386    for document in documents:387        packages = {package["id"]: package for package in document["packages"]}388        nodes = {node["id"]: node for node in document["resolve"]["nodes"]}389390        def identity(package):391            return {"name": package["name"], "version": package["version"], "source": package.get("source")}392393        for key, node in nodes.items():394            package = packages[key]395            if package.get("source") is None:396                continue397            record = identity(package)398            lock_key = (package["name"], package["version"], package["source"])399            if lock_key not in lock_packages:400                raise ValueError(f"resolved tooling dependency absent from lock: {lock_key}")401            checksum = lock_packages[lock_key]402            if package["source"].startswith("registry+"):403                _hash(checksum, "locked dependency checksum")404            record.update(checksum=checksum, features=sorted(node["features"]),405                          dependencies=sorted([identity(packages[dep]) for dep in node["dependencies"]], key=canonical_bytes))406            registry[canonical_bytes(record)] = record407408        roots = [key for key, package in packages.items() if package.get("source") is None409                 and (any("proc-macro" in target["kind"] for target in package["targets"])410                      or package["name"] in ("cdk-rsx-memory-abi", "cdk-rsx-wasm"))]411        visited, pending = set(), roots412        while pending:413            key = pending.pop()414            if key in visited:415                continue416            visited.add(key)417            package = packages[key]418            if package.get("source") is not None:419                continue420            directory = Path(package["manifest_path"]).resolve().parent421            selected_package = dict(identity(package), features=sorted(nodes[key]["features"]))422            local_packages[canonical_bytes(selected_package)] = selected_package423            origin = (directory.relative_to(sdk).as_posix() if directory.is_relative_to(sdk)424                      else "path-package/" + package["name"] + "/" + package["version"])425            # Conservative package inputs, including future include!/template426            # assets. Keep the same cache exclusions as canonical snapshots;427            # tests/docs also enter this tooling qualification, intentionally.428            paths = set()429            for current, directories, names in os.walk(directory):430                current = Path(current)431                directories[:] = sorted(name for name in directories if name not in432                    (".git", ".rustup", ".cargo-home", "node_modules", "__pycache__", "target", "tmp")433                    and not any((current / name).resolve().is_relative_to(path) for path in excluded))434                if any((current / name).is_symlink() for name in directories):435                    raise ValueError(f"unqualified tooling source directory symlink: {current}")436                paths.update(current / name for name in names437                             if not name.endswith((".pyc", ".pyo")) and (current / name).is_file()438                             and not any((current / name).resolve().is_relative_to(path) for path in excluded))439            for path in sorted(paths):440                if path.is_symlink():441                    raise ValueError(f"unqualified tooling source symlink: {path}")442                raw = path.read_bytes()443                label = origin + "/" + path.relative_to(directory).as_posix()444                record = {"name": label, "bytes": len(raw), "sha256": hashlib.sha256(raw).hexdigest()}445                if label in local_files and local_files[label] != record:446                    raise ValueError(f"ambiguous local tooling package identity: {label}")447                local_files[label] = record448                inputs.add(path)449            for dependency in nodes[key]["dependencies"]:450                child = packages[dependency]451                local_edges.add(canonical_bytes({"from": identity(package), "to": identity(child)}))452                if child.get("source") is None:453                    pending.append(dependency)454455    for relative in ("tools/build-app.py", "tools/wire_runtime.py", "tools/compatibility.py", "tools/env.sh"):456        path = sdk / relative457        raw = path.read_bytes()458        local_files[relative] = {"name": relative, "bytes": len(raw), "sha256": hashlib.sha256(raw).hexdigest()}459        inputs.add(path)460    facts = {"format": "cdk-rsx-compat-tooling-v1",461             "scope": "Conservative registry closure and complete local producer/ABI/startup package inputs, including tests/docs/assets; not inferred semantic equivalence",462             "registry_packages": [registry[key] for key in sorted(registry)],463             "local_packages": [local_packages[key] for key in sorted(local_packages)],464             "local_files": [local_files[key] for key in sorted(local_files)],465             "local_edges": [json.loads(raw) for raw in sorted(local_edges)]}466    return hashlib.sha256(canonical_bytes(facts)).hexdigest(), facts, sorted(inputs)