From cb53c53eb792dc347148b8d94f695645bb6c20a3 Mon Sep 17 00:00:00 2001 From: Christian Heimes Date: Mon, 9 Nov 2026 20:29:06 +0100 Subject: [PATCH] feat(build): dispatch build-parallel continuously and cancel queued builds build-parallel now queues a package as soon as its build dependencies are ready instead of waiting for a whole round of builds to finish, which keeps workers busy when one package in a batch runs long. Build order and log output are no longer deterministic between runs. A failure now stops queueing new builds, cancels builds that are queued but not started yet, and waits for builds that are already running before exiting with an error. Cancelled builds are handled explicitly, since concurrent.futures.CancelledError does not derive from Exception. Implements the continuous scheduling part of the build-parallel scheduling proposal (python-wheel-build/fromager#1470). Co-Authored-By: Claude Code Signed-off-by: Christian Heimes --- src/fromager/commands/build.py | 106 +++++++++++++++++++----------- tests/test_commands.py | 114 ++++++++++++++++++++++++++++++++- tests/test_dependency_graph.py | 43 +++++++++++++ 3 files changed, 225 insertions(+), 38 deletions(-) diff --git a/src/fromager/commands/build.py b/src/fromager/commands/build.py index a41b10d44..e118cbfe1 100644 --- a/src/fromager/commands/build.py +++ b/src/fromager/commands/build.py @@ -677,6 +677,18 @@ def build_parallel( can be built concurrently. By default, all possible packages are built in parallel. Use --max-workers to limit the number of concurrent builds. + A package is queued as soon as its build dependencies are ready, without + waiting for unrelated builds to finish. Build order and log output are + therefore no longer deterministic between runs. + + The first failure aborts the run. The command stops queueing new builds, + cancels builds that are queued but not started yet, waits for builds that + are already running, and then exits with an error. + + .. versionchanged:: 0.104.0 + Builds are queued continuously as soon as their build dependencies + are ready instead of waiting for a whole round of builds to finish, + and a failure cancels queued builds instead of letting them run. """ wkctx.enable_parallel_builds() @@ -711,9 +723,9 @@ def build_parallel( _nodes_to_string(topo.dependency_nodes), ) - future2node: dict[BuildSequenceEntryFuture, dependency_graph.DependencyNode] = {} + pending: dict[BuildSequenceEntryFuture, dependency_graph.DependencyNode] = {} built_entries: list[BuildSequenceEntry] = [] - rounds: int = 0 + error: RuntimeError | None = None with ( progress.progress_context(total=len(graph)) as progressbar, @@ -722,53 +734,73 @@ def build_parallel( def update_progressbar_cb(future: concurrent.futures.Future) -> None: """Immediately update the progress and mark node as done""" - progressbar.update() - - while topo.is_active(): - rounds += 1 - nodes_to_build = topo.get_available() - logger.info( - "round %i: starting to build %i node(s): %s", - rounds, - len(nodes_to_build), - _nodes_to_string(nodes_to_build), + if not future.cancelled(): + progressbar.update() + + while topo.is_active() or pending: + if error is None and topo.is_active(): + # Add newly available nodes to the queue, unless a build + # for them is already in flight. + new_nodes = topo.get_available() - set(pending.values()) + for node in new_nodes: + with req_ctxvar_context(node.requirement, node.version): + if node in topo.exclusive_nodes: + logger.info("requires exclusive build") + logger.info("ready to build") + + req = Requirement(f"{node.canonicalized_name}=={node.version}") + + future = executor.submit( + _build_parallel, + wkctx=wkctx, + resolved_version=node.version, + req=req, + source_download_url=node.download_url, + force=force, + cache_wheel_server_url=cache_wheel_server_url, + ) + future.add_done_callback(update_progressbar_cb) + pending[future] = node + + if not pending: + # No builds in flight: either everything is done, or the + # run is aborting and no further builds are started. + break + + # Wait for at least one build to complete, then queue whatever + # became ready in the meantime. + done, _ = concurrent.futures.wait( + pending, return_when=concurrent.futures.FIRST_COMPLETED ) - for node in nodes_to_build: - with req_ctxvar_context(node.requirement, node.version): - if node in topo.exclusive_nodes: - logger.info("requires exclusive build") - logger.info("ready to build") - - req = Requirement(f"{node.canonicalized_name}=={node.version}") - - future = executor.submit( - _build_parallel, - wkctx=wkctx, - resolved_version=node.version, - req=req, - source_download_url=node.download_url, - force=force, - cache_wheel_server_url=cache_wheel_server_url, - ) - future.add_done_callback(update_progressbar_cb) - future2node[future] = node - - # Wait for all builds to complete - for future in concurrent.futures.as_completed(future2node): - node = future2node.pop(future) + for future in done: + node = pending.pop(future) with req_ctxvar_context(node.requirement, node.version): try: entry = future.result() + except concurrent.futures.CancelledError: + # the build was queued but never started because + # another build failed and the run is aborting + logger.info("build of %s was cancelled", node.key) except Exception as e: logger.error(f"Failed to build {node.key}: {e}") - raise RuntimeError(f"Failed to build {node.key}") from e + if error is None: + error = RuntimeError(f"Failed to build {node.key}") + error.__cause__ = e + # Stop queueing new builds and cancel everything + # that is queued but not running yet. Builds that + # are already running cannot be cancelled, so we + # keep draining them below. + for queued in pending: + queued.cancel() else: # success built_entries.append(entry) finally: # mark node as done, progress bar is updated in callback. topo.done(node) - # Re-raise with package context since context var is lost across threads + + if error is not None: + raise error metrics.summarize(wkctx, "Building in parallel") _summary(wkctx, built_entries) diff --git a/tests/test_commands.py b/tests/test_commands.py index bb1113bbd..8723c3c27 100644 --- a/tests/test_commands.py +++ b/tests/test_commands.py @@ -4,6 +4,8 @@ import pathlib import subprocess import tarfile +import threading +import time import typing from unittest.mock import Mock, patch @@ -14,7 +16,11 @@ from packaging.requirements import Requirement from packaging.version import Version -from fromager import packagesettings, server, wheels +from fromager import ( + packagesettings, + server, + wheels, +) from fromager.commands import bootstrap, build, download_sequence, step from fromager.context import WorkContext from fromager.log import requirement_ctxvar @@ -743,6 +749,112 @@ def test_build_sequence_accepts_matching_source_provider( run_build.assert_called_once() +def test_build_parallel_dispatches_continuously( + cli_runner: CliRunner, + tmp_context: WorkContext, + e2e_path: pathlib.Path, +) -> None: + """A package starts building as soon as its build dependencies are ready, + without waiting for unrelated builds to finish.""" + # In e2e/build-parallel/graph.json, jinja2 build-depends on flit-core, + # while setuptools and flit-core have no build dependencies. With + # round-based scheduling, jinja2 could never start before setuptools + # finishes. + fast_started = threading.Event() + events: list[tuple[str, str]] = [] + events_lock = threading.Lock() + + def record(event: str, name: str) -> None: + with events_lock: + events.append((event, name)) + + def fake_build( + wkctx: WorkContext, + resolved_version: Version, + req: Requirement, + source_download_url: str, + force: bool, + cache_wheel_server_url: str | None, + ) -> build.BuildSequenceEntry: + record("start", req.name) + if req.name == "setuptools": + assert fast_started.wait(timeout=30), ( + "jinja2 did not start while setuptools was building" + ) + elif req.name == "jinja2": + fast_started.set() + record("end", req.name) + return build.BuildSequenceEntry( + name=req.name, + version=resolved_version, + prebuilt=False, + download_url=source_download_url, + wheel_filename=pathlib.Path(f"{req.name}-{resolved_version}.whl"), + ) + + with ( + patch.object(build.server, "start_wheel_server"), + patch.object(build, "_build", side_effect=fake_build) as run_build, + patch.object(build.metrics, "summarize"), + patch.object(build, "_summary"), + ): + result = cli_runner.invoke( + build.build_parallel, + [str(e2e_path / "build-parallel" / "graph.json")], + obj=tmp_context, + ) + + assert result.exit_code == 0, result.output + # all 16 packages of the graph were built + assert run_build.call_count == 16 + # jinja2 became ready when flit-core finished and started while + # setuptools was still building + assert events.index(("start", "jinja2")) < events.index(("end", "setuptools")) + + +def test_build_parallel_failure_cancels_queued_builds( + cli_runner: CliRunner, + tmp_context: WorkContext, + e2e_path: pathlib.Path, +) -> None: + """A failure aborts the run: builds that are queued but not running are + cancelled and the command fails with the build error instead of an + unhandled CancelledError.""" + graph_file = e2e_path / "build-parallel" / "graph.json" + + def fake_build( + wkctx: WorkContext, + resolved_version: Version, + req: Requirement, + source_download_url: str, + force: bool, + cache_wheel_server_url: str | None, + ) -> build.BuildSequenceEntry: + # Fail slowly so the other builds stay queued and can be cancelled + # when this failure is processed. + time.sleep(1) + raise RuntimeError(f"boom {req.name}") + + with ( + patch.object(build.server, "start_wheel_server"), + patch.object(build, "_build", side_effect=fake_build) as run_build, + patch.object(build.metrics, "summarize"), + patch.object(build, "_summary"), + ): + result = cli_runner.invoke( + build.build_parallel, + ["--max-workers", "1", str(graph_file)], + obj=tmp_context, + ) + + assert isinstance(result.exception, RuntimeError), result.output + assert str(result.exception).startswith("Failed to build") + # The first build failed and the worker may pick up one more build + # before the cancellation lands, but the remaining queued builds were + # cancelled and never ran. + assert 1 <= run_build.call_count <= 2 + + def test_download_sequence_skips_test_mode_prebuilt_fallback_source( cli_runner: CliRunner, tmp_context: WorkContext, tmp_path: pathlib.Path ) -> None: diff --git a/tests/test_dependency_graph.py b/tests/test_dependency_graph.py index 71f71a829..0117ee1a1 100644 --- a/tests/test_dependency_graph.py +++ b/tests/test_dependency_graph.py @@ -260,6 +260,49 @@ def test_tracking_topology_sorter() -> None: assert topo.get_available() == {d} +def test_tracking_topology_sorter_exclusive_under_polling() -> None: + # build-parallel polls get_available() continuously while builds are + # in flight (nodes that were returned but are not done, yet). An + # exclusive node must never be offered next to another in-flight node, + # and never more than one exclusive node at a time. + a = mknode("a") + b = mknode("b") + x = mknode("x") + y = mknode("y") + + graph: typing.Mapping[DependencyNode, typing.Iterable[DependencyNode]] + graph = { + a: [], + b: [], + x: [], + y: [], + } + + topo = TrackingTopologicalSorter(graph) + topo.add(x, exclusive=True) + topo.add(y, exclusive=True) + topo.prepare() + + # plain nodes are preferred over exclusive nodes + assert topo.get_available() == {a, b} + # polling again while a and b are in flight changes nothing + assert topo.get_available() == {a, b} + + topo.done(a) + assert topo.get_available() == {b} + topo.done(b) + + # exactly one exclusive node at a time, also when polling while it is + # in flight + assert topo.get_available() == {x} + assert topo.get_available() == {x} + + topo.done(x) + assert topo.get_available() == {y} + topo.done(y) + assert not topo.is_active() + + def test_tracking_topology_sorter_cyclic_error() -> None: # cyclic graph a = mknode("a")