ci: build only affected project graphs
Heimdall Gitea / Detect CI scope (pull_request) Successful in 5s
Heimdall Gitea / Build and tests (pull_request) Successful in 19m48s
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (pull_request) Skipped
Heimdall Gitea / Build and scan server image (pull_request) Successful in 8m34s
Heimdall Gitea / Publish versioned installer release (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Successful in 2s

Keep the locked solution restore for dependency auditing, then build only affected test projects and uncovered changed source projects. Retain full solution builds for broad changes and non-PR validation.

Refs #314
This commit is contained in:
arnaud.dartois committed 2026-11-09 16:16:41 +01:00
1 parent d4b4ae8233
commit da89cdff2d
6 files changed
+120 -13

No files matched your search

+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env python3
"""Build only the projects selected by test-plan.py after solution restore."""
import json
from pathlib import Path
import subprocess
ROOT = Path(__file__).resolve().parents[2]
PLAN = ROOT / "artifacts" / "tests" / "plan.json"
def main() -> None:
plan = json.loads(PLAN.read_text())
targets = plan.get("build_projects")
if not isinstance(targets, list) or any(not isinstance(target, str) for target in targets):
raise SystemExit("Test plan has an invalid build_projects list")
if not targets:
print("No .NET build targets selected")
return
for target in targets:
path = ROOT / target
if not path.is_file():
raise SystemExit(f"Build target does not exist: {target}")
print(f"Building affected target: {target}", flush=True)
subprocess.run(
["dotnet", "build", target, "-c", "Release", "--no-restore", "-m:2"],
cwd=ROOT,
check=True,
)
if __name__ == "__main__":
main()
+38 -7
View File
@@ -9,6 +9,8 @@ import xml.etree.ElementTree as ET
ROOT = Path(__file__).resolve().parents[2]
TESTS = sorted(path for path in (ROOT / "tests").glob("*/*.csproj") if path.stem != "Heimdall.TestCommon")
SOURCES = sorted((ROOT / "src").glob("*/*.csproj"))
ALL_PROJECTS = [*SOURCES, *(ROOT / "tests").glob("*/*.csproj")]
def references(project: Path) -> set[Path]:
@@ -19,6 +21,30 @@ def references(project: Path) -> set[Path]:
}
def referenced_projects(project: Path, graph: dict[Path, set[Path]]) -> set[Path]:
result: set[Path] = set()
pending = list(graph.get(project, set()))
while pending:
dependency = pending.pop()
if dependency in result:
continue
result.add(dependency)
pending.extend(graph.get(dependency, set()))
return result
def build_targets(affected: set[Path], suites: list[str], graph: dict[Path, set[Path]],
mode: str) -> list[str]:
if mode == "all":
return ["Heimdall.slnx"]
suite_projects = [project for project in TESTS if project.stem in suites]
covered_sources = set().union(*(referenced_projects(project, graph) for project in suite_projects)) if suite_projects else set()
targets = [*suite_projects, *(project for project in SOURCES
if project.resolve() in affected and project.resolve() not in covered_sources)]
return sorted({project.resolve().relative_to(ROOT).as_posix() for project in targets})
def changed_files() -> list[str] | None:
if os.environ.get("GITEA_EVENT_NAME") != "pull_request":
return None
@@ -31,11 +57,11 @@ def changed_files() -> list[str] | None:
def plan(changed: list[str] | None) -> dict[str, object]:
if changed is None:
return {"mode": "all", "changed": [], "suites": [p.stem for p in TESTS]}
suites = [p.stem for p in TESTS]
return {"mode": "all", "changed": [], "suites": suites,
"build_projects": build_targets(set(), suites, {}, "all")}
all_paths = {p.resolve() for p in (ROOT / "src").glob("*/*.csproj")} | {
p.resolve() for p in (ROOT / "tests").glob("*/*.csproj")
}
all_paths = {p.resolve() for p in ALL_PROJECTS}
graph = {project: references(project) for project in all_paths}
changed_projects: set[Path] = set()
broad = False
@@ -59,10 +85,12 @@ def plan(changed: list[str] | None) -> dict[str, object]:
or name in {"readme.md", "AGENTS.md", ".gitea/PULL_REQUEST_TEMPLATE.md"}
for name in changed
):
return {"mode": "affected", "changed": changed, "suites": []}
return {"mode": "affected", "changed": changed, "suites": [], "build_projects": []}
if broad or (changed and not changed_projects):
return {"mode": "all", "changed": changed, "suites": [p.stem for p in TESTS]}
suites = [p.stem for p in TESTS]
return {"mode": "all", "changed": changed, "suites": suites,
"build_projects": build_targets(set(), suites, graph, "all")}
affected = set(changed_projects)
while True:
@@ -72,7 +100,9 @@ def plan(changed: list[str] | None) -> dict[str, object]:
affected |= additions
suites = [p.stem for p in TESTS if p.resolve() in affected]
return {"mode": "affected", "changed": changed, "suites": suites}
projects = build_targets(affected, suites, graph, "affected")
return {"mode": "affected", "changed": changed, "suites": suites,
"build_projects": projects}
if __name__ == "__main__":
@@ -81,3 +111,4 @@ if __name__ == "__main__":
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(json.dumps(result, indent=2) + "\n")
print(f"Test plan: {result['mode']} — {', '.join(result['suites']) or 'no .NET suite'}")
print(f"Build targets: {', '.join(result['build_projects']) or 'none'}")
+43 -3
View File
@@ -97,6 +97,12 @@ def load_test_plan():
spec.loader.exec_module(module)
return module
def load_build_plan():
spec = importlib.util.spec_from_file_location('heimdall_build_plan', ROOT/'build-plan.py')
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def load_efcore_policy():
spec = importlib.util.spec_from_file_location('efcore_policy', ROOT/'check-efcore-usage.py')
module = importlib.util.module_from_spec(spec)
@@ -128,20 +134,54 @@ class TestPlanTests(unittest.TestCase):
self.assertIn('Heimdall.E2E.Tests', suites)
def test_agent_change_does_not_run_unrelated_web_tests(self):
suites = load_test_plan().plan(['src/Heimdall.Agent/Program.cs'])['suites']
plan = load_test_plan().plan(['src/Heimdall.Agent/Program.cs'])
suites = plan['suites']
self.assertIn('Heimdall.Agent.Tests', suites)
self.assertNotIn('Heimdall.Web.Tests', suites)
self.assertIn('tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj', plan['build_projects'])
self.assertFalse(any('Heimdall.Web' in target for target in plan['build_projects']))
def test_web_change_does_not_rebuild_agent(self):
plan = load_test_plan().plan(['src/Heimdall.Web/Components/App.razor'])
self.assertIn('Heimdall.Web.Tests', plan['suites'])
self.assertFalse(any('Heimdall.Agent' in target for target in plan['build_projects']))
self.assertFalse(any('Heimdall.slnx' == target for target in plan['build_projects']))
def test_solution_change_runs_all_and_docs_change_runs_none(self):
planner = load_test_plan()
self.assertEqual(len(planner.plan(['global.json'])['suites']), len(planner.TESTS))
self.assertEqual(planner.plan(['docs/README.md'])['suites'], [])
solution = planner.plan(['global.json'])
self.assertEqual(len(solution['suites']), len(planner.TESTS))
self.assertEqual(solution['build_projects'], ['Heimdall.slnx'])
docs = planner.plan(['docs/README.md'])
self.assertEqual(docs['suites'], [])
self.assertEqual(docs['build_projects'], [])
def test_removed_backlog_file_does_not_skip_validation_as_docs_only(self):
planner = load_test_plan()
result = planner.plan(['todo.md'])
self.assertEqual(result['mode'], 'all')
self.assertEqual(len(result['suites']), len(planner.TESTS))
self.assertEqual(result['build_projects'], ['Heimdall.slnx'])
class BuildPlanTests(unittest.TestCase):
def test_builds_only_existing_targets_from_the_plan(self):
builder = load_build_plan()
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
target = 'tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj'
project = root/target
project.parent.mkdir(parents=True)
project.write_text('<Project />')
plan_path = root/'artifacts/tests/plan.json'
plan_path.parent.mkdir(parents=True)
plan_path.write_text(json.dumps({'build_projects':[target]}))
builder.ROOT = root
builder.PLAN = plan_path
with patch('subprocess.run') as run, contextlib.redirect_stdout(io.StringIO()):
builder.main()
run.assert_called_once_with(
['dotnet','build',target,'-c','Release','--no-restore','-m:2'],
cwd=root, check=True)
class GpuAgentImageTests(unittest.TestCase):
def test_cpu_default_stays_independent_of_nvidia_runtime(self):