Skip to content
Merged
182 changes: 170 additions & 12 deletions bugbug/build_platforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,27 +7,32 @@

Searchfox's indexing jobs build Firefox for each platform. Their index lists the source files
(including headers) the build compiled, and the build's chrome map the files it packaged (JS, CSS,
...): a file is built on the platforms whose builds list it. A file no build lists (a file added
since the builds, tests, docs, Rust or Java files, ...) is built on the platforms that build files
in its closest ancestor directory, or on all platforms if there's none.
...): a file is built on the platforms whose builds list it. The Kotlin, Java and Gradle files of
the Android apps and libraries are only built on Android, the files of the desktop browser
(browser/) only on desktop, and the ones of the mobile products (mobile/) only on Android. Another
file no build lists (a file added since the builds, tests, docs, Rust files, ...) is built on the
platforms that build files in its closest ancestor directory, or on all platforms if there's none.

A patch only touching files built on some platforms can only break those (e.g. widget/cocoa only
on macOS, gfx/layers/d3d11 only on Windows).
"""

import ast
import io
import logging
import os
import re
import zipfile
from typing import Collection, Iterable, Iterator, Mapping

import requests
from bugbug import utils

logger = logging.getLogger(__name__)

# The OS families, named as test_scheduling.config_platform_family names them.
PLATFORMS = ("android", "linux", "macosx", "windows")
ALL_PLATFORMS = frozenset(PLATFORMS)
DESKTOP_PLATFORMS = frozenset({"linux", "macosx", "windows"})

# The Searchfox jobs of each platform (gecko.v2.mozilla-central.latest.firefox.<job>), for the
# architectures tests run on.
Expand All @@ -44,6 +49,50 @@
# Directories of code that some platforms' jobs don't build, although their tests run it: the Android
# job doesn't build gtests (4 files in gtest directories, against ~800 for the desktop jobs).
UNBUILT_DIRECTORIES = {"android": frozenset({"gtest"})}
# Files no build lists that only the Android builds use: the Android apps and libraries (Fenix, Focus,
# android-components, GeckoView, ...) are built by Gradle from Kotlin and Java code. The HTML parser's
# Java code is translated to the C++ code built on every platform.
ANDROID_EXTENSIONS = frozenset({".kt", ".kts", ".java", ".gradle"})
ANDROID_DIRECTORIES = ("gradle/",)
NOT_ANDROID_DIRECTORIES = ("parser/html/javasrc/",)
# The directories of the code of a product, only built on its platforms (no Android build lists a file of
# browser/, no desktop build a file of mobile/), except for the code generation inputs used by every
# product: Glean's metrics and pings sent by Gecko (e.g. browser/base/content/metrics.yaml), see
# retrieve_shared_files. If they aren't known, every YAML file is considered shared.
PRODUCT_DIRECTORIES = {"browser/": DESKTOP_PLATFORMS, "mobile/": frozenset({"android"})}
YAML_EXTENSIONS = (".yaml", ".yml")
GLEAN_INDEX_URL = "https://hg.mozilla.org/mozilla-central/raw-file/tip/toolkit/components/glean/metrics_index.py"
# The browser-chrome tests (named browser_*), their manifests and the harness files only they use,
# only run on desktop wherever they are (but in the web-platform tests, which are another suite). Their
# support files (e.g. head.js) and the helpers they import (e.g. BrowserTestUtils) can be shared with
# other suites.
BROWSER_CHROME_TEST = re.compile(
r"(^|/)tests?/(.+/)?(browser_[^/]+|browser[\w-]*\.toml)$"
)
BROWSER_CHROME_HARNESS = (
"testing/mochitest/browser-harness.xhtml",
"testing/mochitest/browser-test.js",
)
# Files which don't affect the tests' results on any platform (developer tools, type stubs for the
# linters, docs, ...): they don't count when a patch also modifies other files.
NEUTRAL_DIRECTORIES = (
".agents/",
".claude/",
"python/l10n/fluent_migrations/",
"tools/@types/",
"tools/lint/",
)
NEUTRAL_FILES = ("stylelint-rollouts.config.js",)
NEUTRAL_EXTENSIONS = (".md", ".rst")
# The build files of a directory (moz.build, jar manifests) are only read by the builds building it, unlike
# the test manifests, whose tests can run on platforms which don't build the files of their directory.
BUILD_FILE_NAMES = ("moz.build",)
BUILD_FILE_EXTENSIONS = (".mn",)
TEST_DIRECTORY_NAMES = frozenset({"test", "tests", "gtest", "gtests", "mochitest"})
# The Android Gradle builds also use files out of mobile/, which the Android build's index doesn't list
# (e.g. Android Components packages the webcompat extension of browser/): the paths they refer to from
# the source directory (see find_gradle_paths).
GRADLE_SOURCE_PATH = re.compile(r"topsrcdir\}?/([\w.@/-]+)")

ARTIFACT_URL = "https://firefox-ci-tc.services.mozilla.com/api/index/v1/task/gecko.v2.mozilla-central.latest.firefox.{job}/artifacts/public/build/{artifact}"

Expand All @@ -52,7 +101,9 @@ class _RemoteFile(io.RawIOBase):
"""A file read with HTTP range requests, to list the files of a remote zip without downloading it."""

def __init__(self, url: str) -> None:
response = requests.head(url, allow_redirects=True, timeout=60)
# A session for the range requests of the file.
self.session = utils.get_session("taskcluster")
response = self.session.head(url, allow_redirects=True, timeout=60)
response.raise_for_status()
self.url = response.url
self.size = int(response.headers["Content-Length"])
Expand All @@ -76,7 +127,7 @@ def readinto(self, buffer) -> int:
end = min(self.size, self.position + len(buffer))
if end <= self.position:
return 0
response = requests.get(
response = self.session.get(
self.url,
headers={
"Range": f"bytes={self.position}-{end - 1}",
Expand All @@ -101,7 +152,7 @@ def _job_files(job: str) -> set[str]:
if not name.endswith("/") and not name.startswith("__GENERATED__/")
}

response = requests.get(
response = utils.get_session("taskcluster").get(
ARTIFACT_URL.format(job=job, artifact="chrome-map.json"), timeout=60
)
response.raise_for_status()
Expand All @@ -119,14 +170,58 @@ def _job_files(job: str) -> set[str]:
return files


def find_gradle_paths(contents: Iterable[str]) -> list[str]:
"""The paths out of mobile/ which Gradle files (their contents) refer to from the source directory.

E.g. "${gradle.mozconfig.topsrcdir}/browser/extensions/webcompat" (Android Components' webcompat
feature): the Android builds use them, although the Android build's index doesn't list them.
"""
paths = set()
for content in contents:
for match in GRADLE_SOURCE_PATH.finditer(content):
path = match.group(1).rstrip("/.")
if path and not path.startswith("mobile/"):
paths.add(path)
return sorted(paths)


def retrieve_shared_files() -> list[str]:
"""The YAML files from which code used by every product is generated: Glean's metrics and pings sent by Gecko.

They are the gecko_* lists of the Glean index (e.g. gecko_metrics, gecko_pings) of mozilla-central.
"""
response = utils.get_session("hgmo").get(GLEAN_INDEX_URL, timeout=60)
response.raise_for_status()
files = set()
for node in ast.parse(response.text).body:
if (
isinstance(node, ast.Assign)
and len(node.targets) == 1
and isinstance(node.targets[0], ast.Name)
and node.targets[0].id.startswith("gecko_")
):
files.update(ast.literal_eval(node.value))
# The index always has some: none means it couldn't be parsed.
if not files:
raise ValueError("No gecko_* lists found in the Glean index")
return sorted(files)


def retrieve_built_files() -> dict[str, list[str]]:
"""The files built on each platform. Platforms whose files can't be retrieved are left out."""
"""The files built on each platform, and the shared files (see retrieve_shared_files).

Platforms whose files can't be retrieved are left out, and so are the shared files.
"""
built = {}
for platform, jobs in SEARCHFOX_JOBS.items():
try:
built[platform] = sorted(set().union(*(_job_files(job) for job in jobs)))
except Exception:
logger.exception("Failed to retrieve the files built on %s", platform)
try:
built["shared"] = retrieve_shared_files()
except Exception:
logger.exception("Failed to retrieve the shared files")
return built


Expand All @@ -141,6 +236,12 @@ class BuildPlatforms:
"""The platforms building files, from the files built on each platform (see retrieve_built_files)."""

def __init__(self, built: Mapping[str, Iterable[str]]) -> None:
# The shared YAML files (see retrieve_shared_files), None if they aren't known.
self.shared = frozenset(built["shared"]) if "shared" in built else None
# The paths the Android Gradle builds use (see find_gradle_paths), None if they aren't known.
gradle = built.get("gradle")
self.gradle_files = frozenset(gradle) if gradle is not None else None
self.gradle_directories = tuple(f"{path}/" for path in gradle or ())
self.files = {
platform: frozenset(files)
for platform, files in built.items()
Expand All @@ -160,7 +261,40 @@ def __init__(self, built: Mapping[str, Iterable[str]]) -> None:
self.unknown = ALL_PLATFORMS - set(self.files)

def platforms(self, path: str) -> frozenset[str]:
return self._platforms(path) | self.unknown | self._unbuilt(path)
result = self._platforms(path) | self.unknown | self._unbuilt(path)
# The rules below only apply to the files no build lists, as the builds' lists are accurate.
if not self._listed(path) and not self._shared(path):
result = self._apply_rules(path, result)
if self._used_by_gradle(path):
result |= {"android"}
return result

def _apply_rules(self, path: str, result: frozenset[str]) -> frozenset[str]:
for directory, platforms in PRODUCT_DIRECTORIES.items():
# The rules excluding Android need the files the Android builds use out of mobile/.
if path.startswith(directory) and (
"android" in platforms or self.gradle_files is not None
):
return (result & platforms) or platforms
if path in BROWSER_CHROME_HARNESS or (
BROWSER_CHROME_TEST.search(path)
and not path.startswith("testing/web-platform/")
):
return (result & DESKTOP_PLATFORMS) or DESKTOP_PLATFORMS
return result

def _used_by_gradle(self, path: str) -> bool:
return self.gradle_files is not None and (
path in self.gradle_files or path.startswith(self.gradle_directories)
)

def _listed(self, path: str) -> bool:
return any(path in files for files in self.files.values())

def _shared(self, path: str) -> bool:
return path.endswith(YAML_EXTENSIONS) and (
self.shared is None or path in self.shared
)

def _platforms(self, path: str) -> frozenset[str]:
listed = {p for p, files in self.files.items() if path in files}
Expand All @@ -173,7 +307,13 @@ def _platforms(self, path: str) -> frozenset[str]:
}
return frozenset(listed)

if os.path.splitext(path)[1] not in self.types:
if (
os.path.splitext(path)[1] in ANDROID_EXTENSIONS
or path.startswith(ANDROID_DIRECTORIES)
) and not path.startswith(NOT_ANDROID_DIRECTORIES):
return frozenset({"android"})

if os.path.splitext(path)[1] not in self.types and not is_build_file(path):
return ALL_PLATFORMS

for directory in _ancestors(path):
Expand All @@ -190,6 +330,24 @@ def _unbuilt(self, path: str) -> frozenset[str]:
)

def find_platforms_for_paths(self, paths: Collection[str]) -> frozenset[str]:
"""The platforms building any of `paths`."""
result: frozenset[str] = frozenset().union(*map(self.platforms, paths))
"""The platforms building any of `paths` (ignoring the neutral ones, unless they all are)."""
relevant = [path for path in paths if not is_neutral(path)] or paths
result: frozenset[str] = frozenset().union(*map(self.platforms, relevant))
return result or ALL_PLATFORMS


def is_neutral(path: str) -> bool:
"""Whether a file doesn't affect the tests' results on any platform (see NEUTRAL_DIRECTORIES)."""
return (
path.startswith(NEUTRAL_DIRECTORIES)
or path in NEUTRAL_FILES
or path.endswith(NEUTRAL_EXTENSIONS)
)


def is_build_file(path: str) -> bool:
"""Whether a file is a build file of its directory (see BUILD_FILE_NAMES)."""
return (
os.path.basename(path) in BUILD_FILE_NAMES
or path.endswith(BUILD_FILE_EXTENSIONS)
) and not TEST_DIRECTORY_NAMES & set(path.split("/")[:-1])
19 changes: 18 additions & 1 deletion bugbug/test_scheduling.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
import orjson
from tqdm import tqdm

from bugbug import db, repository
from bugbug import build_platforms, db, repository
from bugbug.utils import ExpQueue, LMDBDict, get_session, get_user_agent

logging.basicConfig(level=logging.INFO)
Expand Down Expand Up @@ -1888,6 +1888,23 @@ def approximate_manifests_for_paths(
return result


def find_gradle_paths(repo_dir: str, rev: str) -> list[str]:
"""The paths out of mobile/ which the Android Gradle builds use, at revision `rev`.

See build_platforms.find_gradle_paths. The files are read with Mercurial, as by
find_manifests_for_paths.
"""
gradle_files = [
path
for path in _get_files(repo_dir, rev)
if path.startswith("mobile/") and path.endswith((".gradle", ".gradle.kts"))
]
return build_platforms.find_gradle_paths(
content.decode("utf-8", "replace")
for content in _read_files(repo_dir, rev, gradle_files).values()
)


_GTEST_RE = re.compile(rb"^[ \t]*(?:TEST|TEST_F)\(", re.MULTILINE)
_GTEST_FOLDERS = ("gtest", "gtests", "googletest")
_CPPUNIT_INFRA_FILES = {
Expand Down
44 changes: 41 additions & 3 deletions http_service/bugbug_http/boot.py
Original file line number Diff line number Diff line change
Expand Up @@ -415,9 +415,45 @@ def retrieve_schedulable_tasks() -> None:
update_config_selection_tasks(revs, known_tasks)


def retrieve_build_platforms() -> None:
# The files built on each platform, see build_platforms.
def _read_build_platforms() -> dict:
"""The files built on each platform, as previously retrieved (empty if they weren't)."""
try:
with open("build_platforms.json", "rb") as f:
return orjson.loads(f.read())
except FileNotFoundError, orjson.JSONDecodeError:
return {}


def retrieve_build_platforms(
repository_ready: concurrent.futures.Future | None = None,
) -> None:
"""Retrieve the files built on each platform (see build_platforms).

The files the Android Gradle builds use are found in the repository, once `repository_ready` (if
given) is done. If they can't be, the previous ones are kept.
"""
built = build_platforms.retrieve_built_files()
previous = _read_build_platforms()
try:
if repository_ready is not None:
repository_ready.result()
with hglib.open(REPO_DIR) as hg:
tip = hg.log(revrange=b"tip")[0].node.decode("ascii")
gradle = test_scheduling.find_gradle_paths(REPO_DIR, tip)
# The Gradle files always refer to some paths: none means they couldn't be parsed.
if not gradle:
raise ValueError("No paths found in the Gradle files")
removed = sorted(set(previous.get("gradle", ())) - set(gradle))
if removed:
logger.warning("Paths not used by the Gradle builds anymore: %s", removed)
built["gradle"] = gradle
except Exception:
logger.exception("Failed to find the files used by the Gradle builds")
if "gradle" in previous:
built["gradle"] = previous["gradle"]
# Keep the previous shared files, if they can't be retrieved (see build_platforms).
if "shared" not in built and "shared" in previous:
built["shared"] = previous["shared"]
_write("build_platforms.json", json.dumps(built))
logger.info("Retrieved the files built on %s.", ", ".join(sorted(built)))

Expand Down Expand Up @@ -644,7 +680,9 @@ def extract_commit_experiences() -> None:

retrieve_schedulable_tasks_future = executor.submit(retrieve_schedulable_tasks)

retrieve_build_platforms_future = executor.submit(retrieve_build_platforms)
retrieve_build_platforms_future = executor.submit(
retrieve_build_platforms, clone_autoland_future
)

commits_db_extracted = extract_commits()
extract_commit_experiences()
Expand Down
Loading