From 34fff40b5615645104f89762c4a2d145eef93f69 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:47:42 -0500 Subject: [PATCH] ci: run Kotlin unit tests separately from APK builds (#3566) Run Kotlin tests beside APK compilation while keeping merge and release checks intact. Pin the APK and test workflows to the same pull request base, retry Robolectric rate limits on both Maven Central hosts, and verify source parity when main advances. --- .github/workflows/authorship.yml | 8 +- .github/workflows/build.yml | 130 ++---------------- .github/workflows/release.yml | 7 + .github/workflows/unit-tests.yml | 182 ++++++++++++++++++++++++++ AGENTS.md | 4 +- app/build.gradle | 6 +- tools/ci/build-label.sh | 19 +++ tools/components/README.md | 7 +- tools/release/report-build.sh | 28 +--- tools/release/validate_apk.py | 62 +++++++-- tools/tests/test_ci_checks.py | 49 ++++++- tools/tests/test_validate_apk.py | 32 ++++- tools/tests/test_xbox_build_source.py | 18 ++- 13 files changed, 381 insertions(+), 171 deletions(-) create mode 100644 .github/workflows/unit-tests.yml create mode 100755 tools/ci/build-label.sh diff --git a/.github/workflows/authorship.yml b/.github/workflows/authorship.yml index 615267b6c..857fb6802 100644 --- a/.github/workflows/authorship.yml +++ b/.github/workflows/authorship.yml @@ -7,7 +7,7 @@ on: push: branches: [main] workflow_run: - workflows: [Build APK] + workflows: [Build APK, Unit tests] types: [completed] workflow_dispatch: inputs: @@ -21,6 +21,12 @@ permissions: pull-requests: read statuses: write +# Build APK and Unit tests each trigger a validation, and the last one to post sets the status. Queued runs for a +# commit wait, so the newest one reads both results and posts last. +concurrency: + group: build-validation-${{ github.event.pull_request.head.sha || github.event.workflow_run.head_sha || inputs.pr_number || github.sha }} + cancel-in-progress: false + jobs: validate: name: Validate source and build result diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index d713d0f49..e4229729d 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,5 +1,5 @@ name: Build APK -run-name: ${{ github.event_name == 'pull_request' && format('building pr {0} on {1}', github.event.pull_request.number, github.event.pull_request.head.sha) || format('building {0} on {1}', github.ref_name, github.sha) }} +run-name: ${{ github.event_name == 'pull_request' && format('building pr {0} on {1} against {2}', github.event.pull_request.number, github.event.pull_request.head.sha, github.event.pull_request.base.sha) || format('building {0} on {1}', github.ref_name, github.sha) }} on: push: @@ -57,15 +57,18 @@ jobs: - name: Pin and merge the APK source id: merge if: github.event_name == 'pull_request' + env: + PR_BASE_SHA: ${{ github.event.pull_request.base.sha }} run: | set -euo pipefail - git fetch --no-tags origin main - echo "base-sha=$(git rev-parse origin/main)" >> "$GITHUB_OUTPUT" + # Unit tests uses the same event snapshot, including when either workflow is rerun. + git fetch --no-tags origin "$PR_BASE_SHA" + echo "base-sha=$PR_BASE_SHA" >> "$GITHUB_OUTPUT" git config user.name "ci" git config user.email "ci@users.noreply.github.com" # Partial clone: a merged blob that only exists in a fork's history can't be lazily fetched (GitHub: "not our ref"); merge-tree writes it locally first. - git merge-tree --write-tree HEAD origin/main >/dev/null || true - git merge --no-ff --no-edit origin/main + git merge-tree --write-tree HEAD FETCH_HEAD >/dev/null || true + git merge --no-ff --no-edit FETCH_HEAD - name: Resolve trusted manifest base id: trusted if: github.event_name != 'pull_request' @@ -349,7 +352,7 @@ jobs: build: needs: [source, components, xbox, build-runner] - name: Compile APK and Android tests + name: Compile APK if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }} runs-on: ${{ fromJSON(needs.build-runner.outputs.labels) }} timeout-minutes: 45 @@ -507,23 +510,7 @@ jobs: PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }} BUILD_REF: ${{ github.ref_name }} BUILD_SHA: ${{ github.sha }} - run: | - if [[ -n "$(git status --porcelain)" ]]; then - tree_state=dirty - else - tree_state=clean - fi - echo "DROIDDECK_BUILD_TREE_STATE=$tree_state" >> "$GITHUB_ENV" - if [[ -n "$PR_NUMBER" ]]; then - label="pr${PR_NUMBER} at ${PR_HEAD_SHA:0:7}" - else - label="${BUILD_REF} at ${BUILD_SHA:0:7}" - fi - echo "label=$label" >> "$GITHUB_OUTPUT" - echo "DROIDDECK_SOURCE_COMMIT=${PR_HEAD_SHA:-$BUILD_SHA}" >> "$GITHUB_ENV" - echo "DROIDDECK_PR_NUMBER=${PR_NUMBER:-0}" >> "$GITHUB_ENV" - echo "DROIDDECK_PR_TITLE=${PR_TITLE//$'\n'/ }" >> "$GITHUB_ENV" - echo "Build: \`$label\`" >> "$GITHUB_STEP_SUMMARY" + run: bash tools/ci/build-label.sh - name: Rust toolchain for the store engines (aarch64-linux-android) id: rust @@ -734,101 +721,6 @@ jobs: if-no-files-found: ignore overwrite: true - - name: Resolve the Robolectric version - id: robolectric - run: | - echo "version=$(grep -o "org.robolectric:robolectric:[0-9.]*" app/build.gradle | cut -d: -f3)" >> "$GITHUB_OUTPUT" - # Robolectric downloads these from Maven Central on first use without retrying, and 429s fail whole test classes. - # The cache path sits beside the workspace because runner homes are at different depths from it, and - # actions/cache stores paths relative to the workspace. It is passed as an absolute path: the save action rejects - # "..". Runners that keep their own ~/.m2 skip the cache. - - name: Place Robolectric's Android jars beside the workspace - id: robolectric-jars - run: | - set -euo pipefail - jars="$GITHUB_WORKSPACE/../robolectric-jars" - m2="$HOME/.m2/repository/org/robolectric/android-all-instrumented" - if [ -d "$m2" ] && [ ! -L "$m2" ]; then - echo "cache=false" >> "$GITHUB_OUTPUT" - else - mkdir -p "$jars" "$(dirname "$m2")" - jars=$(cd "$jars" && pwd) - ln -sfn "$jars" "$m2" - echo "path=$jars" >> "$GITHUB_OUTPUT" - echo "cache=true" >> "$GITHUB_OUTPUT" - fi - - name: Restore Robolectric's Android jars - id: robolectric-cache - if: steps.robolectric-jars.outputs.cache == 'true' - uses: actions/cache/restore@v4 - with: - path: ${{ steps.robolectric-jars.outputs.path }} - key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }} - restore-keys: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}- - - name: Count the restored Robolectric jars - if: steps.robolectric-jars.outputs.cache == 'true' - run: echo "ROBOLECTRIC_JARS_BEFORE=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l)" >> "$GITHUB_ENV" - - name: Unit tests - id: unit-tests - env: - DROIDDECK_BUILD_LABEL: ${{ steps.build-label.outputs.label }} - SGDB_API_KEY: ${{ secrets.SGDB_API_KEY }} - run: | - set -o pipefail - mkdir -p app/build - # A Maven 429 fails every test class that needs the missing jar. The jars an attempt did get stay for the next. - for wait in 60 180 0; do - status=0 - ./gradlew testReleaseUnitTest --console=plain --info --stacktrace -Drobolectric.logging=stderr -PndkVersion="$NDK_VERSION" 2>&1 | tee app/build/unit-tests.log || status=$? - if [ "$status" = 0 ] || [ "$wait" = 0 ] || ! grep -Eq '^[[:space:]]*(Caused by: org\.gradle\.internal\.resource\.transport\.http\.HttpErrorStatusCodeException: Could not GET .*https://repo\.maven\.apache\.org/.*Received status code 429 from server|Caused by: java\.io\.IOException: Server returned HTTP response code: 429 for URL: https://repo\.maven\.apache\.org/)' app/build/unit-tests.log; then - exit "$status" - fi - echo "::warning::Maven Central answered 429; running the unit tests again in ${wait}s" - sleep "$wait" - done - - # actions/cache only saves when the job succeeds, so a run whose tests died on a Maven 429 never filled the cache. - # Save the complete jars even after a failed test step, when this run added some; a partial download is dropped first. - - name: Save Robolectric's Android jars - id: robolectric-jars-final - if: always() && steps.robolectric-jars.outputs.cache == 'true' - run: | - python3 - <<'PY' - import glob, os, zipfile - root = os.path.join(os.environ['GITHUB_WORKSPACE'], '..', 'robolectric-jars') - for f in glob.glob(os.path.join(root, '**', '*'), recursive=True): - if not os.path.isfile(f): - continue - try: - ok = f.endswith('.jar') and zipfile.ZipFile(f).testzip() is None - except Exception: - ok = False - if not ok: - os.remove(f) - PY - after=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l) - [ "$after" -gt "${ROBOLECTRIC_JARS_BEFORE:-0}" ] && echo "save=true" >> "$GITHUB_OUTPUT" || true - - name: Store Robolectric's Android jars - if: always() && steps.robolectric-jars-final.outputs.save == 'true' - uses: actions/cache/save@v4 - with: - path: ${{ steps.robolectric-jars.outputs.path }} - key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }} - - - name: Upload unit test diagnostics - id: unit-test-diagnostics - if: always() && steps.unit-tests.outcome != 'skipped' - uses: actions/upload-artifact@v4 - with: - name: unit-test-results - path: | - app/build/unit-tests.log - app/build/test-results/testReleaseUnitTest/ - app/build/reports/tests/testReleaseUnitTest/ - if-no-files-found: ignore - retention-days: 14 - overwrite: true - - name: Sign with the testkey (v1 + v2 + v3) run: | set -euo pipefail @@ -884,8 +776,6 @@ jobs: PR: ${{ github.event.pull_request.number }} RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} BUILD_OUTCOME: ${{ steps.build.outcome }} - UNIT_TEST_OUTCOME: ${{ steps.unit-tests.outcome }} - TEST_DIAGNOSTICS_URL: ${{ steps.unit-test-diagnostics.outputs.artifact-url }} APK_OUTCOME: ${{ steps.apk-upload.outcome }} run: bash tools/release/report-build.sh diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index eabc77a35..24fd2ffa9 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -47,6 +47,13 @@ jobs: echo "::error::main ${GITHUB_SHA::7} has no successful Build APK run yet: wait for it, then release" exit 1 fi + tests=$(gh run list -R "$GITHUB_REPOSITORY" --workflow unit-tests.yml --branch main --commit "$GITHUB_SHA" \ + --json conclusion,event,headSha -L 20 | + jq -r --arg sha "$GITHUB_SHA" '[.[] | select(.headSha == $sha and (.event == "push" or .event == "workflow_dispatch"))][0].conclusion // empty') + if [ "$tests" != success ]; then + echo "::error::main ${GITHUB_SHA::7} has no passing Unit tests run (${tests:-none yet}): fix or wait for it, then release" + exit 1 + fi variants=$(awk '!/^#/ && NF { print $1 }' tools/release/variants.txt | jq -R . | jq -sc .) echo "run_id=$id" >> "$GITHUB_OUTPUT" echo "variants=$variants" >> "$GITHUB_OUTPUT" diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml new file mode 100644 index 000000000..a525311b3 --- /dev/null +++ b/.github/workflows/unit-tests.yml @@ -0,0 +1,182 @@ +name: Unit tests +run-name: ${{ github.event_name == 'pull_request' && format('unit tests for pr {0} on {1} against {2}', github.event.pull_request.number, github.event.pull_request.head.sha, github.event.pull_request.base.sha) || format('unit tests for {0} on {1}', github.ref_name, github.sha) }} + +# Runs beside Build APK rather than inside it, so a test build is published as soon as the APK compiles. +# Build validation folds this workflow's result into the "Build APK" commit status, and Release APKs requires it. +on: + push: + branches: [ main ] + paths-ignore: + - '**/*.md' + - 'LICENSE' + - '.gitignore' + - 'docs/**' + - '.github/ISSUE_TEMPLATE/**' + pull_request: + branches: [ main ] + types: [ opened, synchronize, reopened, ready_for_review ] + paths-ignore: + - '**/*.md' + - 'LICENSE' + - '.gitignore' + - 'docs/**' + - '.github/ISSUE_TEMPLATE/**' + workflow_dispatch: + +permissions: + contents: read + actions: read + +concurrency: + group: unit-tests-${{ github.event.pull_request.number || (github.event_name == 'push' && 'main') || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'push' }} + +jobs: + unit-tests: + name: Unit tests + if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }} + runs-on: ubuntu-24.04 + timeout-minutes: 45 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} + fetch-depth: 0 + sparse-checkout: | + /* + !/docs/releases/media/ + sparse-checkout-cone-mode: false + persist-credentials: false + + - name: Merge the pinned APK base + if: github.event_name == 'pull_request' + env: + PR_BASE_SHA: ${{ github.event.pull_request.base.sha }} + run: | + set -euo pipefail + git config user.name "ci" + git config user.email "ci@users.noreply.github.com" + git fetch --no-tags origin "$PR_BASE_SHA" + git merge-tree --write-tree HEAD FETCH_HEAD >/dev/null || true + git merge --no-ff --no-edit FETCH_HEAD || { echo "::error::the pull request conflicts with main; Build APK lists the files"; exit 1; } + + - name: Check out MaliBridge + run: git submodule update --init external/MaliBridge + + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + + - uses: gradle/actions/setup-gradle@v4 + with: + cache-read-only: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository }} + cache-cleanup: ${{ github.event_name == 'pull_request' && 'never' || 'on-success' }} + + - name: Resolve the pinned Android NDK + run: bash tools/ci/resolve-ndk.sh + + - name: Set the APK build label + id: build-label + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + PR_TITLE: ${{ github.event.pull_request.title }} + PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }} + BUILD_REF: ${{ github.ref_name }} + BUILD_SHA: ${{ github.sha }} + run: bash tools/ci/build-label.sh + + - name: Resolve the Robolectric version + id: robolectric + run: | + echo "version=$(grep -o "org.robolectric:robolectric:[0-9.]*" app/build.gradle | cut -d: -f3)" >> "$GITHUB_OUTPUT" + # Robolectric downloads these from Maven Central on first use without retrying, and 429s fail whole test classes. + # The cache path sits beside the workspace because runner homes are at different depths from it, and + # actions/cache stores paths relative to the workspace. It is passed as an absolute path: the save action rejects + # "..". Runners that keep their own ~/.m2 skip the cache. + - name: Place Robolectric's Android jars beside the workspace + id: robolectric-jars + run: | + set -euo pipefail + jars="$GITHUB_WORKSPACE/../robolectric-jars" + m2="$HOME/.m2/repository/org/robolectric/android-all-instrumented" + if [ -d "$m2" ] && [ ! -L "$m2" ]; then + echo "cache=false" >> "$GITHUB_OUTPUT" + else + mkdir -p "$jars" "$(dirname "$m2")" + jars=$(cd "$jars" && pwd) + ln -sfn "$jars" "$m2" + echo "path=$jars" >> "$GITHUB_OUTPUT" + echo "cache=true" >> "$GITHUB_OUTPUT" + fi + - name: Restore Robolectric's Android jars + id: robolectric-cache + if: steps.robolectric-jars.outputs.cache == 'true' + uses: actions/cache/restore@v4 + with: + path: ${{ steps.robolectric-jars.outputs.path }} + key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }} + restore-keys: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}- + - name: Count the restored Robolectric jars + if: steps.robolectric-jars.outputs.cache == 'true' + run: echo "ROBOLECTRIC_JARS_BEFORE=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l)" >> "$GITHUB_ENV" + - name: Unit tests + id: unit-tests + env: + DROIDDECK_BUILD_LABEL: ${{ steps.build-label.outputs.label }} + SGDB_API_KEY: ${{ secrets.SGDB_API_KEY }} + run: | + set -o pipefail + mkdir -p app/build + # A Maven 429 fails every test class that needs the missing jar. The jars an attempt did get stay for the next. + for wait in 60 180 0; do + status=0 + ./gradlew testReleaseUnitTest --console=plain --info --stacktrace -Drobolectric.logging=stderr -PskipRust=true -PunitTestsOnly=true -PndkVersion="$NDK_VERSION" 2>&1 | tee app/build/unit-tests.log || status=$? + if [ "$status" = 0 ] || [ "$wait" = 0 ] || ! grep -Eq '^[[:space:]]*(Caused by: org\.gradle\.internal\.resource\.transport\.http\.HttpErrorStatusCodeException: Could not GET .*https://(repo\.maven\.apache\.org|repo1\.maven\.org)/.*Received status code 429 from server|Caused by: java\.io\.IOException: Server returned HTTP response code: 429 for URL: https://(repo\.maven\.apache\.org|repo1\.maven\.org)/)' app/build/unit-tests.log; then + exit "$status" + fi + echo "::warning::Maven Central answered 429; running the unit tests again in ${wait}s" + sleep "$wait" + done + + # actions/cache only saves when the job succeeds, so a run whose tests died on a Maven 429 never filled the cache. + # Save the complete jars even after a failed test step, when this run added some; a partial download is dropped first. + - name: Save Robolectric's Android jars + id: robolectric-jars-final + if: always() && steps.robolectric-jars.outputs.cache == 'true' + run: | + python3 - <<'PY' + import glob, os, zipfile + root = os.path.join(os.environ['GITHUB_WORKSPACE'], '..', 'robolectric-jars') + for f in glob.glob(os.path.join(root, '**', '*'), recursive=True): + if not os.path.isfile(f): + continue + try: + ok = f.endswith('.jar') and zipfile.ZipFile(f).testzip() is None + except Exception: + ok = False + if not ok: + os.remove(f) + PY + after=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l) + [ "$after" -gt "${ROBOLECTRIC_JARS_BEFORE:-0}" ] && echo "save=true" >> "$GITHUB_OUTPUT" || true + - name: Store Robolectric's Android jars + if: always() && steps.robolectric-jars-final.outputs.save == 'true' + uses: actions/cache/save@v4 + with: + path: ${{ steps.robolectric-jars.outputs.path }} + key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }} + + - name: Upload unit test diagnostics + id: unit-test-diagnostics + if: always() && steps.unit-tests.outcome != 'skipped' + uses: actions/upload-artifact@v4 + with: + name: unit-test-results + path: | + app/build/unit-tests.log + app/build/test-results/testReleaseUnitTest/ + app/build/reports/tests/testReleaseUnitTest/ + if-no-files-found: ignore + retention-days: 14 + overwrite: true diff --git a/AGENTS.md b/AGENTS.md index 97930d656..d89bdf632 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,7 +7,7 @@ - For an install-and-look iteration, use `tools/quick_deploy.sh` (build without lint, sign, install, about 30 s). Run `tools/build_local.sh` once to prepare the runtime and again only before a PR. It is not a per-change step. - `tools/build_local.sh` reuses the components a main CI run prepared when every recipe identity matches the local tree (it prints `components: … reusing`). It builds them locally when no usable CI artifact matches (after you change their inputs, or when the lookup fails) or with `DROIDDECK_CI_COMPONENTS=0`. - Helper scripts (`tools/linuxfs/overlay`, `tools/linuxfs/desktop`) are staged on every Gradle build, so editing them needs no `build_local.sh`. After preloads or other runtime components change, the fast loop warns and reuses the old binaries; run `tools/build_local.sh` when those matter. "Missing or changed runtime input" means the prepared files themselves changed: run `tools/build_local.sh` once. Do not revert scripts or copy `app/build` between checkouts; `tools/seed_worktree.sh` seeds a new worktree from the main checkout. -- Every build defaults to the NDK in `tools/ci/toolchains.env`, as CI does. CI runs `testReleaseUnitTest`; when a test fails only in CI, run the release variant locally. +- Every build defaults to the NDK in `tools/ci/toolchains.env`, as CI does. CI runs `testReleaseUnitTest` in the `Unit tests` workflow, beside Build APK; when a test fails only in CI, run the release variant locally. - Run the tests that cover what you changed, including unchanged tests of code you edited: `./gradlew -PskipRust=true :app:testDebugUnitTest --tests ''` and `python3 -m unittest discover -s tools/tests -p 'test_*.py'`. The full Python suite takes about 9 minutes, and some preload tests fail on any host without zram/ntsync. Leave full runs to CI. - For UI screenshots without a device, run `./gradlew -PskipRust=true :app:testDebugUnitTest --tests '*PreviewRenderTest'` and read `app/build/preview-renders/{handheld,portrait}/`. Add cases per `docs/compose-previews.md`. Check portrait, not just landscape. - After changing `SettingsIndex`, regenerate the doc: `UPDATE_SETTINGS_MAP=1 ./gradlew -PskipRust=true :app:testDebugUnitTest --tests '*SettingsMapTest*'`. @@ -31,7 +31,7 @@ - CI builds the PR merged onto `main`. Before pushing, merge or rebase onto `origin/main` and compile: most "works locally" Kotlin failures come from that merge. - Before a PR that touches strings or resources, run `./gradlew :app:lintVitalRelease`. The fast loop skips lint, and lint catches `ExtraTranslation` and missing-locale errors. - Commit messages and PR bodies must not carry `Co-Authored-By` or other bot trailers. `tools/release/check_authorship.py` fails the build on them. -- `gh run view --log-failed` truncates the unit-test log, so the failing test may not show. Read the whole job log with `gh api repos/Droid-Deck/DroidDeck/actions/jobs//logs`, or `gh run download -n unit-test-results`. Don't call a failure a runner problem until you have read it. +- `gh run view --log-failed` truncates the unit-test log, so the failing test may not show. Read the whole job log with `gh api repos/Droid-Deck/DroidDeck/actions/jobs//logs`, or `gh run download -n unit-test-results` from the `Unit tests` workflow run. Don't call a failure a runner problem until you have read it. - Only these are known flakes worth a `gh run rerun --failed`: `ProtonMenuAutoTest` "Proton work did not finish", Robolectric `HTTP response code: 429` from Maven, `Gradle Test Executor N finished with non-zero exit value 2`, apt mirror and GitHub API rate-limit errors. Treat any other failure as real. - A workflow step that names a script your branch lacks means the branch predates a CI change. Rebase onto `main`. diff --git a/app/build.gradle b/app/build.gradle index 70336a047..b858daf49 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -82,6 +82,8 @@ def buildBranch = providers.environmentVariable('GITHUB_HEAD_REF').getOrNull()?. ?: gitValue(['branch', '--show-current']) ?: '' def escapeJava = { String value -> value.replace('\\', '\\\\').replace('"', '\\"').replace('\n', ' ').replace('\r', ' ') } def ciBuild = providers.environmentVariable('GITHUB_ACTIONS').getOrNull() == 'true' +// The Unit tests workflow compiles no APK, so it has no add-on packs to pin. +def unitTestsOnly = project.findProperty('unitTestsOnly')?.toString()?.toBoolean() ?: false def releaseSigner = rootProject.file('keystore/release-signer.sha256').text.trim() def commitTime = (gitValue(['show', '-s', '--format=%ct', '--end-of-options', sourceCommit]) ?: '0').with { it.isLong() ? it : '0' } def desktopKde = rootProject.file('tools/desktop-kde/release.env').readLines() @@ -96,10 +98,12 @@ def prootPackPin = rootProject.file('tools/packs/proot/release.env').readLines() def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt', 'epic'].collectEntries { name -> def pack = file("build/packs/${name}.tar.zst") if (!pack.isFile()) { - if (ciBuild) throw new GradleException("Add-on pack ${pack} is missing: run tools/packs/build.sh app/build/packs") + if (ciBuild && !unitTestsOnly) throw new GradleException("Add-on pack ${pack} is missing: run tools/packs/build.sh app/build/packs") if (name == 'proot' && prootPackPin.PROOT_PACK_SHA256) { return [(name): [sha256: prootPackPin.PROOT_PACK_SHA256, size: (prootPackPin.PROOT_PACK_SIZE ?: '0') as long]] } + // A CI APK pins every pack, and CI_BUILD code assumes that, so the tests see a placeholder pin. + if (unitTestsOnly) return [(name): [sha256: '0' * 64, size: 0L]] return [(name): [sha256: '', size: 0L]] } def digest = java.security.MessageDigest.getInstance('SHA-256') diff --git a/tools/ci/build-label.sh b/tools/ci/build-label.sh new file mode 100755 index 000000000..806e0366f --- /dev/null +++ b/tools/ci/build-label.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Exports the build metadata Gradle bakes into BuildConfig and prints the label for DROIDDECK_BUILD_LABEL. +set -euo pipefail +if [[ -n "$(git status --porcelain)" ]]; then + tree_state=dirty +else + tree_state=clean +fi +echo "DROIDDECK_BUILD_TREE_STATE=$tree_state" >> "$GITHUB_ENV" +if [[ -n "${PR_NUMBER:-}" ]]; then + label="pr${PR_NUMBER} at ${PR_HEAD_SHA:0:7}" +else + label="${BUILD_REF} at ${BUILD_SHA:0:7}" +fi +echo "label=$label" >> "$GITHUB_OUTPUT" +echo "DROIDDECK_SOURCE_COMMIT=${PR_HEAD_SHA:-$BUILD_SHA}" >> "$GITHUB_ENV" +echo "DROIDDECK_PR_NUMBER=${PR_NUMBER:-0}" >> "$GITHUB_ENV" +echo "DROIDDECK_PR_TITLE=${PR_TITLE//$'\n'/ }" >> "$GITHUB_ENV" +echo "Build: \`$label\`" >> "$GITHUB_STEP_SUMMARY" diff --git a/tools/components/README.md b/tools/components/README.md index 782d8b9f1..d1d527631 100644 --- a/tools/components/README.md +++ b/tools/components/README.md @@ -10,13 +10,18 @@ flowchart LR Source[Pin source tree] --> Components[Prepare verified components] Source --> Xbox[Xbox ARM64 backend] Source --> Tests[Python and native tests] - Components --> APK[Compile APK and Android tests] + Components --> APK[Compile APK] Xbox --> APK APK --> Gate[Compile and test APK gate] Tests --> Gate Gate --> Publish[Main only: signing and publishing] ``` +Kotlin unit tests run in the separate `Unit tests` workflow (`unit-tests.yml`), so a +PR test build is published as soon as the APK compiles. Build validation folds both +workflows into the `Build APK` commit status, and Release APKs requires both for the +released commit. + All workers verify the same source tree. The component artifact records that tree, recipe identities and every output hash; the APK worker verifies the inventory before building. This handoff verifies consistency within the same CI run. It is diff --git a/tools/release/report-build.sh b/tools/release/report-build.sh index 835bb6c65..f9757e505 100644 --- a/tools/release/report-build.sh +++ b/tools/release/report-build.sh @@ -7,37 +7,21 @@ MARK="" echo [ -f /tmp/pr-merge.md ] && cat /tmp/pr-merge.md echo - case "$BUILD_OUTCOME:$UNIT_TEST_OUTCOME:$APK_OUTCOME" in - success:success:success) + case "$BUILD_OUTCOME:$APK_OUTCOME" in + success:success) echo "### Build passed" echo - echo "The \`droiddeck-apk\` artifact is [on this run]($RUN_URL), signed with the public test key." + echo "The \`droiddeck-apk\` artifact is [on this run]($RUN_URL), signed with the public test key. Unit tests run in the separate **Unit tests** workflow and must pass before merging." echo - echo "Same-repository PRs and PRs opened by contributors listed in \`.github/trusted-test-builds.txt\` are eligible for automatic release-signed test builds after the full build passes. Label the PR \`no-test-build\` to skip that." + echo "Same-repository PRs and PRs opened by contributors listed in \`.github/trusted-test-builds.txt\` are eligible for automatic release-signed test builds once the APK compiles. Label the PR \`no-test-build\` to skip that." echo "For other PRs, a maintainer can add the \`publish-test\` label to request a signed build." echo echo "Fallback: [open **PR Release Publish**]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/workflows/pr-release-publish.yml) on \`main\` and enter PR \`$PR\`." ;; - success:success:*) + success:*) echo "### APK publication incomplete" echo - echo "Compilation and unit tests passed, but APK publication did not complete. See [the run]($RUN_URL)." - ;; - success:failure:*) - echo "### ERROR: Unit tests failed" - echo - echo "The APK compiled, but unit tests failed. No installable artifact was published." - echo - if [ -n "$TEST_DIAGNOSTICS_URL" ]; then - echo "The [unit-test-results]($TEST_DIAGNOSTICS_URL) artifact contains the test log and any generated reports." - else - echo "The test diagnostics upload did not complete. See [the test log]($RUN_URL)." - fi - ;; - success:*) - echo "### Build incomplete" - echo - echo "The APK compiled, but unit tests did not complete successfully. See [the run]($RUN_URL)." + echo "Compilation passed, but APK publication did not complete. See [the run]($RUN_URL)." ;; failure:*) echo "### ERROR: Build failed" diff --git a/tools/release/validate_apk.py b/tools/release/validate_apk.py index 7a3fb6753..efc96317b 100644 --- a/tools/release/validate_apk.py +++ b/tools/release/validate_apk.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 import json import os +import re import subprocess import sys import time @@ -40,6 +41,39 @@ def compilation_state(run, jobs): return "failure" if run["status"] == "completed" else "pending" +def run_state(run): + if run["status"] != "completed": + return "pending" + return "success" if run["conclusion"] == "success" else "failure" + + +def latest_run(repo, workflow, sha, source_event): + query = urlencode({"head_sha": sha, "event": source_event, "per_page": 20}) + runs = api(f"repos/{repo}/actions/workflows/{workflow}/runs?{query}")["workflow_runs"] + runs = [item for item in runs if item["head_sha"] == sha] + return max(runs, key=lambda item: item["id"]) if runs else None + + +def pull_request_run_base(run, sha): + # A PR can reopen at the same head SHA after main advances. Do not mix results + # from different event snapshots, even if both workflows individually passed. + title = run.get("display_title") or "" + match = re.search(rf" on {re.escape(sha)} against ([0-9a-f]{{40}})$", title) + return match[1] if match else None + + +def combined_state(build, tests): + if build == "failure": + return "failure", "APK compilation failed" + if tests == "failure": + return "failure", "Unit tests failed" + if build == "pending": + return "pending", "Source validated; awaiting APK compilation" + if tests == "pending": + return "pending", "APK compiled; awaiting unit tests" + return "success", "Source validation, APK compilation and unit tests passed" + + def fetch_source(ref, sha): subprocess.run(["git", "fetch", "--no-tags", "origin", ref], check=True) fetched = subprocess.check_output(["git", "rev-parse", "FETCH_HEAD"], text=True).strip() @@ -123,19 +157,25 @@ def main(): state = "success" description = "Source validated; no APK source changes" return - query = urlencode({"head_sha": sha, "event": source_event, "per_page": 20}) - runs = api(f"repos/{repo}/actions/workflows/build.yml/runs?{query}")["workflow_runs"] - runs = [item for item in runs if item["head_sha"] == sha] - if runs: - latest = max(runs, key=lambda item: item["id"]) + build_state = tests_state = "pending" + latest = latest_run(repo, "build.yml", sha, source_event) + if latest: jobs = api(f"repos/{repo}/actions/runs/{latest['id']}/jobs?per_page=100")["jobs"] - state = compilation_state(latest, jobs) + build_state = compilation_state(latest, jobs) target = latest["html_url"] - else: - state = "pending" - description = {"pending": "Source validated; awaiting APK compilation", - "success": "Source validation and APK compilation passed", - "failure": "APK compilation failed"}[state] + tests = latest_run(repo, "unit-tests.yml", sha, source_event) + if tests: + if pr and latest and build_state == "success": + build_base = pull_request_run_base(latest, sha) + tests_base = pull_request_run_base(tests, sha) + if not build_base or build_base != tests_base: + state = "pending" + description = "APK and unit tests must run against the same main commit" + return + tests_state = run_state(tests) + if tests_state == "failure" and build_state != "failure": + target = tests["html_url"] + state, description = combined_state(build_state, tests_state) finally: api(f"repos/{repo}/statuses/{sha}", "--method", "POST", "-f", "context=Build APK", "-f", f"state={state}", diff --git a/tools/tests/test_ci_checks.py b/tools/tests/test_ci_checks.py index a5982366a..5b45850fc 100644 --- a/tools/tests/test_ci_checks.py +++ b/tools/tests/test_ci_checks.py @@ -25,7 +25,7 @@ class CiChecksTest(unittest.TestCase): self.assertIn("gitValue(['show', '-s', '--format=%ct', '--end-of-options', sourceCommit])", gradle) def test_robolectric_cache_saves_and_restores_the_same_absolute_path(self): - steps = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs']['build']['steps'] + steps = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps'] caches = [step['with'] for step in steps if step.get('uses', '').startswith('actions/cache')] for cache in caches: for path in cache['path'].split('\n'): @@ -34,13 +34,17 @@ class CiChecksTest(unittest.TestCase): self.assertEqual(robolectric, ['${{ steps.robolectric-jars.outputs.path }}'] * 2) def test_unit_test_retry_requires_maven_exception(self): - steps = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs']['build']['steps'] + steps = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps'] run = next(step['run'] for step in steps if step.get('id') == 'unit-tests') line = next(line for line in run.splitlines() if 'grep -Eq' in line) pattern = shlex.split(line)[shlex.split(line).index('-Eq') + 1] for log, expected in ( ("Caused by: org.gradle.internal.resource.transport.http.HttpErrorStatusCodeException: Could not GET 'https://repo.maven.apache.org/maven2/a.jar'. Received status code 429 from server: Too Many Requests", 0), ("Caused by: java.io.IOException: Server returned HTTP response code: 429 for URL: https://repo.maven.apache.org/maven2/a.jar", 0), + ("Caused by: org.gradle.internal.resource.transport.http.HttpErrorStatusCodeException: Could not GET 'https://repo1.maven.org/maven2/a.jar'. Received status code 429 from server: Too Many Requests", 0), + ("Caused by: java.io.IOException: Server returned HTTP response code: 429 for URL: https://repo1.maven.org/maven2/a.pom.sha512", 0), + ("Caused by: java.io.IOException: Server returned HTTP response code: 429 for URL: https://example.org/a.jar", 1), + ("Caused by: java.io.IOException: Server returned HTTP response code: 500 for URL: https://repo1.maven.org/maven2/a.jar", 1), ("SomeTest > test FAILED: Too Many Requests", 1), ("Caused by: java.lang.AssertionError: HTTP 429", 1), ): @@ -59,15 +63,46 @@ class CiChecksTest(unittest.TestCase): self.assertEqual(result.strip(), '2') def test_build_and_tests_use_identical_generated_metadata(self): - jobs = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs'] - steps = {step.get('id'): step for step in jobs['build']['steps']} - self.assertEqual(steps['build']['env'], steps['unit-tests']['env']) - self.assertIn('DROIDDECK_BUILD_LABEL', steps['unit-tests']['env']) - self.assertIn('SGDB_API_KEY', steps['unit-tests']['env']) + build = {step.get('id'): step for step in + yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs']['build']['steps']} + tests = {step.get('id'): step for step in + yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps']} + self.assertEqual(build['build']['env'], tests['unit-tests']['env']) + self.assertIn('DROIDDECK_BUILD_LABEL', tests['unit-tests']['env']) + self.assertIn('SGDB_API_KEY', tests['unit-tests']['env']) + self.assertEqual(build['build-label'], tests['build-label']) gradle = (ROOT / 'app/build.gradle').read_text() self.assertIn("outputs.doNotCacheIf('CI executes the test suite on every run') { true }", gradle) self.assertIn('outputs.upToDateWhen { false }', gradle) + def test_unit_tests_do_not_hold_up_the_apk(self): + build = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text()) + for step in build['jobs']['build']['steps']: + self.assertNotIn('UnitTest', step.get('run', '')) + tests = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text()) + for event in ('push', 'pull_request'): + self.assertEqual(tests[True][event], build[True][event]) + authorship = yaml.safe_load((ROOT / '.github/workflows/authorship.yml').read_text()) + self.assertEqual(set(authorship[True]['workflow_run']['workflows']), {build['name'], tests['name']}) + self.assertIn('workflow_run.head_sha', authorship['concurrency']['group']) + self.assertFalse(authorship['concurrency']['cancel-in-progress']) + self.assertIn('unit-tests.yml', (ROOT / '.github/workflows/release.yml').read_text()) + run = next(step['run'] for step in tests['jobs']['unit-tests']['steps'] if step.get('id') == 'unit-tests') + self.assertIn('-PunitTestsOnly=true', run) + + def test_apk_and_unit_tests_pin_the_same_pr_event_base(self): + for filename, job, name in ( + ("build.yml", "source", "Pin and merge the APK source"), + ("unit-tests.yml", "unit-tests", "Merge the pinned APK base"), + ): + with self.subTest(workflow=filename): + workflow = yaml.safe_load((ROOT / ".github/workflows" / filename).read_text()) + step = next(step for step in workflow["jobs"][job]["steps"] if step.get("name") == name) + self.assertEqual(step["env"]["PR_BASE_SHA"], "${{ github.event.pull_request.base.sha }}") + self.assertIn('git fetch --no-tags origin "$PR_BASE_SHA"', step["run"]) + self.assertIn("git merge --no-ff --no-edit FETCH_HEAD", step["run"]) + self.assertIn("github.event.pull_request.base.sha", workflow["run-name"]) + def test_independent_jobs_wait_only_for_the_pinned_source(self): jobs = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs'] for name in ('xbox', 'python-tests', 'components-runner'): diff --git a/tools/tests/test_validate_apk.py b/tools/tests/test_validate_apk.py index 707779a9f..f6afd3371 100644 --- a/tools/tests/test_validate_apk.py +++ b/tools/tests/test_validate_apk.py @@ -28,7 +28,7 @@ class ValidateApkTest(unittest.TestCase): def git(self, *args): return subprocess.check_output(["git", "-C", self.root, *args], text=True).strip() - def validate(self, message="Source change", body="", result="success", stale=False, completed=False, filename="source.kt", permission="write", role_name="write", fork=False): + def validate(self, message="Source change", body="", result="success", stale=False, completed=False, filename="source.kt", permission="write", role_name="write", fork=False, tests="success", build_base="a" * 40, tests_base="a" * 40): (self.root / filename).parent.mkdir(parents=True, exist_ok=True) (self.root / filename).write_text(message) self.git("add", filename) @@ -56,7 +56,16 @@ class ValidateApkTest(unittest.TestCase): if path.endswith("/pulls?state=open&head=contributor%3Afix%2Fbranch"): return [pr] if "workflows/build.yml/runs?" in path: - return {"workflow_runs": [{"id": 7, "head_sha": sha, "status": "completed", "html_url": "https://example.org/build"}]} + title = f"building pr 1 on {sha}" + (f" against {build_base}" if build_base else "") + return {"workflow_runs": [{"id": 7, "head_sha": sha, "status": "completed", + "display_title": title, "html_url": "https://example.org/build"}]} + if "workflows/unit-tests.yml/runs?" in path: + if tests is None: + return {"workflow_runs": []} + title = f"unit tests for pr 1 on {sha}" + (f" against {tests_base}" if tests_base else "") + return {"workflow_runs": [{"id": 9, "head_sha": sha, "html_url": "https://example.org/tests", + "display_title": title, "status": "in_progress" if tests == "pending" else "completed", + "conclusion": None if tests == "pending" else tests}]} if path.endswith("/jobs?per_page=100"): return {"jobs": [{"name": "Compile and test APK", "status": "in_progress" if result == "pending" else "completed", "conclusion": result}]} raise AssertionError(path) @@ -85,6 +94,25 @@ class ValidateApkTest(unittest.TestCase): self.validate(result=result) self.assertEqual(self.statuses[-1]["state"], result) + def test_unit_tests_must_pass_too(self): + for tests, state in (("pending", "pending"), (None, "pending"), ("failure", "failure"), ("cancelled", "failure")): + with self.subTest(tests=tests): + self.validate(tests=tests) + self.assertEqual(self.statuses[-1]["state"], state) + self.assertEqual(self.statuses[-1]["target_url"], "https://example.org/tests") + + def test_successful_runs_must_use_the_same_pr_base(self): + for build_base, tests_base in (("a" * 40, "b" * 40), ("a" * 40, None), (None, "a" * 40)): + with self.subTest(build_base=build_base, tests_base=tests_base): + self.validate(build_base=build_base, tests_base=tests_base) + self.assertEqual(self.statuses[-1]["state"], "pending") + self.assertIn("same main commit", self.statuses[-1]["description"]) + + def test_a_compile_failure_is_reported_before_test_results(self): + self.validate(result="failure", tests="failure") + self.assertEqual(self.statuses[-1]["description"], "APK compilation failed") + self.assertEqual(self.statuses[-1]["target_url"], "https://example.org/build") + def test_superseded_event_cannot_replace_current_status(self): self.validate(stale=True) self.assertEqual(self.statuses, []) diff --git a/tools/tests/test_xbox_build_source.py b/tools/tests/test_xbox_build_source.py index 427cea342..7a3ba0030 100644 --- a/tools/tests/test_xbox_build_source.py +++ b/tools/tests/test_xbox_build_source.py @@ -11,8 +11,10 @@ class XboxBuildSourceTest(unittest.TestCase): import yaml except ImportError: self.fail('PyYAML is required to execute workflow steps') - workflow = yaml.safe_load((Path(__file__).resolve().parents[2] / '.github/workflows/build.yml').read_text()) - jobs = workflow['jobs'] + workflows = Path(__file__).resolve().parents[2] / '.github/workflows' + jobs = yaml.safe_load((workflows / 'build.yml').read_text())['jobs'] + unit_jobs = yaml.safe_load((workflows / 'unit-tests.yml').read_text())['jobs'] + jobs.update(unit_jobs) step = lambda job, name: next(s['run'] for s in jobs[job]['steps'] if s.get('name') == name) with tempfile.TemporaryDirectory() as directory: root = Path(directory) @@ -31,13 +33,17 @@ class XboxBuildSourceTest(unittest.TestCase): git('switch', '-q', 'main') (root / 'backend').write_text('merged backend') git('commit', '-qam', 'backend changed after branch') - for name in ('source', 'xbox', 'components', 'apk', 'tests', 'dispatch'): + event_base = git('rev-parse', 'HEAD') + for name in ('source', 'xbox', 'components', 'apk', 'tests', 'unit-tests', 'dispatch'): git('clone', '-q', str(root), str(root / name)) git('checkout', '-q', head, cwd=root / name) output = root / 'output' - env['GITHUB_OUTPUT'] = str(output) + env.update(GITHUB_OUTPUT=str(output), PR_BASE_SHA=event_base) + (root / 'backend').write_text('newer main, after PR event') + git('commit', '-qam', 'main advanced before source pinning') subprocess.run(['bash', '-c', step('source', 'Pin and merge the APK source')], cwd=root / 'source', env=env, check=True, capture_output=True) base = output.read_text().strip().split('=', 1)[1] + self.assertEqual(base, event_base) tree = git('rev-parse', 'HEAD^{tree}', cwd=root / 'source') (root / 'backend').write_text('newer main, after backend build') git('commit', '-qam', 'main advanced again') @@ -51,6 +57,10 @@ class XboxBuildSourceTest(unittest.TestCase): subprocess.run(['bash', '-c', step('python-tests', 'Verify backend and test source match')], cwd=root / 'tests', env=env, check=True, capture_output=True) self.assertEqual(git('rev-parse', 'HEAD^{tree}', cwd=root / 'tests'), tree) + subprocess.run(['bash', '-c', step('unit-tests', 'Merge the pinned APK base')], cwd=root / 'unit-tests', env=env, check=True, capture_output=True) + self.assertEqual((root / 'unit-tests/backend').read_text(), 'merged backend') + self.assertEqual(git('rev-parse', 'HEAD^{tree}', cwd=root / 'unit-tests'), tree) + env['SOURCE_TREE'] = tree for job in ('xbox', 'components'): subprocess.run(['bash', '-c', step(job, 'Merge the pinned APK base')], cwd=root / job, env=env, check=True, capture_output=True)