Files
clean-architecture-backend-…/scripts/ci/done-build-inputs.py
DongHyeonka e9ee917fcb ci(main): main push도 PR용 빌드 캐시를 채우고 문서만 바꾼 push는 건너뛴다
문제: 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)
2026-11-20 01:57:35 +09:00

104 lines
4.8 KiB
Python

"""Says whether main.yml's `done` job would put anything new in the build cache on this run.
Called by the `done` job of .gitea/workflows/main.yml, after checkout and the marker restore, before
Java and Gradle are set up. That job is not a gate: it runs the pull-request stage on main so that a
pull request finds main's results in the build cache (docs/work/reference/gates.md). The marker is a
small cache entry that every job on main that gets through saves at its end, after the Gradle cache
when it ran Gradle, holding the key of the build inputs it had. The restore brings back the newest.
The build inputs are every tracked file but the documentation: paths under docs/ or .claude/, and
Markdown files outside a source set (`<project>/src/<set>/`, where a Markdown file is a resource or
test fixture). Their key is a digest of their paths, modes and blob ids at HEAD. A push skips, with
one `건너뜀:` line, exactly when the newest marker holds the same key; anything else runs, and so
does a run that is not a push. After a run that changed the build inputs and did not get through,
the next push runs even if it changed documentation only. A push that reverts a change whose run got
through runs too: the newest marker holds the inputs from before the revert. Running is the safe side.
What the marker cannot tell: whether that job's Gradle entry is still in the cache (setup-gradle only
warns when it cannot save, and the cache limit can push the large entry out first). Then pull
requests miss until the next code push or the nightly, which always runs. A few pull-request tests
declare documents under docs/ as inputs (registries, runbooks, ADRs, API surface baselines;
`git grep -n docs/ -- '*.gradle'` shows where); after a push that changed only those, the next pull
request reruns those tests. The cache changes how long a run takes, never what it decides.
Writes `run=true` or `run=false` to $GITHUB_OUTPUT, prints one line, and writes this run's key to the
marker file for the cache step to save. Fails when $GITHUB_OUTPUT is not set or Git cannot list HEAD,
so the job stops with an error instead of deciding without a key.
EVENT=<github.event_name> GITHUB_OUTPUT=<file> python3 scripts/ci/done-build-inputs.py
"""
from __future__ import annotations
import hashlib
import os
import subprocess
import sys
from pathlib import Path
JOB = "done"
# The path main.yml's marker step restores and saves. Relative to the checkout, so the cache version,
# which hashes the path as written, is the same in every run; build/ is ignored, so no check sees it.
MARKER = Path("build/done-cache-marker")
def is_documentation(path: str) -> bool:
if path.startswith(("docs/", ".claude/")):
return True
if "/src/" in path:
return False
return path.endswith(".md")
def tracked_entries() -> list[tuple[str, str]]:
"""(path, `mode type id`) for every tracked file at HEAD."""
listing = subprocess.run(["git", "ls-tree", "-r", "-z", "--full-tree", "HEAD"], capture_output=True, check=True)
entries = []
for line in listing.stdout.decode("utf-8", "surrogateescape").split("\0"):
if line:
meta, path = line.split("\t", 1)
entries.append((path, meta))
return entries
def build_inputs_key() -> str:
inputs = [f"{meta}\t{path}" for path, meta in tracked_entries() if not is_documentation(path)]
digest = hashlib.sha256("\0".join(inputs).encode("utf-8", "surrogateescape")).hexdigest()
return f"{JOB}-build-inputs-{digest}"
def newest_marker() -> str:
"""The key the newest marker holds, or '' when the restore found none."""
try:
return MARKER.read_text(encoding="utf-8").strip()
except FileNotFoundError:
return ""
def decide(event: str, key: str, marker: str) -> tuple[bool, str]:
"""(run, the line to print)."""
if event != "push":
return True, f"{JOB}: {event or '이벤트 없음'} run이라 :prCheck를 돈다 (빌드 입력 {key})"
if marker == key:
return False, f"건너뜀: {JOB} — 가장 최근에 끝까지 간 {JOB} job과 빌드 입력(문서를 뺀 파일)이 같다 ({key})"
return True, f"{JOB}: 빌드 입력 {key}가 가장 최근 표식 {marker or '(없음)'}과 달라 :prCheck를 돈다"
def main() -> int:
output = os.environ.get("GITHUB_OUTPUT")
if not output:
print(f"{JOB}: GITHUB_OUTPUT가 없어 판정을 넘길 수 없다", file=sys.stderr)
return 1
key = build_inputs_key()
run, line = decide(os.environ.get("EVENT", ""), key, newest_marker())
MARKER.parent.mkdir(parents=True, exist_ok=True)
MARKER.write_text(f"{key}\n", encoding="utf-8")
with open(output, "a", encoding="utf-8") as stream:
stream.write(f"run={'true' if run else 'false'}\n")
print(line)
return 0
if __name__ == "__main__":
sys.exit(main())