From e6318da2c5ddbf56d26e6789269210c32ed7922e Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Mon, 23 Nov 2026 22:50:19 +0900 Subject: [PATCH 1/5] =?UTF-8?q?fix(gitignore):=20.claude/=20=EC=95=84?= =?UTF-8?q?=EB=9E=98=20env=20=EC=98=88=EC=8B=9C=20=EC=9D=B4=EB=A6=84?= =?UTF-8?q?=EB=8F=84=20=EB=AC=B4=EC=8B=9C=ED=95=98=EA=B3=A0=20=EC=97=86?= =?UTF-8?q?=EB=8A=94=20env=20=EA=B2=BD=EB=A1=9C=EB=A5=BC=20=EB=AC=B8?= =?UTF-8?q?=EC=84=9C=EC=97=90=EC=84=9C=20=EC=9E=A1=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: `.env*` 블록이 `.claude/*` 뒤에 있어 `!**/.env.example`과 `!**/.env.local.example`이 `.claude/*`를 이긴다. 그래서 `.claude/.env.example`, `.claude/.env.local.example`과 그 이름 폴더 안 파일이 `git add -A`에 올라간다. 블록 주석은 smoke wrapper가 `.env.lane`을 쓴다고 하지만 지금 wrapper는 지우기만 하고, 규칙이 `.env`로 시작하는 모든 이름을 말없이 뺀다는 것과 새 예시를 어떻게 되살리는지는 말하지 않는다. 문서 참조 검사는 무시되는 경로를 건너뛰므로 없는 `src/.env`, `compose/.env.lane.example`을 적은 문서와 registry 행이 통과한다. 고른 방법: 블록을 `.claude/*` 앞으로 옮기고 규칙 세 줄은 그대로 둔다. 주석은 옛 wrapper가 남긴 파일, 실제 범위(`.envrc`·`.env_x`도), `add -A`가 말없이 뺌, 블록 아래 루트부터 적은 정확한 경로로만 되살림을 적는다. `check-docs.py`는 `.env`로 시작하는 마디가 있는 대상을 무시 경로 건너뛰기에서 뺀다. 빌드가 만드는 build/ 출력과 달리 없는 env 파일은 아무것도 만들어 주지 않는다. 버린 안: `**/.env*`를 좁힘(`.envrc`·`.env-local`·`.env_prod`가 열린다), `!**/.env*.example`(비밀 예시 이름이 모든 폴더에서 열린다). 위험·한계: 무시 범위는 그대로다. `.claude/skills/` 같은 되살린 폴더 안의 예시 이름은 여전히 추적된다(예시는 어느 폴더에서든 계약이다). 실제 env 파일 내용은 읽지 않았다. 검증: 가짜 repo의 `git check-ignore --no-index -q`에서 `.claude/` 셋이 고치기 전 rc=1, 뒤 rc=0. `.env`·`src/.env`·`src/.env.local`·`.env.lane`은 rc=0, 예시 넷과 `.claude/skills/d/.env.example`은 rc=1 그대로, 추적 파일 전체 `--stdin` rc=1. 새 시험은 고치기 전 실패, 예외를 빼거나 모두 검사하는 변이에서 실패, 고친 뒤 통과. `check-docs.py --only reference` rc=0(걸림 0). Refs: REV-BE-0052 --- .gitignore | 24 +++++++++++++++--------- scripts/check-docs.py | 14 ++++++++++++-- scripts/tests/test_check_docs.py | 18 ++++++++++++++++++ 3 files changed, 45 insertions(+), 11 deletions(-) diff --git a/.gitignore b/.gitignore index e05d587e..684e7842 100644 --- a/.gitignore +++ b/.gitignore @@ -20,6 +20,21 @@ build/ src/**/src/*/java/**/*.received.* !src/**/src/*/java/**/*.approved.* .DS_Store + +# Operator input, not a build input: a real environment file stays out in any folder, not only at +# the root. That covers .env, .env.local, a src/.env left over from before the relayout, a .env.lane +# an older runtime-smoke wrapper left behind (the wrapper now only deletes it) and any .env.. +# verifyEnvKeys reads the registry, the profile YAMLs and .env.example, never a real one. +# The rule takes every file and folder whose name starts with .env, .envrc and .env_x included, and +# `git add -A` or `git add .` leaves them out without a word; only `git add ` refuses. The two +# examples are the contract and stay tracked in any folder. To track another such file, add its +# exact path from the root below this block (!/compose/x/.env.sample), never !**/: that opens +# the name in every folder. +# The block comes before .claude/*, so a local file under .claude/ stays out under an example's name. +**/.env* +!**/.env.example +!**/.env.local.example + # Local Claude Code state (worktrees, settings.local.json, notes) stays out. The shared project # settings, path rules, skills and subagent definitions are committed: everyone who opens the repository gets them (CLAUDE.md). .claude/* @@ -28,15 +43,6 @@ src/**/src/*/java/**/*.received.* !.claude/agents/ !.claude/skills/ -# Operator input, not a build input: a real environment file stays out in any folder, not only at -# the root. That covers .env, .env.local, a src/.env left over from before the relayout, the -# .env.lane the runtime-smoke wrapper writes per run, and any .env.. Only the two examples -# are tracked; they are the contract, and verifyEnvKeys reads the registry, the profile YAMLs and -# .env.example, never a real one. A new example needs its own ! line, or Git ignores it. -**/.env* -!**/.env.example -!**/.env.local.example - # bootRun's file log when APP_LOG_FILE_ENABLED=true: APP_LOG_FILE_PATH is relative to the repository root. /logs/ diff --git a/scripts/check-docs.py b/scripts/check-docs.py index f079ff47..2abd1d86 100755 --- a/scripts/check-docs.py +++ b/scripts/check-docs.py @@ -22,7 +22,9 @@ 「있다」는 git이 아는 파일(추적 + 무시되지 않은 새 파일)과 그 위 폴더다. 문서 폴더에서 읽어도 된다(leaf 문서의 src/main/…). leaf 상대 경로(src/<소스 세트>/…)는 registry의 어느 leaf 폴더 아래에 있으면 된다(템플릿 폴더의 src/ 나무는 세지 않는다). 디스크에만 있는 것(git mv가 남긴 빈 폴더 등)은 - 새 checkout에 없으므로 세지 않는다. + 새 checkout에 없으므로 세지 않는다. 무시 규칙에 걸리는 경로(build/ 출력, 로컬 파일)는 빌드나 도구가 + 만드므로 없어도 건너뛴다. 다만 `.env`로 시작하는 마디가 있는 경로는 건너뛰지 않는다: 없는 env 파일은 + 아무것도 만들어 주지 않으므로 문서는 추적하는 예시(.env.example 등)만 가리킨다. 기록의 「현재 정본」·「대체됨」 경로도 같다. 코드 블록과 「이력」으로 시작하는 인용 블록은 건너뛴다. 마크다운 링크는 link와 lychee가 본다. registry(docs/registries/*.yaml)의 값(따옴표가 있든 없든)과 주석에 적은 repo 경로도 본다: 행의 `source`·`registered_by`가 옮긴 파일을 가리키면 main @@ -571,6 +573,12 @@ def resolves(root: Path, document: str, target: str, known: set[str]) -> bool: return False +def names_env_file(target: str) -> bool: + """`src/.env`, `compose/.env.lane.example`: a part of the path starts with .env, the names `**/.env*` in + .gitignore ignores.""" + return any(part.startswith(".env") for part in target.split("/")) + + def ignored(root: Path, paths: set[str]) -> set[str]: if not paths: return set() @@ -631,7 +639,9 @@ def check_reference(root: Path, files: list[str]) -> list[Problem]: if target and target not in seen and not resolves(root, path, target, known): seen.add(target) missing.append((path, number, target)) - skip = ignored(root, {target for _, _, target in missing}) + # A path git ignores is made by a build or a tool (build/ output, a local file), so a fresh checkout has it. + # Nothing makes a missing env file: a document names a tracked example, not a path .gitignore hides. + skip = ignored(root, {target for _, _, target in missing if not names_env_file(target)}) sets = source_sets(modules, known) leaf_relative = {target for _, _, target in missing if target.split("/")[0] == "src" and len(target.split("/")) > 1 and target.split("/")[1] in sets} diff --git a/scripts/tests/test_check_docs.py b/scripts/tests/test_check_docs.py index fe533e48..006c4d58 100644 --- a/scripts/tests/test_check_docs.py +++ b/scripts/tests/test_check_docs.py @@ -362,6 +362,24 @@ class ReferenceTest(RepositoryTestCase): self.repo.write("docs/registries/env-keys.yaml", "# 정본은 docs/gone.yaml에 적는다.\nkeys: []\n") self.assertFailsWith(self.repo.run(("reference",)), "env-keys.yaml:1: 없는 경로다: docs/gone.yaml") + def test_a_missing_env_path_fails_though_git_ignores_it_and_other_ignored_paths_are_skipped(self) -> None: + """REV-BE-0052. An ignored path (build/ output, a local file) is skipped: a fresh checkout makes it. Git + ignores every .env* name too, but a document or registry row that names one must name a tracked example: + nothing makes a missing env file appear.""" + # given: the repository's .env* rule and build/ output, none of the named files present + self.repo.write(".gitignore", "build/\n**/.env*\n!**/.env.example\n!**/.env.local.example\n") + self.repo.write("docs/registries/env-keys.yaml", "keys:\n - source: \"src/.env.local\"\n") + + # when + errors = self.errors_for("`src/.env`와 `compose/.env.lane.example`, `src/x/build/out.txt`를 읽는다.\n") + + # then + self.assertEqual(sorted(re.sub(r":\d+: ", ": ", error) for error in errors), [ + "[reference] docs/guide.md: 없는 경로다: compose/.env.lane.example", + "[reference] docs/guide.md: 없는 경로다: src/.env", + "[reference] docs/registries/env-keys.yaml: 없는 경로다: src/.env.local", + ]) + def test_registry_paths_that_exist_pass_with_or_without_a_prefix(self) -> None: self.repo.write("src/app/src/main/java/Headers.java", "class Headers {}\n") self.repo.write("docs/registries/headers.yaml", -- 2.54.0 From 0facd862490bc9a611c6cc9f73f8a25b536abb8d Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Mon, 23 Nov 2026 22:51:58 +0900 Subject: [PATCH 2/5] =?UTF-8?q?fix(scripts):=20verify.sh=20--on=20?= =?UTF-8?q?=EC=9B=90=EA=B2=A9=20=EC=A4=80=EB=B9=84=EA=B0=80=20=EC=8B=A4?= =?UTF-8?q?=ED=8C=A8=ED=95=B4=EB=8F=84=20=EB=B3=B4=EB=82=B8=20patch?= =?UTF-8?q?=EC=99=80=20=EC=9E=84=EC=8B=9C=20=ED=8F=B4=EB=8D=94=EB=A5=BC=20?= =?UTF-8?q?=EC=A7=80=EC=9A=B4=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: `run_remote`는 patch를 원격 `/tmp/.patch`로 먼저 보낸다. 그것을 지우는 trap은 checkout으로 cd, `git fetch`, `mktemp -d`, `git worktree add`를 지난 뒤에야 걸린다. 그 넷 중 하나가 실패하면 rc 4로 끝나고 정리가 돌지 않아, 커밋 안 된 변경이 든 patch(worktree add 실패면 빈 임시 폴더도)가 desktop `/tmp`에 쌓인다. 고른 방법: 정리 함수와 trap을 원격 script 맨 앞, 첫 실패 지점(cd) 앞에 둔다. 정리는 patch를 먼저 지우고, worktree를 만든 뒤에만(`added`) `worktree remove --force`를 하고, worktree가 되기 전의 `mktemp` 폴더는 남아 있고 빈 때만 `rmdir`한다(worktree add가 중간에 실패하면 git이 그 폴더를 지운다). `mktemp -d` 실패도 rc 4로 끝낸다. 버린 안: 실패 줄마다 정리 명령을 붙임(새 실패 지점이 생기면 또 빠진다). 위험·한계: patch를 보내는 ssh 자체가 끊기거나 `bash -s` 연결이 실패하면 원격에서 아무것도 돌지 않으니 patch는 남는다(이 변경으로 고칠 수 없다). 트리 비교, 잠금, 단계 rc 전달은 그대로다. 검증: `scripts/tests/test_verify_remote.py`에 checkout 없음·fetch 실패· worktree add 실패(어느 branch에도 없는 기준)·패치 얹기 실패·통과 다섯 사례를 더했다. 고치기 전 앞 셋은 patch(worktree add는 임시 폴더도)가 남아 실패했고, 뒤 둘은 통과했다. 고친 뒤 다섯 모두 rc 4·0 그대로 통과한다. trap을 원래 자리(worktree add 뒤)로 옮기는 변이에서 앞 셋이, `rmdir`를 빼는 변이에서 worktree add 실패 사례가 실패한다. Refs: REV-BE-0055 --- scripts/tests/test_verify_remote.py | 104 +++++++++++++++++++++++++++- scripts/verify.sh | 20 ++++-- 2 files changed, 117 insertions(+), 7 deletions(-) diff --git a/scripts/tests/test_verify_remote.py b/scripts/tests/test_verify_remote.py index 0b8e6799..b17dcbcd 100644 --- a/scripts/tests/test_verify_remote.py +++ b/scripts/tests/test_verify_remote.py @@ -11,7 +11,9 @@ repo의 clone에서 worktree를 만들고 잠금 아래에서 단계를 돌린 원격 로그의 첫 줄이 보낸 트리와 기준의 전체 해시를 적는지, 다른 프로세스가 잠금을 쥔 동안 지난 로그와 클래스 목록이 그대로인지, 기다리다 client가 끊겼거나 잠금을 얻지 못한 실행이 그것을 바꾸지 않는지, 단계와 합계가 배타 잠금 안에서 도는지, 단계의 rc가 그대로 나가는지, 단계가 stdin을 읽어도 합계·rc 줄과 그 rc로 끝나는지 본다. 잠금 대기는 Linux -`/proc/locks`의 대기 줄(`->`)로 안다. +`/proc/locks`의 대기 줄(`->`)로 안다. 원격 준비(checkout으로 cd, fetch, worktree add, 패치 얹기)가 실패해도, 실행이 +통과해도 /tmp에 보낸 패치와 worktree 폴더가 남지 않는지도 본다. 패치 얹기 실패는 원격 쪽 git을 가짜(FAKE_GIT)로 +바꿔 낸다. python3 -m unittest discover -s scripts/tests """ @@ -229,6 +231,29 @@ 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 that call runs with (its -c options and the environment count) and whether the lock is +# held exclusively. The subcommand named in FAKE_GIT_FAILS fails instead. +FAKE_GIT = """#!/usr/bin/env python3 +import os, subprocess, sys +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"]): + gc_auto = subprocess.run([REAL, *args[:i], "config", "--get", "gc.auto"], capture_output=True, text=True) + 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(" ".join(command) + "\\tgc.auto=" + (gc_auto.stdout.strip() or "-") + + "\\tlock " + ("held" if held else "free") + "\\n") +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 @@ -268,7 +293,32 @@ class RemoteLogTest(ThrowawayRepoTest): 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), **extra} + "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--`: + the patch it sent (`.patch`) and the folder made for its worktree (`.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 = [".XXXXXX/" if path.is_dir() else own.sub(".", 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]: @@ -493,6 +543,56 @@ class RemoteLogTest(ThrowawayRepoTest): # 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) + if __name__ == "__main__": unittest.main() diff --git a/scripts/verify.sh b/scripts/verify.sh index 83fc77d3..6bf8d9ac 100755 --- a/scripts/verify.sh +++ b/scripts/verify.sh @@ -18,6 +18,7 @@ # # --on <호스트>: 지금 작업 트리(커밋 안 된 변경 포함)를 패치로 그 호스트에 옮긴다. 기준 커밋에서 새 worktree를 # 만들어 패치를 적용하고, 트리 해시가 여기와 같은지 본 뒤 잠금 아래에서 같은 단계를 돌리고 worktree를 지운다. +# 준비(cd, fetch, worktree, 패치)가 실패해 rc 4로 끝나도 원격 /tmp에 보낸 패치와 임시 폴더를 남기지 않는다. # push하지 않는다. 기준 커밋은 원격 checkout이 fetch로 받을 수 있어야 한다(기본: origin/main과 갈라진 곳). # docs 밖의 단계는 기본이 desktop이다. desktop에서 직접 돌릴 때는 --on here. # 보내는 것은 추적 파일의 변경과 stage한 새 파일이다. 무시 규칙(.gitignore, .git/info/exclude) 밖의 미추적 파일이 @@ -158,15 +159,24 @@ run_remote() { echo "verify: $host에서 '$stage $target' (기준 ${base:0:12}, 트리 ${tree:0:12}($same), 로그 ~/$log-logs/$stage.log)" >&2 $ssh "$host" "cat > /tmp/$id.patch" < "$patch" # compose lane이 만든 root 소유 파일이 있어도 지울 수 있게 정리는 worktree remove --force 하나로 한다. + # 패치는 이미 원격에 있으므로 정리는 첫 실패 지점(cd) 앞에 건다. worktree가 되기 전에 끝났으면 mktemp 폴더는 + # 빈 때만 지운다(worktree add가 중간에 실패하면 git이 그 폴더를 지운다). $ssh "$host" bash -s < Date: Mon, 23 Nov 2026 22:54:33 +0900 Subject: [PATCH 3/5] =?UTF-8?q?fix(verify):=20=EC=9B=90=EA=B2=A9=20fetch?= =?UTF-8?q?=EC=99=80=20worktree=20add=EA=B0=80=20=EC=9E=90=EB=8F=99=20gc?= =?UTF-8?q?=EB=A5=BC=20=EB=9D=84=EC=9A=B0=EC=A7=80=20=EC=95=8A=EA=B2=8C=20?= =?UTF-8?q?=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 원격 스크립트는 desktop 공용 checkout에서 `git fetch`와 `git worktree add`를 잠금 밖에서 한다. fetch가 띄운 자동 gc는 뒤에서 계속 돌며 모든 worktree의 HEAD를 읽는데, 이 실행이나 겹친 실행이 만드는 중인 worktree를 만나면 `fatal: bad object worktrees/verify-…/HEAD`로 실패하고 `.git/gc.log`를 남긴다. gc.log가 있는 동안(`gc.logExpiry` 기본 1일) 자동 gc는 막히고 그 뒤 실행 로그마다 같은 경고가 찍혀 진짜 실패와 헷갈린다. fetch의 rc는 바뀌지 않아 게이트 판정은 틀리지 않는다. 고른 방법: fetch와 worktree add에 `-c gc.auto=0`을 준다. 값은 자식 git에도 넘어가 fetch가 띄우는 `maintenance run --auto`가 gc를 건너뛴다. 잠금 순서와 대기 방식, 0055가 정한 정리 순서는 그대로다. 손으로 하는 절차 (`docs/work/operate.md` 4.1절)의 같은 두 명령도 맞췄다. 버린 안: 둘을 잠금 안으로 옮김. 자동 gc는 기본으로 뒤에서 도니 같은 실행의 fetch가 띄운 gc가 바로 다음 worktree add와 여전히 겹치고, 겹친 실행이 준비 단계부터 줄을 서며, 트리가 다른 patch가 잠금을 기다린 뒤에야 실패한다. 위험·한계: verify의 fetch는 더는 desktop checkout의 자동 gc를 띄우지 않는다. 그 checkout에서 다른 명령이 gc를 띄우지 않으면 pack과 loose object가 쌓인다(정리는 이 변경 밖이다). verify 밖의 명령(사람이 한 fetch 등)이 띄운 gc는 여전히 만드는 중인 worktree와 겹칠 수 있다. desktop의 지금 gc.log는 지우지 않았다(11-24 08:32 뒤 저절로 풀린다). 검증: `test_verify_remote.py`에 원격 쪽 git을 가짜로 바꿔 fetch·worktree add마다 그 명령이 보는 gc.auto와 잠금 상태를 적는 사례를 더했다. 고치기 전 [fetch False, worktree add False]로 실패, 고친 뒤 통과. 한쪽씩 옵션을 빼는 변이 둘에서 실패한다. git 2.43(노트북·desktop 같음) 실험: 자동 gc 조건(pack 2개 > autoPackLimit 1)을 넘기는 fetch가 옵션 없이 `git gc`를 띄워 pack을 1개로 합치고, `-c gc.auto=0`이면 띄우지 않아 2개로 남는다. `scripts/verify.sh docs` rc=0(시험 381). Refs: REV-BE-0065 --- docs/work/operate.md | 8 ++++---- scripts/tests/test_verify_remote.py | 21 +++++++++++++++++++-- scripts/verify.sh | 8 ++++++-- 3 files changed, 29 insertions(+), 8 deletions(-) diff --git a/docs/work/operate.md b/docs/work/operate.md index 9f17881b..e8889cc8 100644 --- a/docs/work/operate.md +++ b/docs/work/operate.md @@ -37,7 +37,7 @@ - CI runner(2026-11-07): Gitea Actions가 켜졌고, desktop에 `desktop-runner` 하나(`gitea/runner` dind, `capacity: 1`, label `ubuntu-latest`)가 돈다. desktop은 12코어·31GB다. CI job은 공유 잠금을 쓰지 않으므로, 손으로 돌린 게이트가 느리면 `docker ps`로 runner job이 함께 도는지 본다. 노트북에는 가벼운 job용 `laptop-runner`(label `laptop-light`, capacity 1)가 있고, repo 변수 `LIGHT_RUNNER_LABEL=laptop-light`가 main push run의 `links`·`vulnerabilities`를 그리로 보낸다(2026-11-20, nightly·수동 run은 desktop). 노트북이 뜨겁거나 바쁘거나 배터리로 돌면 감시가 새 job을 막고 화면에 알린다. 그동안 두 job은 기다린다. 로그아웃·재부팅은 돌던 job을 5초 만에 끊으므로 먼저 `~/laptop-runner/PAUSE`를 만들고, 상태가 paused가 된 뒤 30초를 더 기다리고(runner가 검사 결과를 30초까지 다시 쓴다), 돌던 job이 끝나길 기다린다. 상한·멈춤·끄기는 노트북의 `~/laptop-runner/README.md`이고, 변수를 지우면 두 job은 desktop으로 돌아간다. - runner의 job 컨테이너 안의 `localhost`는 dind 데몬이 띄운 서비스가 아니다. Testcontainers는 이것을 스스로 처리한다. compose로 띄운 서비스에 `localhost`로 붙는 job은 `scripts/ci/redis-topology.sh`처럼 포트를 넘겨야 한다. -**`scripts/verify.sh`가 아래 절차를 한다.** `scripts/verify.sh <단계>`는 지금 작업 트리(커밋하지 않은 변경 포함)를 패치로 만들어 desktop에 보내고, 기준 커밋에서 새 worktree를 만들어 얹고, 트리 해시가 같은지 본 뒤 잠금 아래에서 단계를 돌리고, 로그를 `~/<브랜치 이름>-logs/<단계>.log`에 남기고, worktree를 지운다. push하지 않는다. 무시 규칙(`.gitignore`, `.git/info/exclude`) 밖의 미추적 파일이 있으면 아무것도 보내지 않고 그 이름을 찍고 멈춘다(rc=5). 보낼 것이면 `git add`하거나 `--include-untracked`를 주고, 보내지 않을 것이면 지우거나 `.git/info/exclude`에 적는다. 노트북 stderr 첫 줄은 보낸 트리가 HEAD 트리와 같은지 말한다. 원격 로그는 첫 줄에 보낸 트리와 기준 커밋의 전체 해시, 둘째 줄에 부하가 있다. 단계와 돌리는 명령은 [reference/gates.md](reference/gates.md) 1절이다. 아래는 스크립트가 하는 일이고, 스크립트를 쓸 수 없을 때(다른 기준 커밋, 단계 밖의 명령 하나) 손으로 한다. +**`scripts/verify.sh`가 아래 절차를 한다.** `scripts/verify.sh <단계>`는 지금 작업 트리(커밋하지 않은 변경 포함)를 패치로 만들어 desktop에 보내고, 기준 커밋에서 새 worktree를 만들어 얹고, 트리 해시가 같은지 본 뒤 잠금 아래에서 단계를 돌리고, 로그를 `~/<브랜치 이름>-logs/<단계>.log`에 남기고, worktree를 지운다. 준비(fetch, worktree 만들기, 패치 얹기)가 실패해 rc=4로 끝나도 보낸 패치와 임시 폴더를 지운다. push하지 않는다. 잠금 밖에서 하는 fetch와 worktree add는 자동 gc를 끄고 한다(`git -c gc.auto=0`). fetch가 띄운 gc는 뒤에서 계속 돌다가 만드는 중인 worktree를 읽으면 `fatal: bad object`로 실패하고, `.git/gc.log`를 남겨 하루 동안 자동 gc를 막는다. 손으로 할 때도 같다. 무시 규칙(`.gitignore`, `.git/info/exclude`) 밖의 미추적 파일이 있으면 아무것도 보내지 않고 그 이름을 찍고 멈춘다(rc=5). 보낼 것이면 `git add`하거나 `--include-untracked`를 주고, 보내지 않을 것이면 지우거나 `.git/info/exclude`에 적는다. 노트북 stderr 첫 줄은 보낸 트리가 HEAD 트리와 같은지 말한다. 원격 로그는 첫 줄에 보낸 트리와 기준 커밋의 전체 해시, 둘째 줄에 부하가 있다. 단계와 돌리는 명령은 [reference/gates.md](reference/gates.md) 1절이다. 아래는 스크립트가 하는 일이고, 스크립트를 쓸 수 없을 때(다른 기준 커밋, 단계 밖의 명령 하나) 손으로 한다. 절차: @@ -48,8 +48,8 @@ git push origin <자기 브랜치> # 2) desktop: 기존 checkout을 건드리지 않게 따로 worktree를 만든다 ssh desktop cd ~/workspace/clean-architecture-backend-template -git fetch origin -git worktree add ~/workspace/<작업 이름> origin/<자기 브랜치> +git -c gc.auto=0 fetch origin +git -c gc.auto=0 worktree add ~/workspace/<작업 이름> origin/<자기 브랜치> mkdir -p ~/<작업 이름>-logs uptime # 다른 빌드가 돌고 있는지 부하를 본다 @@ -74,7 +74,7 @@ git worktree remove ~/workspace/<작업 이름> # 노트북: 커밋할 파일만 stage하고(git status로 확인) 트리 해시를 적어 둔다 git add <바꾼 파일>... && git status --short && git write-tree # desktop: 기준 커밋(push된 커밋)에서 worktree를 만든다 -ssh desktop 'cd ~/workspace/clean-architecture-backend-template && git fetch origin && git worktree add --detach ~/workspace/<작업 이름> <기준 커밋>' +ssh desktop 'cd ~/workspace/clean-architecture-backend-template && git -c gc.auto=0 fetch origin && git -c gc.auto=0 worktree add --detach ~/workspace/<작업 이름> <기준 커밋>' # 노트북: 패치를 보내 얹는다. 마지막 줄이 위 트리 해시와 같아야 한다 git diff --cached --binary <기준 커밋> | ssh desktop 'cd ~/workspace/<작업 이름> && git apply --index && git write-tree' ``` diff --git a/scripts/tests/test_verify_remote.py b/scripts/tests/test_verify_remote.py index b17dcbcd..f6facd46 100644 --- a/scripts/tests/test_verify_remote.py +++ b/scripts/tests/test_verify_remote.py @@ -12,8 +12,9 @@ repo의 clone에서 worktree를 만들고 잠금 아래에서 단계를 돌린 그대로인지, 기다리다 client가 끊겼거나 잠금을 얻지 못한 실행이 그것을 바꾸지 않는지, 단계와 합계가 배타 잠금 안에서 도는지, 단계의 rc가 그대로 나가는지, 단계가 stdin을 읽어도 합계·rc 줄과 그 rc로 끝나는지 본다. 잠금 대기는 Linux `/proc/locks`의 대기 줄(`->`)로 안다. 원격 준비(checkout으로 cd, fetch, worktree add, 패치 얹기)가 실패해도, 실행이 -통과해도 /tmp에 보낸 패치와 worktree 폴더가 남지 않는지도 본다. 패치 얹기 실패는 원격 쪽 git을 가짜(FAKE_GIT)로 -바꿔 낸다. +통과해도 /tmp에 보낸 패치와 worktree 폴더가 남지 않는지, fetch와 worktree add가 자동 gc를 끈 채(또는 잠금 안에서) +도는지도 본다. 두 가지는 원격 쪽 git을 가짜(FAKE_GIT)로 바꿔 본다: 가짜는 fetch·worktree add마다 그 명령이 보는 +gc.auto와 잠금 상태를 적고, 패치 얹기를 실패시킬 수 있고, 나머지는 진짜 git에 넘긴다. python3 -m unittest discover -s scripts/tests """ @@ -593,6 +594,22 @@ class RemoteLogTest(ThrowawayRepoTest): # then self.assertEqual((result.returncode, left, self.worktrees()), (0, [], 1), result.stderr) + def test_the_fetch_and_the_worktree_add_run_without_auto_gc_or_under_the_lock(self) -> None: + """REV-BE-0065. Auto gc that a fetch starts runs on in the background and 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.""" + # given + calls = self.use_the_git_stand_in() + + # when + result = self.run_stage() + + # then + self.assertEqual(0, result.returncode, result.stderr) + seen = [line.split("\t") for line in calls.read_text(encoding="utf-8").splitlines()] + self.assertEqual([(command, gc_auto == "gc.auto=0" or lock == "lock held") for command, gc_auto, lock in seen], + [("fetch", True), ("worktree add", True)], seen) + if __name__ == "__main__": unittest.main() diff --git a/scripts/verify.sh b/scripts/verify.sh index 6bf8d9ac..b9b73c84 100755 --- a/scripts/verify.sh +++ b/scripts/verify.sh @@ -19,6 +19,7 @@ # --on <호스트>: 지금 작업 트리(커밋 안 된 변경 포함)를 패치로 그 호스트에 옮긴다. 기준 커밋에서 새 worktree를 # 만들어 패치를 적용하고, 트리 해시가 여기와 같은지 본 뒤 잠금 아래에서 같은 단계를 돌리고 worktree를 지운다. # 준비(cd, fetch, worktree, 패치)가 실패해 rc 4로 끝나도 원격 /tmp에 보낸 패치와 임시 폴더를 남기지 않는다. +# 잠금 밖인 fetch와 worktree add는 자동 gc를 끄고 돈다(gc가 만드는 중인 worktree를 읽고 실패하지 않게). # push하지 않는다. 기준 커밋은 원격 checkout이 fetch로 받을 수 있어야 한다(기본: origin/main과 갈라진 곳). # docs 밖의 단계는 기본이 desktop이다. desktop에서 직접 돌릴 때는 --on here. # 보내는 것은 추적 파일의 변경과 stage한 새 파일이다. 무시 규칙(.gitignore, .git/info/exclude) 밖의 미추적 파일이 @@ -173,9 +174,12 @@ cleanup() { trap cleanup EXIT trap 'exit 4' PIPE # 끊긴 client에 쓰다 죽어도 위 정리를 하고 끝난다 cd $remote_repo || exit 4 -git fetch -q origin || exit 4 +# 잠금 밖이라 자동 gc를 끈다. fetch가 띄운 gc는 뒤에서 계속 돌며 모든 worktree의 HEAD를 읽는데, 만드는 중인 것(이 +# 실행이나 겹친 실행의 worktree add)을 만나면 'fatal: bad object'로 실패하고 .git/gc.log를 남겨 하루 동안 자동 gc를 +# 막고 실행마다 같은 경고를 찍는다. +git -c gc.auto=0 fetch -q origin || exit 4 wt=\$(mktemp -d /tmp/$id.XXXXXX) || exit 4 -git worktree add -q --detach "\$wt" $base || exit 4 +git -c gc.auto=0 worktree add -q --detach "\$wt" $base || exit 4 added=1 cd "\$wt" if [ -s /tmp/$id.patch ]; then git apply --binary --index /tmp/$id.patch || exit 4; fi -- 2.54.0 From 5f1aba02c4c34d9c3e0e7a175e552c2aec872c3c Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Mon, 23 Nov 2026 23:07:37 +0900 Subject: [PATCH 4/5] =?UTF-8?q?fix(gitignore):=20.env=20=ED=8F=B4=EB=8D=94?= =?UTF-8?q?=20=EC=95=88=20=ED=8C=8C=EC=9D=BC=EC=9D=84=20=EB=90=98=EC=82=B4?= =?UTF-8?q?=EB=A6=AC=EB=8A=94=20=EB=B2=95=EC=9D=84=20=EC=A0=81=EA=B3=A0=20?= =?UTF-8?q?=EB=AC=B8=EC=84=9C=20=EA=B2=80=EC=82=AC=20=EC=8B=9C=ED=97=98?= =?UTF-8?q?=EC=97=90=20=EA=B7=B8=20=EA=B2=BD=EB=A1=9C=EB=A5=BC=20=EB=8D=94?= =?UTF-8?q?=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 첫 리뷰 Low 둘. `.gitignore` 주석은 `.env`로 시작하는 폴더도 무시된다고 하면서 되살리는 법으로 파일의 정확한 경로만 든다. 그런데 부모 폴더가 무시되면 git은 그 안 파일을 되살리지 못한다: `!/compose/.env.d/sample.conf`를 더해도 rc=0(무시)이고 `git add -A`가 말없이 뺀다. 새 문서 검사 시험은 `.env*` 폴더 안 파일 경로를 넣지 않아, `names_env_file`을 마지막 마디만 보게 좁혀도 통과한다. 고른 방법: 주석에 그런 파일은 폴더(`!/compose/.env.d/`)로만 되살아나고 그러면 폴더 안 `.env*` 이름 밖의 파일이 모두 추적된다고 적는다. 시험의 없는 경로에 `compose/.env.d/app.conf`를 더한다. 위험·한계: 규칙 줄은 바뀌지 않는다(주석만). 검증: 임시 repo에서 `!/compose/.env.d/sample.conf`는 rc=0·`add -A` 0개, `!/compose/.env.d/`는 sample.conf rc=1·`add -A` 1개, 폴더 안 `.env.local`과 다른 폴더의 `.env.sample`은 rc=0 그대로. 시험은 마지막 마디만 보는 변이와 고치기 전 `check-docs.py`(1a48a02c5)에서 실패, 지금 코드에서 통과. `scripts/verify.sh docs` rc=0. Refs: REV-BE-0052 --- .gitignore | 3 ++- scripts/tests/test_check_docs.py | 6 ++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index 684e7842..03f335a6 100644 --- a/.gitignore +++ b/.gitignore @@ -29,7 +29,8 @@ src/**/src/*/java/**/*.received.* # `git add -A` or `git add .` leaves them out without a word; only `git add ` refuses. The two # examples are the contract and stay tracked in any folder. To track another such file, add its # exact path from the root below this block (!/compose/x/.env.sample), never !**/: that opens -# the name in every folder. +# the name in every folder. A file inside such a folder comes back only with its folder +# (!/compose/.env.d/), which then tracks every file in it but its .env* names. # The block comes before .claude/*, so a local file under .claude/ stays out under an example's name. **/.env* !**/.env.example diff --git a/scripts/tests/test_check_docs.py b/scripts/tests/test_check_docs.py index 006c4d58..e4455bd7 100644 --- a/scripts/tests/test_check_docs.py +++ b/scripts/tests/test_check_docs.py @@ -371,10 +371,12 @@ class ReferenceTest(RepositoryTestCase): self.repo.write("docs/registries/env-keys.yaml", "keys:\n - source: \"src/.env.local\"\n") # when - errors = self.errors_for("`src/.env`와 `compose/.env.lane.example`, `src/x/build/out.txt`를 읽는다.\n") + errors = self.errors_for("`src/.env`와 `compose/.env.lane.example`, `compose/.env.d/app.conf`, " + "`src/x/build/out.txt`를 읽는다.\n") - # then + # then: a file inside an ignored .env* folder counts too self.assertEqual(sorted(re.sub(r":\d+: ", ": ", error) for error in errors), [ + "[reference] docs/guide.md: 없는 경로다: compose/.env.d/app.conf", "[reference] docs/guide.md: 없는 경로다: compose/.env.lane.example", "[reference] docs/guide.md: 없는 경로다: src/.env", "[reference] docs/registries/env-keys.yaml: 없는 경로다: src/.env.local", -- 2.54.0 From 9b34d2a72856572304092601487d44a0d2261d4b Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Mon, 23 Nov 2026 23:45:36 +0900 Subject: [PATCH 5/5] =?UTF-8?q?fix(verify):=20=EC=9B=90=EA=B2=A9=20fetch?= =?UTF-8?q?=EC=99=80=20worktree=20add=EB=A5=BC=20=EC=9E=A0=EA=B8=88=20?= =?UTF-8?q?=EC=95=88=EC=9C=BC=EB=A1=9C=20=EC=98=AE=EA=B8=B0=EA=B3=A0=20gc?= =?UTF-8?q?=EB=A5=BC=20fetch=20=EC=95=88=EC=97=90=EC=84=9C=20=EB=81=9D?= =?UTF-8?q?=EB=82=B8=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 앞 커밋 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 --- docs/work/operate.md | 12 ++-- scripts/tests/test_verify_remote.py | 90 +++++++++++++++++++++-------- scripts/verify.sh | 29 +++++----- 3 files changed, 88 insertions(+), 43 deletions(-) diff --git a/docs/work/operate.md b/docs/work/operate.md index e8889cc8..17087ea1 100644 --- a/docs/work/operate.md +++ b/docs/work/operate.md @@ -37,7 +37,7 @@ - CI runner(2026-11-07): Gitea Actions가 켜졌고, desktop에 `desktop-runner` 하나(`gitea/runner` dind, `capacity: 1`, label `ubuntu-latest`)가 돈다. desktop은 12코어·31GB다. CI job은 공유 잠금을 쓰지 않으므로, 손으로 돌린 게이트가 느리면 `docker ps`로 runner job이 함께 도는지 본다. 노트북에는 가벼운 job용 `laptop-runner`(label `laptop-light`, capacity 1)가 있고, repo 변수 `LIGHT_RUNNER_LABEL=laptop-light`가 main push run의 `links`·`vulnerabilities`를 그리로 보낸다(2026-11-20, nightly·수동 run은 desktop). 노트북이 뜨겁거나 바쁘거나 배터리로 돌면 감시가 새 job을 막고 화면에 알린다. 그동안 두 job은 기다린다. 로그아웃·재부팅은 돌던 job을 5초 만에 끊으므로 먼저 `~/laptop-runner/PAUSE`를 만들고, 상태가 paused가 된 뒤 30초를 더 기다리고(runner가 검사 결과를 30초까지 다시 쓴다), 돌던 job이 끝나길 기다린다. 상한·멈춤·끄기는 노트북의 `~/laptop-runner/README.md`이고, 변수를 지우면 두 job은 desktop으로 돌아간다. - runner의 job 컨테이너 안의 `localhost`는 dind 데몬이 띄운 서비스가 아니다. Testcontainers는 이것을 스스로 처리한다. compose로 띄운 서비스에 `localhost`로 붙는 job은 `scripts/ci/redis-topology.sh`처럼 포트를 넘겨야 한다. -**`scripts/verify.sh`가 아래 절차를 한다.** `scripts/verify.sh <단계>`는 지금 작업 트리(커밋하지 않은 변경 포함)를 패치로 만들어 desktop에 보내고, 기준 커밋에서 새 worktree를 만들어 얹고, 트리 해시가 같은지 본 뒤 잠금 아래에서 단계를 돌리고, 로그를 `~/<브랜치 이름>-logs/<단계>.log`에 남기고, worktree를 지운다. 준비(fetch, worktree 만들기, 패치 얹기)가 실패해 rc=4로 끝나도 보낸 패치와 임시 폴더를 지운다. push하지 않는다. 잠금 밖에서 하는 fetch와 worktree add는 자동 gc를 끄고 한다(`git -c gc.auto=0`). fetch가 띄운 gc는 뒤에서 계속 돌다가 만드는 중인 worktree를 읽으면 `fatal: bad object`로 실패하고, `.git/gc.log`를 남겨 하루 동안 자동 gc를 막는다. 손으로 할 때도 같다. 무시 규칙(`.gitignore`, `.git/info/exclude`) 밖의 미추적 파일이 있으면 아무것도 보내지 않고 그 이름을 찍고 멈춘다(rc=5). 보낼 것이면 `git add`하거나 `--include-untracked`를 주고, 보내지 않을 것이면 지우거나 `.git/info/exclude`에 적는다. 노트북 stderr 첫 줄은 보낸 트리가 HEAD 트리와 같은지 말한다. 원격 로그는 첫 줄에 보낸 트리와 기준 커밋의 전체 해시, 둘째 줄에 부하가 있다. 단계와 돌리는 명령은 [reference/gates.md](reference/gates.md) 1절이다. 아래는 스크립트가 하는 일이고, 스크립트를 쓸 수 없을 때(다른 기준 커밋, 단계 밖의 명령 하나) 손으로 한다. +**`scripts/verify.sh`가 아래 절차를 한다.** `scripts/verify.sh <단계>`는 지금 작업 트리(커밋하지 않은 변경 포함)를 패치로 만들어 desktop에 보내고, 기준 커밋에서 새 worktree를 만들어 얹고, 트리 해시가 같은지 본 뒤 잠금 아래에서 단계를 돌리고, 로그를 `~/<브랜치 이름>-logs/<단계>.log`에 남기고, worktree를 지운다. 준비(fetch, worktree 만들기, 패치 얹기)가 실패해 rc=4로 끝나도 보낸 패치와 임시 폴더를 지운다. push하지 않는다. fetch와 worktree add도 잠금 안에서 하고, fetch가 띄운 자동 gc는 fetch 안에서 끝낸다(`git -c gc.autoDetach=false fetch`). 자동 gc는 기본으로 fetch가 돌아온 뒤에도 뒤에서 돌며 모든 worktree의 HEAD를 읽는다. 그러다 만드는 중인 worktree를 만나면 `fatal: bad object`로 실패하고, `.git/gc.log`를 남겨 하루 동안 자동 gc를 막는다. 그래서 겹친 실행은 fetch부터 잠금을 기다리고, 트리 해시가 다르다는 것도 잠금을 얻은 뒤에 안다. 손으로 할 때도 아래 절차처럼 같은 잠금을 쓴다. 무시 규칙(`.gitignore`, `.git/info/exclude`) 밖의 미추적 파일이 있으면 아무것도 보내지 않고 그 이름을 찍고 멈춘다(rc=5). 보낼 것이면 `git add`하거나 `--include-untracked`를 주고, 보내지 않을 것이면 지우거나 `.git/info/exclude`에 적는다. 노트북 stderr 첫 줄은 보낸 트리가 HEAD 트리와 같은지 말한다. 원격 로그는 첫 줄에 보낸 트리와 기준 커밋의 전체 해시, 둘째 줄에 부하가 있다. 단계와 돌리는 명령은 [reference/gates.md](reference/gates.md) 1절이다. 아래는 스크립트가 하는 일이고, 스크립트를 쓸 수 없을 때(다른 기준 커밋, 단계 밖의 명령 하나) 손으로 한다. 절차: @@ -45,11 +45,11 @@ # 1) 노트북: 검증할 변경을 자기 브랜치에 커밋하고 push한다(brief가 허용한 경우) git push origin <자기 브랜치> -# 2) desktop: 기존 checkout을 건드리지 않게 따로 worktree를 만든다 +# 2) desktop: 기존 checkout을 건드리지 않게 따로 worktree를 만든다(verify.sh처럼 잠금 안에서, gc는 fetch 안에서 끝낸다) ssh desktop cd ~/workspace/clean-architecture-backend-template -git -c gc.auto=0 fetch origin -git -c gc.auto=0 worktree add ~/workspace/<작업 이름> origin/<자기 브랜치> +flock /tmp/claude-gates/heavy.lock git -c gc.autoDetach=false fetch origin +flock /tmp/claude-gates/heavy.lock git worktree add ~/workspace/<작업 이름> origin/<자기 브랜치> mkdir -p ~/<작업 이름>-logs uptime # 다른 빌드가 돌고 있는지 부하를 본다 @@ -73,8 +73,8 @@ git worktree remove ~/workspace/<작업 이름> ```bash # 노트북: 커밋할 파일만 stage하고(git status로 확인) 트리 해시를 적어 둔다 git add <바꾼 파일>... && git status --short && git write-tree -# desktop: 기준 커밋(push된 커밋)에서 worktree를 만든다 -ssh desktop 'cd ~/workspace/clean-architecture-backend-template && git -c gc.auto=0 fetch origin && git -c gc.auto=0 worktree add --detach ~/workspace/<작업 이름> <기준 커밋>' +# desktop: 기준 커밋(push된 커밋)에서 worktree를 만든다(위 2)처럼 잠금 안에서) +ssh desktop 'cd ~/workspace/clean-architecture-backend-template && flock /tmp/claude-gates/heavy.lock git -c gc.autoDetach=false fetch origin && flock /tmp/claude-gates/heavy.lock git worktree add --detach ~/workspace/<작업 이름> <기준 커밋>' # 노트북: 패치를 보내 얹는다. 마지막 줄이 위 트리 해시와 같아야 한다 git diff --cached --binary <기준 커밋> | ssh desktop 'cd ~/workspace/<작업 이름> && git apply --index && git write-tree' ``` diff --git a/scripts/tests/test_verify_remote.py b/scripts/tests/test_verify_remote.py index f6facd46..96286de8 100644 --- a/scripts/tests/test_verify_remote.py +++ b/scripts/tests/test_verify_remote.py @@ -9,12 +9,13 @@ ssh는 가짜다. 패치를 받는 호출(`cat > /tmp/.patch`)이면 받은 RemoteLogTest의 ssh는 받은 명령을 이 머신에서 그대로 돌린다(HOME과 잠금 파일은 임시 경로). 원격 스크립트가 시험 repo의 clone에서 worktree를 만들고 잠금 아래에서 단계를 돌린다. 단계의 Gradle은 받은 인자를 찍는 가짜 `gradlew`다. 원격 로그의 첫 줄이 보낸 트리와 기준의 전체 해시를 적는지, 다른 프로세스가 잠금을 쥔 동안 지난 로그와 클래스 목록이 -그대로인지, 기다리다 client가 끊겼거나 잠금을 얻지 못한 실행이 그것을 바꾸지 않는지, 단계와 합계가 배타 잠금 안에서 -도는지, 단계의 rc가 그대로 나가는지, 단계가 stdin을 읽어도 합계·rc 줄과 그 rc로 끝나는지 본다. 잠금 대기는 Linux -`/proc/locks`의 대기 줄(`->`)로 안다. 원격 준비(checkout으로 cd, fetch, worktree add, 패치 얹기)가 실패해도, 실행이 -통과해도 /tmp에 보낸 패치와 worktree 폴더가 남지 않는지, fetch와 worktree add가 자동 gc를 끈 채(또는 잠금 안에서) -도는지도 본다. 두 가지는 원격 쪽 git을 가짜(FAKE_GIT)로 바꿔 본다: 가짜는 fetch·worktree add마다 그 명령이 보는 -gc.auto와 잠금 상태를 적고, 패치 얹기를 실패시킬 수 있고, 나머지는 진짜 git에 넘긴다. +그대로인지, 잠금을 기다리거나 잠금 안에서 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 """ @@ -233,10 +234,11 @@ 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 that call runs with (its -c options and the environment count) and whether the lock is -# held exclusively. The subcommand named in FAKE_GIT_FAILS fails instead. +# 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 +import os, subprocess, sys, time REAL = {real!r} args = sys.argv[1:] i = 0 @@ -244,12 +246,19 @@ 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"]): - gc_auto = subprocess.run([REAL, *args[:i], "config", "--get", "gc.auto"], capture_output=True, text=True) + 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(" ".join(command) + "\\tgc.auto=" + (gc_auto.stdout.strip() or "-") + - "\\tlock " + ("held" if held else "free") + "\\n") + 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]) @@ -594,21 +603,56 @@ class RemoteLogTest(ThrowawayRepoTest): # then self.assertEqual((result.returncode, left, self.worktrees()), (0, [], 1), result.stderr) - def test_the_fetch_and_the_worktree_add_run_without_auto_gc_or_under_the_lock(self) -> None: - """REV-BE-0065. Auto gc that a fetch starts runs on in the background and 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.""" - # given - calls = self.use_the_git_stand_in() + # 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. - # when + 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(0, result.returncode, result.stderr) - seen = [line.split("\t") for line in calls.read_text(encoding="utf-8").splitlines()] - self.assertEqual([(command, gc_auto == "gc.auto=0" or lock == "lock held") for command, gc_auto, lock in seen], - [("fetch", True), ("worktree add", True)], seen) + 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__": diff --git a/scripts/verify.sh b/scripts/verify.sh index b9b73c84..b9299429 100755 --- a/scripts/verify.sh +++ b/scripts/verify.sh @@ -17,9 +17,10 @@ # workflow에서만 돈다. # # --on <호스트>: 지금 작업 트리(커밋 안 된 변경 포함)를 패치로 그 호스트에 옮긴다. 기준 커밋에서 새 worktree를 -# 만들어 패치를 적용하고, 트리 해시가 여기와 같은지 본 뒤 잠금 아래에서 같은 단계를 돌리고 worktree를 지운다. +# 만들어 패치를 적용하고, 트리 해시가 여기와 같은지 본 뒤 같은 단계를 돌리고 worktree를 지운다. fetch부터 끝까지 +# 잠금 아래다. fetch가 띄운 자동 gc는 fetch 안에서 끝낸다(gc.autoDetach=false). 뒤에서 도는 gc가 만드는 중인 +# worktree를 읽고 실패하지 않게 하려는 것이다. 그래서 트리가 다르다는 것도 잠금을 얻은 뒤에 안다. # 준비(cd, fetch, worktree, 패치)가 실패해 rc 4로 끝나도 원격 /tmp에 보낸 패치와 임시 폴더를 남기지 않는다. -# 잠금 밖인 fetch와 worktree add는 자동 gc를 끄고 돈다(gc가 만드는 중인 worktree를 읽고 실패하지 않게). # push하지 않는다. 기준 커밋은 원격 checkout이 fetch로 받을 수 있어야 한다(기본: origin/main과 갈라진 곳). # docs 밖의 단계는 기본이 desktop이다. desktop에서 직접 돌릴 때는 --on here. # 보내는 것은 추적 파일의 변경과 stage한 새 파일이다. 무시 규칙(.gitignore, .git/info/exclude) 밖의 미추적 파일이 @@ -174,17 +175,6 @@ cleanup() { trap cleanup EXIT trap 'exit 4' PIPE # 끊긴 client에 쓰다 죽어도 위 정리를 하고 끝난다 cd $remote_repo || exit 4 -# 잠금 밖이라 자동 gc를 끈다. fetch가 띄운 gc는 뒤에서 계속 돌며 모든 worktree의 HEAD를 읽는데, 만드는 중인 것(이 -# 실행이나 겹친 실행의 worktree add)을 만나면 'fatal: bad object'로 실패하고 .git/gc.log를 남겨 하루 동안 자동 gc를 -# 막고 실행마다 같은 경고를 찍는다. -git -c gc.auto=0 fetch -q origin || exit 4 -wt=\$(mktemp -d /tmp/$id.XXXXXX) || exit 4 -git -c gc.auto=0 worktree add -q --detach "\$wt" $base || exit 4 -added=1 -cd "\$wt" -if [ -s /tmp/$id.patch ]; then git apply --binary --index /tmp/$id.patch || exit 4; fi -got=\$(git write-tree) -if [ "\$got" != "$tree" ]; then echo "트리 해시가 다르다: 원격 \$got, 여기 $tree" >&2; exit 4; fi mkdir -p "\$(dirname $LOCK)" ~/$log-logs # 로그와 클래스 목록은 잠금을 얻은 뒤에야 바꾼다. 다른 세션이 잠금을 쥔 동안 기다리는 실행이 지난 실행의 증거를 # 비우지 않는다. fd 9가 스크립트 끝(합계·rc 줄)까지 잠금을 쥐고, 안쪽 verify.sh는 VERIFY_LOCKED로 다시 잡지 않는다. @@ -193,7 +183,18 @@ if ! flock -n 9; then echo "verify: 다른 실행이 잠금 $LOCK을 쥐고 있어 기다린다. 지난 로그는 잠금을 얻을 때까지 그대로다." >&2 flock 9 || exit 4 fi -# 기다리는 동안 client(ssh)가 끊겼으면 이 쓰기가 실패해, 지난 증거를 바꾸기 전에 끝난다. +# fetch와 worktree add도 잠금 안에서 한다. fetch가 띄운 자동 gc는 모든 worktree의 HEAD를 읽는데, 만드는 중인 +# worktree(HEAD가 아직 빈 값)를 만나면 'fatal: bad object'로 실패하고 .git/gc.log를 남겨 하루 동안 자동 gc를 막는다. +# 자동 gc는 기본으로 fetch가 돌아온 뒤에도 뒤에서 돌아 바로 아래 worktree add와 겹치므로 fetch 안에서 끝낸다. +git -c gc.autoDetach=false fetch -q origin || exit 4 +wt=\$(mktemp -d /tmp/$id.XXXXXX) || exit 4 +git worktree add -q --detach "\$wt" $base || exit 4 +added=1 +cd "\$wt" +if [ -s /tmp/$id.patch ]; then git apply --binary --index /tmp/$id.patch || exit 4; fi +got=\$(git write-tree) +if [ "\$got" != "$tree" ]; then echo "트리 해시가 다르다: 원격 \$got, 여기 $tree" >&2; exit 4; fi +# 기다리거나 준비하는 동안 client(ssh)가 끊겼으면 이 쓰기가 실패해, 지난 증거를 바꾸기 전에 끝난다. echo "verify: 잠금을 얻었다" >&2 || exit 4 rm -f ~/$log-logs/$stage-classes.tsv # 단계가 합계 전에 끊겨도 지난 실행의 목록이 새 로그 옆에 남지 않는다 # 첫 줄은 이 로그가 어느 트리·기준의 실행인지, 둘째 줄은 단계 직전 부하다. -- 2.54.0