diff --git a/.gitignore b/.gitignore index e05d587e..03f335a6 100644 --- a/.gitignore +++ b/.gitignore @@ -20,6 +20,22 @@ 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. 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 +!**/.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 +44,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/docs/work/operate.md b/docs/work/operate.md index 9f17881b..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를 지운다. 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도 잠금 안에서 하고, 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 fetch origin -git 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 fetch origin && git 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/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..e4455bd7 100644 --- a/scripts/tests/test_check_docs.py +++ b/scripts/tests/test_check_docs.py @@ -362,6 +362,26 @@ 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`, `compose/.env.d/app.conf`, " + "`src/x/build/out.txt`를 읽는다.\n") + + # 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", + ]) + 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", diff --git a/scripts/tests/test_verify_remote.py b/scripts/tests/test_verify_remote.py index 0b8e6799..96286de8 100644 --- a/scripts/tests/test_verify_remote.py +++ b/scripts/tests/test_verify_remote.py @@ -9,9 +9,13 @@ ssh는 가짜다. 패치를 받는 호출(`cat > /tmp/.patch`)이면 받은 RemoteLogTest의 ssh는 받은 명령을 이 머신에서 그대로 돌린다(HOME과 잠금 파일은 임시 경로). 원격 스크립트가 시험 repo의 clone에서 worktree를 만들고 잠금 아래에서 단계를 돌린다. 단계의 Gradle은 받은 인자를 찍는 가짜 `gradlew`다. 원격 로그의 첫 줄이 보낸 트리와 기준의 전체 해시를 적는지, 다른 프로세스가 잠금을 쥔 동안 지난 로그와 클래스 목록이 -그대로인지, 기다리다 client가 끊겼거나 잠금을 얻지 못한 실행이 그것을 바꾸지 않는지, 단계와 합계가 배타 잠금 안에서 -도는지, 단계의 rc가 그대로 나가는지, 단계가 stdin을 읽어도 합계·rc 줄과 그 rc로 끝나는지 본다. 잠금 대기는 Linux -`/proc/locks`의 대기 줄(`->`)로 안다. +그대로인지, 잠금을 기다리거나 잠금 안에서 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 """ @@ -229,6 +233,37 @@ 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 @@ -268,7 +303,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 +553,107 @@ 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) + + # 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() diff --git a/scripts/verify.sh b/scripts/verify.sh index 83fc77d3..b9299429 100755 --- a/scripts/verify.sh +++ b/scripts/verify.sh @@ -17,7 +17,10 @@ # workflow에서만 돈다. # # --on <호스트>: 지금 작업 트리(커밋 안 된 변경 포함)를 패치로 그 호스트에 옮긴다. 기준 커밋에서 새 worktree를 -# 만들어 패치를 적용하고, 트리 해시가 여기와 같은지 본 뒤 잠금 아래에서 같은 단계를 돌리고 worktree를 지운다. +# 만들어 패치를 적용하고, 트리 해시가 여기와 같은지 본 뒤 같은 단계를 돌리고 worktree를 지운다. fetch부터 끝까지 +# 잠금 아래다. fetch가 띄운 자동 gc는 fetch 안에서 끝낸다(gc.autoDetach=false). 뒤에서 도는 gc가 만드는 중인 +# worktree를 읽고 실패하지 않게 하려는 것이다. 그래서 트리가 다르다는 것도 잠금을 얻은 뒤에 안다. +# 준비(cd, fetch, worktree, 패치)가 실패해 rc 4로 끝나도 원격 /tmp에 보낸 패치와 임시 폴더를 남기지 않는다. # push하지 않는다. 기준 커밋은 원격 checkout이 fetch로 받을 수 있어야 한다(기본: origin/main과 갈라진 곳). # docs 밖의 단계는 기본이 desktop이다. desktop에서 직접 돌릴 때는 --on here. # 보내는 것은 추적 파일의 변경과 stage한 새 파일이다. 무시 규칙(.gitignore, .git/info/exclude) 밖의 미추적 파일이 @@ -158,19 +161,20 @@ 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 <&2; exit 4; fi +cd $remote_repo || exit 4 mkdir -p "\$(dirname $LOCK)" ~/$log-logs # 로그와 클래스 목록은 잠금을 얻은 뒤에야 바꾼다. 다른 세션이 잠금을 쥔 동안 기다리는 실행이 지난 실행의 증거를 # 비우지 않는다. fd 9가 스크립트 끝(합계·rc 줄)까지 잠금을 쥐고, 안쪽 verify.sh는 VERIFY_LOCKED로 다시 잡지 않는다. @@ -179,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 # 단계가 합계 전에 끊겨도 지난 실행의 목록이 새 로그 옆에 남지 않는다 # 첫 줄은 이 로그가 어느 트리·기준의 실행인지, 둘째 줄은 단계 직전 부하다.