Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions dev/breeze/doc/ci/08_fork_ci_for_external_contributors.md
Original file line number Diff line number Diff line change
Expand Up @@ -293,12 +293,13 @@ added `[pilot]` instant, an `enabled_since` moved later, or `enabled` switched o
`enabled_since` is still in the past; contributors use the next day at 00:00 UTC. Moving
`enabled_since` earlier is the backlog reset and is allowed. A base branch without the file,
such as a release branch the file is backported to, has no gate yet, so its entries are not
checked against it. In CI the hook fetches the pull
request's base branch to compare with, because the shallow checkout has none; a push in a
contributor's fork has no base branch, so it fetches `apache/airflow`'s `main`. Without any
base to compare with, the hook fails rather than comparing the change with itself. A merge
after that instant still leaves the window open; the
closure is reported to Slack as an attention item, and the maintainer reopens the pull
checked against it. The hook fetches a pull request's base branch to compare with. When fork CI
merges a push with its upstream base, the hook compares with that exact base commit. For a
fork push without that merge or a local run, Breeze's `AIRFLOW_BRANCH` identifies the upstream
branch to compare with. When a comparison revision is required and unavailable, the hook fails.
Push, scheduled, and manual runs in `apache/airflow` validate the checked-out configuration and
its agreement with `.asf.yaml`. A merge after the configured instant still leaves the window
open. The closure is reported to Slack as an attention item, and the maintainer reopens the pull
request with `use project ci`.

Leaving is a pull request that removes the line. Pull requests already labelled
Expand Down
37 changes: 26 additions & 11 deletions scripts/ci/prek/check_fork_ci_gate_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@
"""
Validate ``.github/fork-ci-gate.toml`` (AIP-120 fork CI gate) and ``.asf.yaml``.

The file must parse with the same rules the gate job uses, and every ``[pilot]`` join instant
and ``enabled_since`` value that is new or changed relative to ``main`` must lie in the future.
The file must parse with the same rules the gate job uses. Before merging a change, new or
changed ``[pilot]`` join instants and later ``enabled_since`` values must be in the future.
Runs of an already merged branch validate its configuration as a snapshot.
The gate reads the file from the base branch, so an entry only takes effect when it merges,
while the instant is compared with pull request creation: an instant before the merge would
gate pull requests that already ran project CI. See "Contributor pilot" in
Expand All @@ -41,14 +42,12 @@
from types import ModuleType

import yaml
from common_prek_utils import AIRFLOW_ROOT_PATH
from common_prek_utils import AIRFLOW_BREEZE_SOURCES_PATH, AIRFLOW_ROOT_PATH, read_airflow_branch

CONFIG_PATH = ".github/fork-ci-gate.toml"
ASF_YAML_PATH = ".asf.yaml"
UPSTREAM_URL = "https://github.com/apache/airflow.git"
GATE_MODULE_PATH = (
AIRFLOW_ROOT_PATH / "dev" / "breeze" / "src" / "airflow_breeze" / "utils" / "fork_ci_gate.py"
)
GATE_MODULE_PATH = AIRFLOW_BREEZE_SOURCES_PATH / "src" / "airflow_breeze" / "utils" / "fork_ci_gate.py"


def load_gate_module() -> ModuleType:
Expand Down Expand Up @@ -183,16 +182,32 @@ def resolve_base_ref() -> str | None:
and _git("fetch", "--quiet", "--depth=1", "origin", f"refs/heads/{base_branch}") is not None
):
return "FETCH_HEAD"
if not base_branch:
event_name = os.environ.get("GITHUB_EVENT_NAME")
if os.environ.get("GITHUB_REPOSITORY") == "apache/airflow" and event_name in (
"push",
"schedule",
"workflow_dispatch",
):
# Entries on a merged branch were checked before their merge, and an entry merged
# after its instant passed must not fail every later run of the branch.
return "HEAD"
if event_name == "push":
# merge-with-base sets the tested base as the first parent and the pushed SHA as the second.
pushed_sha = os.environ.get("GITHUB_SHA")
if pushed_sha and _git("rev-parse", "--verify", "--quiet", "HEAD^2") == f"{pushed_sha}\n":
return "HEAD^1"

branch = base_branch or read_airflow_branch()
head = (_git("rev-parse", "HEAD") or "").strip()
for candidate in ("upstream/main", "origin/main", "main"):
for candidate in (f"upstream/{branch}", f"origin/{branch}", branch):
if _git("rev-parse", "--verify", "--quiet", candidate) is not None:
merge_base = (_git("merge-base", "HEAD", candidate) or "").strip()
# On a push to a fork's own main, that main is HEAD itself and compares with nothing.
if merge_base and merge_base != head:
return merge_base
# A push in a contributor's fork has no base branch and a shallow checkout without main, and
# its origin is the fork: compare with apache/airflow's main, the branch the change targets.
if _git("fetch", "--quiet", "--depth=1", UPSTREAM_URL, "refs/heads/main") is not None:
# A shallow checkout can lack the upstream branch, and origin in a fork is the fork itself.
if _git("fetch", "--quiet", "--depth=1", UPSTREAM_URL, f"refs/heads/{branch}") is not None:
return "FETCH_HEAD"
return None

Expand All @@ -203,7 +218,7 @@ def main() -> int:
if base_ref is None:
# Comparing with the change itself would accept any new past instant, so fail instead.
print(
f"{CONFIG_PATH}: no base revision to compare with; fetch apache/airflow's main and retry.",
f"{CONFIG_PATH}: no base revision to compare with. Fetch the comparison revision and retry.",
file=sys.stderr,
)
return 1
Expand Down
12 changes: 12 additions & 0 deletions scripts/ci/prek/common_prek_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,18 @@ def read_default_python_major_minor_version_for_images() -> str:
return value


BRANCH_DEFAULTS_PATH = AIRFLOW_BREEZE_SOURCES_PATH / "src" / "airflow_breeze" / "branch_defaults.py"


def read_airflow_branch() -> str:
"""Parse AIRFLOW_BRANCH, the upstream branch of this checkout, from branch_defaults.py."""
defaults = BRANCH_DEFAULTS_PATH.read_text(encoding="utf-8")
match = re.search(r'^AIRFLOW_BRANCH = "([^"]+)"$', defaults, re.MULTILINE)
if match is None:
raise RuntimeError(f"No AIRFLOW_BRANCH in {BRANCH_DEFAULTS_PATH}")
return match[1]


def pre_process_mypy_files(files: list[str]) -> list[str]:
"""Pre-process files passed to mypy.

Expand Down
15 changes: 4 additions & 11 deletions scripts/ci/prek/upgrade_important_versions.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
AIRFLOW_CORE_ROOT_PATH,
AIRFLOW_ROOT_PATH,
console,
read_airflow_branch,
read_allowed_python_major_minor_versions,
read_default_python_major_minor_version_for_images,
retrieve_gh_token,
Expand Down Expand Up @@ -523,7 +524,6 @@ def fetch_python_image_digests(latest_python_versions: dict[str, str]) -> dict[s
/ "files"
/ "hardened_os_deps_image_digests.json"
)
BRANCH_DEFAULTS_PATH = AIRFLOW_ROOT_PATH / "dev" / "breeze" / "src" / "airflow_breeze" / "branch_defaults.py"


def fetch_os_deps_image_digests(
Expand Down Expand Up @@ -561,15 +561,6 @@ def fetch_os_deps_image_digests(
return pins


def get_airflow_branch() -> str:
"""Return the branch this checkout belongs to - every branch sets AIRFLOW_BRANCH in its breeze."""
match = re.search(r'^AIRFLOW_BRANCH = "([^"]+)"$', BRANCH_DEFAULTS_PATH.read_text(), re.MULTILINE)
if not match:
console.print(f"[bright_red]No AIRFLOW_BRANCH in {BRANCH_DEFAULTS_PATH}")
sys.exit(1)
return match.group(1)


def compute_os_deps_image_pins(
python_image_digests: dict[str, str], current_pins: dict[str, str], branch: str
) -> dict[str, str]:
Expand Down Expand Up @@ -1465,7 +1456,9 @@ def main() -> None:
changed = write_pins_file(PYTHON_IMAGE_DIGESTS_PATH, python_image_digests) or changed
if OS_DEPS_IMAGE_DIGESTS_PATH.exists():
os_deps_image_digests = compute_os_deps_image_pins(
python_image_digests, json.loads(OS_DEPS_IMAGE_DIGESTS_PATH.read_text()), get_airflow_branch()
python_image_digests,
json.loads(OS_DEPS_IMAGE_DIGESTS_PATH.read_text()),
read_airflow_branch(),
)
changed = write_pins_file(OS_DEPS_IMAGE_DIGESTS_PATH, os_deps_image_digests) or changed
if legacy_python_versions:
Expand Down
75 changes: 72 additions & 3 deletions scripts/tests/ci/prek/test_check_fork_ci_gate_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,13 @@
from unittest import mock

import pytest
from check_fork_ci_gate_config import find_asf_yaml_sync_violations, find_violations, main, resolve_base_ref
from check_fork_ci_gate_config import (
UPSTREAM_URL,
find_asf_yaml_sync_violations,
find_violations,
main,
resolve_base_ref,
)

NOW = datetime(2026, 10, 15, 12, 0, tzinfo=UTC)
BASE = 'enabled_since = 2026-01-01T00:00:00Z\n[pilot]\n"old-user" = 2026-09-01T00:00:00Z\n'
Expand Down Expand Up @@ -90,13 +96,14 @@ def test_rejects(base, new, message):
assert message in violations[0]


@mock.patch("check_fork_ci_gate_config.read_airflow_branch", autospec=True, return_value="main")
@mock.patch("check_fork_ci_gate_config._git", autospec=True)
@pytest.mark.parametrize(
("base_ref_env", "git_results", "expected"),
[
pytest.param("v3-1-test", {"fetch": ""}, "FETCH_HEAD", id="ci-fetches-base-branch"),
pytest.param(None, {"rev-parse": "x", "merge-base": "abc\n"}, "abc", id="local-merge-base"),
pytest.param(None, {"fetch": ""}, "FETCH_HEAD", id="fork-push-fetches-upstream-main"),
pytest.param(None, {"fetch": ""}, "FETCH_HEAD", id="fork-push-fetches-upstream-branch"),
pytest.param(
None,
{"rev-parse": "x\n", "merge-base": "x\n", "fetch": ""},
Expand All @@ -106,7 +113,10 @@ def test_rejects(base, new, message):
pytest.param(None, {}, None, id="no-base-available"),
],
)
def test_resolve_base_ref(mock_git, monkeypatch, base_ref_env, git_results, expected):
def test_resolve_base_ref(mock_git, mock_branch, monkeypatch, base_ref_env, git_results, expected):
monkeypatch.setenv("GITHUB_REPOSITORY", "apache/airflow" if base_ref_env else "contributor/airflow")
monkeypatch.setenv("GITHUB_EVENT_NAME", "pull_request" if base_ref_env else "push")
monkeypatch.delenv("GITHUB_SHA", raising=False)
if base_ref_env:
monkeypatch.setenv("GITHUB_BASE_REF", base_ref_env)
else:
Expand All @@ -118,6 +128,65 @@ def test_resolve_base_ref(mock_git, monkeypatch, base_ref_env, git_results, expe
mock_git.assert_called_once_with("fetch", "--quiet", "--depth=1", "origin", "refs/heads/v3-1-test")


@mock.patch("check_fork_ci_gate_config._git", autospec=True)
@pytest.mark.parametrize("event", ["schedule", "workflow_dispatch", "push"])
def test_resolve_official_snapshot_base_ref(mock_git, monkeypatch, event):
monkeypatch.delenv("GITHUB_BASE_REF", raising=False)
monkeypatch.setenv("GITHUB_REPOSITORY", "apache/airflow")
monkeypatch.setenv("GITHUB_EVENT_NAME", event)

assert resolve_base_ref() == "HEAD"
mock_git.assert_not_called()


@mock.patch("check_fork_ci_gate_config.read_airflow_branch", autospec=True, return_value="v3-4-test")
@mock.patch("check_fork_ci_gate_config._git", autospec=True)
@pytest.mark.parametrize(
("second_parent", "expected"),
[
pytest.param("a" * 40 + "\n", "HEAD^1", id="synthetic-merge"),
pytest.param(None, "FETCH_HEAD", id="shallow-branch-checkout"),
pytest.param("b" * 40 + "\n", "FETCH_HEAD", id="contributor-created-merge"),
],
)
def test_resolve_release_fork_push_base_ref(mock_git, mock_branch, monkeypatch, second_parent, expected):
monkeypatch.delenv("GITHUB_BASE_REF", raising=False)
monkeypatch.setenv("GITHUB_REPOSITORY", "contributor/airflow")
monkeypatch.setenv("GITHUB_EVENT_NAME", "push")
monkeypatch.setenv("GITHUB_SHA", "a" * 40)
read_second_parent = ("rev-parse", "--verify", "--quiet", "HEAD^2")
fetch_branch = ("fetch", "--quiet", "--depth=1", UPSTREAM_URL, "refs/heads/v3-4-test")
git_results = {read_second_parent: second_parent, fetch_branch: ""}
mock_git.side_effect = lambda *args: git_results.get(args)

assert resolve_base_ref() == expected
if expected == "HEAD^1":
mock_git.assert_called_once_with(*read_second_parent)
else:
mock_git.assert_called_with(*fetch_branch)


@mock.patch("check_fork_ci_gate_config.read_airflow_branch", autospec=True, return_value="v3-4-test")
@mock.patch("check_fork_ci_gate_config._git", autospec=True)
@pytest.mark.parametrize("base_branch", [None, "v3-4-test"], ids=["local", "pr-fetch-failed"])
def test_resolve_local_release_merge_base(mock_git, mock_branch, monkeypatch, base_branch):
monkeypatch.delenv("GITHUB_EVENT_NAME", raising=False)
if base_branch:
monkeypatch.setenv("GITHUB_BASE_REF", base_branch)
else:
monkeypatch.delenv("GITHUB_BASE_REF", raising=False)
git_results = {
("rev-parse", "HEAD"): "head\n",
("rev-parse", "--verify", "--quiet", "upstream/v3-4-test"): "upstream-tip\n",
("merge-base", "HEAD", "upstream/v3-4-test"): "base\n",
}
mock_git.side_effect = lambda *args: git_results.get(args)

assert resolve_base_ref() == "base"
if base_branch:
mock_branch.assert_not_called()


@mock.patch("check_fork_ci_gate_config.resolve_base_ref", autospec=True, return_value=None)
def test_main_fails_without_a_base(mock_resolve, capsys):
assert main() == 1
Expand Down
28 changes: 28 additions & 0 deletions scripts/tests/ci/prek/test_common_prek_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
is_duplicated_namespace_init,
is_hidden_within_root,
pre_process_mypy_files,
read_airflow_branch,
read_airflow_version,
read_allowed_kubernetes_versions,
read_allowed_python_major_minor_versions,
Expand Down Expand Up @@ -428,6 +429,33 @@ def test_reads_annotated_assignment(self):
assert "8.4" in read_current_mysql_versions()


class TestReadAirflowBranch:
@pytest.mark.parametrize(
("content", "expected"),
[
pytest.param(' AIRFLOW_BRANCH = "v2-2-test"\nAIRFLOW_BRANCH = "main"\n', "main", id="main"),
pytest.param('AIRFLOW_BRANCH = "v3-4-test"\n', "v3-4-test", id="release-branch"),
],
)
def test_reads_branch_defaults(self, monkeypatch, tmp_path, content, expected):
branch_defaults = tmp_path / "branch_defaults.py"
branch_defaults.write_text(content)
monkeypatch.setattr(common_prek_utils, "BRANCH_DEFAULTS_PATH", branch_defaults)

assert read_airflow_branch() == expected

def test_requires_the_branch_default(self, monkeypatch, tmp_path):
branch_defaults = tmp_path / "branch_defaults.py"
branch_defaults.write_text('DEFAULT_AIRFLOW_CONSTRAINTS_BRANCH = "constraints-main"\n')
monkeypatch.setattr(common_prek_utils, "BRANCH_DEFAULTS_PATH", branch_defaults)

with pytest.raises(RuntimeError, match="No AIRFLOW_BRANCH"):
read_airflow_branch()

def test_this_checkout_has_a_branch(self):
assert read_airflow_branch()


class TestConsoleDiff:
def test_dump_added_lines(self):
diff = ConsoleDiff()
Expand Down
23 changes: 0 additions & 23 deletions scripts/tests/ci/prek/test_upgrade_important_versions.py
Original file line number Diff line number Diff line change
Expand Up @@ -572,29 +572,6 @@ def test_only_main_pins_os_deps_images(monkeypatch, branch, expected):
assert fetch.called is (branch == "main")


@pytest.mark.parametrize(
("content", "expected"),
[
pytest.param(' AIRFLOW_BRANCH = "v2-2-test"\nAIRFLOW_BRANCH = "main"\n', "main", id="main"),
pytest.param('AIRFLOW_BRANCH = "v3-4-test"\n', "v3-4-test", id="release-branch"),
],
)
def test_airflow_branch_is_read_from_branch_defaults(monkeypatch, tmp_path, content, expected):
from ci.prek import upgrade_important_versions as uiv

branch_defaults = tmp_path / "branch_defaults.py"
branch_defaults.write_text(content)
monkeypatch.setattr(uiv, "BRANCH_DEFAULTS_PATH", branch_defaults)

assert uiv.get_airflow_branch() == expected


def test_airflow_branch_of_this_checkout_is_found():
from ci.prek import upgrade_important_versions as uiv

assert uiv.get_airflow_branch()


def test_ghcr_image_digest_is_none_for_a_missing_tag(monkeypatch):
from ci.prek import upgrade_important_versions as uiv

Expand Down