build-app.py

cdk-rsx/tools/build-app.py

build-app.py838 lines← SDK documentation
1#!/usr/bin/env python32"""Build one cdk-rsx application and its descriptor-derived Wire interface.34Application/SDK inputs must stay fixed for the complete pipeline. Advisory locks5coordinate cooperating builders, not bare Cargo commands or source edits. Named6outputs are replaceable; readers need the destination lock or their own snapshot.7"""89import argparse10import base6411from collections import defaultdict12from contextlib import contextmanager, ExitStack13import fcntl14import gzip15import hashlib16import json17import os18from pathlib import Path19import shlex20import shutil21import signal22import subprocess23import sys24import tempfile25import time26import tomllib2728SDK = Path(__file__).resolve().parents[1]29if str(SDK / "tools") not in sys.path:30    sys.path.insert(0, str(SDK / "tools"))31from compatibility import (PACKAGE_ROOTS_ENV, build_context, canonical_bytes, load_document,32                           load_registry, merge_aliases, tooling_fingerprint, validate_inventory,33                           verified_sdk_packages)34from wire_runtime import node_identity, transform as transform_wire_runtime35WASM_TARGET = "wasm64-unknown-unknown"36BUILD_STD_CRATES = "std,panic_abort"37WASM_TARGETS = (WASM_TARGET, "wasm32-unknown-unknown")383940def lock_path(directory, *identity):41    """One registry for physical output namespaces, independent of features/pkg."""42    digest = hashlib.sha256(json.dumps(identity).encode()).hexdigest()43    return Path(directory).resolve() / ".cdk-rsx-build-locks" / f"{digest}.lock"444546def library_lock(target_directory, name):47    # One gate covers native and Wasm release library outputs.48    return lock_path(target_directory, "release", "library", name)495051@contextmanager52def locked(paths):53    """Close our references, never unlink/unlock an inode still held by a child."""54    with ExitStack() as stack:55        descriptors = []56        for path in sorted(set(paths)):57            path.parent.mkdir(parents=True, exist_ok=True)58            handle = stack.enter_context(path.open("a+b"))59            fcntl.flock(handle, fcntl.LOCK_EX)60            descriptors.append(handle.fileno())61        yield tuple(descriptors)626364def materialize_compatibility_aliases(target_directory, payload):65    """Keep the tracked alias-file path stable for identical semantic bytes.6667    Cache entries are immutable build outputs, not source/approval evidence.68    Publish a complete private file by exclusive link; never replace a hit.69    """70    target_directory = Path(target_directory).resolve()71    digest = hashlib.sha256(payload).hexdigest()72    directory = target_directory / ".cdk-rsx-compat-aliases"73    destination = directory / f"{digest}.json"7475    def verify():76        if (destination.is_symlink() or not destination.is_file()77                or destination.read_bytes() != payload):78            raise ValueError(f"compatibility alias cache differs from its digest: {destination}")7980    with locked([lock_path(target_directory, "compatibility-aliases", digest)]):81        if directory.is_symlink():82            raise ValueError(f"compatibility alias cache cannot be a symlink: {directory}")83        directory.mkdir(parents=True, exist_ok=True)84        if destination.exists() or destination.is_symlink():85            verify()86            return destination87        with tempfile.TemporaryDirectory(prefix=".publish-", dir=directory) as temporary:88            staged = Path(temporary) / "aliases.json"89            staged.write_bytes(payload)90            try:91                os.link(staged, destination)92            except FileExistsError:93                pass  # An immutable concurrent publication must still match.94            verify()95    return destination969798def execute(argv, *, cwd, env, capture=False, capture_stderr=False, pass_fds=()):99    # Shared-path writers retain the same open-file-description locks if this100    # Python process is killed. Normal cancellation kills/reaps its process group.101    command = list(map(str, argv))102    with subprocess.Popen(command, cwd=cwd, env=env, text=True, pass_fds=pass_fds,103                          start_new_session=True, stdout=subprocess.PIPE if capture else None,104                          stderr=subprocess.PIPE if capture_stderr else None) as child:105        try:106            stdout, stderr = child.communicate()107        except BaseException:108            try:109                os.killpg(child.pid, signal.SIGKILL)110            except ProcessLookupError:111                pass112            child.wait()113            raise114        return subprocess.CompletedProcess(command, child.returncode, stdout, stderr)115116117def run(argv, *, cwd, env, capture=False, capture_stderr=False, label=None, pass_fds=()):118    print("+ " + (label or shlex.join(map(str, argv))), file=sys.stderr, flush=True)119    result = execute(argv, cwd=cwd, env=env, capture=capture, capture_stderr=capture_stderr,120                     pass_fds=pass_fds)121    if result.stderr:122        print(result.stderr, file=sys.stderr, end="", flush=True)123    result.check_returncode()124    return result.stdout125126127def cargo_metadata(cargo, manifest, options, *, stage, env, pass_fds=()):128    command = [cargo, "metadata", "--format-version=1", "--manifest-path", manifest, *options]129    try:130        return json.loads(run(command, cwd=manifest.parent, env=env, capture=True,131                              capture_stderr=True, pass_fds=pass_fds))132    except subprocess.CalledProcessError as error:133        diagnostic = error.stderr or ""134        missing_archive = "attempting to make an HTTP request, but --offline was specified" in diagnostic135        missing_index_entry = "offline mode (via `--offline`)" in diagnostic and (136            "no matching package named " in diagnostic137            or "failed to select a version for the requirement " in diagnostic138        )139        if missing_archive or missing_index_entry:140            fetch = shlex.join(["cargo", "fetch", "--locked", "--manifest-path", str(manifest)])141            print(f"build-app: {stage} Cargo metadata could not resolve offline dependencies. "142                  f"Run this command with the pinned SDK environment and the same CARGO_HOME.\n  {fetch}",143                  file=sys.stderr, flush=True)144        raise145146147def cargo_build(cargo, arguments, *, cwd, env, pass_fds=()):148    """Use Cargo's artifact addresses, never guess filenames from package names."""149    command = list(map(str, [cargo, "build", *arguments, "--message-format=json-render-diagnostics"]))150    print("+ " + shlex.join(command), file=sys.stderr, flush=True)151    result = execute(command, cwd=cwd, env=env, capture=True, pass_fds=pass_fds)152    messages = [json.loads(line) for line in result.stdout.splitlines() if line.startswith("{")]153    for message in messages:154        if message.get("reason") == "compiler-message":155            print(message["message"].get("rendered", ""), file=sys.stderr, end="")156    result.check_returncode()157    return messages158159160def artifact(messages, package_id, target_name, suffix):161    candidates = [162        (Path(filename), message)163        for message in messages164        if message.get("reason") == "compiler-artifact"165        and message["package_id"] == package_id166        and message["target"]["name"] == target_name167        for filename in message["filenames"]168        if filename.endswith(suffix)169    ]170    if len(candidates) != 1:171        raise ValueError(f"Cargo did not report one {suffix} artifact for {target_name}")172    return candidates[0]173174175def select_package(metadata, manifest, requested):176    members = [p for p in metadata["packages"] if p["id"] in metadata["workspace_members"]]177    if requested:178        candidates = [p for p in members if p["name"] == requested]179    else:180        candidates = [p for p in members if Path(p["manifest_path"]).resolve() == manifest]181        if not candidates:182            candidates = [p for p in members if p["id"] in metadata["workspace_default_members"]]183    if len(candidates) != 1:184        names = ", ".join(p["name"] for p in members)185        raise ValueError(f"select one application with --package (workspace packages: {names})")186    package = candidates[0]187    libraries = [t for t in package["targets"] if "cdylib" in t["crate_types"]]188    if len(libraries) != 1 or "rlib" not in libraries[0]["crate_types"]:189        raise ValueError('the application needs [lib] crate-type = ["cdylib", "rlib"]')190    return package, libraries[0]191192193def tool_outputs(metadata, target_directory, host):194    packages = [p for p in metadata["packages"] if p["name"] == "cdk-rsx-wasm"195                and p["id"] in metadata["workspace_members"]]196    if len(packages) != 1:197        raise ValueError("SDK metadata must select one cdk-rsx-wasm package")198    package = packages[0]199    paths = []200    for target in package["targets"]:201        if "bin" in target["kind"]:202            paths.append(lock_path(target_directory, "release", "binary", host, target["name"]))203        elif set(target["kind"]) & {"lib", "rlib", "dylib", "cdylib", "staticlib", "proc-macro"}:204            paths.append(library_lock(target_directory, target["name"]))205    return package, paths206207208def native_interface(cargo, common, host, manifest, native_env, pass_fds, package, library, did_path):209    """Export this revision's interface from the original application's native rlib."""210    rustc = native_env["RUSTC"]211    native = cargo_build(cargo, [*common, "--target", host], cwd=manifest.parent,212                         env=native_env, pass_fds=pass_fds)213    rmeta, native_app = artifact(native, package["id"], library["name"], ".rmeta")214    rlib, _ = artifact(native, package["id"], library["name"], ".rlib")215    with tempfile.TemporaryDirectory(prefix="cdk-rsx-wire-", dir=native_env["TMPDIR"]) as temporary:216        driver = Path(temporary) / "main.rs"217        driver.write_text(218            "extern crate rsx_app;\n"219            "unsafe extern \"Rust\" {\n"220            "    fn __cdk_rsx_wire_interface() -> Result<String, String>;\n"221            "}\n"222            "fn main() -> Result<(), Box<dyn std::error::Error>> {\n"223            "    // SAFETY: the linked root exports this exact Rust signature.\n"224            "    println!(\"{}\", unsafe { __cdk_rsx_wire_interface()? });\n"225            "    Ok(())\n}\n"226        )227        executable = Path(temporary) / "wire-interface"228        search_paths = set()229        for message in native:230            if message.get("reason") == "build-script-executed":231                search_paths.update(message["linked_paths"])232            elif message.get("reason") == "compiler-artifact":233                search_paths.update(f"dependency={Path(path).parent}" for path in message["filenames"])234        link_options = [option for path in sorted(search_paths) for option in ("-L", path)]235        run([rustc, "--edition=2024", "--target", host, driver,236             "--extern", f"rsx_app={rmeta}", "--extern", f"rsx_app={rlib}",237             *link_options, "-o", executable], cwd=manifest.parent, env=native_env,238            label="link generated native Wire descriptor driver", pass_fds=pass_fds)239        did_path.write_text(run([executable], cwd=manifest.parent, env=native_env,240                                capture=True, pass_fds=pass_fds))241    return native_app242243244def wasm_application(cargo, common, manifest, env, pass_fds, package, library, package_config):245    messages = cargo_build(cargo, [*common, "--config", package_config,246                                 "--target", env["CARGO_BUILD_TARGET"], f"-Zbuild-std={BUILD_STD_CRATES}"],247                           cwd=manifest.parent, env=env, pass_fds=pass_fds)248    path, application = artifact(messages, package["id"], library["name"], ".wasm")249    application = dict(application, generated_source_directories=sorted({250        message["out_dir"] for message in messages251        if message.get("reason") == "build-script-executed" and message.get("out_dir")252    }))253    return path, application254255256def record(path, *, published=None):257    path = Path(path).resolve()258    data = path.read_bytes()259    return {"path": str(Path(published).resolve() if published else path),260            "bytes": len(data), "sha256": hashlib.sha256(data).hexdigest()}261262263def generated_directories(metadata, directories):264    """Exclude declared outputs without hiding Cargo or canonical builder inputs."""265    roots = sorted({Path(path).resolve() for path in directories})266    if not roots:267        return roots268    files = {Path(__file__).resolve(), SDK / "tools/env.sh"}269    source_roots = {SDK / "tools"}270    workspaces = {SDK.resolve()}271    for document in metadata:272        if document.get("workspace_root"):273            workspaces.add(Path(document["workspace_root"]).resolve())274        for package in document["packages"]:275            manifest = Path(package["manifest_path"]).resolve()276            files.add(manifest)277            source_roots.add(manifest.parent / "src")278            for target in package["targets"]:279                source = Path(target["src_path"]).resolve()280                files.add(source)281                # A root-level lib.rs/build.rs shares its directory with outputs.282                # Protect that entry file, and every distinct source directory.283                if source.parent != manifest.parent:284                    source_roots.add(source.parent)285    for workspace in workspaces:286        files.update(workspace / name for name in ("Cargo.toml", "Cargo.lock", "rust-toolchain.toml"))287        for ancestor in (workspace, *workspace.parents):288            files.update(ancestor / name for name in (".cargo/config", ".cargo/config.toml"))289    files = {path.resolve() for path in files}290    source_roots = {path.resolve() for path in source_roots}291    for root in roots:292        if root.exists() and not root.is_dir():293            raise ValueError(f"--generated-dir must name a directory: {root}")294        hidden = next((path for path in sorted(files) if path.is_relative_to(root)), None)295        if hidden is None:296            hidden = next((path for path in sorted(source_roots)297                           if path.is_relative_to(root) or root.is_relative_to(path)), None)298        if hidden is not None:299            raise ValueError(f"--generated-dir {root} overlaps a build input: {hidden}")300    return roots301302303def source_snapshot(metadata, *, output, target, cargo_home, extra_files=(), generated_dirs=(),304                    debug_sources=False, rust_sources=None):305    """Pin local Cargo packages, workspace manifests and effective configuration.306307    Debug bundles additionally pin dependency and standard-library sources.308    Generated OUT_DIR Rust is captured separately from the exact Wasm build.309    """310    excluded = [Path(path).resolve() for path in311                (output, target, SDK / ".rustup", SDK / "tmp")]312    excluded.extend(generated_directories(metadata, generated_dirs))313    if not debug_sources:314        excluded.append(Path(cargo_home).resolve())315    files = {Path(__file__).resolve()}316    files.update(Path(path).resolve() for path in extra_files)317    workspaces = {SDK.resolve()}318    for document in metadata:319        if document.get("workspace_root"):320            workspaces.add(Path(document["workspace_root"]).resolve())321        for package in document["packages"]:322            if package.get("source") is not None and not debug_sources:323                continue324            root = Path(package["manifest_path"]).resolve().parent325            for current, directories, names in os.walk(root):326                current = Path(current)327                directories[:] = sorted(name for name in directories328                    if name not in (".git", ".rustup", ".cargo-home", "node_modules", "__pycache__")329                    and not any((current / name).resolve().is_relative_to(path) for path in excluded))330                files.update(current / name for name in names331                    if not name.endswith((".pyc", ".pyo")) and (current / name).is_file())332    for workspace in workspaces:333        files.update(path for path in (workspace / "Cargo.toml", workspace / "Cargo.lock",334                                      workspace / "rust-toolchain.toml") if path.is_file())335        for ancestor in (workspace, *workspace.parents):336            files.update(path for path in (ancestor / ".cargo/config", ancestor / ".cargo/config.toml")337                         if path.is_file())338    files.update(path for path in (Path(cargo_home) / "config", Path(cargo_home) / "config.toml",339                                  SDK / "tools/env.sh") if path.is_file())340    if debug_sources and rust_sources:341        files.update((Path(rust_sources) / "library").rglob("*.rs"))342    return [record(path) for path in sorted(files)]343344345def first_source_difference(before, after):346    if before == after:347        return None348349    previous = defaultdict(list)350    current = defaultdict(list)351    for snapshot, by_path in ((before, previous), (after, current)):352        for row in snapshot:353            by_path[row["path"]].append(row)354    for path in sorted(previous.keys() | current.keys()):355        if path not in previous:356            return "added", path357        if path not in current:358            return "removed", path359        if previous[path] != current[path]:360            return "changed", path361362    # Paths resolved through aliases can change order in the recorded snapshot.363    return "reordered", next(new["path"] for old, new in zip(before, after) if old != new)364365366def write_gzip(path, value):367    Path(path).write_bytes(gzip.compress(json.dumps(value, separators=(",", ":")).encode(), mtime=0))368369370def write_source_archive(path, archive):371    write_gzip(path, archive)372    path.chmod(0o600)373374375def archive_sources(sources):376    root = Path(os.path.commonpath([str(Path(row["path"]).parent) for row in sources]))377    files = []378    for row in sources:379        path = Path(row["path"])380        data = path.read_bytes()381        if len(data) != row["bytes"] or hashlib.sha256(data).hexdigest() != row["sha256"]:382            raise ValueError(f"source changed during build: {path}")383        files.append({"path": str(path.relative_to(root)), "bytes": len(data),384                      "sha256": row["sha256"], "contents_base64": base64.b64encode(data).decode()})385    return {"format": "cdk-rsx-exact-source-v1", "recorded_build_root": str(root) + "/", "files": files}386387388def source_remappings(metadata, cargo_home, target, rust_sources):389    """Give every local Cargo source a stable path without changing known roots."""390    remappings = list({391        (str(SDK.resolve()), "/icrustmem"), (str(Path(cargo_home).resolve()), "/cargo"),392        (str(Path(target).resolve()), "/build"), (str(Path(rust_sources).resolve()), "/rust-src"),393    })394395    def covered(path, roots):396        return any(path.is_relative_to(root) for root, _ in roots)397398    workspace = Path(metadata["workspace_root"]).resolve()399    if not covered(workspace, remappings):400        remappings.append((str(workspace), "/workspace"))401    roots = tuple(remappings)402    local = {}403    for package in metadata["packages"]:404        if package.get("source") is not None:405            continue406        directory = Path(package["manifest_path"]).resolve().parent407        if covered(directory, roots):408            continue409        logical = f"/packages/{package['name']}-{package['version']}"410        previous = local.setdefault(logical, str(directory))411        if previous != str(directory):412            raise ValueError(f"local package path mapping {logical} is ambiguous: {previous}, {directory}")413    remappings.extend((physical, logical) for logical, physical in sorted(local.items()))414    # Prefix length controls precedence. Unrelated equal-length prefixes need415    # a stable order too because the ABI class hashes the complete Rust flags.416    return sorted(remappings, key=lambda pair: (len(pair[0]), pair[1], pair[0]))417418419def debug_source_archive(sources, generated_directories, remappings, installed_sha256):420    """Archive compiled inputs and exact OUT_DIR Rust, never browse live files."""421    rows = {row["path"]: row for row in sources}422    for directory in generated_directories:423        for path in Path(directory).rglob("*"):424            if path.is_file() and (path.suffix == ".rs" or path.name.endswith(".rs.map.json")):425                rows[str(path.resolve())] = record(path)426    files = []427    for row in sorted(rows.values(), key=lambda row: row["path"]):428        path = Path(row["path"])429        data = path.read_bytes()430        if len(data) != row["bytes"] or hashlib.sha256(data).hexdigest() != row["sha256"]:431            raise ValueError(f"source changed before debug archive: {path}")432        logical = str(path)433        for physical, prefix in sorted(remappings, key=lambda pair: len(pair[0]), reverse=True):434            if path.is_relative_to(physical):435                logical = str(Path(prefix) / path.relative_to(physical))436                break437        files.append({"path": logical, "physical_path": str(path), "bytes": len(data),438                      "sha256": row["sha256"], "contents_base64": base64.b64encode(data).decode()})439    return {"format": "cdk-rsx-debug-sources-v1", "installed_sha256": installed_sha256,440            "path_remappings": [{"physical": physical, "logical": logical}441                                for physical, logical in remappings], "files": files}442443444def build(args):445    if not args.offline or not args.locked:446        raise ValueError("canonical builds require --offline --locked")447    wasm_target = getattr(args, "wasm_target", WASM_TARGET)448    if wasm_target not in WASM_TARGETS:449        raise ValueError(f"unsupported Wasm target: {wasm_target}")450    started = time.monotonic()451    node = node_identity()452    manifest = Path(args.manifest_path).resolve(strict=True)453    output = Path(args.out_dir).resolve()454    env = os.environ.copy()455    # Canonical provenance is reconstructed below, never inherited from an456    # earlier candidate build or applied to native descriptor/tool aliasing.457    for key in ("CDK_RSX_COMPAT_CONTEXT", "CDK_RSX_COMPAT_ALIASES", "CDK_RSX_COMPAT_TOOLING",458                PACKAGE_ROOTS_ENV):459        env.pop(key, None)460    for name, default in (461        ("CARGO_HOME", SDK / ".cargo-home"),462        ("CARGO_TARGET_DIR", SDK / "target"),463        ("TMPDIR", SDK / "tmp"),464    ):465        env[name] = str(Path(env.get(name, default)).resolve())466        Path(env[name]).mkdir(parents=True, exist_ok=True)467    env.setdefault("CARGO_BUILD_JOBS", "4")468    env.setdefault("CARGO_INCREMENTAL", "0")469    # Worktrees sharing a target may have older source mtimes than its artifacts.470    # This pinned Cargo separates the checksum feature gate from its selection.471    env.update(CARGO_UNSTABLE_CHECKSUM_FRESHNESS="true", CARGO_BUILD_FINGERPRINT="content")472    env["RUSTUP_HOME"] = str((SDK / ".rustup").resolve())473    env.update(CARGO_PROFILE_RELEASE_LTO="thin", CARGO_PROFILE_RELEASE_CODEGEN_UNITS="1",474               CARGO_PROFILE_RELEASE_OPT_LEVEL="3", CARGO_PROFILE_RELEASE_DEBUG="0",475               CARGO_PROFILE_RELEASE_DEBUG_ASSERTIONS="false", CARGO_PROFILE_RELEASE_OVERFLOW_CHECKS="false")476    toolchain = tomllib.loads((SDK / "rust-toolchain.toml").read_text())["toolchain"]["channel"]477    env["RUSTUP_TOOLCHAIN"] = toolchain478    try:479        rustc = str(Path(run(["rustup", "which", "--toolchain", toolchain, "rustc"],480                             cwd=SDK, env=env, capture=True).strip()).resolve())481    except subprocess.CalledProcessError as error:482        raise ValueError(f"install the pinned local compiler first: bash {SDK}/tools/wasm-retain/setup.sh") from error483    compiler_dir = Path(rustc).parent484    cargo = compiler_dir / "cargo"485    env["RUSTC"] = rustc486    env["RUSTDOC"] = str(compiler_dir / "rustdoc")487    env["PATH"] = str(compiler_dir) + os.pathsep + env["PATH"]488    compiler = run([rustc, "-Vv"], cwd=SDK, env=env, capture=True)489    host = next((line.removeprefix("host: ") for line in compiler.splitlines() if line.startswith("host: ")), None)490    if not host:491        raise ValueError("the pinned compiler did not report its native host target")492    native_env = dict(env, CARGO_BUILD_TARGET=host, CARGO_ENCODED_RUSTFLAGS="", RUSTFLAGS="",493                      CARGO_PROFILE_RELEASE_PANIC="unwind")494    cargo_options = ["--offline", "--locked"]495    feature_options = []496    for features in args.features:497        feature_options.extend(["--features", features])498    if args.all_features:499        feature_options.append("--all-features")500    if args.no_default_features:501        feature_options.append("--no-default-features")502    metadata = cargo_metadata(cargo, manifest, [*feature_options, *cargo_options],503                              stage="application", env=native_env)504    package, library = select_package(metadata, manifest, args.package)505    name = args.name or package["name"]506    if not name or name in (".", "..") or Path(name).name != name or "/" in name or "\\" in name:507        raise ValueError("--name must be a filename stem without directory separators")508    common = [509        "--manifest-path", manifest, "--package", package["name"], "--lib", "--release",510        *feature_options, *cargo_options,511    ]512    profile = tomllib.loads((SDK / ".cargo/config.toml").read_text())["target"][wasm_target]["rustflags"]513    rust_sources = compiler_dir.parent / "lib/rustlib/src/rust"514    remappings = source_remappings(metadata, env["CARGO_HOME"], env["CARGO_TARGET_DIR"], rust_sources)515    debug_artifacts = getattr(args, "debug_artifacts", False)516    include_source_archive = getattr(args, "archive_sources", False)517    keep_names = getattr(args, "keep_names", False)518    # Capture full function names in the raw host artifact in both modes.519    # DWARF stays out of ordinary release output; debug mode keeps its sidecars.520    env["CARGO_PROFILE_RELEASE_STRIP"] = "none" if debug_artifacts else "debuginfo"521    native_env["CARGO_PROFILE_RELEASE_STRIP"] = env["CARGO_PROFILE_RELEASE_STRIP"]522    if debug_artifacts:523        profile = [*profile, "-Cdebuginfo=2", "-Cstrip=none"]524    profile = [*profile, *(f"--remap-path-prefix={physical}={logical}"525                          for physical, logical in remappings)]526    wasm_env = dict(env, CARGO_BUILD_TARGET=wasm_target, CARGO_ENCODED_RUSTFLAGS="\x1f".join(profile))527    if debug_artifacts:528        wasm_env["CARGO_PROFILE_RELEASE_DEBUG"] = "2"529    # These settings apply even when the application is outside the SDK workspace.530    wasm_env["CARGO_PROFILE_RELEASE_PANIC"] = "abort"531    output.mkdir(parents=True, exist_ok=True)532    with locked([lock_path(output, "destination", name)]) as destination_fds:533        # No other writer can recreate this marker while this rebuild can fail.534        marker = output / f"{name}.SHA256SUMS"535        marker.unlink(missing_ok=True)536        # Same filesystem for atomic per-file rename; failed checks leave the537        # previous data files intact. The six files are not an unlocked snapshot.538        with tempfile.TemporaryDirectory(prefix=".cdk-rsx-build-", dir=output) as staging:539            stage = Path(staging)540            tool_options = cargo_options541            tool_metadata = cargo_metadata(cargo, SDK / "Cargo.toml", tool_options,542                                           stage="SDK workspace", env=native_env,543                                           pass_fds=destination_fds)544            documents = [metadata, tool_metadata]545            archives = getattr(args, "compatibility_package_archives", None)546            if archives is not None:547                archives = Path(archives).resolve(strict=True)548            package_inputs = verified_sdk_packages(metadata, tool_metadata, SDK, env["CARGO_HOME"], archives)549            package_roots, package_records, package_files = package_inputs550            registry_path = SDK / "compatibility/approved.json"551            candidate_path = getattr(args, "compatibility_candidate", None)552            if candidate_path is not None:553                candidate_path = Path(candidate_path).resolve(strict=True)554555            def alias_inputs():556                approved, inputs = load_registry(registry_path)557                inputs.append(SDK / "tools/compatibility.py")558                if candidate_path is not None:559                    approved = merge_aliases(approved, load_document(candidate_path))560                    inputs.append(candidate_path)561                return approved, sorted(set(inputs))562563            aliases, compatibility_inputs = alias_inputs()564            generated_dirs = generated_directories(documents, args.generated_dir)565            tooling_excluded = [output, env["CARGO_TARGET_DIR"], env["CARGO_HOME"], *generated_dirs]566            tooling, tooling_facts, tooling_inputs = tooling_fingerprint(documents, SDK, excluded=tooling_excluded)567            native_env["CDK_RSX_COMPAT_TOOLING"] = tooling568            wasm_env["CDK_RSX_COMPAT_TOOLING"] = tooling569            context, context_facts = build_context(metadata, wasm_target, profile, compiler, tooling)570            alias_bytes = canonical_bytes(aliases)571            alias_path = materialize_compatibility_aliases(env["CARGO_TARGET_DIR"], alias_bytes)572            wasm_env.update(CDK_RSX_COMPAT_CONTEXT=context, CDK_RSX_COMPAT_ALIASES=str(alias_path))573            # Command-line Cargo configuration takes precedence over a consumer's574            # [env] settings, including when the verified ownership map is empty.575            package_config = stage / "package-ownership.toml"576            ownership = json.dumps(canonical_bytes(package_roots).decode().strip())577            package_config.write_text(f"[env]\n{PACKAGE_ROOTS_ENV} = {{value = {ownership}, force = true}}\n")578            tracked_files = [*args.source_file, *compatibility_inputs, *tooling_inputs, *package_files]579            before = source_snapshot(documents, output=output, target=env["CARGO_TARGET_DIR"],580                                     cargo_home=env["CARGO_HOME"], extra_files=tracked_files,581                                     generated_dirs=generated_dirs,582                                     debug_sources=debug_artifacts, rust_sources=rust_sources)583            write_gzip(stage / f"{name}.metadata.json.gz", documents)584            (stage / f"{name}.source-before.json").write_text(json.dumps(before, indent=2) + "\n")585            tool_package, gates = tool_outputs(tool_metadata, env["CARGO_TARGET_DIR"], host)586            # The tool also writes a root library (cdk_rsx_wasm). Share that587            # namespace with applications, and never take tool gates under an588            # application gate: colliding library names would otherwise deadlock.589            with locked(gates) as tool_fds:590                tool_messages = cargo_build(591                    cargo, ["--manifest-path", SDK / "Cargo.toml", "--package", "cdk-rsx-wasm",592                            "--release", "--target", host, *tool_options],593                    cwd=SDK, env=native_env, pass_fds=destination_fds + tool_fds,594                )595                executables = [m["executable"] for m in tool_messages596                               if m.get("reason") == "compiler-artifact" and m["package_id"] == tool_package["id"]597                               and m["target"]["name"] == "cdk-rsx-wasm" and m.get("executable")]598                if len(executables) != 1:599                    raise ValueError("Cargo did not report one cdk-rsx-wasm executable")600                wasm_tool = stage / f"{name}.wasm-tool"601                shutil.copy2(executables[0], wasm_tool)602            tool_sha256 = hashlib.sha256(wasm_tool.read_bytes()).hexdigest()603            did_path = stage / f"{name}.wire.json"604            wasm_path = stage / f"{name}.wasm"605            app_gates = [library_lock(env["CARGO_TARGET_DIR"], library["name"])]606            with locked(app_gates) as app_fds:607                pass_fds = destination_fds + app_fds608                # Preserve the original workspace's lockfile, patches, feature609                # forwarding and build scripts. Its inputs must remain fixed.610                native_app = native_interface(cargo, common, host, manifest, native_env,611                                              pass_fds, package, library, did_path)612                raw_wasm, wasm_app = wasm_application(cargo, common, manifest, wasm_env,613                                                     pass_fds, package, library, package_config)614                if native_app["features"] != wasm_app["features"]:615                    raise ValueError("native descriptor and Wasm application feature sets differ")616                raw_sha256 = hashlib.sha256(raw_wasm.read_bytes()).hexdigest()617                shutil.copy2(raw_wasm, stage / f"{name}.raw.wasm")618                raw_inventory = validate_inventory(json.loads(run(619                    [wasm_tool, "compatibility", raw_wasm], cwd=manifest.parent, env=native_env,620                    capture=True, pass_fds=pass_fds)), aliases, context=context, target=wasm_target)621                (stage / f"{name}.raw.policies.json").write_bytes(canonical_bytes(raw_inventory))622                prepare_input = raw_wasm623                if debug_artifacts:624                    objcopy = compiler_dir.parent / f"lib/rustlib/{host}/bin/rust-objcopy"625                    prepare_input = stage / f"{name}.stripped.raw.wasm"626                    run([objcopy, "--strip-debug", raw_wasm, prepare_input], cwd=manifest.parent,627                        env=native_env, pass_fds=pass_fds)628                    run([wasm_tool, "check-debug-strip", raw_wasm, prepare_input], cwd=manifest.parent,629                        env=native_env, pass_fds=pass_fds)630                    stripped_inventory = validate_inventory(json.loads(run(631                        [wasm_tool, "compatibility", prepare_input], cwd=manifest.parent, env=native_env,632                        capture=True, pass_fds=pass_fds)), aliases, context=context, target=wasm_target)633                    if stripped_inventory != raw_inventory:634                        raise ValueError("debug stripping changed compatibility inventory")635                # prepare has one production runtime: the compiled typed root.636                prepare_options = ["--keep-names"] if keep_names else []637                run([wasm_tool, "prepare", prepare_input, wasm_path, "--wire-interface", did_path,638                     *prepare_options],639                    cwd=manifest.parent, env=native_env, pass_fds=pass_fds)640                inventory = validate_inventory(json.loads(run(641                    [wasm_tool, "compatibility", wasm_path], cwd=manifest.parent, env=native_env,642                    capture=True, pass_fds=pass_fds)), aliases, context=context, target=wasm_target)643                if inventory != raw_inventory:644                    raise ValueError("SDK preparation changed compatibility inventory")645                (stage / f"{name}.policies.json").write_bytes(canonical_bytes(inventory))646                memory = json.loads(wasm_path.with_suffix(".memory.json").read_text())647                width = 64 if wasm_target == "wasm64-unknown-unknown" else 32648                address_limit = 6 << 30 if width == 64 else (1 << 32) - 65536649                if (memory.get("memory64") is not (width == 64)650                        or memory.get("pointer_width") != width651                        or memory.get("address_limit") != address_limit):652                    raise ValueError("prepared memory profile differs from requested Wasm target")653                run([wasm_tool, "origin-map", raw_wasm, wasm_path, stage / f"{name}.origin.json"],654                    cwd=manifest.parent, env=native_env, pass_fds=pass_fds)655            inspection = run([wasm_tool, "inspect", wasm_path], cwd=manifest.parent, env=native_env,656                             capture=True, pass_fds=destination_fds)657            (stage / f"{name}.inspect.json").write_text(inspection)658            run([wasm_tool, "check-wire", wasm_path, did_path], cwd=manifest.parent, env=native_env,659                pass_fds=destination_fds)660            run([wasm_tool, "wire-bindings", did_path, stage / f"{name}.wire.ts"], cwd=manifest.parent, env=native_env,661                pass_fds=destination_fds)662            runtime_sources = [stage / f"{name}.wire.{part}.mts" for part in ("runtime", "codec")]663            runtime_javascript = transform_wire_runtime(runtime_sources, node)664            if node_identity(node["path"]) != node:665                raise ValueError("Node executable changed during Wire client generation")666            (stage / f"{name}.toolchain.txt").write_text(compiler)667            try:668                after = source_snapshot(documents, output=output, target=env["CARGO_TARGET_DIR"],669                                        cargo_home=env["CARGO_HOME"], extra_files=tracked_files,670                                        generated_dirs=generated_dirs,671                                        debug_sources=debug_artifacts, rust_sources=rust_sources)672            except FileNotFoundError as error:673                difference = "removed", error.filename674            else:675                difference = first_source_difference(before, after)676            if difference is not None:677                action, path = difference678                raise ValueError(f"source inputs changed during build ({action} {path!r}). "679                                 "Freeze inputs and rebuild. Keep logs and generated files beside "680                                 "the app or declare their directory with --generated-dir.")681            if alias_inputs() != (aliases, compatibility_inputs):682                raise ValueError("compatibility registry/candidate changed during build")683            if verified_sdk_packages(metadata, tool_metadata, SDK, env["CARGO_HOME"], archives) != package_inputs:684                raise ValueError("compatibility SDK package inputs changed during build")685            if tooling_fingerprint(documents, SDK, excluded=tooling_excluded)[0] != tooling:686                raise ValueError("compatibility tooling inputs changed during build")687            try:688                commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=manifest.parent,689                                                 text=True, stderr=subprocess.DEVNULL).strip()690            except subprocess.CalledProcessError:691                commit = None692            source_archive = stage / f"{name}.source-archive.json.gz"693            debug_sources = stage / f"{name}.debug-sources.json.gz"694            if include_source_archive:695                archive = archive_sources(before)696                archive["commit"] = commit697                write_source_archive(source_archive, archive)698                if debug_artifacts:699                    write_source_archive(debug_sources, debug_source_archive(700                        before, wasm_app["generated_source_directories"], remappings,701                        record(wasm_path)["sha256"]))702            receipt = {703                "manifest_path": str(manifest), "package": package["name"], "library": library["name"],704                "features": wasm_app["features"], "feature_options": feature_options,705                "target": wasm_target, "toolchain": toolchain, "rustflags": profile,706                "compiler_path": rustc, "host": host,707                "profile": {"lto": "thin", "codegen_units": 1, "opt_level": 3, "panic": "abort",708                            "strip": env["CARGO_PROFILE_RELEASE_STRIP"]},709                "raw_wasm": str(raw_wasm), "raw_wasm_sha256": raw_sha256, "wasm_tool_sha256": tool_sha256,710                "cargo_profile": wasm_app["profile"],711                "wire_source": "generated __cdk_rsx_wire_interface symbol from the application's native rlib",712                "wire_runtime_transform": {"implementation": "node:module.stripTypeScriptTypes", **node},713                "cargo_fingerprint": "content",714                "runtime": "typed-root", "source_unchanged_during_build": True,715                "source_files": len(before), "build_seconds": time.monotonic() - started,716                "debug_artifacts": debug_artifacts,717                "source_archive": include_source_archive,718                "names": {"installed": "retained" if keep_names else "external",719                          "raw_artifact": f"{name}.raw.wasm", "origin_map": f"{name}.origin.json",720                          "backtraces": "full function names" if keep_names else721                                        "full function names require the matching raw artifact and origin map"},722                "generated_directories": list(map(str, generated_dirs)),723                "compatibility": {724                    "status": "candidate" if candidate_path is not None else "approved",725                    "context": context, "context_inputs": context_facts,726                    "tooling": {"sha256": tooling, "inputs": tooling_facts},727                    "sdk_packages": package_records,728                    "aliases_sha256": hashlib.sha256(alias_bytes).hexdigest(), "aliases": aliases,729                    "registry": record(registry_path),730                    **({"candidate": record(candidate_path)} if candidate_path is not None else {}),731                },732            }733            if debug_artifacts:734                receipt["debug"] = {"debuginfo": 2, "strip": "none", "deployed_debug": False,735                                    "objcopy": record(objcopy),736                                    "objcopy_version": run([objcopy, "--version"], cwd=SDK, env=native_env,737                                                           capture=True, pass_fds=destination_fds),738                                    "path_remappings": remappings,739                                    "installed_sha256": record(wasm_path)["sha256"]}740            (stage / f"{name}.build.json").write_text(json.dumps(receipt, indent=2) + "\n")741            artifacts = [stage / f"{name}.{suffix}" for suffix in (742                "wasm", "raw.wasm", "wire.json", "wire.ts", "memory.json", "inspect.json", "toolchain.txt", "build.json",743                "metadata.json.gz", "source-before.json", "wasm-tool",744                "raw.policies.json", "policies.json", "origin.json",745            )]746            artifacts.extend([*runtime_sources, *runtime_javascript])747            if debug_artifacts:748                artifacts.append(stage / f"{name}.stripped.raw.wasm")749            source_archives = (source_archive, debug_sources)750            artifacts.extend(path for path in source_archives if path.is_file())751            manifest_path = stage / f"{name}.manifest.json"752            manifest_path.write_text(json.dumps({753                "format": "cdk-rsx-typed-root-artifacts-v1", "implementation": "cdk-rsx",754                "package": package["name"], "commit": commit, "compiler": compiler,755                "wasmSha256": record(wasm_path)["sha256"], "features": wasm_app["features"],756                "sourceUnchangedDuringBuild": True, "buildSeconds": receipt["build_seconds"],757                "canonicalBuild": receipt, "sources": before,758                "outputs": [record(path, published=output / path.name) for path in artifacts],759            }, indent=2) + "\n")760            artifacts.append(manifest_path)761            staged_marker = stage / marker.name762            staged_marker.write_text("".join(763                f"{hashlib.sha256(path.read_bytes()).hexdigest()}  {path.name}\n" for path in artifacts764            ))765            for path in artifacts:766                path.replace(output / path.name)767            # Retire prior private sidecars before marking this build complete.768            for path in source_archives:769                if path not in artifacts:770                    (output / path.name).unlink(missing_ok=True)771            staged_marker.replace(marker)  # The only completion publication, always last.772    print(f"Prepared {output / (name + '.wasm')}\nWire   {output / (name + '.wire.json')}")773774775776def fetch_command(manifest, *, cargo="cargo", target=WASM_TARGET):777    """Fetch the locked target closure, including the canonical rebuilt std.778779    Cargo fetch covers locked feature dependencies and accepts no feature flags.780    Actual feature selection remains in metadata/build commands.781    """782    return [str(cargo), "fetch", "--manifest-path", str(manifest), "--locked",783            "--target", target, f"-Zbuild-std={BUILD_STD_CRATES}"]784785786787def dependency_commands(manifest, *, cargo="cargo", target=WASM_TARGET):788    # Descriptor/build-host tools also need native and target-specific packages.789    # Fetch the full lock first; std is a separate workspace selected by -Z.790    return [[str(cargo), "fetch", "--manifest-path", str(manifest), "--locked"],791            fetch_command(manifest, cargo=cargo, target=target)]792793794def argument_parser():795    parser = argparse.ArgumentParser(description=__doc__)796    parser.add_argument("--manifest-path", required=True, help="application or workspace Cargo.toml")797    parser.add_argument("--package", "-p", help="select an application in a workspace")798    parser.add_argument("--wasm-target", choices=WASM_TARGETS, default=WASM_TARGET,799                        help="canister target (default: wasm64-unknown-unknown); native tools stay on the host")800    parser.add_argument("--features", "-F", action="append", default=[], help="Cargo features; repeat or separate with commas/spaces")801    parser.add_argument("--all-features", action="store_true")802    parser.add_argument("--no-default-features", action="store_true")803    parser.add_argument("--out-dir", required=True, help="directory for checked final artifacts")804    parser.add_argument("--name", help="artifact filename stem (default: Cargo package name)")805    parser.add_argument("--source-file", action="append", default=[],806                        help="explicit build input, including files inside excluded generated directories")807    parser.add_argument("--generated-dir", action="append", default=[],808                        help="exclude a generated output tree from source snapshots; repeat for multiple directories")809    parser.add_argument("--debug-artifacts", action="store_true",810                        help="keep optimized DWARF sidecars; strip DWARF before SDK prepare")811    parser.add_argument("--archive-sources", action="store_true",812                        help="write private exact source archives, including local config and ignored inputs")813    parser.add_argument("--keep-names", action="store_true",814                        help="retain full canister backtrace names; default keeps names in raw host artifact only")815    parser.add_argument("--compatibility-candidate", metavar="FILE",816                        help="merge a proposed exact alias payload; label outputs as a qualification candidate")817    parser.add_argument("--compatibility-package-archives", metavar="DIR",818                        help="verify locked SDK .crate archives for a directory source replacement")819    parser.add_argument("--offline", action="store_true", required=True, help="use only cached Cargo dependencies")820    parser.add_argument("--locked", action="store_true", required=True, help="require existing, unchanged Cargo lockfiles")821    return parser822823824def main():825    parser = argument_parser()826    args = parser.parse_args()827    try:828        build(args)829    except subprocess.CalledProcessError as error:830        parser.exit(1, f"build-app: {Path(error.cmd[0]).name} failed (exit {error.returncode})\n")831    except KeyboardInterrupt:832        parser.exit(130, "build-app: interrupted\n")833    except (ValueError, OSError) as error:834        parser.exit(1, f"build-app: {error}\n")835836837if __name__ == "__main__":838    main()