From 25ee14aa2ff5272bd84bef9629928ca24f0191d6 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Wed, 2 Dec 2026 00:04:46 -0500 Subject: [PATCH] ci: run Kotlin unit tests beside Build APK instead of inside it The release unit tests ran inside the compile job, after assembleRelease and before the testkey-signed APK was uploaded. PR Release Publish waits for the Build APK workflow to finish, so every test build waited 3-6 minutes on the tests, and a Maven 429 during Robolectric's jar download failed the build outright. testReleaseUnitTest now runs in its own Unit tests workflow on a hosted runner, where the Robolectric jar cache always applies. It needs neither the prepared components nor the Rust stores (-PskipRust=true). Build APK publishes as soon as the APK compiles. Merges and releases stay gated: Build validation folds the Unit tests result into the "Build APK" commit status, and Release APKs refuses a commit without a passing Unit tests run. The main Preview build no longer waits for the Kotlin unit tests; the PR's tests have already passed by then. --- .github/workflows/authorship.yml | 2 +- .github/workflows/build.yml | 117 +------------------- .github/workflows/release.yml | 7 ++ .github/workflows/unit-tests.yml | 180 +++++++++++++++++++++++++++++++ AGENTS.md | 4 +- tools/ci/build-label.sh | 19 ++++ tools/components/README.md | 7 +- tools/release/report-build.sh | 28 ++--- tools/release/validate_apk.py | 46 ++++++-- tools/tests/test_ci_checks.py | 28 +++-- tools/tests/test_validate_apk.py | 20 +++- 11 files changed, 298 insertions(+), 160 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 615267b6c0..048f96a859 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: diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index d713d0f493..e6f92b0f97 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -349,7 +349,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 +507,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 +718,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 +773,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 eabc77a358..24fd2ffa9a 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 0000000000..bb621f35c3 --- /dev/null +++ b/.github/workflows/unit-tests.yml @@ -0,0 +1,180 @@ +name: Unit tests +run-name: ${{ github.event_name == 'pull_request' && format('unit tests for pr {0} on {1}', github.event.pull_request.number, github.event.pull_request.head.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 onto main + if: github.event_name == 'pull_request' + run: | + set -euo pipefail + git config user.name "ci" + git config user.email "ci@users.noreply.github.com" + git fetch --no-tags origin main + 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 -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 diff --git a/AGENTS.md b/AGENTS.md index 97930d6563..d89bdf632c 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/tools/ci/build-label.sh b/tools/ci/build-label.sh new file mode 100755 index 0000000000..806e0366fc --- /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 782d8b9f14..d1d5276311 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 835bb6c65e..f9757e5052 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 7a3fb67530..d76c52bb5c 100644 --- a/tools/release/validate_apk.py +++ b/tools/release/validate_apk.py @@ -40,6 +40,31 @@ 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 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 +148,18 @@ 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: + 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 a5982366ac..216fda798d 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,7 +34,7 @@ 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] @@ -59,15 +59,29 @@ 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('unit-tests.yml', (ROOT / '.github/workflows/release.yml').read_text()) + 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 707779a9f6..16dca4a699 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"): (self.root / filename).parent.mkdir(parents=True, exist_ok=True) (self.root / filename).write_text(message) self.git("add", filename) @@ -57,6 +57,12 @@ class ValidateApkTest(unittest.TestCase): 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"}]} + if "workflows/unit-tests.yml/runs?" in path: + if tests is None: + return {"workflow_runs": []} + return {"workflow_runs": [{"id": 9, "head_sha": sha, "html_url": "https://example.org/tests", + "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 +91,18 @@ 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_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, [])