From 515f7fcfe05f2e402421a1933889ecdbf6f6854e Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Wed, 2 Dec 2026 05:56:47 -0500 Subject: [PATCH 1/2] Package the Android arm64 Hexagon sidecar for prepared releases --- .../workflows/android_hexagon_candidate.yml | 31 ++- .github/workflows/native_release.yml | 98 +++++++- README.md | 9 +- docs/android_hexagon.md | 30 ++- docs/release_version_policy.md | 6 + scripts/generate_assets_manifest.sh | 2 + scripts/publish_prepared_release.py | 14 +- scripts/release_contract.py | 48 ++-- scripts/release_publication.py | 9 +- scripts/verify_release_provenance.py | 53 +++- tests/test_android_hexagon.py | 226 +++++++++++++++++- tests/test_assets_manifest.py | 5 + tests/test_linux_release_rows.py | 2 +- tests/test_publish_prepared.py | 38 ++- tests/test_release_contract.py | 22 +- tests/test_release_publication.py | 32 ++- tests/test_release_source_identity.py | 2 +- tools/android_hexagon.py | 205 ++++++++++++---- tools/validate_android_artifacts.py | 42 +++- 19 files changed, 708 insertions(+), 166 deletions(-) diff --git a/.github/workflows/android_hexagon_candidate.yml b/.github/workflows/android_hexagon_candidate.yml index 50f8b3cf..7880e8fe 100644 --- a/.github/workflows/android_hexagon_candidate.yml +++ b/.github/workflows/android_hexagon_candidate.yml @@ -4,15 +4,18 @@ on: pull_request: paths: - '.github/workflows/android_hexagon_candidate.yml' + - '.github/workflows/native_release.yml' - 'CMakeLists.txt' - 'cmake/llama_cpp_patches.cmake' - 'patches/llama.cpp/**' + - 'scripts/publish_prepared_release.py' - 'third_party/llama.cpp' - 'tests/test_android_hexagon.py' - 'tools/android_hexagon.py' - 'tools/build.py' - 'tools/build_android_hexagon_candidate.sh' - 'tools/llama_cpp_patches.py' + - 'tools/validate_android_artifacts.py' workflow_call: inputs: native_commit: @@ -35,7 +38,7 @@ jobs: candidate: if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository runs-on: ubuntu-24.04 - timeout-minutes: 40 + timeout-minutes: 60 steps: - uses: actions/checkout@v7 with: @@ -93,7 +96,7 @@ jobs: path: ${{ runner.temp }}/android-ndk-install-diagnostics.json if-no-files-found: error retention-days: 7 - - name: Build and verify the release-gated archive + - name: Build and verify the Hexagon candidate archive env: NATIVE_TAG: ${{ steps.source.outputs.tag }} run: | @@ -107,3 +110,27 @@ jobs: path: artifacts/hexagon-candidate/ if-no-files-found: error retention-days: 7 + - name: Build Android arm64 Vulkan core for the PR pair + if: github.event_name == 'pull_request' + run: | + set -euo pipefail + sudo apt-get update + sudo apt-get install -y ninja-build glslc + ANDROID_VULKAN_GLSLC="$(command -v glslc)" + export ANDROID_VULKAN_GLSLC + export ANDROID_NDK_HOME="${ANDROID_SDK_ROOT:-${ANDROID_HOME:-/usr/local/lib/android/sdk}}/ndk/28.2.13676358" + python3 tools/build.py android --abi arm64-v8a --backend vulkan --jobs 4 2>&1 | tee configure-vulkan.log + grep -Fx -- '-- GL_EXT_integer_dot_product not supported by glslc' configure-vulkan.log + - name: Verify a real sidecar and Vulkan core pair for this PR + if: github.event_name == 'pull_request' + env: + NATIVE_TAG: ${{ steps.source.outputs.tag }} + run: | + set -euo pipefail + ndk="${ANDROID_SDK_ROOT:-${ANDROID_HOME:-/usr/local/lib/android/sdk}}/ndk/28.2.13676358" + readelf="$ndk/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-readelf" + archive="llamadart-native-android-arm64-hexagon-$NATIVE_TAG.tar.gz" + python3 tools/validate_android_artifacts.py --readelf "$readelf" --core-dir bin/android/arm64 \ + --package-hexagon-sidecar "hexagon-sidecar/$archive" "artifacts/hexagon-candidate/$archive" + python3 tools/validate_android_artifacts.py --readelf "$readelf" --core-dir bin/android/arm64 \ + --hexagon-sidecar-archive "hexagon-sidecar/$archive" diff --git a/.github/workflows/native_release.yml b/.github/workflows/native_release.yml index 10306d60..031de7ea 100644 --- a/.github/workflows/native_release.yml +++ b/.github/workflows/native_release.yml @@ -23,12 +23,8 @@ on: correlation_id: description: 'Stable caller correlation identifier (1-128 safe characters)' required: true - prepare_android_hexagon: - description: 'Build experimental Android arm64 Hexagon for qualification only (#260)' - default: false - type: boolean publish_release: - description: 'Publish GitHub release' + description: 'Publish directly without Hexagon. Select false to prepare a release with Hexagon.' required: true default: true type: boolean @@ -80,15 +76,9 @@ jobs: INPUT_SMOKE_POLICY: ${{ github.event.inputs.smoke_policy }} INPUT_CORRELATION_ID: ${{ github.event.inputs.correlation_id }} INPUT_PUBLISH_RELEASE: ${{ github.event.inputs.publish_release }} - INPUT_PREPARE_ANDROID_HEXAGON: ${{ inputs.prepare_android_hexagon }} run: | set -euo pipefail - if [ "$INPUT_PREPARE_ANDROID_HEXAGON" = "true" ] && [ "$INPUT_PUBLISH_RELEASE" != "false" ]; then - echo "Hexagon SDK agreement review is pending (#260). Use publish_release=false." >&2 - exit 1 - fi - TAG="$INPUT_LLAMA_CPP_TAG" EXPECTED_COMMIT="$INPUT_LLAMA_CPP_COMMIT" RELEASE_TAG="$INPUT_NATIVE_RELEASE_TAG" @@ -180,7 +170,7 @@ jobs: build-android-hexagon: needs: resolve-tag - if: inputs.prepare_android_hexagon + if: inputs.publish_release == false uses: ./.github/workflows/android_hexagon_candidate.yml with: native_commit: ${{ needs.resolve-tag.outputs.native_commit }} @@ -1146,6 +1136,61 @@ jobs: llama_cpp_commit: ${{ needs.resolve-tag.outputs.llama_cpp_commit }} - uses: ./.github/actions/openvino-sidecar-pair + hexagon-sidecar-pair: + needs: [resolve-tag, build-android, build-android-hexagon] + if: inputs.publish_release == false + runs-on: ubuntu-24.04 + timeout-minutes: 20 + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + submodules: recursive + persist-credentials: false + - name: Checkout llama.cpp ref + uses: ./.github/actions/checkout-llama-ref + with: + tag: ${{ needs.resolve-tag.outputs.llama_cpp_ref }} + expected_commit: ${{ needs.resolve-tag.outputs.llama_cpp_commit }} + github_token: ${{ github.token }} + - name: Checkout exact release source + uses: ./.github/actions/checkout-native-source + with: + native_commit: ${{ needs.resolve-tag.outputs.native_commit }} + llama_cpp_commit: ${{ needs.resolve-tag.outputs.llama_cpp_commit }} + - uses: android-actions/setup-android@v4 + with: + packages: platform-tools ndk;${{ env.ANDROID_NDK_VERSION }} + - name: Download Android arm64 Vulkan core + uses: actions/download-artifact@v8 + with: + name: native_android_arm64-v8a_vulkan + path: android-core + - name: Download Android arm64 Hexagon candidate + uses: actions/download-artifact@v8 + with: + name: android-arm64-hexagon-candidate + path: hexagon-candidate + - name: Package and validate the Hexagon sidecar against the release core + env: + RELEASE_TAG: ${{ needs.resolve-tag.outputs.release_tag }} + run: | + set -euo pipefail + ndk="${ANDROID_SDK_ROOT:-${ANDROID_HOME:-/usr/local/lib/android/sdk}}/ndk/$ANDROID_NDK_VERSION" + readelf="$ndk/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-readelf" + archive="llamadart-native-android-arm64-hexagon-$RELEASE_TAG.tar.gz" + (cd hexagon-candidate && sha256sum -c SHA256SUMS) + python3 tools/validate_android_artifacts.py --readelf "$readelf" --core-dir android-core \ + --package-hexagon-sidecar "hexagon-sidecar/$archive" "hexagon-candidate/$archive" + python3 tools/validate_android_artifacts.py --readelf "$readelf" --core-dir android-core \ + --hexagon-sidecar-archive "hexagon-sidecar/$archive" + - name: Upload packaged Hexagon sidecar + uses: actions/upload-artifact@v7 + with: + name: sidecar_android_arm64_hexagon + path: hexagon-sidecar/*.tar.gz + if-no-files-found: error + smoke-release-contract: needs: [resolve-tag, build-linux] runs-on: ubuntu-latest @@ -1181,7 +1226,20 @@ jobs: fi package-and-release: - needs: [resolve-tag, build-android, build-apple, metal-os-floor, build-linux, build-linux-hip, build-windows, smoke-release-contract, openvino-sidecar-pair] + needs: [resolve-tag, build-android, build-apple, metal-os-floor, build-linux, build-linux-hip, build-windows, smoke-release-contract, openvino-sidecar-pair, hexagon-sidecar-pair] + if: >- + ${{ !cancelled() && + needs.resolve-tag.result == 'success' && + needs.build-android.result == 'success' && + needs.build-apple.result == 'success' && + needs.metal-os-floor.result == 'success' && + needs.build-linux.result == 'success' && + needs.build-linux-hip.result == 'success' && + needs.build-windows.result == 'success' && + needs.smoke-release-contract.result == 'success' && + needs.openvino-sidecar-pair.result == 'success' && + ((!inputs.publish_release && needs.hexagon-sidecar-pair.result == 'success') || + (inputs.publish_release && needs.hexagon-sidecar-pair.result == 'skipped')) }} runs-on: macos-latest outputs: native_commit: ${{ needs.resolve-tag.outputs.native_commit }} @@ -1210,7 +1268,11 @@ jobs: with: path: artifacts - name: Prepare release assets + env: + INPUT_PUBLISH_RELEASE: ${{ github.event.inputs.publish_release }} + RELEASE_TAG: ${{ needs.resolve-tag.outputs.release_tag }} run: | + set -euo pipefail mkdir -p release_assets mkdir -p bundles @@ -1269,6 +1331,16 @@ jobs: openvino_archive="llamadart-native-linux-x64-openvino-${{ needs.resolve-tag.outputs.release_tag }}.tar.gz" cp "artifacts/sidecar_linux_x64_openvino/$openvino_archive" "release_assets/$openvino_archive" + PYTHONPATH=tools python3 -c 'from pathlib import Path; from android_hexagon import validate_core_layout; validate_core_layout(Path("bundles/android-arm64"))' + if [ "$INPUT_PUBLISH_RELEASE" = "false" ]; then + # The paired Vulkan artifacts must survive the backend merge byte for byte. + for library in libllamadart.so libggml-base.so; do + cmp "artifacts/native_android_arm64-v8a_vulkan/$library" "bundles/android-arm64/$library" + done + hexagon_archive="llamadart-native-android-arm64-hexagon-$RELEASE_TAG.tar.gz" + cp "artifacts/sidecar_android_arm64_hexagon/$hexagon_archive" "release_assets/$hexagon_archive" + fi + for bundle_dir in bundles/windows-*; do [ -d "$bundle_dir" ] || continue python3 tools/package_windows_runtime.py install --arch "${bundle_dir##*/windows-}" "$bundle_dir" artifacts diff --git a/README.md b/README.md index 11100839..914db448 100644 --- a/README.md +++ b/README.md @@ -146,11 +146,10 @@ the following per-target bundles: - Windows x64: Vulkan + CUDA + BLAS + CPU - Windows arm64: Vulkan + BLAS + Kleidi + CPU -An experimental [Android arm64 Hexagon candidate](docs/android_hexagon.md) -provides a separate CPU + HTP bundle for qualification. The maintainer approved -hosted SDK use and redistribution of the generated DSP skeletons in -[#260](https://github.com/leehack/llamadart-native/issues/260#issuecomment-7326932721). -Publishing the candidate requires a separate maintainer decision. +The experimental [Android arm64 Hexagon sidecar](docs/android_hexagon.md) +adds HTP to the same release's Android arm64 core. It is available through the +prepared-release flow with a separate maintainer publication decision. The +standalone CPU + HTP candidate remains available for qualification. Non-Apple targets use `GGML_BACKEND_DL=ON`, so backend libs are optional at package/runtime level. diff --git a/docs/android_hexagon.md b/docs/android_hexagon.md index 545581a1..dcc95704 100644 --- a/docs/android_hexagon.md +++ b/docs/android_hexagon.md @@ -1,9 +1,11 @@ -# Experimental Android arm64 Hexagon candidate +# Experimental Android arm64 Hexagon sidecar The maintainer approved use of Qualcomm Hexagon SDK Community Edition 6.7.0.0 in hosted CI and redistribution of the generated DSP skeletons in [#260](https://github.com/leehack/llamadart-native/issues/260#issuecomment-7326932721). -Publishing the candidate requires a separate maintainer decision. +The [recorded approval](https://github.com/leehack/llamadart-native/issues/260#issuecomment-7328335092) +leaves publication to a separate maintainer decision. Qualcomm hosts the +click-through terms in Software Center. The [Qualcomm catalog](https://softwarecenter.qualcomm.com/catalog/item/Hexagon_SDK?version=6.7.0.0) links the vendor distribution. The [public SDK repack](https://github.com/snapdragon-toolchain/hexagon-sdk/releases/tag/v6.7.0.0) contains third-party notices that refer Qualcomm terms to a separate agreement. @@ -38,10 +40,26 @@ values. The validator checks the archive and directory layout, shared-library machines, supported Android API and NDK, 16 KiB host segment alignment, CPU ISA and C++ runtime sharing, dynamic exports, and the host and DSP dependency sets. -GitHub Actions stores a tag-coupled candidate and its SHA-256 separately from -the native release assets. The release workflow accepts `prepare_android_hexagon=true` -for qualification with `publish_release=false`. The prepared-release importer -refuses a source run that built a Hexagon candidate. +## Prepared release + +A native preparation with `publish_release=false` runs the standalone +candidate build and pairs it with the same run's Vulkan core. The pair checks +that source, patch, configuration, compiler and target identities match, that +the host's ggml imports resolve against the core's `libggml-base.so`, and that +the host and skeletons pass artifact validation. + +The Contract-2 archive `llamadart-native-android-arm64-hexagon-.tar.gz` +contains eight files: the host module, five DSP skeletons, the notices and the +manifest. The manifest records the identity and SHA-256 of the core archive's +`libllamadart.so`. The core's Android arm64 archive contains no Hexagon +payload. Consumers opt in to the sidecar and stage the verified skeletons as +app assets. The standalone candidate remains a CPU + HTP bundle for local +qualification and carries its own primary library. + +After inspecting the same-run archives and obtaining the separate publication +decision, use `publish_prepared.yml` with `publish_approved=true`. See the +[release version policy](release_version_policy.md#publishing-a-qualified-preparation-without-rebuilding). +Direct release runs publish the existing inventory without Hexagon. ## App qualification diff --git a/docs/release_version_policy.md b/docs/release_version_policy.md index 43fbb493..08fdff5f 100644 --- a/docs/release_version_policy.md +++ b/docs/release_version_policy.md @@ -211,6 +211,12 @@ read-only no-op after newer releases; its report records that new publication would now be blocked. Unmarked/mismatched tags, release metadata and assets can never use that exception, and it never invokes the publisher. +The [Android arm64 Hexagon sidecar](android_hexagon.md) is part of the prepared +inventory. The importer requires successful candidate and pair jobs. A direct +`publish_release=true` run retains the existing inventory and rejects Hexagon. +Publishing the prepared sidecar requires the separate maintainer decision +recorded in the Hexagon documentation. + The dedicated publication job reuses `release_publication.py`; it does not build or alter an asset. Prerelease classification comes from the version policy, including `true` for wrapper rebuilds. The original build run/head, artifact diff --git a/scripts/generate_assets_manifest.sh b/scripts/generate_assets_manifest.sh index 864dae16..9a3c9879 100755 --- a/scripts/generate_assets_manifest.sh +++ b/scripts/generate_assets_manifest.sh @@ -62,6 +62,8 @@ infer_meta() { platform="ios"; arch="x86_64-sim"; backend="core" ;; "llamadart-native-android-arm64-$tag.tar.gz") platform="android"; arch="arm64"; backend="core" ;; + "llamadart-native-android-arm64-hexagon-$tag.tar.gz") + platform="android"; arch="arm64"; backend="hexagon"; module="backend-hexagon" ;; "llamadart-native-android-x64-$tag.tar.gz") platform="android"; arch="x64"; backend="core" ;; esac diff --git a/scripts/publish_prepared_release.py b/scripts/publish_prepared_release.py index f3f66d1d..256a766a 100644 --- a/scripts/publish_prepared_release.py +++ b/scripts/publish_prepared_release.py @@ -25,7 +25,8 @@ WORKFLOW_PATH = '.github/workflows/native_release.yml' MAX_ARCHIVE_BYTES = 4 * 1024 ** 3 SUCCESS_JOBS = ('resolve-tag', 'build-linux-hip', 'build-linux-openvino', - 'openvino-sidecar-pair', 'smoke-release-contract', + 'openvino-sidecar-pair', 'build-android-hexagon / candidate', 'hexagon-sidecar-pair', + 'smoke-release-contract', 'package-and-release', 'emit-release-result', 'metal-os-floor / macos (macos-15)', 'metal-os-floor / macos (macos-26)', 'metal-os-floor / ios-simulator') @@ -149,13 +150,6 @@ def validate_run(expected: Expected, run: dict, jobs: list[dict]) -> None: names = [job.get('name') for job in jobs] require(len(names) == len(set(names)), 'ambiguous source job names') for job in jobs: - name = job.get('name') - if (name in ('build-android-hexagon', 'build-android-hexagon / candidate') - and job.get('conclusion') == 'skipped'): - require(job.get('status') == 'completed', 'Hexagon job has not settled') - continue - require(not isinstance(name, str) or not name.startswith('build-android-hexagon'), - 'Hexagon SDK agreement review is pending (#260)') require(job.get('status') == 'completed' and job.get('conclusion') == ('skipped' if job.get('name') in SKIPPED_JOBS else 'success'), 'source job is failed, incomplete or unexpectedly skipped') @@ -190,7 +184,7 @@ def validate_artifact(expected: Expected, run: dict, jobs: list[dict], artifact: def extract_publication(archive: Path, output: Path, expected: Expected) -> None: - allowed = {f'release_assets/{name}' for name in _expected_release_assets(expected.native_release_tag)} + allowed = {f'release_assets/{name}' for name in _expected_release_assets(expected.native_release_tag, prepared=True)} allowed |= {'publication/native_commit', 'publication/release-provenance.bundle'} seen: set[str] = set() total = 0 @@ -288,7 +282,7 @@ def prepare(expected: Expected, api: GitHub, directory: Path, repository: Path, prerelease=contract['github_prerelease'] == 'true', assets_dir=assets, workflow_run_url=expected.run_url, artifact_digest='sha256:' + expected.artifact_sha256, correlation_id=expected.correlation_id, smoke_policy='required', smoke_conclusion='passed', - workflow_head_sha=expected.workflow_head_sha) + workflow_head_sha=expected.workflow_head_sha, prepared=True) report = {'source': result, 'source_result_artifact_id': result_artifact['id'], 'source_result_artifact_digest': result_artifact['digest'], 'transaction_id': desired.transaction_id, 'github_prerelease': desired.prerelease} diff --git a/scripts/release_contract.py b/scripts/release_contract.py index 5f856c6e..177b9e49 100644 --- a/scripts/release_contract.py +++ b/scripts/release_contract.py @@ -14,7 +14,10 @@ from typing import Any from urllib.parse import urlparse -from release_publication import Asset, build_publication_transaction_id +from release_publication import ( + Asset, BACKEND_SIDECARS, HEXAGON_SIDECAR, RUNTIME_BUNDLES, + _expected_release_assets, build_publication_transaction_id, +) from release_version_policy import PolicyError, validate_pair @@ -28,22 +31,6 @@ DISCOVERY_STATUSES = ("candidate", "noop", "incompatible") SMOKE_POLICIES = ("required", "skip") SMOKE_CONCLUSIONS = ("passed", "skipped") -RUNTIME_BUNDLES = ( - "android-arm64", - "android-x64", - "ios-arm64", - "ios-arm64-sim", - "ios-x86_64-sim", - "linux-arm64", - "linux-x64", - "macos-arm64", - "macos-x86_64", - "windows-arm64", - "windows-x64", -) -# Backend archives published beside a runtime bundle and fetched only when an -# app selects that backend. -BACKEND_SIDECARS = ("windows-x64-cuda12", "linux-x64-openvino") class ContractError(ValueError): @@ -231,18 +218,8 @@ def _read_checksums(path: Path) -> dict[str, str]: return checksums -def _expected_assets(tag: str) -> set[str]: - assets = { - f"llamadart-native-{bundle}-{tag}.tar.gz" - for bundle in (*RUNTIME_BUNDLES, *BACKEND_SIDECARS) - } - assets.update( - { - f"llamadart-native-apple-xcframework-{tag}.zip", - f"llamadart-native-headers-{tag}.tar.gz", - } - ) - return assets +def _expected_assets(tag: str, *, prepared: bool = False) -> set[str]: + return _expected_release_assets(tag, prepared=prepared) - {"assets.json", "SHA256SUMS"} def _manifest_asset_entries(value: Any) -> list[dict[str, Any]]: @@ -361,7 +338,7 @@ def build_release_result( if manifest.get(field) != expected: raise ContractError(f"manifest {field} does not match dispatch/result") - expected_assets = _expected_assets(native_release_tag) + expected_assets = _expected_assets(native_release_tag, prepared=not publish_release) manifest_assets = _manifest_asset_entries(manifest.get("artifacts")) manifest_names = {item["file"] for item in manifest_assets} if manifest_names != expected_assets: @@ -369,6 +346,17 @@ def build_release_result( f"release bundle coverage mismatch: expected {sorted(expected_assets)}, got {sorted(manifest_names)}" ) + if not publish_release: + name = f"llamadart-native-{HEXAGON_SIDECAR}-{native_release_tag}.tar.gz" + entry = next(item for item in manifest_assets if item["file"] == name) + if manifest.get("hook_contract_version") != 2 or any( + entry.get(field) != expected + for field, expected in { + "platform": "android", "arch": "arm64", "backend": "hexagon", "module": "backend-hexagon" + }.items() + ): + raise ContractError("prepared Hexagon sidecar metadata does not match hook contract 2") + checksums = _read_checksums(checksums_path) if set(checksums) != expected_assets: raise ContractError("SHA256SUMS asset set does not match required bundle coverage") diff --git a/scripts/release_publication.py b/scripts/release_publication.py index fcf2574e..4c730785 100644 --- a/scripts/release_publication.py +++ b/scripts/release_publication.py @@ -43,7 +43,8 @@ class PublicationError(RuntimeError): ) # Backend archives published beside a runtime bundle and fetched only when an # app selects that backend. -BACKEND_SIDECARS = ("windows-x64-cuda12", "linux-x64-openvino") +HEXAGON_SIDECAR = "android-arm64-hexagon" +BACKEND_SIDECARS = ("windows-x64-cuda12", "linux-x64-openvino", HEXAGON_SIDECAR) @dataclass(frozen=True) @@ -97,7 +98,7 @@ def _sha256(path: Path) -> str: return digest.hexdigest() -def _expected_release_assets(tag: str) -> set[str]: +def _expected_release_assets(tag: str, *, prepared: bool = False) -> set[str]: return { "assets.json", "SHA256SUMS", @@ -106,6 +107,7 @@ def _expected_release_assets(tag: str) -> set[str]: *( f"llamadart-native-{bundle}-{tag}.tar.gz" for bundle in (*RUNTIME_BUNDLES, *BACKEND_SIDECARS) + if prepared or bundle != HEXAGON_SIDECAR ), } @@ -161,6 +163,7 @@ def build_desired_release( smoke_policy: str, smoke_conclusion: str, workflow_head_sha: str, + prepared: bool = False, ) -> DesiredRelease: if COMMIT_SHA_RE.fullmatch(native_commit) is None: raise PublicationError("native commit must be a full 40-hex SHA") @@ -207,7 +210,7 @@ def build_desired_release( f"unable to enumerate release assets directory {assets_dir}: {error}" ) from error - expected_assets = _expected_release_assets(tag) + expected_assets = _expected_release_assets(tag, prepared=prepared) actual_assets = {path.name for path in asset_paths} if actual_assets != expected_assets: missing = sorted(expected_assets - actual_assets) diff --git a/scripts/verify_release_provenance.py b/scripts/verify_release_provenance.py index 19034418..a772e9d0 100755 --- a/scripts/verify_release_provenance.py +++ b/scripts/verify_release_provenance.py @@ -44,6 +44,7 @@ BACKEND_SIDECARS = { "windows-x64-cuda12": ("windows", "x64", "cuda", "backend-cuda12"), "linux-x64-openvino": ("linux", "x64", "openvino", "backend-openvino"), + "android-arm64-hexagon": ("android", "arm64", "hexagon", "backend-hexagon"), } @@ -149,6 +150,7 @@ def verify_workflow_contract(errors: list[str]) -> None: errors.extend(metal_floor_contract_errors( WORKFLOW.read_text(), (ROOT / ".github/workflows/metal_os_floor.yml").read_text())) workflow = WORKFLOW.read_text() + errors.extend(hexagon_release_contract_errors(workflow)) wrapper_workflow = WRAPPER_WORKFLOW.read_text() auto_workflow = AUTO_WORKFLOW.read_text() validation_workflow = VALIDATION_WORKFLOW.read_text() @@ -223,8 +225,8 @@ def verify_workflow_contract(errors: list[str]) -> None: errors, ) require( - workflow.count(expected_commit_input) == 9, - "all eight build/package checkouts and the submodule update must assert the resolved commit", + workflow.count(expected_commit_input) == 10, + "all nine build/package checkouts and the submodule update must assert the resolved commit", errors, ) require( @@ -274,6 +276,8 @@ def verify_workflow_contract(errors: list[str]) -> None: read_only_jobs = ( "resolve-tag", "build-android", + "build-android-hexagon", + "hexagon-sidecar-pair", "build-apple", "build-linux", "build-linux-hip", @@ -420,7 +424,7 @@ def verify_workflow_contract(errors: list[str]) -> None: ) require( "needs: [resolve-tag, build-android, build-apple, metal-os-floor, build-linux, " - "build-linux-hip, build-windows, smoke-release-contract, openvino-sidecar-pair]" + "build-linux-hip, build-windows, smoke-release-contract, openvino-sidecar-pair, hexagon-sidecar-pair]" in package_job and "needs: [resolve-tag, smoke-release-contract, package-and-release]" in publish_job and "needs.package-and-release.result == 'success'" in publish_job, @@ -620,6 +624,45 @@ def verify_workflow_contract(errors: list[str]) -> None: ) +def hexagon_release_contract_errors(workflow: str) -> list[str]: + errors: list[str] = [] + candidate = workflow_job(workflow, "build-android-hexagon") + pair = workflow_job(workflow, "hexagon-sidecar-pair") + package = workflow_job(workflow, "package-and-release") + require( + "if: inputs.publish_release == false" in candidate + and "uses: ./.github/workflows/android_hexagon_candidate.yml" in candidate + and "native_commit: ${{ needs.resolve-tag.outputs.native_commit }}" in candidate + and "llama_cpp_commit: ${{ needs.resolve-tag.outputs.llama_cpp_commit }}" in candidate + and "if: inputs.publish_release == false" in pair + and "needs: [resolve-tag, build-android, build-android-hexagon]" in pair + and "name: native_android_arm64-v8a_vulkan" in pair + and "name: android-arm64-hexagon-candidate" in pair + and "--package-hexagon-sidecar" in pair + and '--hexagon-sidecar-archive "hexagon-sidecar/$archive"' in pair + and "name: sidecar_android_arm64_hexagon" in pair, + "Hexagon preparation must pair the same-run candidate and Vulkan core, then validate the packed archive", + errors, + ) + require( + "(!inputs.publish_release && needs.hexagon-sidecar-pair.result == 'success')" in package + and "(inputs.publish_release && needs.hexagon-sidecar-pair.result == 'skipped')" in package + and """if [ "$INPUT_PUBLISH_RELEASE" = "false" ]; then""" in package + and 'for library in libllamadart.so libggml-base.so' in package + and 'cmp "artifacts/native_android_arm64-v8a_vulkan/$library" "bundles/android-arm64/$library"' in package + and 'cp "artifacts/sidecar_android_arm64_hexagon/$hexagon_archive" "release_assets/$hexagon_archive"' in package, + "prepared packaging must require the pair, preserve both paired core libraries and ship its sidecar", + errors, + ) + guard = package.find('validate_core_layout(Path("bundles/android-arm64"))') + require( + 0 <= guard < package.find("for bundle_dir in bundles/*"), + "Android arm64 core packaging must reject Hexagon and HTP entries before archiving", + errors, + ) + return errors + + def release_source_contract_errors(workflow: str) -> list[str]: errors: list[str] = [] resolve = workflow_job(workflow, "resolve-tag") @@ -634,7 +677,8 @@ def release_source_contract_errors(workflow: str) -> list[str]: errors, ) for name in ("build-android", "build-apple", "build-linux", "build-linux-hip", - "build-linux-openvino", "openvino-sidecar-pair", "build-windows", "package-and-release"): + "build-linux-openvino", "openvino-sidecar-pair", "hexagon-sidecar-pair", + "build-windows", "package-and-release"): job = workflow_job(workflow, name) source = job.find("uses: ./.github/actions/checkout-native-source") start = job.rfind("\n -", 0, source) @@ -644,6 +688,7 @@ def release_source_contract_errors(workflow: str) -> list[str]: "package-and-release": "- name: Prepare release assets", "build-linux-openvino": "uses: ./.github/actions/openvino-sidecar-build", "openvino-sidecar-pair": "uses: ./.github/actions/openvino-sidecar-pair", + "hexagon-sidecar-pair": "--package-hexagon-sidecar", }.get(name, "tools/build.py") build = job.find(task) require( diff --git a/tests/test_android_hexagon.py b/tests/test_android_hexagon.py index 3a0dd967..53a57cb1 100644 --- a/tests/test_android_hexagon.py +++ b/tests/test_android_hexagon.py @@ -1,5 +1,6 @@ import io import json +import os import struct import sys import tarfile @@ -22,7 +23,7 @@ def elf(elf_class, machine, flags=0): return data -class AndroidHexagonTests(unittest.TestCase): +class AndroidHexagonFixture(unittest.TestCase): def setUp(self): temp = tempfile.TemporaryDirectory() self.addCleanup(temp.cleanup) @@ -68,6 +69,8 @@ def validate(self, out=None): def refresh_manifest(self): (self.out / hexagon.MANIFEST).write_text(json.dumps(hexagon.asset_manifest(self.out))) + +class AndroidHexagonTests(AndroidHexagonFixture): def test_opt_in_archive_round_trips_with_exact_notices_and_assets(self): archive = self.root / "bundle.tar.gz" hexagon.pack_archive(self.out, archive, self.variants) @@ -136,9 +139,230 @@ def test_rejects_extra_archive_entries(self): with self.assertRaisesRegex(ValueError, "Unexpected Hexagon archive member"): hexagon.unpack_archive(archive, self.root / "extracted", self.variants) + def test_rejects_modified_sdk_notice_at_build_time(self): + name = next(iter(hexagon.NOTICE_FILES)) + (self.sdk / name).write_bytes(b"unexpected SDK notice") + with self.assertRaisesRegex(ValueError, "notice differs from the pinned image"): + hexagon.notices_bytes(self.sdk) + + def test_rejects_unexpected_skeleton_build_inventory(self): + (self.dsp / "libggml-htp-v99.so").touch() + with self.assertRaisesRegex(ValueError, "Unexpected Hexagon skeleton set"): + hexagon.stage_assets(self.build, self.out, self.sdk) + + def test_rejects_unpinned_sdk_version(self): + ndk = self.root / "ndk" + ndk.mkdir() + (ndk / "source.properties").write_text(f"Pkg.Revision = {hexagon.NDK_VERSION}\n") + env = {"HEXAGON_SDK_ROOT": str(self.root / "other"), "HEXAGON_TOOLS_ROOT": str(self.sdk / hexagon.TOOLS_DIR)} + with self.assertRaisesRegex(ValueError, "requires SDK"): + hexagon.cache_vars(ndk, env) + + def test_requires_the_pinned_android_note(self): + library = self.out / hexagon.HOST_LIBRARY + note = bytearray(96) + struct.pack_into(" None: (assets / "fixture.bin").write_bytes(b"fixture") sidecar = "llamadart-native-linux-x64-openvino-v0.2.0.tar.gz" (assets / sidecar).write_bytes(b"openvino") + hexagon = "llamadart-native-android-arm64-hexagon-v0.2.0.tar.gz" + (assets / hexagon).write_bytes(b"hexagon") output = root / "assets.json" checksums = root / "SHA256SUMS" environment = os.environ.copy() @@ -60,3 +62,6 @@ def test_dynamic_metadata_is_json_escaped(self) -> None: row = next(asset for asset in manifest["artifacts"] if asset["file"] == sidecar) self.assertEqual((row["platform"], row["arch"], row["backend"], row["module"]), ("linux", "x64", "openvino", "backend-openvino")) + row = next(asset for asset in manifest["artifacts"] if asset["file"] == hexagon) + self.assertEqual((row["platform"], row["arch"], row["backend"], row["module"]), + ("android", "arm64", "hexagon", "backend-hexagon")) diff --git a/tests/test_linux_release_rows.py b/tests/test_linux_release_rows.py index 96902712..9a062b88 100644 --- a/tests/test_linux_release_rows.py +++ b/tests/test_linux_release_rows.py @@ -63,7 +63,7 @@ def test_packaged_openvino_pair_runs_on_the_same_release_inputs(self) -> None: self.assertIn("build-linux, build-linux-openvino]", pair) self.assertIn("uses: ./.github/actions/openvino-sidecar-pair", pair) release = job_block(RELEASE, "package-and-release") - self.assertIn("openvino-sidecar-pair]", release) + self.assertIn("openvino-sidecar-pair,", release) self.assertIn("find bundles/linux-x64 -iname '*openvino*'", release) def test_the_lane_runs_exactly_the_release_rows(self) -> None: diff --git a/tests/test_publish_prepared.py b/tests/test_publish_prepared.py index 1a99abb2..de48c056 100644 --- a/tests/test_publish_prepared.py +++ b/tests/test_publish_prepared.py @@ -21,7 +21,7 @@ import publish_prepared_release as prepared from release_contract import ContractError, build_release_result from release_publication import ExistingTag, _sha256, _expected_release_assets -from verify_release_provenance import (direct_dispatch_input_expressions, +from verify_release_provenance import (direct_dispatch_input_expressions, hexagon_release_contract_errors, publication_serialization_errors, workflow_run_blocks) @@ -77,9 +77,12 @@ def setUp(self): 'v0.8.0', upstream_sha, 'v0.8.0-2', 'review/prepared-123') self.files = self.temp / 'files'; assets = self.files / 'release_assets'; assets.mkdir(parents=True) entries = [] - for name in sorted(_expected_release_assets(self.expected.native_release_tag) - {'assets.json', 'SHA256SUMS'}): + for name in sorted(_expected_release_assets(self.expected.native_release_tag, prepared=True) - {'assets.json', 'SHA256SUMS'}): path = assets / name; path.write_bytes(('qualified:' + name).encode()) - entries.append({'file': name, 'size': path.stat().st_size, 'sha256': _sha256(path)}) + entry = {'file': name, 'size': path.stat().st_size, 'sha256': _sha256(path)} + if name == f'llamadart-native-android-arm64-hexagon-{self.expected.native_release_tag}.tar.gz': + entry.update(platform='android', arch='arm64', backend='hexagon', module='backend-hexagon') + entries.append(entry) manifest = {'tag': self.expected.native_release_tag, 'native_release_tag': self.expected.native_release_tag, 'llama_cpp_tag': self.expected.upstream_ref, 'llama_cpp_commit': upstream_sha, 'native_commit': native, 'correlation_id': self.expected.correlation_id, 'smoke_policy': 'required', 'smoke_conclusion': 'passed', @@ -133,7 +136,9 @@ def prepare(self): def test_exact_bytes_source_and_policy_derived_wrapper_prerelease(self): report, desired = self.prepare() self.assertEqual(self.source_result, report['source']); self.assertTrue(desired.prerelease) - self.assertEqual(17, len(desired.assets)); self.assertIn(self.expected.run_url, desired.body) + self.assertEqual(18, len(desired.assets)) + self.assertIn(f'llamadart-native-android-arm64-hexagon-{self.expected.native_release_tag}.tar.gz', desired.assets) + self.assertIn(self.expected.run_url, desired.body) self.assertIn('a' * 40, desired.body); self.assertEqual(self.expected.native_commit, git(self.reader, 'rev-parse', 'refs/remotes/prepared/release-provenance')) for path in (self.files / 'release_assets').iterdir(): self.assertEqual(path.read_bytes(), (self.temp / 'verified/prepared/release_assets' / path.name).read_bytes()) @@ -161,13 +166,24 @@ def test_all_required_smoke_matrix_and_skip_gates(self): jobs = copy.deepcopy(self.jobs); next(j for j in jobs if j['name'] == 'publish-release')['conclusion'] = 'success' with self.assertRaises(ContractError): prepared.validate_run(self.expected, self.run, jobs) - def test_hexagon_preparation_cannot_publish(self): - job = {'name': 'build-android-hexagon', 'status': 'completed', 'conclusion': 'skipped'} - prepared.validate_run(self.expected, self.run, [*self.jobs, job]) - - job = dict(job, name='build-android-hexagon / candidate', conclusion='success') - with self.assertRaisesRegex(ContractError, 'Hexagon SDK agreement review is pending'): - prepared.validate_run(self.expected, self.run, [*self.jobs, job]) + def test_requires_successful_hexagon_candidate_and_pair(self): + for name in ("build-android-hexagon / candidate", "hexagon-sidecar-pair"): + for conclusion in (None, "failure", "skipped"): + jobs = [job for job in self.jobs if job["name"] != name] + if conclusion is not None: + jobs.append(dict(name=name, status="completed", conclusion=conclusion)) + with self.subTest(name=name, conclusion=conclusion), self.assertRaises(ContractError): + prepared.validate_run(self.expected, self.run, jobs) + prepared.validate_run(self.expected, self.run, self.jobs) + + def test_workflow_checks_packaged_pair_and_rejects_core_leak(self): + workflow = (ROOT / ".github/workflows/native_release.yml").read_text() + self.assertEqual([], hexagon_release_contract_errors(workflow)) + guard = 'validate_core_layout(Path("bundles/android-arm64"))' + self.assertTrue(hexagon_release_contract_errors(workflow.replace(guard, 'None'))) + self.assertTrue(hexagon_release_contract_errors( + workflow.replace('--hexagon-sidecar-archive "hexagon-sidecar/$archive"', '') + )) def test_artifact_source_digest_id_and_producer_controls(self): for field, value in [('id', 999), ('name', 'other'), ('expired', True), ('digest', None), ('created_at', '2025-12-31T00:00:00Z')]: diff --git a/tests/test_release_contract.py b/tests/test_release_contract.py index 634325c9..a3103ae1 100644 --- a/tests/test_release_contract.py +++ b/tests/test_release_contract.py @@ -104,9 +104,16 @@ class ReleaseResultTests(unittest.TestCase): def test_publication_and_result_inventory_contracts_match(self) -> None: self.assertEqual(RUNTIME_BUNDLES, PUBLICATION_RUNTIME_BUNDLES) self.assertEqual(BACKEND_SIDECARS, PUBLICATION_BACKEND_SIDECARS) + tag = "v0.2.0-1" + for prepared in (False, True): + with self.subTest(prepared=prepared): + self.assertEqual( + _expected_assets(tag, prepared=prepared) | {"assets.json", "SHA256SUMS"}, + _expected_release_assets(tag, prepared=prepared), + ) self.assertEqual( - _expected_assets("v0.2.0-1") | {"assets.json", "SHA256SUMS"}, - _expected_release_assets("v0.2.0-1"), + {f"llamadart-native-android-arm64-hexagon-{tag}.tar.gz"}, + _expected_assets(tag, prepared=True) - _expected_assets(tag), ) def _cli_result_args(self, root: Path, metadata: Path) -> list[str]: @@ -158,16 +165,7 @@ def _fixture(self, root: Path) -> tuple[Path, dict[str, object]]: assets = root / "release_assets" assets.mkdir() tag = "v0.2.0" - names = { - f"llamadart-native-{bundle}-{tag}.tar.gz" - for bundle in (*RUNTIME_BUNDLES, *BACKEND_SIDECARS) - } - names.update( - { - f"llamadart-native-apple-xcframework-{tag}.zip", - f"llamadart-native-headers-{tag}.tar.gz", - } - ) + names = _expected_assets(tag) artifacts = [] checksums = [] for name in sorted(names): diff --git a/tests/test_release_publication.py b/tests/test_release_publication.py index 3eda8a7d..38f3a938 100644 --- a/tests/test_release_publication.py +++ b/tests/test_release_publication.py @@ -3,6 +3,8 @@ from __future__ import annotations +import contextlib +import io import json from pathlib import Path import subprocess @@ -15,14 +17,15 @@ ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "scripts")) +import release_publication + from release_publication import ( # noqa: E402 Asset, ExistingRelease, ExistingTag, - BACKEND_SIDECARS, PublicationError, - RUNTIME_BUNDLES, _ensure_tag, + _expected_release_assets, _release_json, _remote_tag, _run, @@ -80,16 +83,8 @@ def setUp(self) -> None: (assets / "assets.json").write_text("{}\n") (assets / "SHA256SUMS").write_text("fixture\n") tag = "v0.2.0-1" - for bundle in (*RUNTIME_BUNDLES, *BACKEND_SIDECARS): - (assets / f"llamadart-native-{bundle}-{tag}.tar.gz").write_bytes( - f"native bundle:{bundle}".encode() - ) - (assets / f"llamadart-native-apple-xcframework-{tag}.zip").write_bytes( - b"apple bundle" - ) - (assets / f"llamadart-native-headers-{tag}.tar.gz").write_bytes( - b"headers" - ) + for name in _expected_release_assets(tag) - {"assets.json", "SHA256SUMS"}: + (assets / name).write_bytes(f"native bundle:{name}".encode()) self.desired = build_desired_release( tag=tag, native_commit="1" * 40, @@ -102,6 +97,19 @@ def setUp(self) -> None: **EXACT_PROVENANCE, ) + def test_direct_publication_refuses_hexagon_asset_before_remote_calls(self) -> None: + assets = Path(self.temp.name) + name = f"llamadart-native-android-arm64-hexagon-{self.desired.tag}.tar.gz" + (assets / name).write_bytes(b"prepared sidecar") + stderr = io.StringIO() + with patch.object(sys, "argv", self._cli_args(assets)[1:]), \ + patch.object(release_publication, "publish") as publisher, \ + contextlib.redirect_stderr(stderr), self.assertRaises(SystemExit): + release_publication.main() + publisher.assert_not_called() + self.assertIn("inventory mismatch before publication", stderr.getvalue()) + self.assertIn(name, stderr.getvalue()) + def test_publication_rejects_missing_unexpected_or_non_file_assets(self) -> None: assets = Path(self.temp.name) base = { diff --git a/tests/test_release_source_identity.py b/tests/test_release_source_identity.py index dce1cc1b..54f06d81 100644 --- a/tests/test_release_source_identity.py +++ b/tests/test_release_source_identity.py @@ -169,7 +169,7 @@ def test_all_builds_import_the_resolved_owner_commit(self) -> None: def test_bypassing_any_lane_is_rejected(self) -> None: workflow = WORKFLOW.read_text() for name in ('build-android', 'build-apple', 'build-linux', 'build-linux-hip', - 'build-windows', 'package-and-release'): + 'build-windows', 'hexagon-sidecar-pair', 'package-and-release'): with self.subTest(lane=name): original = workflow_job(workflow, name) for before, after in ( diff --git a/tools/android_hexagon.py b/tools/android_hexagon.py index 76b92304..27797df6 100644 --- a/tools/android_hexagon.py +++ b/tools/android_hexagon.py @@ -1,5 +1,6 @@ from __future__ import annotations +import gzip import hashlib import json import re @@ -9,7 +10,9 @@ import tarfile from pathlib import Path +import llama_cpp_patches import validate_build_identity +from mutate_embedded_identity import read_identity TOOLCHAIN_IMAGE = ( "ghcr.io/snapdragon-toolchain/arm64-android@" @@ -21,10 +24,14 @@ SDK_REPACK_SHA256 = "00725fc449916d7b9af2c2a3c6b54d61f3c872d5dbc1d3ca3fd2f839b1d5dc70" HOST_LIBRARY = "libggml-hexagon.so" +PRIMARY_LIBRARY = Path("libllamadart.so") +GGML_BASE = "libggml-base.so" ASSET_DIR = Path("assets/hexagon") SKELETONS = {f"libggml-htp-v{version}.so": int(version, 16) for version in ("73", "75", "79", "81", "85")} NOTICES = Path("HEXAGON-NOTICES.txt") MANIFEST = Path("hexagon-assets.json") +SIDECAR_PAYLOAD = {Path(HOST_LIBRARY), NOTICES, *(ASSET_DIR / name for name in SKELETONS)} +SIDECAR_FILES = SIDECAR_PAYLOAD | {MANIFEST} CORE_LIBRARIES = { "libggml-base.so", "libggml.so", "libllama-common.so", "libllama.so", "libllamadart.so", "libmtmd.so", HOST_LIBRARY, @@ -62,6 +69,8 @@ f"Qualcomm catalog: https://softwarecenter.qualcomm.com/catalog/item/Hexagon_SDK?version={SDK_VERSION}\n" "Maintainer approved SDK use in hosted CI and redistribution of the generated DSP skeletons.\n" "Approval: https://github.com/leehack/llamadart-native/issues/260#issuecomment-7326932721\n" + "Publication requires separate maintainer approval.\n" + "Decision record: https://github.com/leehack/llamadart-native/issues/260#issuecomment-7328335092\n" ).encode() @@ -118,20 +127,27 @@ def validate_notices(data: bytes) -> None: raise ValueError(f"Hexagon SDK notice bytes differ: {path}") -def asset_manifest(out_dir: Path) -> dict: - files = sorted( - [path.relative_to(out_dir) for path in out_dir.glob("*.so")] - + [NOTICES, *(ASSET_DIR / name for name in SKELETONS)] - ) +def manifest_for(files: dict[Path, Path]) -> dict: return { - "owner_build_identity": sorted(validate_build_identity.identities(out_dir / "libllamadart.so")), + "owner_build_identity": sorted(validate_build_identity.identities(files[PRIMARY_LIBRARY])), "toolchain_image": TOOLCHAIN_IMAGE, "android_ndk": NDK_VERSION, "hexagon_sdk": SDK_VERSION, - "files": {path.as_posix(): digest((out_dir / path).read_bytes()) for path in files}, + "files": {path.as_posix(): digest(files[path].read_bytes()) for path in sorted(files)}, } +def asset_manifest(out_dir: Path) -> dict: + files = SIDECAR_PAYLOAD | {path.relative_to(out_dir) for path in out_dir.glob("*.so")} + return manifest_for({path: out_dir / path for path in files}) + + +def sidecar_manifest(sidecar_dir: Path, core_dir: Path) -> dict: + files = {path: sidecar_dir / path for path in SIDECAR_PAYLOAD} + files[PRIMARY_LIBRARY] = core_dir / PRIMARY_LIBRARY + return manifest_for(files) + + def stage_assets(build_dir: Path, out_dir: Path, sdk: Path) -> None: output = build_dir / "third_party/llama.cpp/ggml/src/ggml-hexagon" if {path.name for path in output.glob("libggml-htp-*.so")} != SKELETONS.keys(): @@ -178,14 +194,12 @@ def check_android_note(readelf: Path, path: Path) -> None: def expected_files(cpu_variants: tuple[str, ...]) -> set[Path]: - return {Path(name) for name in CORE_LIBRARIES | set(cpu_variants)} | { - NOTICES, MANIFEST, *(ASSET_DIR / name for name in SKELETONS), - } + return {Path(name) for name in CORE_LIBRARIES | set(cpu_variants)} | SIDECAR_FILES -def validate(out_dir: Path, readelf: Path, cpu_variants: tuple[str, ...], - symbols: dict[str, tuple[set[str], set[str]]], read_symbols) -> None: - expected = expected_files(cpu_variants) +def validate_inventory(out_dir: Path, expected: set[Path]) -> None: + if out_dir.is_symlink() or not out_dir.is_dir(): + raise ValueError("Expected a regular Hexagon bundle directory") actual = set() for path in out_dir.rglob("*"): if path.is_symlink() or not (path.is_file() or path.is_dir()): @@ -198,33 +212,31 @@ def validate(out_dir: Path, readelf: Path, cpu_variants: tuple[str, ...], f"unexpected {sorted(actual - expected)}" ) - validate_notices((out_dir / NOTICES).read_bytes()) - if json.loads((out_dir / MANIFEST).read_bytes()) != asset_manifest(out_dir): - raise ValueError("Hexagon bundle manifest identity or SHA-256 values differ") - - runtime = CORE_LIBRARIES | set(cpu_variants) - for name in sorted(runtime): - path = out_dir / name - if elf_header(path) != (2, 183, 0): - raise ValueError(f"{name}: expected Android AArch64 ELF64") - check_android_note(readelf, path) - needed, soname = dynamic_tags(readelf, path) - if soname is not None and soname != name: - raise ValueError(f"{name}: unexpected SONAME {soname}") - if missing := needed - runtime - ANDROID_LIBRARIES: - raise ValueError(f"{name}: dependencies outside the Android runtime set: {sorted(missing)}") - if name == HOST_LIBRARY and "libggml-base.so" not in needed: - raise ValueError(f"{name}: missing libggml-base.so dependency") - host = out_dir / HOST_LIBRARY - defined, imported = symbols[HOST_LIBRARY] - if "ggml_backend_init" not in defined or b"libcdsprpc.so\0" not in host.read_bytes(): +def validate_host_library(path: Path, readelf: Path, runtime: set[str]) -> set[str]: + name = path.name + if elf_header(path) != (2, 183, 0): + raise ValueError(f"{name}: expected Android AArch64 ELF64") + check_android_note(readelf, path) + needed, soname = dynamic_tags(readelf, path) + if soname is not None and soname != name: + raise ValueError(f"{name}: unexpected SONAME {soname}") + if missing := needed - runtime - ANDROID_LIBRARIES: + raise ValueError(f"{name}: dependencies outside the Android runtime set: {sorted(missing)}") + return needed + + +def validate_hexagon_host(out_dir: Path, needed: set[str], symbols: tuple[set[str], set[str]], + core_exports: set[str]) -> None: + if GGML_BASE not in needed: + raise ValueError(f"{HOST_LIBRARY}: missing {GGML_BASE} dependency") + defined, imported = symbols + if "ggml_backend_init" not in defined or b"libcdsprpc.so\0" not in (out_dir / HOST_LIBRARY).read_bytes(): raise ValueError(f"{HOST_LIBRARY}: missing backend initializer or FastRPC soname") - if missing := {name for name in imported if name.startswith("ggml_")} - symbols["libggml-base.so"][0]: + if missing := {name for name in imported if name.startswith("ggml_")} - core_exports: raise ValueError(f"{HOST_LIBRARY}: unresolved ggml imports: {sorted(missing)}") - for name in cpu_variants: - if not {"ggml_backend_init", "ggml_backend_score"} <= symbols[name][0]: - raise ValueError(f"{name}: missing CPU backend initializer or score export") + +def validate_skeletons(out_dir: Path, readelf: Path, read_symbols) -> None: for name, flags in SKELETONS.items(): path = out_dir / ASSET_DIR / name if elf_header(path) != (1, 164, flags): @@ -236,21 +248,120 @@ def validate(out_dir: Path, readelf: Path, cpu_variants: tuple[str, ...], raise ValueError(f"{name}: missing FastRPC skeleton export") -def unpack_archive(archive: Path, out_dir: Path, cpu_variants: tuple[str, ...]) -> None: - expected = expected_files(cpu_variants) +def validate(out_dir: Path, readelf: Path, cpu_variants: tuple[str, ...], + symbols: dict[str, tuple[set[str], set[str]]], read_symbols) -> None: + validate_inventory(out_dir, expected_files(cpu_variants)) + validate_notices((out_dir / NOTICES).read_bytes()) + if json.loads((out_dir / MANIFEST).read_bytes()) != asset_manifest(out_dir): + raise ValueError("Hexagon bundle manifest identity or SHA-256 values differ") + + runtime = CORE_LIBRARIES | set(cpu_variants) + for name in sorted(runtime): + needed = validate_host_library(out_dir / name, readelf, runtime) + if name == HOST_LIBRARY: + validate_hexagon_host(out_dir, needed, symbols[name], symbols[GGML_BASE][0]) + for name in cpu_variants: + if not {"ggml_backend_init", "ggml_backend_score"} <= symbols[name][0]: + raise ValueError(f"{name}: missing CPU backend initializer or score export") + validate_skeletons(out_dir, readelf, read_symbols) + + +def validate_core_layout(core_dir: Path) -> None: + if not core_dir.is_dir() or core_dir.is_symlink(): + raise ValueError("Expected a regular Android core bundle directory") + for path in core_dir.rglob("*"): + name = path.name.lower() + if "hexagon" in name or "htp" in name: + raise ValueError(f"Default Android artifacts must exclude Hexagon host and DSP files: {path.name}") + + +def android_identity(path: Path, backend: str) -> dict[str, str]: + if path.is_symlink() or elf_header(path) != (2, 183, 0): + raise ValueError(f"{path.name}: expected Android AArch64 ELF64") + _, _, fields = read_identity(path.read_bytes()) + if set(fields["backends"].split(",")) != {"cpu", backend}: + raise ValueError(f"{path.name}: build identity must provide CPU and {backend}") + return fields + + +def validate_sidecar(sidecar_dir: Path, core_dir: Path, readelf: Path, *, + read_symbols, read_load_alignments, min_load_align: int = 0x4000) -> None: + validate_inventory(sidecar_dir, SIDECAR_FILES) + validate_core_layout(core_dir) + android_identity(core_dir / PRIMARY_LIBRARY, "vulkan") + base = core_dir / GGML_BASE + if base.is_symlink() or elf_header(base) != (2, 183, 0): + raise ValueError(f"{GGML_BASE}: expected Android AArch64 ELF64") + + validate_notices((sidecar_dir / NOTICES).read_bytes()) + if json.loads((sidecar_dir / MANIFEST).read_bytes()) != sidecar_manifest(sidecar_dir, core_dir): + raise ValueError("Hexagon sidecar manifest identity or SHA-256 values differ") + + host = sidecar_dir / HOST_LIBRARY + needed = validate_host_library(host, readelf, {GGML_BASE}) + validate_hexagon_host(sidecar_dir, needed, read_symbols(readelf, host), read_symbols(readelf, base)[0]) + alignments = read_load_alignments(readelf, host) + if not alignments or min(alignments) < max(min_load_align, 0x4000): + raise ValueError(f"{HOST_LIBRARY}: expected LOAD alignments >= 0x{max(min_load_align, 0x4000):x}") + if errors := llama_cpp_patches.android_marker_errors(sidecar_dir, include_cpu=False): + raise ValueError("\n".join(errors)) + validate_skeletons(sidecar_dir, readelf, read_symbols) + + +def package_sidecar(candidate_dir: Path, core_dir: Path, out_dir: Path, archive: Path, readelf: Path, + *, read_symbols, read_load_alignments) -> None: + candidate = android_identity(candidate_dir / PRIMARY_LIBRARY, "hexagon") + core = android_identity(core_dir / PRIMARY_LIBRARY, "vulkan") + for field in validate_build_identity.KEYS: + if field not in {"backends", "options"} and candidate[field] != core[field]: + raise ValueError(f"Hexagon candidate/core build identity mismatch: {field}") + + out_dir.mkdir(parents=True) + (out_dir / ASSET_DIR).mkdir(parents=True) + for path in sorted(SIDECAR_PAYLOAD): + source = candidate_dir / path + if source.is_symlink() or not source.is_file(): + raise ValueError(f"Expected a regular Hexagon candidate file: {path}") + shutil.copyfile(source, out_dir / path) + (out_dir / MANIFEST).write_text(json.dumps(sidecar_manifest(out_dir, core_dir), indent=2) + "\n") + validate_sidecar(out_dir, core_dir, readelf, read_symbols=read_symbols, + read_load_alignments=read_load_alignments) + + archive.parent.mkdir(parents=True, exist_ok=True) + with archive.open("wb") as stream, gzip.GzipFile(filename="", mode="wb", fileobj=stream, mtime=0) as compressed: + with tarfile.open(mode="w|", fileobj=compressed) as tar: + for path in sorted(SIDECAR_FILES): + source = out_dir / path + entry = tarfile.TarInfo(path.as_posix()) + entry.size = source.stat().st_size + with source.open("rb") as contents: + tar.addfile(entry, contents) + + +def unpack_files(archive: Path, out_dir: Path, expected: set[Path]) -> None: + names = {path.as_posix() for path in expected} + out_dir.mkdir() unpacked = set() with tarfile.open(archive, "r:gz") as tar: for member in tar: - path = Path(member.name) - if path not in expected or path in unpacked or not member.isfile(): - raise ValueError(f"Unexpected Hexagon archive member: {member.name}") - destination = out_dir / path + name = member.name + if name not in names or name in unpacked or member.type != tarfile.REGTYPE: + raise ValueError(f"Unexpected Hexagon archive member: {name}") + destination = out_dir / name destination.parent.mkdir(parents=True, exist_ok=True) - with tar.extractfile(member) as source, destination.open("wb") as file: + with tar.extractfile(member) as source, destination.open("xb") as file: shutil.copyfileobj(source, file) - unpacked.add(path) - if unpacked != expected: - raise ValueError(f"Missing Hexagon archive members: {sorted(expected - unpacked)}") + unpacked.add(name) + if unpacked != names: + raise ValueError(f"Missing Hexagon archive members: {sorted(names - unpacked)}") + + +def unpack_archive(archive: Path, out_dir: Path, cpu_variants: tuple[str, ...]) -> None: + unpack_files(archive, out_dir, expected_files(cpu_variants)) + + +def unpack_sidecar_archive(archive: Path, out_dir: Path) -> None: + unpack_files(archive, out_dir, SIDECAR_FILES) def pack_archive(out_dir: Path, archive: Path, cpu_variants: tuple[str, ...]) -> None: diff --git a/tools/validate_android_artifacts.py b/tools/validate_android_artifacts.py index ce036065..5a1a521e 100644 --- a/tools/validate_android_artifacts.py +++ b/tools/validate_android_artifacts.py @@ -22,9 +22,19 @@ def parse_args() -> argparse.Namespace: hexagon = parser.add_mutually_exclusive_group() hexagon.add_argument("--hexagon", action="store_true", help="validate the opt-in Android arm64 bundle") hexagon.add_argument("--hexagon-archive", action="store_true", - help="validate an opt-in Android arm64 release tar.gz instead of a directory") + help="validate an opt-in standalone Android arm64 candidate archive") + hexagon.add_argument("--hexagon-sidecar", action="store_true", + help="validate a Hexagon sidecar directory against --core-dir") + hexagon.add_argument("--hexagon-sidecar-archive", action="store_true", + help="validate a Hexagon sidecar archive against --core-dir") + hexagon.add_argument("--package-hexagon-sidecar", type=Path, metavar="ARCHIVE", + help="pair the input candidate archive with --core-dir and write the sidecar") + parser.add_argument("--core-dir", type=Path, help="the paired Android arm64 Vulkan core") args = parser.parse_args() - if args.backend_only and (args.hexagon or args.hexagon_archive): + sidecar = args.hexagon_sidecar or args.hexagon_sidecar_archive or args.package_hexagon_sidecar + if bool(sidecar) != bool(args.core_dir): + parser.error("--core-dir is required exactly for Hexagon sidecar validation and packaging") + if args.backend_only and (args.hexagon or args.hexagon_archive or sidecar): parser.error("Hexagon validation requires the complete Android arm64 bundle") return args @@ -140,10 +150,8 @@ def validate_directory(args: argparse.Namespace) -> None: if args.hexagon or args.hexagon_archive: android_hexagon.validate(args.out_dir, args.readelf, build.android_arm64_cpu_variant_libs(), symbols, read_dynamic_symbols) - elif (args.out_dir / android_hexagon.HOST_LIBRARY).exists() or any( - args.out_dir.rglob("libggml-htp-*.so") - ) or (args.out_dir / android_hexagon.MANIFEST).exists() or (args.out_dir / android_hexagon.NOTICES).exists(): - errors.append("Default Android artifacts must exclude Hexagon host and DSP files") + else: + android_hexagon.validate_core_layout(args.out_dir) errors.extend(exception_runtime_errors(symbols)) errors.extend(llama_cpp_patches.android_marker_errors( args.out_dir, include_cpu=not args.backend_only)) @@ -183,10 +191,28 @@ def main() -> None: if not args.readelf.is_file(): raise SystemExit(f"Missing llvm-readelf binary: {args.readelf}") try: - if args.hexagon_archive: + if args.package_hexagon_sidecar: + with tempfile.TemporaryDirectory() as temp: + candidate = Path(temp) / "candidate" + android_hexagon.unpack_archive(args.out_dir, candidate, build.android_arm64_cpu_variant_libs()) + android_hexagon.package_sidecar( + candidate, args.core_dir, Path(temp) / "sidecar", args.package_hexagon_sidecar, + args.readelf, read_symbols=read_dynamic_symbols, read_load_alignments=read_load_alignments, + ) + elif args.hexagon_sidecar or args.hexagon_sidecar_archive: + with tempfile.TemporaryDirectory() as temp: + sidecar = args.out_dir + if args.hexagon_sidecar_archive: + sidecar = Path(temp) / "sidecar" + android_hexagon.unpack_sidecar_archive(args.out_dir, sidecar) + android_hexagon.validate_sidecar( + sidecar, args.core_dir, args.readelf, read_symbols=read_dynamic_symbols, + read_load_alignments=read_load_alignments, min_load_align=args.min_load_align, + ) + elif args.hexagon_archive: with tempfile.TemporaryDirectory() as temp: archive = args.out_dir - args.out_dir = Path(temp) + args.out_dir = Path(temp) / "candidate" android_hexagon.unpack_archive(archive, args.out_dir, build.android_arm64_cpu_variant_libs()) validate_directory(args) else: From 3f95c7f848f1ba90c378a59184c804a71d91bd2d Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Wed, 2 Dec 2026 06:25:16 -0500 Subject: [PATCH 2/2] Record Hexagon sidecar publication approval --- docs/android_hexagon.md | 11 ++++---- tests/test_android_hexagon.py | 12 +++++++++ tests/test_release_contract.py | 46 ++++++++++++++++++++++++++++++++-- tools/android_hexagon.py | 7 +++--- 4 files changed, 64 insertions(+), 12 deletions(-) diff --git a/docs/android_hexagon.md b/docs/android_hexagon.md index dcc95704..6858561f 100644 --- a/docs/android_hexagon.md +++ b/docs/android_hexagon.md @@ -1,11 +1,10 @@ # Experimental Android arm64 Hexagon sidecar -The maintainer approved use of Qualcomm Hexagon SDK Community Edition 6.7.0.0 -in hosted CI and redistribution of the generated DSP skeletons in -[#260](https://github.com/leehack/llamadart-native/issues/260#issuecomment-7326932721). -The [recorded approval](https://github.com/leehack/llamadart-native/issues/260#issuecomment-7328335092) -leaves publication to a separate maintainer decision. Qualcomm hosts the -click-through terms in Software Center. +On 2026-12-01, the maintainer approved use of Qualcomm Hexagon SDK Community +Edition 6.7.0.0 in hosted CI and redistribution of the generated DSP skeletons +in [#260](https://github.com/leehack/llamadart-native/issues/260#issuecomment-7326932721). +On 2026-12-02, the maintainer approved publication of the Hexagon sidecar in +v1.1.0-6. Qualcomm hosts the click-through terms in Software Center. The [Qualcomm catalog](https://softwarecenter.qualcomm.com/catalog/item/Hexagon_SDK?version=6.7.0.0) links the vendor distribution. The [public SDK repack](https://github.com/snapdragon-toolchain/hexagon-sdk/releases/tag/v6.7.0.0) contains third-party notices that refer Qualcomm terms to a separate agreement. diff --git a/tests/test_android_hexagon.py b/tests/test_android_hexagon.py index 53a57cb1..8273d174 100644 --- a/tests/test_android_hexagon.py +++ b/tests/test_android_hexagon.py @@ -245,6 +245,12 @@ def test_packages_only_sidecar_files_and_binds_shipped_core(self): extracted = self.root / "extracted" hexagon.unpack_sidecar_archive(self.archive, extracted) self.validate_pair(extracted) + notices = (extracted / hexagon.NOTICES).read_bytes() + self.assertIn(b"On 2026-12-01, the maintainer approved SDK use in hosted CI", notices) + self.assertIn( + b"On 2026-12-02, the maintainer approved publication of the Hexagon sidecar in v1.1.0-6.", + notices, + ) with tarfile.open(self.archive) as tar: members = tar.getmembers() names = [hexagon.HOST_LIBRARY, "HEXAGON-NOTICES.txt", "hexagon-assets.json"] @@ -291,6 +297,12 @@ def test_rejects_core_library_in_sidecar_directory_or_archive(self): with self.assertRaisesRegex(ValueError, "Unexpected Hexagon archive member"): hexagon.unpack_sidecar_archive(self.archive, self.root / "extracted") + def test_sidecar_validation_rejects_hexagon_payload_added_to_core(self): + self.package() + (self.core / hexagon.HOST_LIBRARY).touch() + with self.assertRaisesRegex(ValueError, "must exclude Hexagon"): + self.validate_pair() + def test_rejects_stale_core_digest_even_with_matching_identity(self): self.package() primary = self.core / "libllamadart.so" diff --git a/tests/test_release_contract.py b/tests/test_release_contract.py index a3103ae1..a4f5722b 100644 --- a/tests/test_release_contract.py +++ b/tests/test_release_contract.py @@ -233,7 +233,9 @@ def _fixture(self, root: Path) -> tuple[Path, dict[str, object]]: ).body return assets, release - def _result(self, assets: Path, release: dict[str, object]) -> dict[str, object]: + def _result( + self, assets: Path, release: dict[str, object] | None, *, publish_release: bool = True + ) -> dict[str, object]: return build_release_result( assets_dir=assets, release_metadata=release, @@ -244,7 +246,7 @@ def _result(self, assets: Path, release: dict[str, object]) -> dict[str, object] correlation_id="central-123", smoke_policy="required", smoke_conclusion="passed", - publish_release=True, + publish_release=publish_release, workflow_repository="leehack/llamadart-native", workflow_run_id="123", workflow_run_attempt="1", @@ -266,6 +268,46 @@ def test_result_returns_exact_provenance_coverage_digests_and_smoke(self) -> Non self.assertEqual("passed", result["smoke"]["conclusion"]) self.assertEqual(42, result["release"]["id"]) + def test_prepared_result_rejects_incorrect_hexagon_metadata(self) -> None: + with tempfile.TemporaryDirectory() as directory: + assets, _ = self._fixture(Path(directory)) + name = "llamadart-native-android-arm64-hexagon-v0.2.0.tar.gz" + payload = b"hexagon sidecar" + (assets / name).write_bytes(payload) + digest = hashlib.sha256(payload).hexdigest() + with (assets / "SHA256SUMS").open("a") as checksums: + checksums.write(f"{digest} {name}\n") + manifest_path = assets / "assets.json" + manifest = json.loads(manifest_path.read_text()) + manifest["hook_contract_version"] = 2 + entry = { + "file": name, + "sha256": digest, + "size": len(payload), + "platform": "android", + "arch": "arm64", + "backend": "hexagon", + "module": "backend-hexagon", + } + manifest["artifacts"].append(entry) + manifest_path.write_text(json.dumps(manifest)) + self.assertEqual("prepared", self._result(assets, None, publish_release=False)["status"]) + + for target, field, invalid in ( + (manifest, "hook_contract_version", 1), + (entry, "platform", "linux"), + (entry, "arch", "x64"), + (entry, "backend", "vulkan"), + (entry, "module", "backend-vulkan"), + ): + with self.subTest(field=field): + original = target[field] + target[field] = invalid + manifest_path.write_text(json.dumps(manifest)) + with self.assertRaisesRegex(ContractError, "prepared Hexagon sidecar metadata"): + self._result(assets, None, publish_release=False) + target[field] = original + def test_result_rejects_digest_or_bundle_mismatch(self) -> None: with tempfile.TemporaryDirectory() as directory: assets, release = self._fixture(Path(directory)) diff --git a/tools/android_hexagon.py b/tools/android_hexagon.py index 27797df6..02d3a8cf 100644 --- a/tools/android_hexagon.py +++ b/tools/android_hexagon.py @@ -67,10 +67,9 @@ f"SDK repack: https://github.com/snapdragon-toolchain/hexagon-sdk/releases/tag/v{SDK_VERSION}\n" f"Linux amd64 SDK repack SHA-256: {SDK_REPACK_SHA256}\n" f"Qualcomm catalog: https://softwarecenter.qualcomm.com/catalog/item/Hexagon_SDK?version={SDK_VERSION}\n" - "Maintainer approved SDK use in hosted CI and redistribution of the generated DSP skeletons.\n" - "Approval: https://github.com/leehack/llamadart-native/issues/260#issuecomment-7326932721\n" - "Publication requires separate maintainer approval.\n" - "Decision record: https://github.com/leehack/llamadart-native/issues/260#issuecomment-7328335092\n" + "On 2026-12-01, the maintainer approved SDK use in hosted CI and redistribution of the generated DSP skeletons.\n" + "SDK approval: https://github.com/leehack/llamadart-native/issues/260#issuecomment-7326932721\n" + "On 2026-12-02, the maintainer approved publication of the Hexagon sidecar in v1.1.0-6.\n" ).encode()