Skip to content

Commit da0aca8

Browse files
committed
ENH: Reuse the build tree until the build inputs change
BuildManager records the ITK commit, the package version, and a fingerprint of the build inputs in the build report, and runs every step again when any of them changes. Wheels from earlier runs move out of dist/ before the wheel step, so they are not repaired, tested, or reported again. Co-Authored-By: Cavan Riley <cavan-riley@uiowa.edu> Co-Authored-By: Dženan Zukić <dzenan.zukic@kitware.com>
1 parent 8985363 commit da0aca8

11 files changed

Lines changed: 643 additions & 25 deletions

‎docs/Build_ITK_Python_packages.rst‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,14 @@ seven sequential steps:
3434

3535
Step state is persisted to ``<build-dir-root>/dist/build_log_<platform-env>.json`` so that a
3636
build interrupted part-way through can be resumed by re-running the same command.
37+
The log also records the build's inputs: the ITK commit, the package version,
38+
a fingerprint of the build scripts, CMake settings, and ``pixi.lock``, and for a
39+
remote module its git commit and uncommitted changes. When any of them differs
40+
from the recorded run, every step runs again.
41+
42+
Wheels already in ``dist/`` when the wheel step starts are moved to
43+
``dist/earlier-wheels/<YYYYmmdd_HHMMSS>/``, so ``dist/`` holds only this run's
44+
wheels.
3745

3846

3947
Setup

‎scripts/build_inputs.py‎

Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
"""What a build's outputs depend on, as recorded in the step report.
2+
3+
A run whose inputs differ from the recorded ones runs every step again.
4+
"""
5+
6+
from __future__ import annotations
7+
8+
import hashlib
9+
import os
10+
import subprocess
11+
from pathlib import Path
12+
from typing import TYPE_CHECKING
13+
14+
if TYPE_CHECKING:
15+
from collections.abc import Mapping
16+
17+
#: ITKPythonPackage files, relative to its root, that shape every build.
18+
FINGERPRINT_SOURCES: tuple[str, ...] = (
19+
"pixi.lock",
20+
"BuildWheelsSupport",
21+
"SuperbuildSupport",
22+
"cmake",
23+
"scripts",
24+
)
25+
26+
27+
def fingerprint_files(ipp_dir: Path) -> list[Path]:
28+
"""Return the files under *ipp_dir* that enter the fingerprint, sorted."""
29+
files: list[Path] = []
30+
for name in FINGERPRINT_SOURCES:
31+
source = Path(ipp_dir) / name
32+
if source.is_file():
33+
files.append(source)
34+
elif source.is_dir():
35+
files.extend(
36+
p
37+
for p in source.rglob("*")
38+
if p.is_file() and "__pycache__" not in p.parts and p.suffix != ".pyc"
39+
)
40+
return sorted(files)
41+
42+
43+
def build_fingerprint(ipp_dir: Path, settings: Mapping[str, str]) -> str:
44+
"""Hash the build scripts, CMake files, ``pixi.lock``, and *settings*."""
45+
digest = hashlib.sha256()
46+
for path in fingerprint_files(ipp_dir):
47+
digest.update(path.relative_to(ipp_dir).as_posix().encode() + b"\0")
48+
digest.update(path.read_bytes() + b"\0")
49+
for key, value in sorted(settings.items()):
50+
digest.update(f"{key}={value}\n".encode())
51+
return digest.hexdigest()
52+
53+
54+
def resolved_itk_commit(itk_source_dir: Path, fallback: str, git: str = "git") -> str:
55+
"""Return the commit checked out in *itk_source_dir*, else *fallback*.
56+
57+
A branch name is not enough: the same name builds a new commit each day.
58+
A tree restored from a build cache has no repository, hence the fallback.
59+
"""
60+
env = os.environ.copy()
61+
# A cache-restored tree must not report an enclosing repository's commit.
62+
env["GIT_CEILING_DIRECTORIES"] = str(Path(itk_source_dir).resolve().parent)
63+
try:
64+
result = subprocess.run(
65+
[git, "rev-parse", "--verify", "HEAD^{commit}"],
66+
cwd=itk_source_dir,
67+
env=env,
68+
capture_output=True,
69+
text=True,
70+
check=False,
71+
)
72+
except OSError:
73+
return fallback
74+
return result.stdout.strip() if result.returncode == 0 else fallback
75+
76+
77+
#: Names a module build writes into, or that hold caches, inside a module tree.
78+
MODULE_STATE_SKIP: frozenset[str] = frozenset(
79+
{
80+
"build",
81+
"dist",
82+
"ITKPythonPackage",
83+
"ITKPythonPackage-build",
84+
"MODULE_DEPENDENCIES",
85+
"__pycache__",
86+
"pyproject.toml.orig",
87+
"pyproject.toml.whl",
88+
}
89+
)
90+
91+
92+
def module_source_state(module_dir: Path, git: str = "git") -> str:
93+
"""Return a remote module's git HEAD plus a hash of its uncommitted changes.
94+
95+
Without a repository, return a hash of the module's files instead.
96+
"""
97+
env = os.environ.copy()
98+
env["GIT_CEILING_DIRECTORIES"] = str(Path(module_dir).resolve().parent)
99+
try:
100+
head = subprocess.run(
101+
[git, "rev-parse", "--verify", "HEAD^{commit}"],
102+
cwd=module_dir,
103+
env=env,
104+
capture_output=True,
105+
check=False,
106+
)
107+
if head.returncode == 0:
108+
diff = subprocess.run(
109+
[git, "diff", "HEAD", "--binary"],
110+
cwd=module_dir,
111+
env=env,
112+
capture_output=True,
113+
check=True,
114+
)
115+
changes = hashlib.sha256(diff.stdout).hexdigest()
116+
return f"{head.stdout.decode().strip()}+{changes}"
117+
except (OSError, subprocess.CalledProcessError):
118+
pass
119+
digest = hashlib.sha256()
120+
for dirpath, dirnames, filenames in os.walk(module_dir):
121+
dirnames[:] = sorted(
122+
d for d in dirnames if d not in MODULE_STATE_SKIP and not d.startswith(".")
123+
)
124+
for name in sorted(filenames):
125+
if name in MODULE_STATE_SKIP:
126+
continue
127+
path = Path(dirpath) / name
128+
digest.update(path.relative_to(module_dir).as_posix().encode() + b"\0")
129+
digest.update(path.read_bytes() + b"\0")
130+
return f"content:{digest.hexdigest()}"
131+
132+
133+
def build_inputs(
134+
itk_commit: str,
135+
package_version: str,
136+
fingerprint: str,
137+
module_state: str | None = None,
138+
) -> dict[str, str]:
139+
"""Return the inputs recorded in the step report."""
140+
inputs = {
141+
"itk_commit": itk_commit,
142+
"package_version": package_version,
143+
"fingerprint": fingerprint,
144+
}
145+
if module_state is not None:
146+
inputs["module_state"] = module_state
147+
return inputs

‎scripts/build_manager.py‎

Lines changed: 42 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -101,20 +101,24 @@ def from_json(cls, name: str, value: object) -> StepRecord:
101101

102102
@dataclass
103103
class BuildReport:
104-
"""The JSON build report: step states and timestamps."""
104+
"""The JSON build report: step states, timestamps, and the build's inputs."""
105105

106106
created_at: str
107107
updated_at: str
108108
steps: dict[str, StepRecord] = field(default_factory=dict)
109+
inputs: dict[str, str] | None = None
109110
version: int = REPORT_VERSION
110111

111112
def to_json(self) -> dict[str, object]:
112-
return {
113+
data: dict[str, object] = {
113114
"version": self.version,
114115
"created_at": self.created_at,
115116
"updated_at": self.updated_at,
116117
"steps": {name: step.to_json() for name, step in self.steps.items()},
117118
}
119+
if self.inputs is not None:
120+
data["inputs"] = dict(self.inputs)
121+
return data
118122

119123
@classmethod
120124
def from_json(cls, value: object) -> BuildReport:
@@ -143,10 +147,20 @@ def from_json(cls, value: object) -> BuildReport:
143147
name: StepRecord.from_json(name, step)
144148
for name, step in _object("report.steps", data["steps"]).items()
145149
}
150+
inputs: dict[str, str] | None = None
151+
if data.get("inputs") is not None:
152+
recorded = _object("report.inputs", data["inputs"])
153+
inputs = {}
154+
for key, item in recorded.items():
155+
if not isinstance(item, str):
156+
msg = f"report.inputs.{key}: expected a string, got {item!r}"
157+
raise BuildReportError(msg)
158+
inputs[key] = item
146159
return cls(
147160
created_at=_required_text("report", data, "created_at"),
148161
updated_at=_required_text("report", data, "updated_at"),
149162
steps=steps,
163+
inputs=inputs,
150164
version=version,
151165
)
152166

@@ -156,23 +170,37 @@ class BuildManager:
156170
157171
Persists status and timing for each named step to a JSON file.
158172
Steps already marked ``"done"`` are skipped on subsequent runs,
159-
enabling resumable builds.
173+
enabling resumable builds. When *inputs* are given and differ from
174+
the ones recorded in the report, every step starts again as pending.
160175
161176
Parameters
162177
----------
163178
report_path : Path
164179
Path to the JSON report file (created if absent).
165180
step_names : list[str]
166181
Ordered names of build steps to track.
182+
inputs : Mapping[str, str], optional
183+
What the build's outputs depend on, such as the ITK commit and the
184+
package version. Recorded in the report under ``inputs``.
167185
168186
Attributes
169187
----------
170188
report : BuildReport
171189
In-memory report, written to *report_path* by ``save``.
190+
changed_inputs : list[str]
191+
Names of the inputs that differ from the recorded report, or are
192+
missing from it; empty when the recorded steps were kept.
172193
"""
173194

174-
def __init__(self, report_path: Path, step_names: list[str]):
195+
def __init__(
196+
self,
197+
report_path: Path,
198+
step_names: list[str],
199+
inputs: Mapping[str, str] | None = None,
200+
):
175201
self.report_path = Path(report_path)
202+
self.inputs = dict(inputs) if inputs is not None else None
203+
self.changed_inputs: list[str] = []
176204
self._init_structure(step_names)
177205
self._load_if_exists()
178206

@@ -243,6 +271,7 @@ def _init_structure(self, step_names: list[str]) -> None:
243271
created_at=now,
244272
updated_at=now,
245273
steps={name: StepRecord() for name in step_names},
274+
inputs=dict(self.inputs) if self.inputs is not None else None,
246275
)
247276

248277
def _load_if_exists(self) -> None:
@@ -258,6 +287,15 @@ def _load_if_exists(self) -> None:
258287
f"Fix or delete it to continue."
259288
)
260289
raise RuntimeError(msg) from e
290+
if self.inputs is not None:
291+
recorded = existing.inputs or {}
292+
self.changed_inputs = sorted(
293+
name
294+
for name in self.inputs.keys() | recorded.keys()
295+
if self.inputs.get(name) != recorded.get(name)
296+
)
297+
if self.changed_inputs:
298+
return
261299
# Merge existing with current set of steps, preserving statuses
262300
for name in self.report.steps:
263301
if name in existing.steps:

‎scripts/build_python_instance_base.py‎

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,20 @@
66
from abc import ABC, abstractmethod
77
from collections import OrderedDict
88
from collections.abc import Callable, Mapping, Sequence
9+
from datetime import datetime
910
from pathlib import Path
1011
from typing import Any
1112

1213
import build_environment
1314
import wheel_packaging
1415
from build_config import BuildConfig
1516
from build_environment import PythonEnvironment
17+
from build_inputs import (
18+
build_fingerprint,
19+
build_inputs,
20+
module_source_state,
21+
resolved_itk_commit,
22+
)
1623
from build_jobs import compute_build_jobs, compute_load_limit, physical_memory_gb
1724
from build_manager import BuildManager
1825
from cmake_argument_builder import CMakeArgumentBuilder, definitions_from_cmake_options
@@ -420,8 +427,15 @@ def run(self) -> None:
420427
self.dist_dir.mkdir(parents=True, exist_ok=True)
421428
build_report_fn: Path = self.dist_dir / f"build_log_{self.platform_env}.json"
422429
build_manager: BuildManager = BuildManager(
423-
build_report_fn, list(python_package_build_steps.keys())
430+
build_report_fn,
431+
list(python_package_build_steps.keys()),
432+
self.build_inputs(),
424433
)
434+
if build_manager.changed_inputs:
435+
print(
436+
f"Build inputs changed ({', '.join(build_manager.changed_inputs)}) "
437+
f"since {build_report_fn} was written: running every step."
438+
)
425439
build_manager.save()
426440
cache_before, cache_after = self.compiler_cache_commands
427441
for cmd in cache_before:
@@ -442,6 +456,32 @@ def build_dependency_module(self, module_source_dir: Path) -> None:
442456
dependency_build.itk_module_deps = None # Prevent recursion
443457
dependency_build.run()
444458

459+
def build_inputs(self) -> dict[str, str]:
460+
"""Return the ITK commit, package version, and fingerprint of this build."""
461+
cfg = self.config.to_environment()
462+
settings: dict[str, str] = {}
463+
for group, definitions in (
464+
("compiler", self.cmake_compiler_configurations),
465+
("itk", self.cmake_itk_source_build_configurations),
466+
("cmdline", self.cmake_cmdline_definitions),
467+
):
468+
settings.update({f"{group}:{k}": str(v) for k, v in definitions.items()})
469+
for key in ("USE_CCACHE", "MANYLINUX_VERSION", "CONTAINER_SOURCE"):
470+
settings[key] = cfg.get(key, "")
471+
git = str(self.config.git_executable)
472+
module_state = None
473+
if self.module_source_dir is not None:
474+
settings["itk_module_deps"] = str(self.itk_module_deps or "")
475+
module_state = module_source_state(Path(self.module_source_dir), git)
476+
return build_inputs(
477+
itk_commit=resolved_itk_commit(
478+
self.config.itk_source_dir, self.config.itk_git_tag, git
479+
),
480+
package_version=self.config.itk_package_version,
481+
fingerprint=build_fingerprint(self.ipp_dir, settings),
482+
module_state=module_state,
483+
)
484+
445485
def _run_build_steps(
446486
self,
447487
build_manager: BuildManager,
@@ -879,7 +919,11 @@ def build_external_module_python_wheel(self) -> None:
879919

880920
def build_itk_python_wheels(self) -> None:
881921
"""Build all ITK Python wheels listed in ``WHEEL_NAMES.txt``."""
882-
# Build wheels
922+
earlier = wheel_packaging.move_earlier_wheels(
923+
self.build_dir_root / "dist", datetime.now().strftime("%Y%m%d_%H%M%S")
924+
)
925+
if earlier:
926+
print(f"Moved wheels of an earlier run to {earlier}")
883927
for wheel_name in self.wheel_names:
884928
print("#")
885929
print(f"# Build ITK wheel {wheel_name} from {self.wheel_names}")

‎scripts/release_wheels.py‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -360,6 +360,15 @@ def plan(
360360
return steps
361361

362362

363+
def built_wheels(step: Step) -> list[Path]:
364+
"""The wheels *step* left at the top of its ``dist/``.
365+
366+
Wheels of earlier runs are moved to a subdirectory before the wheel
367+
build, so they are not listed.
368+
"""
369+
return sorted(step.dist_dir.glob(RELEASE_TARGETS[step.target].wheel_glob))
370+
371+
363372
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
364373
parser = argparse.ArgumentParser(
365374
description=__doc__.split("\n\n")[0],
@@ -430,9 +439,7 @@ def main(argv: list[str] | None = None) -> int:
430439
print(f"=== {step.target} FAILED (exit {result.returncode})", flush=True)
431440
continue
432441
print(f"=== {step.target} wheels in {step.dist_dir}:", flush=True)
433-
for wheel in sorted(
434-
step.dist_dir.glob(RELEASE_TARGETS[step.target].wheel_glob)
435-
):
442+
for wheel in built_wheels(step):
436443
print(f" {wheel.name} {wheel.stat().st_size / 1e6:.1f} MB")
437444

438445
if failed:

0 commit comments

Comments
 (0)