Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Cross-version testing infrastructure - Stage 1 (#70063)

Nemanja Glumac18d8dadf1b01
diff --git a/.github/scripts/build-cross-version-matrix.js b/.github/scripts/build-cross-version-matrix.js
new file mode 100644
index 00000000000..ec3d59dc26d
--- /dev/null
+++ b/.github/scripts/build-cross-version-matrix.js
@@ -0,0 +1,52 @@
+// This script is used in .github/workflows/cross-version.yml
+// to generate a matrix for cross-version migration testing
+
+/**
+ * Generate a CI matrix for cross-version migration testing (EE only).
+ *
+ * Creates pairs of [source, target] for testing HEAD against the last N
+ * minor versions in both upgrade and downgrade directions.
+ *
+ * @param {number} currentVersion - The current major version number (e.g., 59)
+ * @param {number} count - Number of previous minor versions to test against (default: 3)
+ * @returns {{ config: Array<{ source: string, target: string }> }}
+ *
+ * @example
+ * buildMatrix(59)
+ * // Returns:
+ * // {
+ * // config: [
+ * // { source: "HEAD", target: "v1.59.x" },
+ * // { source: "v1.59.x", target: "HEAD" },
+ * // { source: "HEAD", target: "v1.58.x" },
+ * // { source: "v1.58.x", target: "HEAD" },
+ * // { source: "HEAD", target: "v1.57.x" },
+ * // { source: "v1.57.x", target: "HEAD" },
+ * // ]
+ * // }
+ */
+function buildCrossVersionMatrix(currentVersion, count = 3) {
+ if (!Number.isInteger(currentVersion) || currentVersion < 1) {
+ throw new Error(
+ `Invalid currentVersion: ${currentVersion}. Must be a positive integer.`,
+ );
+ }
+
+ if (!Number.isInteger(count) || count < 1) {
+ throw new Error(`Invalid count: ${count}. Must be a positive integer.`);
+ }
+
+ const config = Array.from({ length: count }, (_, i) => currentVersion - i)
+ .filter((majorVersion) => majorVersion >= 1)
+ .flatMap((majorVersion) => {
+ const version = `v1.${majorVersion}.x`;
+ return [
+ { source: "HEAD", target: version },
+ { source: version, target: "HEAD" },
+ ];
+ });
+
+ return { config };
+}
+
+module.exports = { buildCrossVersionMatrix };
diff --git a/.github/scripts/build-cross-version-matrix.unit.spec.js b/.github/scripts/build-cross-version-matrix.unit.spec.js
new file mode 100644
index 00000000000..2a7ed8d1df3
--- /dev/null
+++ b/.github/scripts/build-cross-version-matrix.unit.spec.js
@@ -0,0 +1,242 @@
+const { buildCrossVersionMatrix } = require("./build-cross-version-matrix");
+
+describe("buildCrossVersionMatrix", () => {
+ describe("default behavior", () => {
+ it("should generate matrix with 3 versions by default", () => {
+ const result = buildCrossVersionMatrix(59);
+ expect(result).toEqual({
+ config: [
+ { source: "HEAD", target: "v1.59.x" },
+ { source: "v1.59.x", target: "HEAD" },
+ { source: "HEAD", target: "v1.58.x" },
+ { source: "v1.58.x", target: "HEAD" },
+ { source: "HEAD", target: "v1.57.x" },
+ { source: "v1.57.x", target: "HEAD" },
+ ],
+ });
+ });
+
+ it("should use EE prefix (v1)", () => {
+ const result = buildCrossVersionMatrix(50);
+ expect(result.config[0].target).toBe("v1.50.x");
+ expect(result.config[1].source).toBe("v1.50.x");
+ });
+
+ it("should create pairs in both directions (upgrade and downgrade)", () => {
+ const result = buildCrossVersionMatrix(59);
+ const entries = result.config;
+
+ // Check HEAD -> version (upgrade test)
+ expect(entries.filter((e) => e.source === "HEAD")).toHaveLength(3);
+ // Check version -> HEAD (downgrade test)
+ expect(entries.filter((e) => e.target === "HEAD")).toHaveLength(3);
+ });
+ });
+
+ describe("custom count", () => {
+ it("should generate matrix with custom count", () => {
+ const result = buildCrossVersionMatrix(59, 5);
+ expect(result.config).toHaveLength(10); // 5 versions × 2 directions
+ expect(result.config).toEqual([
+ { source: "HEAD", target: "v1.59.x" },
+ { source: "v1.59.x", target: "HEAD" },
+ { source: "HEAD", target: "v1.58.x" },
+ { source: "v1.58.x", target: "HEAD" },
+ { source: "HEAD", target: "v1.57.x" },
+ { source: "v1.57.x", target: "HEAD" },
+ { source: "HEAD", target: "v1.56.x" },
+ { source: "v1.56.x", target: "HEAD" },
+ { source: "HEAD", target: "v1.55.x" },
+ { source: "v1.55.x", target: "HEAD" },
+ ]);
+ });
+
+ it("should generate matrix with count=1", () => {
+ const result = buildCrossVersionMatrix(59, 1);
+ expect(result.config).toHaveLength(2);
+ expect(result.config).toEqual([
+ { source: "HEAD", target: "v1.59.x" },
+ { source: "v1.59.x", target: "HEAD" },
+ ]);
+ });
+
+ it("should generate matrix with large count", () => {
+ const result = buildCrossVersionMatrix(59, 10);
+ expect(result.config).toHaveLength(20);
+
+ // Check first and last entries
+ expect(result.config[0]).toEqual({
+ source: "HEAD",
+ target: "v1.59.x",
+ });
+ expect(result.config[18]).toEqual({
+ source: "HEAD",
+ target: "v1.50.x",
+ });
+ expect(result.config[19]).toEqual({
+ source: "v1.50.x",
+ target: "HEAD",
+ });
+ });
+ });
+
+ describe("edge cases", () => {
+ it("should handle version 1", () => {
+ const result = buildCrossVersionMatrix(1);
+ expect(result).toEqual({
+ config: [
+ { source: "HEAD", target: "v1.1.x" },
+ { source: "v1.1.x", target: "HEAD" },
+ ],
+ });
+ });
+
+ it("should stop when version would go below 1", () => {
+ const result = buildCrossVersionMatrix(2, 5);
+ // Can only generate v1.2.x and v1.1.x (2 versions, not 5)
+ expect(result.config).toHaveLength(4);
+ expect(result).toEqual({
+ config: [
+ { source: "HEAD", target: "v1.2.x" },
+ { source: "v1.2.x", target: "HEAD" },
+ { source: "HEAD", target: "v1.1.x" },
+ { source: "v1.1.x", target: "HEAD" },
+ ],
+ });
+ });
+
+ it("should handle high version numbers", () => {
+ const result = buildCrossVersionMatrix(100, 2);
+ expect(result).toEqual({
+ config: [
+ { source: "HEAD", target: "v1.100.x" },
+ { source: "v1.100.x", target: "HEAD" },
+ { source: "HEAD", target: "v1.99.x" },
+ { source: "v1.99.x", target: "HEAD" },
+ ],
+ });
+ });
+ });
+
+ describe("error handling", () => {
+ it("should throw for undefined currentVersion", () => {
+ expect(() => buildCrossVersionMatrix()).toThrow(
+ "Invalid currentVersion: undefined. Must be a positive integer.",
+ );
+ });
+
+ it("should throw for non-integer currentVersion", () => {
+ expect(() => buildCrossVersionMatrix(59.5)).toThrow(
+ "Invalid currentVersion: 59.5. Must be a positive integer.",
+ );
+ });
+
+ it("should throw for zero currentVersion", () => {
+ expect(() => buildCrossVersionMatrix(0)).toThrow(
+ "Invalid currentVersion: 0. Must be a positive integer.",
+ );
+ });
+
+ it("should throw for negative currentVersion", () => {
+ expect(() => buildCrossVersionMatrix(-1)).toThrow(
+ "Invalid currentVersion: -1. Must be a positive integer.",
+ );
+ });
+
+ it("should throw for NaN currentVersion", () => {
+ expect(() => buildCrossVersionMatrix(NaN)).toThrow(
+ "Invalid currentVersion: NaN. Must be a positive integer.",
+ );
+ });
+
+ it("should throw for non-integer count", () => {
+ expect(() => buildCrossVersionMatrix(59, 2.5)).toThrow(
+ "Invalid count: 2.5. Must be a positive integer.",
+ );
+ });
+
+ it("should throw for zero count", () => {
+ expect(() => buildCrossVersionMatrix(59, 0)).toThrow(
+ "Invalid count: 0. Must be a positive integer.",
+ );
+ });
+
+ it("should throw for negative count", () => {
+ expect(() => buildCrossVersionMatrix(59, -1)).toThrow(
+ "Invalid count: -1. Must be a positive integer.",
+ );
+ });
+ });
+
+ describe("matrix structure for GitHub Actions", () => {
+ it("should return object with config array", () => {
+ const result = buildCrossVersionMatrix(59);
+ expect(result).toHaveProperty("config");
+ expect(Array.isArray(result.config)).toBe(true);
+ });
+
+ it("should produce valid JSON for GitHub Actions", () => {
+ const result = buildCrossVersionMatrix(59);
+ const json = JSON.stringify(result);
+ expect(() => JSON.parse(json)).not.toThrow();
+
+ const parsed = JSON.parse(json);
+ expect(parsed.config).toHaveLength(6);
+ expect(parsed.config[0]).toEqual({
+ source: "HEAD",
+ target: "v1.59.x",
+ });
+ });
+
+ it("should have consistent entry structure", () => {
+ const result = buildCrossVersionMatrix(59, 5);
+
+ result.config.forEach((entry) => {
+ expect(entry).toHaveProperty("source");
+ expect(entry).toHaveProperty("target");
+ expect(typeof entry.source).toBe("string");
+ expect(typeof entry.target).toBe("string");
+ // Either source or target should be HEAD
+ expect(entry.source === "HEAD" || entry.target === "HEAD").toBeTruthy();
+ });
+ });
+ });
+
+ describe("version ordering", () => {
+ it("should generate versions in descending order", () => {
+ const result = buildCrossVersionMatrix(59, 5);
+ const versions = result.config
+ .filter((e) => e.source === "HEAD")
+ .map((e) => e.target);
+
+ expect(versions).toEqual([
+ "v1.59.x",
+ "v1.58.x",
+ "v1.57.x",
+ "v1.56.x",
+ "v1.55.x",
+ ]);
+ });
+
+ it("should interleave upgrade and downgrade tests", () => {
+ const result = buildCrossVersionMatrix(59, 2);
+
+ expect(result.config[0]).toEqual({
+ source: "HEAD",
+ target: "v1.59.x",
+ });
+ expect(result.config[1]).toEqual({
+ source: "v1.59.x",
+ target: "HEAD",
+ });
+ expect(result.config[2]).toEqual({
+ source: "HEAD",
+ target: "v1.58.x",
+ });
+ expect(result.config[3]).toEqual({
+ source: "v1.58.x",
+ target: "HEAD",
+ });
+ });
+ });
+});
diff --git a/.github/workflows/cross-version.yml b/.github/workflows/cross-version.yml
new file mode 100644
index 00000000000..bd7b23718e8
--- /dev/null
+++ b/.github/workflows/cross-version.yml
@@ -0,0 +1,103 @@
+name: Cross-Version Migration Tests
+
+on:
+ workflow_dispatch:
+ inputs:
+ source_version:
+ description: "Source version (e.g., v1.58.6 for EE, v0.58.6 for OSS, or HEAD)"
+ required: true
+ type: string
+ target_version:
+ description: "Target version (e.g., v1.58.7 for EE, v0.58.7 for OSS, or HEAD)"
+ required: true
+ type: string
+
+ pull_request:
+ paths:
+ - "cross-version/**"
+ - "resources/migrations/**"
+ - ".github/workflows/cross-version.yml"
+ - ".github/scripts/build-cross-version-matrix.js"
+
+ schedule:
+ # Run nightly at 3 AM UTC
+ - cron: "0 3 * * *"
+
+jobs:
+ # Generate matrix for scheduled/PR runs
+ generate-matrix:
+ if: github.event_name != 'workflow_dispatch'
+ runs-on: ubuntu-latest
+ outputs:
+ matrix: ${{ steps.set-matrix.outputs.matrix }}
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ sparse-checkout: .github
+
+ - name: Generate version matrix
+ id: set-matrix
+ uses: actions/github-script@v7
+ with:
+ script: |
+ const { buildCrossVersionMatrix } = require('${{ github.workspace }}/.github/scripts/build-cross-version-matrix');
+ const { config } = buildCrossVersionMatrix(${{ vars.CURRENT_VERSION }});
+ const matrix = JSON.stringify({ include: config });
+ core.setOutput("matrix", matrix);
+ console.log("matrix:", matrix);
+
+ # Matrix-based tests for scheduled/PR runs
+ test-matrix:
+ if: github.event_name != 'workflow_dispatch'
+ needs: generate-matrix
+ runs-on: ubuntu-latest
+ timeout-minutes: 30
+ strategy:
+ matrix: ${{ fromJson(needs.generate-matrix.outputs.matrix) }}
+ fail-fast: false
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Prepare release scripts
+ uses: ./.github/actions/prepare-release-scripts
+
+ - name: Run cross-version test
+ env:
+ CURRENT_VERSION: ${{ vars.CURRENT_VERSION }}
+ run: |
+ cd cross-version
+ ./test.sh --source "${{ matrix.source }}" --target "${{ matrix.target }}"
+
+ - name: Show logs on failure
+ if: failure()
+ run: |
+ cd cross-version
+ docker compose logs metabase || true
+ docker compose logs postgres || true
+
+ # Manual test for workflow_dispatch
+ test-manual:
+ if: github.event_name == 'workflow_dispatch'
+ runs-on: ubuntu-latest
+ timeout-minutes: 30
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Prepare release scripts
+ uses: ./.github/actions/prepare-release-scripts
+
+ - name: Run cross-version test
+ env:
+ CURRENT_VERSION: ${{ vars.CURRENT_VERSION }}
+ run: |
+ cd cross-version
+ ./test.sh --source "${{ inputs.source_version }}" --target "${{ inputs.target_version }}"
+
+ - name: Show logs on failure
+ if: failure()
+ run: |
+ cd cross-version
+ docker compose logs metabase || true
+ docker compose logs postgres || true
diff --git a/cross-version/README.md b/cross-version/README.md
new file mode 100644
index 00000000000..a5511869d9b
--- /dev/null
+++ b/cross-version/README.md
@@ -0,0 +1,55 @@
+# Cross-Version Migration Testing
+
+Tests Metabase database migrations across version upgrades and downgrades.
+
+## Quick Start
+
+```bash
+# Test upgrade (OSS)
+./test.sh --source v0.58.6 --target v0.58.7
+
+# Test downgrade (OSS)
+./test.sh --source v0.58.7 --target v0.58.6
+
+# Test Enterprise edition (use v1.x.x)
+./test.sh --source v1.58.6 --target v1.58.7
+```
+
+Edition is inferred from version prefix: `v0.x.x` = OSS, `v1.x.x` = EE.
+
+## Requirements
+
+- Docker
+- Docker Compose v2
+- Bun (for version helpers CLI)
+
+## How It Works
+
+### Upgrade Test
+1. Start PostgreSQL container
+2. Start SOURCE Metabase version, wait for healthy
+3. Stop SOURCE container (PostgreSQL persists)
+4. Start TARGET version - migrations run automatically
+5. Verify health check passes
+
+### Downgrade Test
+1. Start PostgreSQL container
+2. Start SOURCE (newer) Metabase version, wait for healthy
+3. Stop SOURCE container
+4. Start TARGET (older) version - expects refusal
+5. Run `migrate down` command
+6. Start TARGET version again
+7. Verify health check passes
+
+## Environment Variables
+
+| Variable | Default | Description |
+|----------|---------|-------------|
+| `METABASE_PORT` | 3000 | Port to expose Metabase |
+| `HEALTH_TIMEOUT` | 120 | Seconds to wait for health check |
+
+## CI
+
+The GitHub workflow (`.github/workflows/cross-version.yml`) supports:
+- **Manual trigger**: Specify source/target versions
+- **Nightly schedule**: Runs predefined version matrix
diff --git a/cross-version/cli.ts b/cross-version/cli.ts
new file mode 100644
index 00000000000..40309fea731
--- /dev/null
+++ b/cross-version/cli.ts
@@ -0,0 +1,19 @@
+#!/usr/bin/env bun
+import {
+ compareVersions,
+ getDockerImage,
+ getMajorVersion,
+} from "../release/src/cross-version-helpers";
+
+const [cmd, ...args] = process.argv.slice(2);
+
+if (cmd === "compare") {
+ console.log(compareVersions(args[0], args[1]));
+} else if (cmd === "image") {
+ console.log(getDockerImage(args[0]));
+} else if (cmd === "major") {
+ console.log(getMajorVersion(args[0]));
+} else {
+ console.error("Usage: cli.ts <compare|image|major> [args]");
+ process.exit(1);
+}
diff --git a/cross-version/docker-compose.yml b/cross-version/docker-compose.yml
new file mode 100644
index 00000000000..c10437c78bb
--- /dev/null
+++ b/cross-version/docker-compose.yml
@@ -0,0 +1,32 @@
+services:
+ postgres:
+ image: postgres:15
+ environment:
+ POSTGRES_USER: metabase
+ POSTGRES_PASSWORD: metabase
+ POSTGRES_DB: metabase
+ healthcheck:
+ test: ["CMD-SHELL", "pg_isready -U metabase"]
+ interval: 5s
+ timeout: 5s
+ retries: 5
+ volumes:
+ - postgres_data:/var/lib/postgresql/data
+
+ metabase:
+ image: ${METABASE_IMAGE:-metabase/metabase:latest}
+ ports:
+ - "${METABASE_PORT:-3000}:3000"
+ environment:
+ MB_DB_TYPE: postgres
+ MB_DB_DBNAME: metabase
+ MB_DB_PORT: 5432
+ MB_DB_USER: metabase
+ MB_DB_PASS: metabase
+ MB_DB_HOST: postgres
+ depends_on:
+ postgres:
+ condition: service_healthy
+
+volumes:
+ postgres_data:
diff --git a/cross-version/test.sh b/cross-version/test.sh
new file mode 100755
index 00000000000..fa4de40a9c6
--- /dev/null
+++ b/cross-version/test.sh
@@ -0,0 +1,383 @@
+#!/usr/bin/env bash
+#
+# Cross-version migration testing for Metabase
+#
+# Usage:
+# ./test.sh --source v0.58.6 --target v0.58.7
+#
+# Edition (OSS/EE) is inferred from version prefix (v0.x = OSS, v1.x = EE).
+# Direction (upgrade/downgrade) is inferred from version comparison.
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+cd "$SCRIPT_DIR"
+
+# Defaults
+SOURCE_VERSION=""
+TARGET_VERSION=""
+METABASE_PORT="${METABASE_PORT:-3000}"
+HEALTH_TIMEOUT="${HEALTH_TIMEOUT:-120}"
+
+# Colors for output
+RED='\033[0;31m'
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+NC='\033[0m' # No Color
+
+log() { echo -e "${GREEN}[cross-version]${NC} $*"; }
+warn() { echo -e "${YELLOW}[cross-version]${NC} $*"; }
+error() { echo -e "${RED}[cross-version]${NC} $*" >&2; }
+
+usage() {
+ cat <<EOF
+Usage: $0 --source VERSION --target VERSION
+
+Options:
+ --source VERSION Source version (e.g., v0.58.6 for OSS, v1.58.6 for EE)
+ --target VERSION Target version (e.g., v0.58.7 for OSS, v1.58.7 for EE)
+ --help Show this help
+
+Examples:
+ $0 --source v0.58.6 --target v0.58.7 # Upgrade test (OSS)
+ $0 --source v0.58.7 --target v0.58.6 # Downgrade test (OSS)
+ $0 --source v1.58.6 --target v1.58.7 # Upgrade test (EE)
+EOF
+ exit 1
+}
+
+# Parse arguments
+while [[ $# -gt 0 ]]; do
+ case $1 in
+ --source) SOURCE_VERSION="$2"; shift 2 ;;
+ --target) TARGET_VERSION="$2"; shift 2 ;;
+ --help) usage ;;
+ *) error "Unknown option: $1"; usage ;;
+ esac
+done
+
+if [[ -z "$SOURCE_VERSION" || -z "$TARGET_VERSION" ]]; then
+ error "Both --source and --target are required"
+ usage
+fi
+
+# CLI wrapper for version helpers (uses tested TypeScript implementation)
+cli() {
+ bun "$SCRIPT_DIR/cli.ts" "$@"
+}
+
+wait_for_health() {
+ local timeout="$1"
+ local start_time=$(date +%s)
+
+ log "Waiting for Metabase to be healthy (timeout: ${timeout}s)..."
+
+ while true; do
+ local current_time=$(date +%s)
+ local elapsed=$((current_time - start_time))
+
+ if (( elapsed >= timeout )); then
+ error "Health check timed out after ${timeout}s"
+ return 1
+ fi
+
+ if curl -sf "http://localhost:${METABASE_PORT}/api/health" > /dev/null 2>&1; then
+ local response=$(curl -sf "http://localhost:${METABASE_PORT}/api/health")
+ if [[ "$response" == '{"status":"ok"}' ]]; then
+ log "Health check passed after ${elapsed}s"
+ return 0
+ fi
+ fi
+
+ sleep 2
+ done
+}
+
+# Start Metabase with a specific image
+start_metabase() {
+ local image="$1"
+ log "Starting Metabase with image: $image"
+
+ METABASE_IMAGE="$image" METABASE_PORT="$METABASE_PORT" \
+ docker compose up -d --quiet-pull
+}
+
+# Stop Metabase (but keep postgres)
+stop_metabase() {
+ log "Stopping Metabase container..."
+ docker compose stop metabase
+ docker compose rm -f metabase
+}
+
+# Get edition prefix from version (0 for OSS, 1 for EE)
+get_edition_prefix() {
+ local version="$1"
+ if [[ "$version" == "HEAD" ]]; then
+ echo "1" # HEAD is EE
+ elif [[ "$version" =~ ^v([01])\. ]]; then
+ echo "${BASH_REMATCH[1]}"
+ else
+ error "Cannot determine edition from version: $version"
+ return 1
+ fi
+}
+
+# https://www.metabase.com/docs/latest/installation-and-operation/upgrading-metabase#using-the-migrate-down-command
+# Run a single migrate down step (rolls back exactly one major version)
+# This function is idempotent - it takes a version string and handles everything internally.
+migrate_down_step() {
+ local version="$1"
+ local image is_head="false"
+
+ # Resolve image from version
+ image=$(cli image "$version") || return 1
+ [[ "$version" == "HEAD" ]] && is_head="true"
+
+ log "Running 'migrate down' for version: $version (image: $image)"
+
+ local output
+ local exit_code=0
+
+ # The HEAD Docker image has version "vUNKNOWN" in its version.properties,
+ # which causes `migrate down` to fail with a NullPointerException when trying
+ # to determine the current major version. To work around this, we extract the
+ # JAR, replace version.properties with the upcoming version, and mount the
+ # modified JAR.
+ #
+ # HEAD is the next major version (CURRENT_VERSION + 1).
+ #
+ # See DEV-1636 for a potential backend fix that would make this unnecessary.
+ if [[ "$is_head" == "true" ]]; then
+ if [[ -z "$CURRENT_VERSION" ]]; then
+ error "CURRENT_VERSION must be set when testing HEAD downgrades"
+ return 1
+ fi
+ local next_version=$((CURRENT_VERSION + 1))
+ local upcoming_version="v1.${next_version}.0"
+ local work_dir="/tmp/metabase-head-jar"
+ local modified_jar="$work_dir/metabase.jar"
+
+ log "HEAD JAR needs patching (version.properties says 'vUNKNOWN', setting to $upcoming_version)"
+ rm -rf "$work_dir"
+ mkdir -p "$work_dir"
+
+ # Extract JAR from container (copy to host with proper permissions)
+ docker create --name metabase-jar-extract "$image" >/dev/null
+ docker cp metabase-jar-extract:/app/metabase.jar "$modified_jar"
+ docker rm metabase-jar-extract >/dev/null
+
+ # Create version.properties with upcoming version and update the JAR
+ echo "tag=$upcoming_version" > "$work_dir/version.properties"
+ echo "hash=HEAD" >> "$work_dir/version.properties"
+ echo "date=$(date +%Y-%m-%d)" >> "$work_dir/version.properties"
+ (cd "$work_dir" && zip -u metabase.jar version.properties >/dev/null)
+
+ log "HEAD JAR patched - proceeding with migrate down"
+
+ output=$(METABASE_IMAGE="$image" docker compose run --rm --quiet-pull \
+ -v "$modified_jar:/app/metabase.jar:ro" \
+ metabase "migrate down" 2>&1) || exit_code=$?
+ else
+ output=$(METABASE_IMAGE="$image" docker compose run --rm --quiet-pull metabase "migrate down" 2>&1) || exit_code=$?
+ fi
+
+ # Always print output for visibility
+ echo "$output"
+
+ # Check for errors - Metabase returns 0 even on partial rollback failures
+ if [[ $exit_code -ne 0 ]]; then
+ error "migrate down failed with exit code $exit_code"
+ return 1
+ fi
+
+ if echo "$output" | grep -q "ERROR.*liquibase\|RollbackFailedException\|Command failed with exception"; then
+ error "migrate down encountered errors (check logs above)"
+ return 1
+ fi
+}
+
+# Cascading migrate down: rolls back multiple major versions one at a time
+# Metabase only supports rolling back one major version per `migrate down` call,
+# so we need to iterate through intermediate versions.
+cascading_migrate_down() {
+ local source_version="$1"
+ local target_version="$2"
+
+ local source_major target_major edition_prefix
+ source_major=$(cli major "$source_version") || return 1
+ target_major=$(cli major "$target_version") || return 1
+ edition_prefix=$(get_edition_prefix "$source_version") || return 1
+
+ local steps=$((source_major - target_major))
+ log "Cascading migrate down: v$source_major → v$target_major ($steps step(s))"
+
+ # Build version sequence: source version first, then intermediate rolling versions
+ local versions=("$source_version")
+ local current=$((source_major - 1))
+ while (( current > target_major )); do
+ versions+=("v${edition_prefix}.${current}.x")
+ ((current--))
+ done
+
+ # Simple loop - each step handles its own image resolution
+ local step=1
+ for version in "${versions[@]}"; do
+ log "--------------------------------------------"
+ log "Cascade step $step/$steps: $version"
+ log "--------------------------------------------"
+ if ! migrate_down_step "$version"; then
+ error "Migrate down failed at step $step ($version)"
+ return 1
+ fi
+ ((step++))
+ done
+
+ log "--------------------------------------------"
+ log "Cascading migrate down complete"
+}
+
+# Check if Metabase refuses to start (downgrade detection)
+check_downgrade_refused() {
+ local timeout=60
+ local start_time=$(date +%s)
+
+ log "Checking if Metabase detects downgrade and refuses to start..."
+
+ while true; do
+ local current_time=$(date +%s)
+ local elapsed=$((current_time - start_time))
+
+ if (( elapsed >= timeout )); then
+ error "Timed out waiting for downgrade detection"
+ return 1
+ fi
+
+ # Check container logs for downgrade error
+ local logs=$(docker compose logs metabase 2>&1 || true)
+
+ if echo "$logs" | grep -qi "migrate.*down\|downgrade\|database.*newer"; then
+ log "Metabase correctly detected downgrade scenario"
+ return 0
+ fi
+
+ local status=$(docker compose ps metabase --format '{{.Status}}' 2>/dev/null || echo "")
+ if [[ "$status" =~ [Ee]xit ]]; then
+ log "Metabase container exited (expected for downgrade)"
+ return 0
+ fi
+
+ sleep 2
+ done
+}
+
+cleanup() {
+ log "Cleaning up..."
+ docker compose down -v --remove-orphans 2>/dev/null || true
+}
+
+check_image_exists() {
+ local image="$1"
+ if ! docker manifest inspect "$image" > /dev/null 2>&1; then
+ error "Docker image not found: $image"
+ exit 1
+ fi
+}
+
+main() {
+ local direction source_image target_image
+
+ direction=$(cli compare "$SOURCE_VERSION" "$TARGET_VERSION") || exit 1
+ source_image=$(cli image "$SOURCE_VERSION") || exit 1
+ target_image=$(cli image "$TARGET_VERSION") || exit 1
+
+ if [[ "$direction" == "same" ]]; then
+ error "Source and target versions are the same"
+ exit 1
+ fi
+
+ log "Checking if Docker images exist..."
+ check_image_exists "$source_image"
+ check_image_exists "$target_image"
+
+ log "============================================"
+ log "Cross-Version Migration Test"
+ log "============================================"
+ log "Direction: $direction"
+ log "Source: $source_image"
+ log "Target: $target_image"
+ log "============================================"
+
+ # Ensure clean state
+ cleanup
+
+ trap cleanup EXIT
+
+ log ""
+ log "Step 1: Starting SOURCE version ($SOURCE_VERSION)..."
+ start_metabase "$source_image"
+
+ if ! wait_for_health "$HEALTH_TIMEOUT"; then
+ error "❌ SOURCE version ($SOURCE_VERSION) failed health check"
+ docker compose logs metabase
+ exit 1
+ fi
+
+ log "✅ SOURCE version ($SOURCE_VERSION) is healthy"
+
+ log ""
+ log "Step 2: Stopping SOURCE version ($SOURCE_VERSION)..."
+ stop_metabase
+
+ log ""
+ log "Step 3: Starting TARGET version ($TARGET_VERSION)..."
+ start_metabase "$target_image"
+
+ if [[ "$direction" == "upgrade" ]]; then
+ # Upgrade: should migrate automatically and become healthy
+ if ! wait_for_health "$HEALTH_TIMEOUT"; then
+ error "❌ TARGET version ($TARGET_VERSION) failed health check after upgrade"
+ docker compose logs metabase
+ exit 1
+ fi
+ log "✅ UPGRADE successful - TARGET version ($TARGET_VERSION) is healthy"
+
+ else
+ # Downgrade: should refuse to start, then we run migrate down
+ if ! check_downgrade_refused; then
+ error "❌ TARGET version ($TARGET_VERSION) did not properly detect downgrade"
+ docker compose logs metabase
+ exit 1
+ fi
+
+ # Stop the failed container
+ stop_metabase
+
+ log ""
+ log "============================================"
+ log "Step 4: Rolling back database ($SOURCE_VERSION → $TARGET_VERSION)..."
+ log "============================================"
+ if ! cascading_migrate_down "$SOURCE_VERSION" "$TARGET_VERSION"; then
+ error "❌ migrate down failed"
+ exit 1
+ fi
+
+ # Try starting again
+ log ""
+ log "Step 5: Starting TARGET version ($TARGET_VERSION) after migrate down..."
+ start_metabase "$target_image"
+
+ if ! wait_for_health "$HEALTH_TIMEOUT"; then
+ error "❌ TARGET version ($TARGET_VERSION) failed health check after migrate down"
+ docker compose logs metabase
+ exit 1
+ fi
+ log "✅ DOWNGRADE successful - TARGET version ($TARGET_VERSION) is healthy after migrate down"
+ fi
+
+ log ""
+ log "============================================"
+ log "✅ TEST PASSED"
+ log "============================================"
+}
+
+main
diff --git a/release/src/cross-version-helpers.ts b/release/src/cross-version-helpers.ts
new file mode 100644
index 00000000000..4e52850caf7
--- /dev/null
+++ b/release/src/cross-version-helpers.ts
@@ -0,0 +1,158 @@
+/**
+ * Version helpers for cross-version migration testing.
+ *
+ * These extend the core version-helpers with support for:
+ * - HEAD (unreleased builds from the current branch)
+ * - Rolling .x tags (e.g., v1.59.x)
+ *
+ * These concepts don't exist in regular release tooling, so they're isolated here.
+ * This file can import from version-helpers, but not vice versa.
+ */
+import {
+ getMajorVersion as getReleaseMajorVersion,
+ isEnterpriseVersion,
+ isValidVersionString,
+ versionSort,
+} from "./version-helpers";
+
+export type VersionComparisonResult = "upgrade" | "downgrade" | "same";
+
+// ============================================================================
+// Predicates
+// ============================================================================
+
+export const isHead = (version: string): boolean => version === "HEAD";
+
+export const isRollingTag = (version: string): boolean => version.endsWith(".x");
+
+// ============================================================================
+// Pure helpers for HEAD versions
+// ============================================================================
+
+/** Given the current major version, returns the next major version (HEAD). */
+export const getHeadMajorVersion = (currentVersion: string): string => {
+ if (!currentVersion) {
+ throw new Error("currentVersion is required");
+ }
+ return String(Number(currentVersion) + 1);
+};
+
+/** Docker image for HEAD builds. */
+export const HEAD_DOCKER_IMAGE = "metabase/metabase-enterprise-head:latest";
+
+// ============================================================================
+// Pure helpers for rolling .x tags
+// ============================================================================
+
+/** Extract major version from a rolling tag like v1.59.x */
+export const getRollingTagMajorVersion = (version: string): string => {
+ const match = version.match(/v\d+\.(\d+)\.x$/);
+ if (!match) {
+ throw new Error(`Invalid rolling tag: ${version}`);
+ }
+ return match[1];
+};
+
+/** Check if a rolling tag is enterprise edition (v1.x.x) */
+export const isRollingTagEnterprise = (version: string): boolean =>
+ version.startsWith("v1.");
+
+// ============================================================================
+// Composed helpers (exported for use by CLI)
+// ============================================================================
+
+/**
+ * Get the major version number from a version string.
+ * Supports HEAD and rolling .x tags.
+ */
+export const getMajorVersion = (version: string): string => {
+ if (isHead(version)) {
+ const currentVersion = process.env.CURRENT_VERSION;
+ if (!currentVersion) {
+ throw new Error("CURRENT_VERSION env var must be set when using HEAD");
+ }
+ return getHeadMajorVersion(currentVersion);
+ }
+
+ if (isRollingTag(version)) {
+ return getRollingTagMajorVersion(version);
+ }
+
+ return getReleaseMajorVersion(version);
+};
+
+/**
+ * Compare two versions to determine upgrade/downgrade direction.
+ * Supports HEAD and rolling .x tags.
+ */
+export const compareVersions = (
+ source: string,
+ target: string,
+): VersionComparisonResult => {
+ // HEAD is always newer than any released version
+ if (isHead(source) && isHead(target)) {
+ return "same";
+ }
+ if (isHead(source)) {
+ return "downgrade";
+ }
+ if (isHead(target)) {
+ return "upgrade";
+ }
+
+ // Rolling tags - compare by major version only
+ if (isRollingTag(source) || isRollingTag(target)) {
+ const sourceMajor = isRollingTag(source)
+ ? parseInt(getRollingTagMajorVersion(source), 10)
+ : parseInt(getReleaseMajorVersion(source), 10);
+ const targetMajor = isRollingTag(target)
+ ? parseInt(getRollingTagMajorVersion(target), 10)
+ : parseInt(getReleaseMajorVersion(target), 10);
+
+ if (sourceMajor < targetMajor) {
+ return "upgrade";
+ }
+ if (sourceMajor > targetMajor) {
+ return "downgrade";
+ }
+ return "same";
+ }
+
+ // Regular versions - validate and compare
+ if (!isValidVersionString(source)) {
+ throw new Error(`Invalid version string: ${source}`);
+ }
+ if (!isValidVersionString(target)) {
+ throw new Error(`Invalid version string: ${target}`);
+ }
+
+ const result = versionSort(source, target);
+ if (result < 0) {
+ return "upgrade";
+ }
+ if (result > 0) {
+ return "downgrade";
+ }
+ return "same";
+};
+
+/**
+ * Get the Docker image for a version.
+ * Supports HEAD and rolling .x tags.
+ */
+export const getDockerImage = (version: string): string => {
+ if (isHead(version)) {
+ return HEAD_DOCKER_IMAGE;
+ }
+
+ if (!isRollingTag(version) && !isValidVersionString(version)) {
+ throw new Error(`Invalid version string: ${version}`);
+ }
+
+ const isEE = isRollingTag(version)
+ ? isRollingTagEnterprise(version)
+ : isEnterpriseVersion(version);
+
+ const repo = isEE ? "metabase/metabase-enterprise" : "metabase/metabase";
+ return `${repo}:${version}`;
+};
diff --git a/release/src/cross-version-helpers.unit.spec.ts b/release/src/cross-version-helpers.unit.spec.ts
new file mode 100644
index 00000000000..4dc76dd0006
--- /dev/null
+++ b/release/src/cross-version-helpers.unit.spec.ts
@@ -0,0 +1,216 @@
+import {
+ compareVersions,
+ getDockerImage,
+ getHeadMajorVersion,
+ getMajorVersion,
+ getRollingTagMajorVersion,
+ HEAD_DOCKER_IMAGE,
+ isHead,
+ isRollingTag,
+ isRollingTagEnterprise,
+} from "./cross-version-helpers";
+
+describe("cross-version-helpers", () => {
+ describe("predicates", () => {
+ describe("isHead", () => {
+ it("returns true for HEAD", () => {
+ expect(isHead("HEAD")).toBe(true);
+ });
+
+ it("returns false for other versions", () => {
+ expect(isHead("v1.59.0")).toBe(false);
+ expect(isHead("v0.58.x")).toBe(false);
+ expect(isHead("head")).toBe(false);
+ });
+ });
+
+ describe("isRollingTag", () => {
+ it("returns true for .x tags", () => {
+ expect(isRollingTag("v1.59.x")).toBe(true);
+ expect(isRollingTag("v0.58.x")).toBe(true);
+ });
+
+ it("returns false for specific versions", () => {
+ expect(isRollingTag("v1.59.0")).toBe(false);
+ expect(isRollingTag("HEAD")).toBe(false);
+ });
+ });
+ });
+
+ describe("pure helpers", () => {
+ describe("getHeadMajorVersion", () => {
+ it("returns currentVersion + 1", () => {
+ expect(getHeadMajorVersion("59")).toBe("60");
+ expect(getHeadMajorVersion("52")).toBe("53");
+ expect(getHeadMajorVersion("0")).toBe("1");
+ });
+
+ it("throws when currentVersion is empty", () => {
+ expect(() => getHeadMajorVersion("")).toThrow(
+ "currentVersion is required",
+ );
+ });
+ });
+
+ describe("getRollingTagMajorVersion", () => {
+ it("extracts major version from rolling tag", () => {
+ expect(getRollingTagMajorVersion("v1.59.x")).toBe("59");
+ expect(getRollingTagMajorVersion("v0.58.x")).toBe("58");
+ expect(getRollingTagMajorVersion("v1.50.x")).toBe("50");
+ });
+
+ it("throws for invalid rolling tags", () => {
+ expect(() => getRollingTagMajorVersion("v1.59.0")).toThrow(
+ "Invalid rolling tag",
+ );
+ expect(() => getRollingTagMajorVersion("HEAD")).toThrow(
+ "Invalid rolling tag",
+ );
+ });
+ });
+
+ describe("isRollingTagEnterprise", () => {
+ it("returns true for v1.x tags", () => {
+ expect(isRollingTagEnterprise("v1.59.x")).toBe(true);
+ expect(isRollingTagEnterprise("v1.50.x")).toBe(true);
+ });
+
+ it("returns false for v0.x tags", () => {
+ expect(isRollingTagEnterprise("v0.59.x")).toBe(false);
+ expect(isRollingTagEnterprise("v0.50.x")).toBe(false);
+ });
+ });
+
+ describe("HEAD_DOCKER_IMAGE", () => {
+ it("is the enterprise head image", () => {
+ expect(HEAD_DOCKER_IMAGE).toBe(
+ "metabase/metabase-enterprise-head:latest",
+ );
+ });
+ });
+ });
+
+ describe("composed helpers", () => {
+ describe("getMajorVersion", () => {
+ it.each([
+ ["v0.52.3", "52"],
+ ["v1.52", "52"],
+ ["v1.43.2.1", "43"],
+ // Rolling tags
+ ["v1.59.x", "59"],
+ ["v0.58.x", "58"],
+ ])("%s -> %s", (input, expected) => {
+ expect(getMajorVersion(input)).toBe(expected);
+ });
+
+ it("handles HEAD when CURRENT_VERSION is set", () => {
+ const originalEnv = process.env.CURRENT_VERSION;
+ process.env.CURRENT_VERSION = "59";
+ try {
+ expect(getMajorVersion("HEAD")).toBe("60");
+ } finally {
+ process.env.CURRENT_VERSION = originalEnv;
+ }
+ });
+
+ it("throws for HEAD when CURRENT_VERSION is not set", () => {
+ const originalEnv = process.env.CURRENT_VERSION;
+ delete process.env.CURRENT_VERSION;
+ try {
+ expect(() => getMajorVersion("HEAD")).toThrow(
+ "CURRENT_VERSION env var must be set when using HEAD",
+ );
+ } finally {
+ process.env.CURRENT_VERSION = originalEnv;
+ }
+ });
+ });
+
+ describe("compareVersions", () => {
+ it.each([
+ // major version changes
+ ["v0.50.0", "v0.51.0", "upgrade"],
+ ["v0.57.13", "v0.58.7", "upgrade"],
+ ["v0.51.0", "v0.50.0", "downgrade"],
+ ["v0.58.7", "v0.57.13", "downgrade"],
+ // minor version changes
+ ["v0.58.6", "v0.58.7", "upgrade"],
+ ["v0.58.7", "v0.58.6", "downgrade"],
+ // patch version changes
+ ["v0.50.13.5", "v0.50.13.6", "upgrade"],
+ ["v0.50.13.6", "v0.50.13.5", "downgrade"],
+ ["v0.50.13.5", "v0.50.13.5", "same"],
+ // patch to minor
+ ["v0.50.13.5", "v0.50.14", "upgrade"],
+ ["v0.50.14", "v0.50.13.5", "downgrade"],
+ // patch to major
+ ["v0.50.13.5", "v0.51.0", "upgrade"],
+ ["v0.51.0", "v0.50.13.5", "downgrade"],
+ // same versions
+ ["v0.50.0", "v0.50.0", "same"],
+ ["v0.58.7", "v0.58.7", "same"],
+ // ignores edition prefix (v0 vs v1)
+ ["v1.58.6", "v0.58.7", "upgrade"],
+ ["v0.58.7", "v1.58.6", "downgrade"],
+ // HEAD (always newer than any released version)
+ ["HEAD", "HEAD", "same"],
+ ["HEAD", "v0.59.0", "downgrade"],
+ ["HEAD", "v1.59.0", "downgrade"],
+ ["v0.59.0", "HEAD", "upgrade"],
+ ["v1.59.0", "HEAD", "upgrade"],
+ // Rolling tags (.x)
+ ["v1.58.x", "v1.59.x", "upgrade"],
+ ["v1.59.x", "v1.58.x", "downgrade"],
+ ["v1.59.x", "v1.59.x", "same"],
+ ["v0.58.x", "v0.59.x", "upgrade"],
+ // Mixed rolling and specific
+ ["v1.58.x", "v1.59.0", "upgrade"],
+ ["v1.59.0", "v1.58.x", "downgrade"],
+ ] as const)("%s -> %s = %s", (source, target, expected) => {
+ expect(compareVersions(source, target)).toBe(expected);
+ });
+
+ it("throws for invalid source version", () => {
+ expect(() => compareVersions("invalid", "v0.58.7")).toThrow(
+ "Invalid version string: invalid",
+ );
+ });
+
+ it("throws for invalid target version", () => {
+ expect(() => compareVersions("v0.58.7", "invalid")).toThrow(
+ "Invalid version string: invalid",
+ );
+ });
+ });
+
+ describe("getDockerImage", () => {
+ it.each([
+ // OSS versions (v0.x.x)
+ ["v0.58.7", "metabase/metabase:v0.58.7"],
+ ["v0.57.13", "metabase/metabase:v0.57.13"],
+ ["v0.50.13.5", "metabase/metabase:v0.50.13.5"],
+ // EE versions (v1.x.x)
+ ["v1.58.7", "metabase/metabase-enterprise:v1.58.7"],
+ ["v1.57.13", "metabase/metabase-enterprise:v1.57.13"],
+ ["v1.50.13.5", "metabase/metabase-enterprise:v1.50.13.5"],
+ // Rolling tags (.x)
+ ["v0.59.x", "metabase/metabase:v0.59.x"],
+ ["v1.59.x", "metabase/metabase-enterprise:v1.59.x"],
+ ["v0.50.x", "metabase/metabase:v0.50.x"],
+ ["v1.50.x", "metabase/metabase-enterprise:v1.50.x"],
+ ] as const)("%s -> %s", (version, expected) => {
+ expect(getDockerImage(version)).toBe(expected);
+ });
+
+ it("throws for invalid version", () => {
+ expect(() => getDockerImage("invalid")).toThrow(
+ "Invalid version string: invalid",
+ );
+ });
+
+ it("returns enterprise HEAD image for HEAD", () => {
+ expect(getDockerImage("HEAD")).toBe(HEAD_DOCKER_IMAGE);
+ });
+ });
+ });
+});