문제: 앞 커밋 fb7f2ab80은 원격 준비의 fetch와 worktree add에 `-c gc.auto=0`을 주어, 자동 gc가 만드는 중인 worktree를 읽고 실패하는 것을 막았다. 그런데 desktop 공용 checkout은 verify와 `docs/work/operate.md` 4.1절 손 절차로만 쓰고 둘 다 gc를 끄므로, 그 checkout에서 자동 gc가 도는 길이 사실상 없어진다. 23:35에 읽기만 해서 본 그 checkout은 loose 9379개·pack 52개로 자동 기준(6700개·50개)을 넘었고, gc·maintenance 설정과 예약이 없다. 고른 방법: fetch와 worktree add를 잠금(fd 9의 flock) 뒤로 옮기고 `gc.auto=0`을 뺀다. 다른 실행은 잠금에서 기다리므로 그 gc와 겹치지 않는다. 같은 실행 안의 겹침은 fetch에 `-c gc.autoDetach=false`를 주어 막는다. 자동 gc는 기본으로 fetch가 돌아온 뒤에도 뒤에서 돌아 바로 다음 worktree add와 겹치기 때문이다. client가 끊긴 실행이 지난 로그를 바꾸지 않게 하는 쓰기(「잠금을 얻었다」)는 준비 뒤, 로그를 바꾸기 바로 앞으로 옮겼다. 잠금 이름·대기 방식과 0055의 정리 순서는 그대로다. 손 절차도 같은 잠금과 옵션으로 fetch·worktree add를 한다. 버린 안: fb7f2ab80의 `-c gc.auto=0`(위 문제). review가 2026-11-23 23:2x에 이 안으로 판정했다. 위험·한계: 겹친 실행이 fetch부터 기다리고, 트리 해시가 다른 patch도 잠금을 얻은 뒤에야 실패한다. autoDetach=false인 gc는 gc.log를 보지 않고 돌며, 끝나면 git이 gc.log를 지운다. 그래서 병합 뒤 desktop 첫 실행은 11-24 08:32를 기다리지 않고 쌓인 object를 잠금 안에서 gc한다(desktop /tmp 사본에서 4.18초, pack 52→2, loose 0). 그 뒤 최근(2주 안) 도달 못 하는 loose가 다시 기준을 넘고 pack이 50 아래이면 실행마다 증분 gc(노트북 사본 0.2초)가 돌고 `warning: There are too many unreachable loose objects`가 찍힌다. pack이 50을 넘으면 전체 repack이 그 loose를 cruft pack으로 거둔다. verify 밖에서 잠금 없이 띄운 gc는 여전히 겹칠 수 있다. 검증: `test_verify_remote.py`의 0065 사례를 셋으로 바꿨다. fetch와 worktree add가 잠금을 쥔 채 돈다. fetch가 gc.auto를 끄지 않고 gc.autoDetach=false로 돈다. 잠금 안 fetch 중 client가 끊긴 실행은 rc 4로 끝나고 지난 로그와 worktree를 남기지 않는다. 앞 둘은 고치기 전(1a48a02c5)과 앞 안(5f1aba02c)에서 실패한다. 변이 넷(준비를 잠금 앞으로, autoDetach 빼기, gc.auto=0 다시 넣기, 끊김 확인을 잠금 바로 뒤로)이 각각 한 사례에서 실패한다. git 2.43 실험: 도달 못 하는 loose 7000개 repo에서 잠금 안 fetch는 기본이면 돌아온 순간 gc.pid가 있고 gc가 0.1초 뒤에 끝나며 gc.log를 남긴다. autoDetach=false면 gc가 fetch 안에서 끝나고 gc.log가 없다. `python3 -m unittest discover -s scripts/tests` 383개 OK, `check-docs.py --only reference`·`scripts/verify.sh docs` rc=0. Refs: REV-BE-0065
660 lines
31 KiB
Python
660 lines
31 KiB
Python
"""scripts/verify.sh `--on <호스트>`의 시험. 원격으로 보내는 패치가 추적 파일의 변경과 stage한 새 파일뿐인지,
|
|
미추적 파일이 있으면 아무것도 보내지 않고 이름을 찍고 멈추는지(rc=5), 트리 줄이 HEAD 트리와 같은지 말하는지,
|
|
index를 쓴 그 초에 같은 크기로 고친 파일도 보내는지 본다.
|
|
|
|
ssh는 가짜다. 패치를 받는 호출(`cat > /tmp/<id>.patch`)이면 받은 것을 파일에 쓰고, 원격 실행(`bash -s`)이면 입력을
|
|
버리고 0으로 끝난다. Gradle·네트워크를 쓰지 않는다. 가짜 ssh와 그 기록은 시험 repo 밖에 두어 미추적 파일로 잡히지
|
|
않게 한다.
|
|
|
|
RemoteLogTest의 ssh는 받은 명령을 이 머신에서 그대로 돌린다(HOME과 잠금 파일은 임시 경로). 원격 스크립트가 시험
|
|
repo의 clone에서 worktree를 만들고 잠금 아래에서 단계를 돌린다. 단계의 Gradle은 받은 인자를 찍는 가짜 `gradlew`다.
|
|
원격 로그의 첫 줄이 보낸 트리와 기준의 전체 해시를 적는지, 다른 프로세스가 잠금을 쥔 동안 지난 로그와 클래스 목록이
|
|
그대로인지, 잠금을 기다리거나 잠금 안에서 fetch하다 client가 끊겼거나 잠금을 얻지 못한 실행이 그것을 바꾸지 않는지,
|
|
단계와 합계가 배타 잠금 안에서 도는지, 단계의 rc가 그대로 나가는지, 단계가 stdin을 읽어도 합계·rc 줄과 그 rc로
|
|
끝나는지 본다. 잠금 대기는 Linux `/proc/locks`의 대기 줄(`->`)로 안다. 원격 준비(checkout으로 cd, fetch, worktree
|
|
add, 패치 얹기)가 실패해도, 실행이 통과해도 /tmp에 보낸 패치와 worktree 폴더가 남지 않는지, fetch와 worktree add가
|
|
잠금 안에서 돌고 fetch가 띄운 자동 gc를 fetch 안에서 끝내는지(gc.autoDetach=false)도 본다. fetch·worktree add·패치
|
|
얹기는 원격 쪽 git을 가짜(FAKE_GIT)로 바꿔 본다: 가짜는 fetch·worktree add마다 그 명령이 보는 gc.auto·gc.autoDetach와
|
|
잠금 상태를 적고, fetch를 붙잡거나 패치 얹기를 실패시킬 수 있고, 나머지는 진짜 git에 넘긴다.
|
|
|
|
python3 -m unittest discover -s scripts/tests
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import contextlib
|
|
import fcntl
|
|
import os
|
|
import re
|
|
import shutil
|
|
import signal
|
|
import subprocess
|
|
import tempfile
|
|
import time
|
|
import unittest
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
SCRIPT = ROOT / "scripts/verify.sh"
|
|
|
|
# The developer's global git settings (hooks, signing, excludes) must not reach the throwaway repository.
|
|
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",
|
|
}
|
|
|
|
FAKE_SSH = """#!/bin/sh
|
|
printf '%s\\n' "$*" >> "$FAKE_SSH_CALLS"
|
|
case "$2" in
|
|
"cat > "*) cat > "$FAKE_SSH_PATCH" ;;
|
|
*) cat > /dev/null ;;
|
|
esac
|
|
"""
|
|
|
|
|
|
class ThrowawayRepoTest(unittest.TestCase):
|
|
"""A repository whose first commit holds this verify.sh, a tracked document and a .gitignore for build/, and
|
|
a folder outside it for the ssh stand-in and what it keeps."""
|
|
|
|
def setUp(self) -> None:
|
|
directory = tempfile.TemporaryDirectory()
|
|
self.addCleanup(directory.cleanup)
|
|
self.repo = Path(directory.name) / "repo"
|
|
self.outside = Path(directory.name) / "outside"
|
|
self.outside.mkdir()
|
|
self.git("init", "-q", "-b", "main", str(self.repo), cwd=Path(directory.name))
|
|
(self.repo / "scripts").mkdir()
|
|
shutil.copy2(SCRIPT, self.repo / "scripts/verify.sh")
|
|
self.write("docs/guide.md", "# guide\n")
|
|
self.write(".gitignore", "build/\n")
|
|
self.git("add", "-A")
|
|
self.git("commit", "-q", "-m", "first")
|
|
self.ssh = self.outside / "ssh"
|
|
|
|
def git(self, *args: str, cwd: Path | None = None) -> str:
|
|
return subprocess.run(["git", *args], cwd=cwd or self.repo, env=GIT_ENV, check=True,
|
|
capture_output=True, text=True).stdout.strip()
|
|
|
|
def write(self, path: str, text: str) -> None:
|
|
target = self.repo / path
|
|
target.parent.mkdir(parents=True, exist_ok=True)
|
|
target.write_text(text, encoding="utf-8")
|
|
|
|
def working_tree(self) -> str:
|
|
"""작업 트리의 트리 해시. 빈 index에서 만들어 index의 stat 기록에 기대지 않는다."""
|
|
index = self.outside / "fresh-index"
|
|
index.unlink(missing_ok=True)
|
|
env = {**GIT_ENV, "GIT_INDEX_FILE": str(index)}
|
|
subprocess.run(["git", "add", "-A"], cwd=self.repo, env=env, check=True, capture_output=True)
|
|
return subprocess.run(["git", "write-tree"], cwd=self.repo, env=env, check=True, capture_output=True,
|
|
text=True).stdout.strip()
|
|
|
|
|
|
class RemoteVerifyTest(ThrowawayRepoTest):
|
|
|
|
def setUp(self) -> None:
|
|
super().setUp()
|
|
self.ssh.write_text(FAKE_SSH, encoding="utf-8")
|
|
self.ssh.chmod(0o755)
|
|
self.calls = self.outside / "calls"
|
|
self.patch = self.outside / "patch"
|
|
|
|
def verify(self, *extra: str) -> subprocess.CompletedProcess[str]:
|
|
env = {**GIT_ENV, "VERIFY_SSH": str(self.ssh), "VERIFY_BASE_REF": "HEAD",
|
|
"FAKE_SSH_CALLS": str(self.calls), "FAKE_SSH_PATCH": str(self.patch)}
|
|
return subprocess.run(["bash", "scripts/verify.sh", "pr", "--on", "fake", *extra], cwd=self.repo, env=env,
|
|
capture_output=True, text=True, timeout=60)
|
|
|
|
def sent_patch(self) -> str:
|
|
return self.patch.read_text(encoding="utf-8")
|
|
|
|
def test_an_untracked_file_stops_it_before_anything_is_sent(self) -> None:
|
|
self.write("probe-untracked.txt", "left behind\n")
|
|
|
|
result = self.verify()
|
|
|
|
self.assertEqual(5, result.returncode, result.stderr)
|
|
self.assertIn("probe-untracked.txt", result.stderr)
|
|
self.assertFalse(self.calls.exists(), "ssh must not be called")
|
|
|
|
def test_include_untracked_sends_the_untracked_file(self) -> None:
|
|
self.write("probe-untracked.txt", "meant to go\n")
|
|
|
|
result = self.verify("--include-untracked")
|
|
|
|
self.assertEqual(0, result.returncode, result.stderr)
|
|
self.assertIn("probe-untracked.txt", self.sent_patch())
|
|
|
|
def test_a_tracked_change_is_sent_and_the_tree_line_says_it_differs_from_head(self) -> None:
|
|
self.write("docs/guide.md", "# guide\n\nchanged line\n")
|
|
|
|
result = self.verify()
|
|
|
|
self.assertEqual(0, result.returncode, result.stderr)
|
|
self.assertIn("+changed line", self.sent_patch())
|
|
self.assertIn("다름", result.stderr)
|
|
|
|
def test_a_staged_new_file_is_sent(self) -> None:
|
|
self.write("docs/new.md", "# new\n")
|
|
self.git("add", "docs/new.md")
|
|
|
|
result = self.verify()
|
|
|
|
self.assertEqual(0, result.returncode, result.stderr)
|
|
self.assertIn("docs/new.md", self.sent_patch())
|
|
|
|
def test_an_ignored_file_does_not_stop_it_and_is_not_sent(self) -> None:
|
|
self.write("build/output.txt", "generated\n")
|
|
|
|
result = self.verify()
|
|
|
|
self.assertEqual(0, result.returncode, result.stderr)
|
|
self.assertNotIn("build/output.txt", self.sent_patch())
|
|
|
|
def test_a_file_listed_in_info_exclude_does_not_stop_it_and_is_not_sent(self) -> None:
|
|
self.write("notes/mine.txt", "personal\n")
|
|
(self.repo / ".git/info").mkdir(parents=True, exist_ok=True)
|
|
(self.repo / ".git/info/exclude").write_text("notes/\n", encoding="utf-8")
|
|
|
|
result = self.verify()
|
|
|
|
self.assertEqual(0, result.returncode, result.stderr)
|
|
self.assertNotIn("notes/mine.txt", self.sent_patch())
|
|
|
|
def test_an_edit_git_sees_only_by_reading_the_file_is_sent_too(self) -> None:
|
|
"""REV-BE-0012. 같은 크기로 고친 파일의 stat이 index 기록과 같으면, git은 index 파일보다 늦지 않은 항목(racy)만
|
|
내용을 읽어 수정을 본다. 보낼 트리를 만드는 index 사본이 mtime을 잃으면 그 항목이 racy가 아니게 되어 사본의
|
|
`git add`가 수정을 빼고, 원격은 HEAD 트리를 작업 트리라며 돌린다. 프론트 #77 시험을 옮겼다."""
|
|
edited = self.repo / "docs/guide.md"
|
|
# 시각을 손으로 정해 매번 같은 결과를 낸다. ctime은 고친 초에 따라 기록과 같기도 달라서 보지 않게 한다.
|
|
self.git("config", "core.trustctime", "false")
|
|
old = int(time.time()) - 3600
|
|
os.utime(edited, (old, old))
|
|
self.git("update-index", "--refresh")
|
|
edited.write_text("# GUIDE\n", encoding="utf-8")
|
|
os.utime(edited, (old, old))
|
|
# git이 index를 쓴 그 초에 파일을 같은 크기로 고친 상태다.
|
|
os.utime(self.repo / ".git/index", (old, old))
|
|
|
|
result = self.verify()
|
|
|
|
self.assertEqual(0, result.returncode, result.stderr)
|
|
self.assertIn(f"트리 {self.working_tree()[:12]}(", result.stderr)
|
|
self.assertIn("+# GUIDE", self.sent_patch())
|
|
# 진짜 index는 건드리지 않는다: 수정은 stage되지 않은 채 남는다.
|
|
self.assertEqual("docs/guide.md", self.git("diff", "--name-only"))
|
|
|
|
def test_a_clean_tree_says_it_is_the_head_tree(self) -> None:
|
|
result = self.verify()
|
|
|
|
self.assertEqual(0, result.returncode, result.stderr)
|
|
self.assertIn("HEAD 트리와 같음", result.stderr)
|
|
self.assertEqual("", self.sent_patch())
|
|
|
|
|
|
# Runs here what verify.sh sends, as ssh runs a command line through the remote shell, with a home of its own
|
|
# and the stand-ins below first on the path.
|
|
RUNNING_SSH = """#!/bin/sh
|
|
shift
|
|
HOME="$FAKE_HOME" PATH="$FAKE_BIN:$PATH" exec sh -c "$*"
|
|
"""
|
|
|
|
# The load line does not hang on the host's uptime or its locale.
|
|
FAKE_UPTIME = """#!/bin/sh
|
|
echo " 09:00:00 up 1 day, load average: 0.39, 0.40, 0.41"
|
|
"""
|
|
|
|
# Stands in for Gradle in the stage: prints what it was asked and whether the lock is held exclusively (only
|
|
# then does a shared try fail), reads its stdin to the end if the test asks, and ends with the rc the test chose.
|
|
FAKE_GRADLEW = """#!/bin/sh
|
|
echo "gradle $*"
|
|
[ -z "${FAKE_STAGE_READS_STDIN:-}" ] || cat > /dev/null
|
|
if flock -n -s "$FAKE_LOCK" true; then echo "stage: lock free"; else echo "stage: lock held"; fi
|
|
exit "${FAKE_STAGE_RC:-0}"
|
|
"""
|
|
|
|
# Stands in for junit-summary.py: says whether the lock is still held and leaves a class list of this run.
|
|
FAKE_SUMMARY = """import os, subprocess, sys
|
|
free = subprocess.run(["flock", "-n", "-s", os.environ["FAKE_LOCK"], "true"]).returncode == 0
|
|
print("summary: lock free" if free else "summary: lock held")
|
|
with open(sys.argv[sys.argv.index("--classes") + 1], "w", encoding="utf-8") as classes:
|
|
classes.write("this run\\n")
|
|
"""
|
|
|
|
# Stands in for run-compose-runtime-smoke.sh: reads its stdin to the end, as `docker compose exec -T` does, and
|
|
# ends with the rc the test chose.
|
|
FAKE_SMOKE = """#!/bin/sh
|
|
cat > /dev/null
|
|
exit "${FAKE_SMOKE_RC:-0}"
|
|
"""
|
|
|
|
# Stands in for git on the remote side and hands every call to the real git. Before a fetch or a worktree add it
|
|
# writes down the gc.auto and gc.autoDetach that call runs with (its -c options and the environment count, "-" when
|
|
# unset) and whether the lock is held exclusively. A fetch then waits until the file named in
|
|
# FAKE_GIT_FETCH_WAITS_FOR is there, if the test names one. The subcommand named in FAKE_GIT_FAILS fails instead.
|
|
FAKE_GIT = """#!/usr/bin/env python3
|
|
import os, subprocess, sys, time
|
|
REAL = {real!r}
|
|
args = sys.argv[1:]
|
|
i = 0
|
|
while i < len(args) and args[i].startswith("-"):
|
|
i += 2 if args[i] in ("-c", "-C") else 1
|
|
command = args[i:i + 2] if args[i:i + 1] == ["worktree"] else args[i:i + 1]
|
|
if command in (["fetch"], ["worktree", "add"]):
|
|
def config(key):
|
|
got = subprocess.run([REAL, *args[:i], "config", "--get", key], capture_output=True, text=True)
|
|
return key + "=" + (got.stdout.strip() or "-")
|
|
lock = os.environ["FAKE_LOCK"]
|
|
held = os.path.exists(lock) and subprocess.run(["flock", "-n", "-s", lock, "true"]).returncode != 0
|
|
with open(os.environ["FAKE_GIT_CALLS"], "a", encoding="utf-8") as calls:
|
|
calls.write("\\t".join([" ".join(command), config("gc.auto"), config("gc.autoDetach"),
|
|
"lock " + ("held" if held else "free")]) + "\\n")
|
|
go = os.environ.get("FAKE_GIT_FETCH_WAITS_FOR")
|
|
if command == ["fetch"] and go:
|
|
deadline = time.monotonic() + 60
|
|
while not os.path.exists(go) and time.monotonic() < deadline:
|
|
time.sleep(0.05)
|
|
if command[:1] == [os.environ.get("FAKE_GIT_FAILS")]:
|
|
sys.exit(1)
|
|
os.execv(REAL, [REAL, *args])
|
|
"""
|
|
|
|
LEAF = ":adapter:outbound:sample"
|
|
RUN_LIMIT = 60 # seconds a run may take once nothing holds it back
|
|
|
|
HEADER = r"verify: tree {tree} base {base} {stage} \d{{4}}-\d\d-\d\dT\d\d:\d\d:\d\d[+-]\d{{4}}"
|
|
|
|
|
|
class RemoteLogTest(ThrowawayRepoTest):
|
|
"""The remote side runs on this machine: a clone of the test repository is the remote checkout, the
|
|
lock file and the home that holds ~/<log>-logs are temporary."""
|
|
|
|
def setUp(self) -> None:
|
|
super().setUp()
|
|
self.write("scripts/junit-summary.py", FAKE_SUMMARY)
|
|
self.write("scripts/run-compose-runtime-smoke.sh", FAKE_SMOKE)
|
|
self.write("scripts/ci/verify-configuration-cache.sh", "exit 0\n") # round runs it before the smoke
|
|
self.write("gradle/modules.json", f'{{"modules": [{{"gradle_path": "{LEAF}"}}]}}\n')
|
|
self.write("gradlew", FAKE_GRADLEW)
|
|
(self.repo / "gradlew").chmod(0o755)
|
|
self.git("add", "-A")
|
|
self.git("commit", "-q", "-m", "stage stand-ins")
|
|
self.base = self.git("rev-parse", "HEAD")
|
|
self.write("docs/after-base.md", "# after base\n")
|
|
self.git("add", "-A")
|
|
self.git("commit", "-q", "-m", "after the base") # so neither the base nor its tree is the HEAD's
|
|
self.remote = self.outside / "remote"
|
|
self.git("clone", "-q", str(self.repo), str(self.remote), cwd=self.outside)
|
|
self.home = self.outside / "home"
|
|
self.logs = self.home / "t-logs"
|
|
self.lock = self.outside / "gates/heavy.lock"
|
|
self.ssh.write_text(RUNNING_SSH, encoding="utf-8")
|
|
self.ssh.chmod(0o755)
|
|
self.bin = self.outside / "bin"
|
|
self.bin.mkdir()
|
|
(self.bin / "uptime").write_text(FAKE_UPTIME, encoding="utf-8")
|
|
(self.bin / "uptime").chmod(0o755)
|
|
|
|
def env(self, **extra: str) -> dict[str, str]:
|
|
return {**GIT_ENV, "VERIFY_SSH": str(self.ssh), "VERIFY_BASE_REF": self.base, "FAKE_LOCK": str(self.lock),
|
|
"VERIFY_REMOTE_REPO": str(self.remote), "VERIFY_LOCK": str(self.lock),
|
|
"FAKE_HOME": str(self.home), "FAKE_BIN": str(self.bin),
|
|
"FAKE_GIT_CALLS": str(self.outside / "git-calls"), **extra}
|
|
|
|
def use_the_git_stand_in(self) -> Path:
|
|
"""Puts FAKE_GIT first on the remote side's path and returns the file it writes its calls to."""
|
|
(self.bin / "git").write_text(FAKE_GIT.format(real=shutil.which("git")), encoding="utf-8")
|
|
(self.bin / "git").chmod(0o755)
|
|
return self.outside / "git-calls"
|
|
|
|
def run_and_look_in_tmp(self, *stage: str, **extra: str) -> tuple[subprocess.CompletedProcess[str], list[str]]:
|
|
"""Runs a stage and names what the run left in /tmp under its id, `verify-<seconds>-<pid of verify.sh>`:
|
|
the patch it sent (`<id>.patch`) and the folder made for its worktree (`<id>.XXXXXX/`). Whatever it left
|
|
is removed when the test ends."""
|
|
started = int(time.time())
|
|
run = self.start(*stage, **extra)
|
|
out, err = run.communicate(timeout=RUN_LIMIT)
|
|
own = re.compile(rf"verify-(\d+)-{run.pid}\.")
|
|
left = sorted(path for path in Path("/tmp").glob(f"verify-*-{run.pid}.*")
|
|
if (found := own.match(path.name)) and int(found.group(1)) >= started)
|
|
for path in left:
|
|
self.addCleanup(shutil.rmtree if path.is_dir() else path.unlink, path)
|
|
names = ["<id>.XXXXXX/" if path.is_dir() else own.sub("<id>.", path.name) for path in left]
|
|
return subprocess.CompletedProcess(run.args, run.returncode, out, err), names
|
|
|
|
def worktrees(self) -> int:
|
|
return len(self.git("worktree", "list", cwd=self.remote).splitlines())
|
|
|
|
def start(self, *stage: str, stdout: object = subprocess.PIPE, stderr: object = subprocess.PIPE,
|
|
restore_signals: bool = True, **extra: str) -> subprocess.Popen[str]:
|
|
"""Starts a run in a process group of its own. When the test ends, whatever is left of it (the "remote"
|
|
side too) is killed."""
|
|
run = subprocess.Popen(["bash", "scripts/verify.sh", *(stage or ("pr",)), "--on", "fake", "--log", "t"],
|
|
cwd=self.repo, env=self.env(**extra), stdout=stdout, stderr=stderr, text=True,
|
|
restore_signals=restore_signals, start_new_session=True)
|
|
|
|
def end_the_run() -> None:
|
|
try:
|
|
run.wait(RUN_LIMIT)
|
|
finally:
|
|
with contextlib.suppress(ProcessLookupError):
|
|
os.killpg(run.pid, signal.SIGKILL)
|
|
run.wait()
|
|
for pipe in (run.stdout, run.stderr):
|
|
if pipe:
|
|
pipe.close()
|
|
|
|
self.addCleanup(end_the_run)
|
|
return run
|
|
|
|
def run_stage(self, *stage: str, **extra: str) -> subprocess.CompletedProcess[str]:
|
|
run = self.start(*stage, **extra)
|
|
out, err = run.communicate(timeout=RUN_LIMIT)
|
|
return subprocess.CompletedProcess(run.args, run.returncode, out, err)
|
|
|
|
def log(self, stage: str = "pr") -> str:
|
|
return (self.logs / f"{stage}.log").read_text(encoding="utf-8")
|
|
|
|
def keep_a_last_run(self) -> tuple[tuple[str, str], ...]:
|
|
self.logs.mkdir(parents=True)
|
|
(self.logs / "pr.log").write_text(f"verify: tree {'a' * 40} base {'b' * 40} pr\nlast run\n", encoding="utf-8")
|
|
(self.logs / "pr-classes.tsv").write_text(".\ttest\tdev.x.LastTest\t1\t0\t0\t0\t0.100\n", encoding="utf-8")
|
|
return self.log_folder()
|
|
|
|
def log_folder(self) -> tuple[tuple[str, str], ...]:
|
|
return tuple((path.name, path.read_text(encoding="utf-8")) for path in sorted(self.logs.iterdir()))
|
|
|
|
def lock_waited_on(self) -> bool:
|
|
"""Whether a process waits for the flock on the lock file: Linux lists each waiter with "->"."""
|
|
status = self.lock.stat()
|
|
key = f"{os.major(status.st_dev):02x}:{os.minor(status.st_dev):02x}:{status.st_ino}"
|
|
return any("->" in fields and fields[-3] == key
|
|
for fields in map(str.split, Path("/proc/locks").read_text(encoding="utf-8").splitlines()))
|
|
|
|
def wait_until_it_waits(self, run: subprocess.Popen[str]) -> None:
|
|
deadline = time.monotonic() + 30
|
|
while not self.lock_waited_on():
|
|
self.assertLess(time.monotonic(), deadline, "the run never waited for the lock")
|
|
self.assertIsNone(run.poll(), "the run ended without waiting for the lock")
|
|
time.sleep(0.05)
|
|
|
|
def hold_the_lock(self):
|
|
self.lock.parent.mkdir()
|
|
held = self.lock.open("w")
|
|
fcntl.flock(held, fcntl.LOCK_EX)
|
|
return held
|
|
|
|
def test_the_log_starts_with_the_full_hashes_of_the_tree_it_sent_and_its_base_then_the_load(self) -> None:
|
|
# given: a commit after the base and a change not committed, so the tree sent is neither's tree
|
|
self.write("docs/guide.md", "# guide\n\nchanged line\n")
|
|
|
|
# when
|
|
result = self.run_stage()
|
|
|
|
# then
|
|
self.assertEqual(0, result.returncode, result.stderr)
|
|
header = HEADER.format(tree=self.working_tree(), base=self.base, stage="pr")
|
|
self.assertRegex(self.log(), rf"\A{header}\n"
|
|
r"verify: 09:00:00 up 1 day, load average: 0\.39, 0\.40, 0\.41\n")
|
|
|
|
def test_the_first_line_of_a_leaf_run_names_the_leaf_after_the_stage(self) -> None:
|
|
# when
|
|
result = self.run_stage("leaf", LEAF)
|
|
|
|
# then
|
|
self.assertEqual(0, result.returncode, result.stderr)
|
|
header = HEADER.format(tree=self.working_tree(), base=self.base, stage=f"leaf {LEAF}")
|
|
self.assertRegex(self.log("leaf"), rf"\A{header}\n")
|
|
|
|
def test_of_two_runs_with_two_trees_the_log_names_the_tree_of_the_last_one(self) -> None:
|
|
# given: a run of the HEAD tree, then a change
|
|
first = self.working_tree()
|
|
self.assertEqual(0, self.run_stage().returncode)
|
|
self.write("docs/guide.md", "# guide\n\nchanged line\n")
|
|
|
|
# when
|
|
result = self.run_stage()
|
|
|
|
# then: the log alone tells which tree the run was
|
|
self.assertEqual(0, result.returncode, result.stderr)
|
|
named = re.match(r"verify: tree (\S+) ", self.log())
|
|
self.assertEqual((named and named.group(1), first in self.log()), (self.working_tree(), False))
|
|
|
|
def test_while_another_run_holds_the_lock_the_last_log_and_class_list_stay_as_they_were(self) -> None:
|
|
# given: the last run's log and class list, and the lock held by this process
|
|
last = self.keep_a_last_run()
|
|
held = self.hold_the_lock()
|
|
run = self.start(stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
self.addCleanup(held.close) # runs first: the lock goes before the wait
|
|
self.wait_until_it_waits(run)
|
|
|
|
# when: the run waits for the lock a while
|
|
seen = set()
|
|
for _ in range(20):
|
|
seen.add(self.log_folder())
|
|
time.sleep(0.05)
|
|
|
|
# then
|
|
self.assertEqual(seen, {last})
|
|
|
|
def test_a_run_that_waits_for_the_lock_says_so_on_stderr(self) -> None:
|
|
# given
|
|
held = self.hold_the_lock()
|
|
told = self.outside / "stderr"
|
|
with told.open("w") as stderr:
|
|
run = self.start(stdout=subprocess.DEVNULL, stderr=stderr)
|
|
self.addCleanup(held.close)
|
|
|
|
# when
|
|
self.wait_until_it_waits(run)
|
|
|
|
# then
|
|
self.assertIn(f"verify: 다른 실행이 잠금 {self.lock}을 쥐고 있어 기다린다. "
|
|
"지난 로그는 잠금을 얻을 때까지 그대로다.\n", told.read_text(encoding="utf-8"))
|
|
|
|
def test_a_run_that_waited_runs_the_stage_once_the_lock_is_free_and_replaces_the_last_log(self) -> None:
|
|
# given
|
|
self.keep_a_last_run()
|
|
held = self.hold_the_lock()
|
|
run = self.start()
|
|
self.addCleanup(held.close)
|
|
self.wait_until_it_waits(run)
|
|
|
|
# when
|
|
held.close()
|
|
_, err = run.communicate(timeout=RUN_LIMIT)
|
|
|
|
# then
|
|
self.assertEqual(0, run.returncode, err)
|
|
header = HEADER.format(tree=self.working_tree(), base=self.base, stage="pr")
|
|
self.assertRegex(self.log(), rf"\A{header}\n(?:.*\n)*gradle :prCheck .*\nstage: lock held\n")
|
|
self.assertEqual("this run\n", (self.logs / "pr-classes.tsv").read_text(encoding="utf-8"))
|
|
|
|
def test_the_stage_and_the_summary_run_while_the_lock_is_held_exclusively(self) -> None:
|
|
# when
|
|
result = self.run_stage()
|
|
|
|
# then: pr asks Gradle twice
|
|
self.assertEqual(0, result.returncode, result.stderr)
|
|
self.assertEqual(re.findall(r"^(?:stage|summary): lock \w+$", self.log(), re.MULTILINE),
|
|
["stage: lock held", "stage: lock held", "summary: lock held"])
|
|
|
|
def test_a_run_that_cannot_take_the_lock_ends_with_4_and_changes_nothing(self) -> None:
|
|
# given: every flock fails
|
|
last = self.keep_a_last_run()
|
|
(self.bin / "flock").write_text("#!/bin/sh\nexit 1\n", encoding="utf-8")
|
|
(self.bin / "flock").chmod(0o755)
|
|
|
|
# when
|
|
result = self.run_stage()
|
|
|
|
# then
|
|
self.assertEqual((result.returncode, self.log_folder()), (4, last), result.stderr)
|
|
|
|
def assert_a_lost_client_changes_nothing(self, restore_signals: bool) -> None:
|
|
# given: a run that waits for the lock, its output read through pipes as sshd reads it
|
|
last = self.keep_a_last_run()
|
|
held = self.hold_the_lock()
|
|
run = self.start(restore_signals=restore_signals)
|
|
self.addCleanup(held.close)
|
|
self.wait_until_it_waits(run)
|
|
|
|
# when: the client goes away, then the lock is free
|
|
run.stdout.close()
|
|
run.stderr.close()
|
|
held.close()
|
|
rc = run.wait(RUN_LIMIT)
|
|
|
|
# then: it ends before it changes anything and still removes its worktree
|
|
self.assertEqual((rc, self.log_folder(), len(self.git("worktree", "list", cwd=self.remote).splitlines())),
|
|
(4, last, 1))
|
|
|
|
def test_a_run_whose_client_left_while_it_waited_changes_nothing(self) -> None:
|
|
self.assert_a_lost_client_changes_nothing(restore_signals=True)
|
|
|
|
def test_a_run_whose_client_left_changes_nothing_where_sigpipe_is_ignored(self) -> None:
|
|
# Python ignores SIGPIPE and the run inherits that: the failed write is all that can end it.
|
|
self.assert_a_lost_client_changes_nothing(restore_signals=False)
|
|
|
|
def test_the_rc_of_the_stage_is_the_exit_and_the_last_line_of_the_log(self) -> None:
|
|
# when
|
|
result = self.run_stage(FAKE_STAGE_RC="3")
|
|
|
|
# then
|
|
self.assertEqual((result.returncode, self.log().splitlines()[-1]), (3, "verify: rc=3"), result.stderr)
|
|
|
|
def assert_a_stdin_reading_stage_ends_with(self, rc: int, stage: str, **child: str) -> None:
|
|
"""REV-BE-0050. The remote script is the stdin of `bash -s`: a stage that reads its stdin must not get
|
|
the lines after it (summary, rc line, exit)."""
|
|
# when
|
|
result = self.run_stage(stage, **child)
|
|
|
|
# then
|
|
log = self.log(stage)
|
|
end = re.search(r"^summary: .*\nverify: rc=(\d+)\n\Z", log, re.MULTILINE)
|
|
self.assertEqual((result.returncode, end and end.group(1)), (rc, str(rc)), log + result.stderr)
|
|
|
|
def test_a_smoke_that_reads_stdin_and_fails_ends_with_the_summary_and_its_rc(self) -> None:
|
|
for stage in ("nightly", "round"): # the two stages that run the smoke
|
|
with self.subTest(stage=stage):
|
|
self.assert_a_stdin_reading_stage_ends_with(3, stage, FAKE_SMOKE_RC="3")
|
|
|
|
def test_a_smoke_that_reads_stdin_and_passes_ends_with_the_summary_and_its_rc(self) -> None:
|
|
for stage in ("nightly", "round"):
|
|
with self.subTest(stage=stage):
|
|
self.assert_a_stdin_reading_stage_ends_with(0, stage, FAKE_SMOKE_RC="0")
|
|
|
|
def test_a_gradle_that_reads_stdin_and_fails_ends_with_the_summary_and_its_rc(self) -> None:
|
|
# pr has no smoke: an empty stdin given to the smoke alone does not pass this
|
|
self.assert_a_stdin_reading_stage_ends_with(3, "pr", FAKE_STAGE_READS_STDIN="1", FAKE_STAGE_RC="3")
|
|
|
|
# REV-BE-0055. The patch is sent before the remote script starts; each way its preparation can fail must
|
|
# still remove it, and the folder made for the worktree when there is one.
|
|
|
|
def test_a_run_whose_remote_checkout_is_missing_ends_with_4_and_leaves_nothing_in_tmp(self) -> None:
|
|
# when
|
|
result, left = self.run_and_look_in_tmp(VERIFY_REMOTE_REPO=str(self.outside / "missing"))
|
|
|
|
# then
|
|
self.assertEqual((result.returncode, left), (4, []), result.stderr)
|
|
|
|
def test_a_run_whose_fetch_fails_ends_with_4_and_leaves_nothing_in_tmp(self) -> None:
|
|
# given: the remote checkout's origin is gone
|
|
self.git("remote", "set-url", "origin", str(self.outside / "gone"), cwd=self.remote)
|
|
|
|
# when
|
|
result, left = self.run_and_look_in_tmp()
|
|
|
|
# then
|
|
self.assertEqual((result.returncode, left, self.worktrees()), (4, [], 1), result.stderr)
|
|
|
|
def test_a_run_whose_worktree_add_fails_ends_with_4_and_leaves_nothing_in_tmp(self) -> None:
|
|
# given: a base the remote checkout cannot fetch, a commit on no branch
|
|
self.git("checkout", "-q", "--detach")
|
|
self.write("docs/on-no-branch.md", "# on no branch\n")
|
|
self.git("add", "-A")
|
|
self.git("commit", "-q", "-m", "on no branch")
|
|
|
|
# when
|
|
result, left = self.run_and_look_in_tmp(VERIFY_BASE_REF="HEAD")
|
|
|
|
# then
|
|
self.assertEqual((result.returncode, left, self.worktrees()), (4, [], 1), result.stderr)
|
|
|
|
def test_a_run_whose_patch_does_not_apply_ends_with_4_and_leaves_nothing_behind(self) -> None:
|
|
# given
|
|
self.use_the_git_stand_in()
|
|
|
|
# when
|
|
result, left = self.run_and_look_in_tmp(FAKE_GIT_FAILS="apply")
|
|
|
|
# then
|
|
self.assertEqual((result.returncode, left, self.worktrees()), (4, [], 1), result.stderr)
|
|
|
|
def test_a_run_that_passes_leaves_nothing_behind(self) -> None:
|
|
# when
|
|
result, left = self.run_and_look_in_tmp()
|
|
|
|
# then
|
|
self.assertEqual((result.returncode, left, self.worktrees()), (0, [], 1), result.stderr)
|
|
|
|
# REV-BE-0065. Auto gc that a fetch starts reads the HEAD of every worktree. One that meets a worktree still being
|
|
# made fails with `fatal: bad object` and leaves .git/gc.log, which stops auto gc for a day and prints the same
|
|
# warning on every run after. So no worktree may be made while that gc runs.
|
|
|
|
def git_calls(self) -> list[list[str]]:
|
|
"""Runs a stage with the git stand-in and returns what it wrote down for each fetch and worktree add:
|
|
[command, gc.auto=…, gc.autoDetach=…, lock held|free]."""
|
|
calls = self.use_the_git_stand_in()
|
|
result = self.run_stage()
|
|
self.assertEqual(0, result.returncode, result.stderr)
|
|
return [line.split("\t") for line in calls.read_text(encoding="utf-8").splitlines()]
|
|
|
|
def test_the_fetch_and_the_worktree_add_run_while_the_lock_is_held(self) -> None:
|
|
# when: another run waits for the lock before it fetches, so its gc cannot meet this run's worktree add
|
|
seen = self.git_calls()
|
|
|
|
# then
|
|
self.assertEqual([(command, lock) for command, _, _, lock in seen],
|
|
[("fetch", "lock held"), ("worktree add", "lock held")], seen)
|
|
|
|
def test_the_fetch_runs_its_auto_gc_and_ends_it_before_it_returns(self) -> None:
|
|
# when: by default auto gc goes on in the background after the fetch returns and meets the worktree add below
|
|
seen = self.git_calls()
|
|
|
|
# then: auto gc is not turned off (that would leave the checkout never packed) and does not detach
|
|
self.assertEqual([(command, gc_auto, detach) for command, gc_auto, detach, _ in seen if command == "fetch"],
|
|
[("fetch", "gc.auto=-", "gc.autoDetach=false")], seen)
|
|
|
|
def test_a_run_whose_client_left_while_it_fetched_under_the_lock_changes_nothing(self) -> None:
|
|
"""The fetch, with the gc it may run, now comes after the lock: a client that leaves then must not get a
|
|
run that replaces the last log."""
|
|
# given: a run that holds the lock and fetches until the test lets it go
|
|
last = self.keep_a_last_run()
|
|
calls = self.use_the_git_stand_in()
|
|
go = self.outside / "go"
|
|
run = self.start(FAKE_GIT_FETCH_WAITS_FOR=str(go))
|
|
deadline = time.monotonic() + 30
|
|
while not (calls.exists() and calls.read_text(encoding="utf-8").startswith("fetch\t")):
|
|
self.assertLess(time.monotonic(), deadline, "the run never fetched")
|
|
self.assertIsNone(run.poll(), "the run ended before it fetched")
|
|
time.sleep(0.05)
|
|
|
|
# when: the client goes away, then the fetch ends
|
|
run.stdout.close()
|
|
run.stderr.close()
|
|
go.touch()
|
|
rc = run.wait(RUN_LIMIT)
|
|
|
|
# then: it ends before it changes anything and still removes its worktree
|
|
self.assertEqual((rc, self.log_folder(), self.worktrees()), (4, last, 1))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|