문제: main.yml의 done(PR 단계를 main에서 한 번 더 돌려 PR이 읽는 빌드 캐시를 채우는 job, 게이트 아님)이 nightly·수동 run에서만 돈다. 빌드 입력을 바꾼 병합 뒤에는 다음 nightly까지 PR마다 그 변경이 건드린 태스크를 다시 돈다. 11-19 build-logic 변경 뒤 PR run 347·350의 :prCheck는 9:26·12:09였다(캐시가 찬 날 1:35~2:04). nightly 353 직후 PR은 from cache 266(2.1분)이었고, main이 움직이며 207·191·190(6.0분)으로 떨어졌다. 고친 것: done을 push에서도 돌린다. 문서만 바꾼 push는 checkout 뒤 `건너뜀: done — …` 한 줄로 끝난다. 판정은 scripts/ci/done-build-inputs.py가 한다. 문서(docs/·.claude/ 아래, 소스 세트 밖 *.md)를 뺀 추적 파일의 경로· mode·blob id로 키를 만들고, 가장 최근 표식의 키와 같을 때만 건너뛴다. 표식은 main에서 성공한 done job이 끝에 남기는 작은 캐시 항목이다. actions/cache가 run마다 새 키로 setup-gradle 저장 뒤에 저장하고, 다음 job은 접두 restore로 가장 최근 것을 받는다. 그래서 가장 최근 표식과 가장 최근 Gradle 항목은 같은 job에서 나온다. 버린 것: - (가) push마다 무조건 돈다: 문서 push마다 1:34~2:10을 쓴다(11-05 뒤 main 병합 38건 중 4건, 11-18에는 push 9건 중 5건). - (다) main job 줄에 :prCheck를 붙이고 build-cache를 따로 저장: 캐시 키· 복원 설계가 커진다. - github.event.before와 비교(초안 HEAD^1 비교의 개선안): 앞 push run이 concurrency로 취소된 뒤 문서 push가 오면 건너뛰어 채우기가 nightly까지 밀린다. - 입력 키마다 표식(lookup-only): K1→K2→K1 되돌림에서 최신 Gradle 항목은 K2인데 K1 표식을 보고 건너뛴다. 위험·한계: - 코드 push마다 main run +1:34~2:10, 전역 빌드 입력을 바꾼 push는 약 10분(nightly done이 그만큼 준다). main push p50 19.6분(11-18~19). - runner 캐시(5.0G = 상한 5GB, 두 repo가 같이 씀)에 코드 push마다 Gradle 항목이 하나 더 생긴다. 밀려남이 늘 수 있다. - 표식은 그 Gradle 항목이 남았는지 모른다. 저장 실패나 밀려남이면 다음 코드 push·nightly까지 PR이 캐시를 못 받는다. 판정은 같다. - 문서를 입력으로 선언한 PR 시험(registry·runbook·ADR·API surface 기준)은 그 문서만 바꾼 push 뒤 다음 PR에서 다시 돈다. - 병합 뒤 runner 로그로 볼 것: 표식 restore 줄, post 순서(setup-gradle 저장 뒤 표식 저장), 문서 push의 건너뜀 줄. 검증: - desktop scripts/verify.sh pr --no-cache(트리7370dd73, 기준5b00b7eb): :prCheck rc=0 5분 46초, 530 executed·FROM-CACHE 0, 시험 7269개(실패 0, 건너뜀 35). :verifyStrictLaneStages --dry-run rc=0. - desktop scripts/verify.sh main --no-cache(같은 트리): rc=0. :integrationCheck :mainCheck 23분, 446 executed·from cache 0(안쪽 :verifyFeatureScaffold 생성 왕복 빌드만 자기 캐시를 씀), -p build-logic test, verify-configuration-cache.sh. 시험 1975개(실패 0, 건너뜀 19). - 노트북 scripts/verify.sh docs rc=0(scripts 시험 185개). - test_done_build_inputs 14개, 변이 15개(문서 규칙 셋, 키에서 mode·blob id 빼기, 문서를 키에 넣기, 출력 없이 rc 0, 비 push 건너뜀, 표식 없이 건너뜀, 표식 다시 쓰기 빼기, 표식 경로, 도는 조건, job 단위 if, 표식 step의 main 조건, 고정 표식 키, EVENT 없음) 모두 실패로 잡힘. - desktop --dry-run: :prCheck 783개와 :integrationCheck :mainCheck 742개가 겹치는 317개는 모두 컴파일·리소스·jar이고 시험·검사는 겹치지 않는다. Refs: design-docs ci/05-backend-ci-speed-handoff.md 4.1·6.1·7.1절 (BE-5)
260 lines
12 KiB
Python
260 lines
12 KiB
Python
"""scripts/ci/done-build-inputs.py의 시험. 키가 문서를 뺀 파일만 따르는지, 가장 최근 표식과 같은 push만 건너뛰는지,
|
|
main.yml `done`이 그 판정·표식 파일을 그대로 쓰는지 본다.
|
|
|
|
workflow는 checkout을 기본 깊이 1로 하므로, 그 깊이로 clone한 사본에서도 같은 키인지 본다.
|
|
|
|
python3 -m unittest discover -s scripts/tests
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import importlib.util
|
|
import os
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
SCRIPT = ROOT / "scripts/ci/done-build-inputs.py"
|
|
WORKFLOW = ROOT / ".gitea/workflows/main.yml"
|
|
_spec = importlib.util.spec_from_file_location("done_build_inputs", SCRIPT)
|
|
done_build_inputs = importlib.util.module_from_spec(_spec)
|
|
sys.modules["done_build_inputs"] = done_build_inputs
|
|
_spec.loader.exec_module(done_build_inputs)
|
|
|
|
# The developer's global git settings (hooks, signing) must not reach the throwaway repositories.
|
|
GIT_ENV = {
|
|
**os.environ,
|
|
"GIT_CONFIG_GLOBAL": os.devnull,
|
|
"GIT_CONFIG_NOSYSTEM": "1",
|
|
"GIT_AUTHOR_NAME": "test",
|
|
"GIT_AUTHOR_EMAIL": "test@example.invalid",
|
|
"GIT_COMMITTER_NAME": "test",
|
|
"GIT_COMMITTER_EMAIL": "test@example.invalid",
|
|
}
|
|
|
|
|
|
class Repository:
|
|
"""A throwaway repository with a source file, a script and a document on main, ignoring build/ as this one does."""
|
|
|
|
def __init__(self) -> None:
|
|
self._directory = tempfile.TemporaryDirectory()
|
|
self.root = Path(self._directory.name) / "origin"
|
|
self.git("init", "-q", "-b", "main", str(self.root), cwd=Path(self._directory.name))
|
|
self.write("src/adapter/inbound/web/src/main/java/Web.java", "class Web {}\n")
|
|
self.write("scripts/check.sh", "true\n")
|
|
self.write("docs/guide.md", "# guide\n")
|
|
self.write(".gitignore", "build/\n")
|
|
self.commit("first")
|
|
|
|
def git(self, *args: str, cwd: Path | None = None) -> str:
|
|
return subprocess.run(["git", *args], cwd=cwd or self.root, env=GIT_ENV, check=True,
|
|
capture_output=True, text=True).stdout.strip()
|
|
|
|
def write(self, path: str, text: str) -> None:
|
|
target = self.root / path
|
|
target.parent.mkdir(parents=True, exist_ok=True)
|
|
target.write_text(text, encoding="utf-8")
|
|
|
|
def commit(self, message: str) -> None:
|
|
self.git("add", "-A")
|
|
self.git("commit", "-q", "--allow-empty", "-m", message)
|
|
|
|
def shallow_clone(self) -> Path:
|
|
target = Path(self._directory.name) / "depth-1"
|
|
self.git("clone", "-q", "--depth=1", "--branch", "main", self.root.as_uri(), str(target),
|
|
cwd=Path(self._directory.name))
|
|
return target
|
|
|
|
def run_script(self, event: str = "push", marker: str | None = None, cwd: Path | None = None,
|
|
output: bool = True) -> subprocess.CompletedProcess[str]:
|
|
"""Runs the script as the job does: `marker` is what the restore brought back, None for nothing."""
|
|
where = cwd or self.root
|
|
marker_file = where / done_build_inputs.MARKER
|
|
if marker is None:
|
|
marker_file.unlink(missing_ok=True)
|
|
else:
|
|
marker_file.parent.mkdir(parents=True, exist_ok=True)
|
|
marker_file.write_text(f"{marker}\n", encoding="utf-8")
|
|
env = {key: value for key, value in GIT_ENV.items() if key not in ("GITHUB_OUTPUT", "EVENT")}
|
|
env["EVENT"] = event
|
|
if output:
|
|
self.output_file.write_text("", encoding="utf-8")
|
|
env["GITHUB_OUTPUT"] = str(self.output_file)
|
|
return subprocess.run([sys.executable, str(SCRIPT)], cwd=where, env=env, capture_output=True, text=True)
|
|
|
|
@property
|
|
def output_file(self) -> Path:
|
|
return Path(self._directory.name) / "github-output"
|
|
|
|
def decide(self, event: str = "push", marker: str | None = None) -> tuple[str, list[str]]:
|
|
"""(the GITHUB_OUTPUT text, the printed lines)."""
|
|
result = self.run_script(event, marker)
|
|
if result.returncode != 0:
|
|
raise AssertionError(result.stderr)
|
|
return self.output_file.read_text(encoding="utf-8"), result.stdout.splitlines()
|
|
|
|
def key(self, cwd: Path | None = None) -> str:
|
|
"""The key this run writes to the marker file for the save."""
|
|
result = self.run_script(cwd=cwd)
|
|
if result.returncode != 0:
|
|
raise AssertionError(result.stderr)
|
|
return ((cwd or self.root) / done_build_inputs.MARKER).read_text(encoding="utf-8").strip()
|
|
|
|
def close(self) -> None:
|
|
self._directory.cleanup()
|
|
|
|
|
|
class DocumentationPathTest(unittest.TestCase):
|
|
def test_documents_and_guidance_are_documentation(self) -> None:
|
|
for path in ("docs/guide.md", "docs/registries/env-keys.yaml", "docs/ledger/estimates.jsonl",
|
|
".claude/settings.json", ".claude/skills/desktop-gates/SKILL.md", "README.md", "AGENTS.md",
|
|
"src/adapter/inbound/web/README.md", "src/adapter/inbound/web/AGENTS.md",
|
|
"build-logic/AGENTS.md", ".github/dependency-vulnerability-policy.md"):
|
|
with self.subTest(path=path):
|
|
self.assertTrue(done_build_inputs.is_documentation(path))
|
|
|
|
def test_everything_the_build_or_a_workflow_reads_is_not(self) -> None:
|
|
for path in ("src/adapter/inbound/web/src/main/java/Web.java",
|
|
"src/bootstrap/app/src/test/resources/developer-experience/broken-readme.md",
|
|
"build-logic/src/main/resources/notes.md", "build.gradle", "settings.gradle",
|
|
"gradle/libs.versions.toml", "gradle/modules.json", "config/checkstyle/checkstyle.xml",
|
|
".gitea/workflows/main.yml", "scripts/ci/done-build-inputs.py", "Dockerfile", "compose/app.yml",
|
|
".tool-versions"):
|
|
with self.subTest(path=path):
|
|
self.assertFalse(done_build_inputs.is_documentation(path))
|
|
|
|
|
|
class KeyTest(unittest.TestCase):
|
|
def setUp(self) -> None:
|
|
self.repo = Repository()
|
|
self.addCleanup(self.repo.close)
|
|
self.first = self.repo.key()
|
|
|
|
def test_a_change_to_documents_only_keeps_the_key(self) -> None:
|
|
self.repo.write("docs/guide.md", "# guide, again\n")
|
|
self.repo.write(".claude/rules/docs.md", "# rule\n")
|
|
self.repo.write("src/adapter/inbound/web/README.md", "# web\n")
|
|
self.repo.commit("docs")
|
|
|
|
self.assertEqual(self.first, self.repo.key())
|
|
|
|
def test_a_change_to_any_build_input_changes_the_key(self) -> None:
|
|
changes = {
|
|
"source": lambda: self.repo.write("src/adapter/inbound/web/src/main/java/Web.java", "final class Web {}\n"),
|
|
"new file": lambda: self.repo.write("gradle/libs.versions.toml", "[versions]\n"),
|
|
"source-set document": lambda: self.repo.write(
|
|
"src/bootstrap/app/src/test/resources/developer-experience/broken-readme.md", "# fixture\n"),
|
|
"mode": lambda: (self.repo.root / "scripts/check.sh").chmod(0o755),
|
|
"moved into docs": lambda: self.repo.git("mv", "scripts/check.sh", "docs/check.sh"),
|
|
}
|
|
for name, change in changes.items():
|
|
with self.subTest(change=name):
|
|
before = self.repo.key()
|
|
change()
|
|
self.repo.commit(name)
|
|
self.assertNotEqual(before, self.repo.key())
|
|
|
|
def test_a_clone_one_commit_deep_has_the_same_key(self) -> None:
|
|
self.repo.write("src/adapter/inbound/web/src/main/java/Web.java", "final class Web {}\n")
|
|
self.repo.commit("code")
|
|
|
|
self.assertEqual(self.repo.key(), self.repo.key(cwd=self.repo.shallow_clone()))
|
|
|
|
def test_the_key_has_its_name_and_a_sha256_digest(self) -> None:
|
|
self.assertRegex(self.first, r"^done-build-inputs-[0-9a-f]{64}$")
|
|
|
|
|
|
class DecisionTest(unittest.TestCase):
|
|
def setUp(self) -> None:
|
|
self.repo = Repository()
|
|
self.addCleanup(self.repo.close)
|
|
self.first = self.repo.key()
|
|
|
|
def test_a_push_with_the_newest_markers_inputs_skips_with_one_skip_line(self) -> None:
|
|
self.repo.write("docs/guide.md", "# guide, again\n")
|
|
self.repo.commit("docs")
|
|
|
|
output, printed = self.repo.decide(marker=self.first)
|
|
|
|
self.assertEqual("run=false\n", output)
|
|
self.assertEqual([f"건너뜀: done — 가장 최근에 끝까지 간 done job과 빌드 입력(문서를 뺀 파일)이 같다 ({self.first})"],
|
|
printed)
|
|
|
|
def test_a_push_with_other_inputs_or_no_marker_runs(self) -> None:
|
|
self.repo.write("src/adapter/inbound/web/src/main/java/Web.java", "final class Web {}\n")
|
|
self.repo.commit("code")
|
|
for marker in (self.first, None, ""):
|
|
with self.subTest(marker=marker):
|
|
output, printed = self.repo.decide(marker=marker)
|
|
self.assertEqual("run=true\n", output)
|
|
self.assertEqual(1, len(printed))
|
|
self.assertIn(":prCheck를 돈다", printed[0])
|
|
|
|
def test_a_revert_runs_because_the_newest_marker_is_the_reverted_change(self) -> None:
|
|
self.repo.write("src/adapter/inbound/web/src/main/java/Web.java", "final class Web {}\n")
|
|
self.repo.commit("code")
|
|
reverted = self.repo.key()
|
|
self.repo.git("revert", "--no-edit", "HEAD")
|
|
|
|
self.assertEqual(self.first, self.repo.key())
|
|
self.assertEqual("run=true\n", self.repo.decide(marker=reverted)[0])
|
|
|
|
def test_a_scheduled_or_manual_run_always_runs(self) -> None:
|
|
for event in ("schedule", "workflow_dispatch", ""):
|
|
with self.subTest(event=event):
|
|
self.assertEqual("run=true\n", self.repo.decide(event=event, marker=self.first)[0])
|
|
|
|
def test_it_leaves_its_own_key_in_the_marker_file_for_the_save(self) -> None:
|
|
self.repo.write("src/adapter/inbound/web/src/main/java/Web.java", "final class Web {}\n")
|
|
self.repo.commit("code")
|
|
|
|
self.repo.decide(marker=self.first)
|
|
|
|
marker = (self.repo.root / done_build_inputs.MARKER).read_text(encoding="utf-8")
|
|
self.assertNotEqual(f"{self.first}\n", marker)
|
|
self.assertRegex(marker, r"^done-build-inputs-[0-9a-f]{64}\n$")
|
|
|
|
def test_without_an_output_file_or_a_repository_it_fails(self) -> None:
|
|
self.assertNotEqual(0, self.repo.run_script(output=False).returncode)
|
|
with tempfile.TemporaryDirectory() as elsewhere:
|
|
self.assertNotEqual(0, self.repo.run_script(cwd=Path(elsewhere)).returncode)
|
|
|
|
|
|
class WorkflowWiringTest(unittest.TestCase):
|
|
"""main.yml's `done` restores the newest marker where the script reads it, and runs unless the script says skip."""
|
|
|
|
def setUp(self) -> None:
|
|
text = WORKFLOW.read_text(encoding="utf-8")
|
|
match = re.search(r"^ done:\n(?P<body>(?: .*\n|\n)+)", text, re.MULTILINE)
|
|
self.assertIsNotNone(match, "main.yml has no `done` job")
|
|
self.job = match.group("body")
|
|
|
|
def test_the_marker_is_restored_on_main_before_the_script_at_the_path_it_reads(self) -> None:
|
|
marker = (" - if: ${{ github.ref == 'refs/heads/main' }}\n"
|
|
" uses: https://github.com/actions/cache@")
|
|
script = (" - id: inputs\n env:\n EVENT: ${{ github.event_name }}\n"
|
|
" run: python3 scripts/ci/done-build-inputs.py\n")
|
|
self.assertIn(marker, self.job)
|
|
self.assertIn(script, self.job)
|
|
self.assertLess(self.job.index(marker), self.job.index(script))
|
|
self.assertIn(f" path: {done_build_inputs.MARKER.as_posix()}\n", self.job)
|
|
# A key per run, so the save is never refused and the restore takes the newest marker by prefix.
|
|
# `/` ends the repository name, so another repository whose name starts with this one never matches.
|
|
self.assertIn(" key: done-marker-${{ github.repository }}/${{ github.run_id }}\n", self.job)
|
|
self.assertIn(" restore-keys: done-marker-${{ github.repository }}/\n", self.job)
|
|
|
|
def test_gradle_runs_unless_the_script_said_skip(self) -> None:
|
|
run = "${{ steps.inputs.outputs.run != 'false' }}"
|
|
self.assertEqual([run, run], re.findall(r"^ - if: (\$\{\{ steps\..*)$", self.job, re.MULTILINE))
|
|
self.assertIn(f" - if: {run}\n uses: ./.gitea/actions/setup-java-gradle\n", self.job)
|
|
self.assertIn(f" - if: {run}\n run: ./gradlew :prCheck\n", self.job)
|
|
self.assertNotRegex(self.job, r"(?m)^ if:", "a job-level condition would skip the whole job quietly")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|