The user wants to build a Mobile Continuous Integration (CI) system.
Key requirements:
Sharding: Splitting tests across multiple machines.
Caching: Speeding up builds by reusing dependencies/build artifacts.
Emulators: Running Android (AVD) or iOS (Simulator) instances.
Flake Reduction: Strategies to handle flaky tests (retrying, quarantining).
Timeouts: Preventing builds from hanging indefinitely.
The output needs to be a practical guide or a configuration structure, likely for a popular CI platform (like GitHub Actions, CircleCI, or Bitrise), but general enough to apply concepts. GitHub Actions is usually the most accessible "lingua franca" for these examples.
Plan:
Architecture Overview: Briefly explain how these pieces fit together in a matrix/shard configuration.
Tooling Selection:
CI Provider: GitHub Actions (most common, easy to demonstrate).
Test Runner: adb/xcrun are low-level; Flank (Firebase Test Lab) or Maestro are modern options, but standard AndroidJUnitRunner is the baseline. I should focus on self-hosted or on-runner emulators to keep costs low and control high, or mention cloud options. Let's stick to hardware-accelerated emulators on CI runners (e.g. macos-latest).
Language: YAML (for config).
Detailed Implementation Steps:
Sharding (The Core):
How to calculate slices? Total Tests / Num Shards.
Need a matrix strategy (e.g., shard: [1, 2, 3, 4]).
Need a script to split the test list.
Caching:
Gradle dependencies (~/.gradle/caches).
Android SDK components.
AVD images (if pre-warmed).
Emulators:
Android: android-emulator-runner is a standard action.
iOS: xcodebuild with destinations.
Crucial: Hardware acceleration (KVM on Linux, Hypervisor on macOS).
Flake Reduction:
Retry logic (run failed tests again).
JUnit XML parsing to detect flakiness.
Tooling: flank is great for this, but simple shell scripting works too.
Timeouts:
Global job timeout.
Step timeout.
Emulator boot timeout.
Drafting the Configuration (GitHub Actions Example):
Job 1: Build & Shard: Compile the code, generate a list of tests, divide the list into files (e.g., shard_0.txt, shard_1.txt).
Job 2: Test Matrix: Run N jobs. Each job picks up a shard file. Start emulator. Run tests. Upload results.
Job 3: Report: Collect results (optional, but good practice).
Refining the "Flake Reduction" & "Caching":
Caching: Use actions/cache.
Flakes: Add a retry step. If the first run fails, run again with --tests filtering for only the failed ones.
Refining the "Emulator":
On Linux (Ubuntu), use KVM.
On macOS, use HAX/Nested Virt.
Actionable tip: Use a script to wait for the emulator to boot (adb wait-for-device).
Code Structure:
I will write a comprehensive GitHub Actions YAML workflow.
I will provide a shell script for the actual sharding logic.
Review against constraints:
Shards? Yes (Matrix).
Caching? Yes (Gradle/AVD).
Emulators? Yes (Android focus as it's harder than iOS on generic CI, but mention iOS).
Flake reduction? Yes (Retry logic).
Timeouts? Yes (Timeout-minutes).
Self-Correction/Optimization during drafting:
Initial thought: Use Firebase Test Lab. Correction: The prompt implies building the CI infrastructure (emulators included), likely to save money or keep it internal. I will stick to hosted emulators.
Sharding logic: Instead of a complex python script, I'll use a simple bash loop or split command to demonstrate simplicity, or a standard matrix approach.
Flakiness: The best way to handle flakes in CI without false positives is "Fail fast" disabled + Retry failed tests. Or just strict retries.
Final Output Generation: Produce the YAML and explanations.
(Self-Correction during YAML generation):
I need to make sure the sharding mechanism is clear.
Strategy:
Build APK + Test APK.
List all test classes/methods.
Split list into $N files.
Pass file to matrix job.
Let's create a robust example using GitHub Actions targeting Android (as it's the most common request for this specific stack). I will add notes for iOS.
Steps to code:
setup-java & cache.
AVD cache (huge time saver).
Matrix definition.
Retry logic using continue-on-error or a wrapper script.
Let's write the content.
Here is a comprehensive guide and a production-ready template for building a robust Mobile CI pipeline. This example uses GitHub Actions, but the architecture is transferable to CircleCI, Bitrise, or Jenkins.
The architecture uses a Matrix Strategy to parallelize tests (Sharding) combined with smart caching, managed emulators, and retry logic.
The Architecture
Calculates Shards: A preliminary job determines how to split the tests (e.g., by class or annotation).
Matrix Execution: Runs N emulators in parallel. Each job receives a specific "slice" of the test suite.
Caching: Restores Gradle dependencies and AVD (Emulator) system images.
Flake Reduction: Uses a "Retry on Failure" strategy specifically for UI tests.
Hard Timeouts: Kills the job if the emulator hangs or tests take too long.
1. The Configuration (.github/workflows/android-ci.yml)
This workflow is designed for an Android project (using Gradle), but the concepts apply to iOS/XCTest as well.
yaml
2. Implementation Details Deep Dive
A. Sharding (Splitting the Load)
We use a Matrix Strategy to parallelize.
The Problem: Running 1,000 UI tests on a single emulator takes hours.
The Solution: We split the tests into 4 (or N) groups.
Implementation:
The setup job outputs a list: [0, 1, 2, 3].
GitHub Actions spawns 4 parallel VMs.
Gradle Implementation: You must tell Gradle which tests to run. In your build.gradle, you can filter tests based on a custom argument passed from the CI:
groovy
// In app/build.gradle
android {
testOptions {
execution 'ANDROIDX_TEST_ORCHESTRATOR'
// Simple sharding logic pseudo-code
// You usually need a custom runner or scripts to split test classes files
}
}
Pro Tip: Use Android Test Orchestrator. It ensures tests don't leak state into each other (crucial for reducing flakes), though it increases test time slightly.
B. Caching (Speed Optimization)
Mobile builds are heavy. We cache two distinct layers:
Dependencies (.gradle/caches): Handled by gradle/actions/setup-gradle. This prevents re-downloading libraries every build.
Emulator Images (AVD): Creating an emulator from scratch (downloading the system image + creating the VM) takes 3–5 minutes.
We use actions/cache specifically on the ~/.android/avd directory.
If the cache hits, we skip the emulator creation step and boot directly from the snapshot.
C. Emulator Management
Hardware Acceleration: On macOS, use hypervisor. On Linux (Ubuntu), use kvm.
Headless Mode: Always run with -no-window and -noaudio. Do not waste resources rendering pixels no one sees.
Boot Lock: The script must wait for the emulator to fully boot (adb wait-for-device) before launching tests.
D. Flake Reduction
Flakes are tests that pass/fail arbitrarily.
Disable Animations: Essential. Android emulators are slow; animations often timeout tests. The workflow sets disable-animations: true.
Orchestrator: As mentioned, isolates process memory.
Retry Logic (The Script Block):
The most effective flake reduction in CI is an automatic retry.
bash
# Try running tests
if ./gradlew connectedAndroidTest; then
echo "Success"
else
echo "Failed, retrying..."
./gradlew connectedAndroidTest # Retry once
fi
Note: If a test fails twice in a row, it is a real bug, not a flake.
E. Timeouts
Job Timeout:timeout-minutes: 45. If the whole job hangs (e.g., emulator boot loop), the CI kills it.
Step Timeout: You can apply timeouts to specific steps.
Adb Timeout: Set adb shell settings put system screen_off_timeout 2147483647 inside the emulator to prevent the screen from sleeping during long test runs.
name: Mobile CI - Sharded & Cached
on:
pull_request:
branches: [ main ]
# 1. CONCURRENCY: Cancel previous runs on the same branch to save resources
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
env:
GRADLE_OPTS: "-Dorg.gradle.daemon=false -Dorg.gradle.parallel=true"
# Number of parallel emulators to spawn
SHARD_COUNT: 4
# Hard limit for the test execution step (prevents zombie jobs)
TEST_TIMEOUT_MINUTES: 30
jobs:
# JOB 1: Setup & Determine Shards
setup:
runs-on: ubuntu-latest
outputs:
test-matrix: ${{ steps.set-matrix.outputs.matrix }}
steps:
- uses: actions/checkout@v4
# Caching: Gradle Dependencies
- uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '17'
- uses: gradle/actions/setup-gradle@v3
with:
cache-read-only: ${{ github.ref != 'refs/heads/main' }}
# Logic: Generate a matrix of shards (0, 1, 2, 3)
# In a real scenario, you might query ./gradlew androidTests to list classes
# and split them evenly. Here we simulate 4 shards.
- id: set-matrix
run: |
# Create a JSON array of indices: [0, 1, 2, 3]
MATRIX=$(seq 0 $((${{ env.SHARD_COUNT }} - 1)) | jq -R -s -c 'split("\n")[:-1]')
echo "matrix=${MATRIX}" >> $GITHUB_OUTPUT
# JOB 2: Run Tests (Parallel Matrix)
test:
needs: setup
runs-on: ubuntu-latest
# Timeout: Kill the entire job if it hangs (Total Time)
timeout-minutes: 45
strategy:
fail-fast: false # Continue other shards even if one fails
matrix:
shard-index: ${{ fromJson(needs.setup.outputs.test-matrix) }}
steps:
- uses: actions/checkout@v4
# Caching: Java & Gradle
- uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '17'
- uses: gradle/actions/setup-gradle@v3
with:
cache-read-only: ${{ github.ref != 'refs/heads/main' }}
# Caching: Android Emulator System Image (Huge time saver)
- name: AVD Cache
uses: actions/cache@v4
id: avd-cache
with:
path: |
~/.android/avd/*
~/.android/adb*
key: avd-v1-${{ runner.os }}-api30
# Setup: Create Emulator if cache miss
- name: Create Emulator
if: steps.avd-cache.outputs.cache-hit != 'true'
uses: reactivecircus/android-emulator-runner@v2
with:
api-level: 30
build-tools: "30.0.3"
arch: x86_64
force-avd-creation: false
emulator-options: -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none
disable-animations: true
script: echo "Generated AVD snapshot for caching"
# Run Tests with Flake Reduction
- name: Run Tests (Shard ${{ matrix.shard-index }})
uses: reactivecircus/android-emulator-runner@v2
with:
api-level: 30
arch: x86_64
force-avd-creation: false
emulator-options: -no-snapshot-save -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none
disable-animations: true
# CORE LOGIC: Sharding, Timeouts, and Flake Handling
script: |
# Generate a unique file for this shard's results
REPORT_FILE="build/reports/shard-${{ matrix.shard-index }}.xml"
# Run the specific shard
# -Pandroid.testInstrumentationRunnerArguments.class=com.example.Shard${{ matrix.shard-index }}Class
# FLAKE REDUCTION: Retry logic wrapper
# Attempt 1
./gradlew connectedAndroidTest -PshardIndex=${{ matrix.shard-index }} -PshardTotal=${{ env.SHARD_COUNT }} && exit 0
echo "First attempt failed. Retrying..."
# Attempt 2 (Retry only failed tests logic can be inserted here,
# but usually a full retry of the shard is sufficient for flakiness)
./gradlew connectedAndroidTest -PshardIndex=${{ matrix.shard-index }} -PshardTotal=${{ env.SHARD_COUNT }}
- name: Upload Results
if: always()
uses: actions/upload-artifact@v4
with:
name: test-results-shard-${{ matrix.shard-index }}
path: app/build/reports/androidTests/