diff options
| author | Mohamed Hegazy <8000722+mhegazy@users.noreply.github.com> | 2026-10-07 11:17:50 -0700 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-10-07 11:17:50 -0700 |
| commit | b78ac49cdc6b3d7b61c4439470e311f4291265b1 (patch) | |
| tree | 14d356cb690f1950937933fa421cce39ba942026 /plugins | |
| parent | 054417d0fc687dd7d639331f21522d0e06c09cf9 (diff) | |
| parent | f711194a9ecdf004b655dbc5006610fbb9e7c7bb (diff) | |
Merge pull request #6374 from anthropics/mhegazy/sg-reclaim-after-hook-kill
security-guidance: stop killed hooks from filling the disk (2.0.11)
Diffstat (limited to 'plugins')
5 files changed, 550 insertions, 36 deletions
diff --git a/plugins/security-guidance/.claude-plugin/plugin.json b/plugins/security-guidance/.claude-plugin/plugin.json index 6ee520df..921a63b7 100644 --- a/plugins/security-guidance/.claude-plugin/plugin.json +++ b/plugins/security-guidance/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "security-guidance", - "version": "2.0.10", + "version": "2.0.11", "description": "Security review for Claude-generated code. Pattern-based warnings on edits, LLM-powered diff review on Stop, and an agentic commit reviewer that catches injection, XSS, SSRF, hardcoded secrets, and 25+ other vulnerability classes.", "author": { "name": "David Dworken", diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py index 726f2ba1..2036b45e 100644 --- a/plugins/security-guidance/hooks/gitutil.py +++ b/plugins/security-guidance/hooks/gitutil.py @@ -37,6 +37,10 @@ GIT_CMD = [ # reflog %gs subjects, ls-files, status, etc. — without per-site # flag duplication. See #2082, #2099. "-c", "core.quotePath=false", + # A work-tree `git diff` that meets stat-stale entries (mtime changed, + # content same) rewrites the index under index.lock, GIT_OPTIONAL_LOCKS or + # not. Off, every diff here only reads the index, so none needs a copy. + "-c", "diff.autoRefreshIndex=false", ] SAFE_GIT_CONFIG = ( @@ -140,6 +144,10 @@ def _diff_pathspec(cwd, paths): _TEMP_INDEX_PREFIX = "security_hook_idx_" +# A copy is named <prefix>pid<hook pid>_<8 random chars>, so a later run can +# tell that the hook which made it is gone. Names from earlier releases have +# only the 8 random characters and never match. +_OWNER_PID = re.compile(re.escape(_TEMP_INDEX_PREFIX) + r"pid(\d+)_[^.]{8}(?:\.|$)") # A live copy is in use for under a minute (a couple of bounded git calls), so # anything this old belongs to a run that was killed. _TEMP_INDEX_STALE_S = 1800 @@ -148,10 +156,32 @@ _TEMP_INDEX_STALE_S = 1800 _SWEEP_BUDGET_S = 2 +def _owner_is_gone(name): + """True when `name` records the pid of the hook that made it and no such + process exists. A reused pid reads as alive: the file then waits for the + age limit. Never probes on Windows, where os.kill would end the process.""" + if not hasattr(os, "getuid"): + return False + m = _OWNER_PID.match(name) + if not m: + return False + try: + os.kill(int(m.group(1)), 0) + except ProcessLookupError: + return True + except (OSError, OverflowError, ValueError): + return False + return False + + def _sweep_stale_indexes(dirpath, uid): """Delete index copies in `dirpath` that a killed run left behind. Only regular files owned by `uid` (None: no ownership check) are touched. + A copy goes as soon as the hook that made it is gone: a killed hook can + leave one per run, and index-sized files fill a disk long before the age + limit. The age limit covers names without a pid and reused pids. + Age is the newer of mtime and ctime: a copy keeps .git/index's mtime, which may be days old, so mtime alone would delete a file that another running hook is still using.""" @@ -173,6 +203,41 @@ def _sweep_stale_indexes(dirpath, uid): continue if uid is not None and st.st_uid != uid: continue + if max(st.st_mtime, st.st_ctime) < cutoff or _owner_is_gone(name): + os.unlink(p) + if time.monotonic() > deadline: + return + except OSError: + pass + + +def _sweep_stale_stash_indexes(real_index): + """Delete `<index>.stash.<pid>` files a killed `git stash create` left + next to the real index. Releases before 2.0.10 ran it there, so a clone + can hold hundreds, each the size of the index, and nothing else removes + them. Only our own regular files past the age limit go: git keeps one for + seconds. `index.lock` is never touched; a live git may hold it.""" + import stat + import time + uid = os.getuid() if hasattr(os, "getuid") else None + cutoff = time.time() - _TEMP_INDEX_STALE_S + deadline = time.monotonic() + _SWEEP_BUDGET_S + dirpath = os.path.dirname(real_index) + stale = re.compile(re.escape(os.path.basename(real_index)) + r"\.stash\.\d+$") + try: + names = os.listdir(dirpath) + except OSError: + return + for name in names: + if not stale.match(name): + continue + p = os.path.join(dirpath, name) + try: + st = os.lstat(p) + if not stat.S_ISREG(st.st_mode): + continue + if uid is not None and st.st_uid != uid: + continue if max(st.st_mtime, st.st_ctime) < cutoff: os.unlink(p) if time.monotonic() > deadline: @@ -181,6 +246,95 @@ def _sweep_stale_indexes(dirpath, uid): pass +# Index copies this process has made and not yet removed. +_live_copies = set() + +# A hook working on a copy needs up to three times the index's size for a +# moment (the copy, and git's rewrite and stash index next to it). With many +# agents in one clone that alone can fill a disk, so only so many hooks per +# user work on a copy at once; the others wait, then go without. +_MAX_LIVE_COPIES = 8 +_SLOT_WAIT_S = 5 + + +def _copy_slots(tmpdir, index_bytes): + """How many hooks may work on a copy at once: what fits into a quarter of + the free space at three times the index each, from 1 to + _MAX_LIVE_COPIES.""" + import shutil + try: + free = shutil.disk_usage(tmpdir).free + except OSError: + return 1 + return max(1, min(_MAX_LIVE_COPIES, free // (12 * max(index_bytes, 1)))) + + +@contextlib.contextmanager +def _copy_slot(tmpdir, index_bytes=0): + """Hold one of the copy slots; yields False when none came free in + _SLOT_WAIT_S. A slot is an flock, so the kernel frees it when its holder + dies, however it dies. No cap without flock or a private dir.""" + import time + try: + import fcntl + except ImportError: + fcntl = None + if fcntl is None or tmpdir is None: + yield True + return + deadline = time.monotonic() + _SLOT_WAIT_S + held = None + while held is None: + for i in range(_copy_slots(tmpdir, index_bytes)): + try: + fd = os.open(os.path.join(tmpdir, f"slot{i}.lock"), + os.O_RDWR | os.O_CREAT, 0o600) + except OSError: + continue + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + held = fd + break + except OSError: + os.close(fd) + if held is None: + if time.monotonic() >= deadline: + break + time.sleep(0.1) + try: + yield held is not None + finally: + if held is not None: + os.close(held) + + +def _remove_copy(tmp_index): + """Remove an index copy and the files git wrote next to it.""" + import glob + for p in glob.glob(glob.escape(tmp_index) + "*"): + try: + os.unlink(p) + except OSError: + pass + + +def remove_copies_on_termination(): + """Remove this process's index copies when it is told to terminate. + Python's default SIGTERM action ends the process without running + `finally`, which left an index-sized file behind each time.""" + import signal + + def _on_term(signum, _frame): + for tmp_index in list(_live_copies): + _remove_copy(tmp_index) + os._exit(128 + signum) + + try: + signal.signal(signal.SIGTERM, _on_term) + except (ValueError, OSError, AttributeError): + pass # not the main thread, or no SIGTERM here + + def _hook_tmpdir(): """Private per-user directory for throwaway index copies, or None to use the bare temp dir. @@ -223,8 +377,9 @@ def _temp_index(cwd, untracked_paths=None): """Yield an env dict pointing GIT_INDEX_FILE at a throwaway copy of the repo's index with `git add --intent-to-add` applied, so untracked files show up in subsequent `git diff` calls without touching the user's real - index. Yields None if no index can be found (bare repo / not a repo); the - caller should fall back to a plain diff. Always cleans up the temp file. + index. Yields None if no index can be found (bare repo / not a repo) or + no copy slot came free; the caller should fall back to a plain diff. + Always cleans up the temp file. Perf: when `untracked_paths` is given, only those paths are added (O(n) in untracked count). The default `add -N .` stats every file in the @@ -235,24 +390,48 @@ def _temp_index(cwd, untracked_paths=None): Cleanup removes `<tmp_index>*`, not just the copy: git writes `<index>.lock` and `<index>.stash.<pid>` next to the index it is given and cannot remove them itself when a subprocess timeout kills it.""" - import glob - import shutil - import tempfile - real_index = _find_git_index(cwd) if not real_index: yield None return - tmp_fd, tmp_index = tempfile.mkstemp(prefix=_TEMP_INDEX_PREFIX, - dir=_hook_tmpdir()) + _sweep_stale_stash_indexes(real_index) + tmpdir = _hook_tmpdir() + try: + index_bytes = os.path.getsize(real_index) + except OSError: + index_bytes = 0 + with _copy_slot(tmpdir, index_bytes) as got_slot: + if not got_slot: + debug_log("no index copy slot came free; going without a copy") + yield None + return + with _copied_index(cwd, real_index, tmpdir, untracked_paths) as env: + yield env + + +@contextlib.contextmanager +def _copied_index(cwd, real_index, tmpdir, untracked_paths): + import shutil + import tempfile + + tmp_fd, tmp_index = tempfile.mkstemp( + prefix=f"{_TEMP_INDEX_PREFIX}pid{os.getpid()}_", dir=tmpdir) os.close(tmp_fd) + _live_copies.add(tmp_index) try: - # copy2, not copyfile: the copy must keep .git/index's mtime. Git - # re-reads any file whose mtime is not older than the index file's; - # with a fresh mtime it would miss a same-size edit made in the same - # second as the last index write. - shutil.copy2(real_index, tmp_index) + # A hard link where the filesystem allows it: no bytes are copied, and + # git never writes an index in place (it renames a new file over it), + # so the real index cannot change through the link. Either way the + # copy must keep .git/index's mtime (copy2, not copyfile): git + # re-reads any file whose mtime is not older than the index file's, + # and with a fresh mtime it would miss a same-size edit made in the + # same second as the last index write. + try: + os.unlink(tmp_index) + os.link(real_index, tmp_index) + except (OSError, NotImplementedError, AttributeError): + shutil.copy2(real_index, tmp_index) env = {**os.environ, "GIT_INDEX_FILE": tmp_index} if untracked_paths is None: add_args = ["."] @@ -279,11 +458,8 @@ def _temp_index(cwd, untracked_paths=None): ) yield env finally: - for p in glob.glob(glob.escape(tmp_index) + "*"): - try: - os.unlink(p) - except OSError: - pass + _remove_copy(tmp_index) + _live_copies.discard(tmp_index) def _git_toplevel(cwd): @@ -476,7 +652,11 @@ def _git_name_only(cwd, base, include_untracked=False): or None if git failed (unresolvable ref, not a repo, timeout). Callers must distinguish None (error → don't trust as a filter) from set() (genuinely nothing changed). `-c core.quotePath=false -z` keeps non-ASCII - and space-containing paths intact.""" + and space-containing paths intact. + + Against the work tree the set can also hold a file whose stat changed and + whose content did not: the diff does not refresh the index. Callers + intersect with `git status`, which compares content.""" # Decode stdout/stderr as UTF-8 with errors="replace" instead of using # text=True. core.quotePath=false makes git emit raw UTF-8 for non-ASCII # paths, and text=True on Windows decodes via cp1252 strict — a non-ASCII @@ -498,12 +678,11 @@ def _git_name_only(cwd, base, include_untracked=False): return {p for p in stdout.split("\0") if p} try: - # A work-tree diff rewrites the index under <index>.lock when entries - # are stat-stale (mtime changed, content same), GIT_OPTIONAL_LOCKS or - # not, so it runs on a throwaway copy; an a..b range never opens it. - if not include_untracked and ".." in base: + # The diff only reads the index (diff.autoRefreshIndex is off in + # GIT_CMD); a copy is for `add -N` alone. + if not include_untracked: return _run(None) - with _temp_index(cwd, None if include_untracked else []) as env: + with _temp_index(cwd) as env: return _run(env) except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e: debug_log(f"_git_name_only({base!r}) error: {e}") @@ -607,10 +786,15 @@ def get_git_diff(cwd, baseline_sha, full_context=False, paths=None, untracked_pa # core.quotePath=false comes from GIT_CMD globally (see definition). cmd = [*GIT_CMD, "diff", "--no-color", "--no-ext-diff", "--no-textconv", baseline_sha] + (["--unified=99999"] if full_context else []) + pathspec try: - with _temp_index(cwd, untracked_paths) as env: - # env is None when no index could be found (bare repo / not a - # repo) — diff still runs, just without untracked-file support. - result = subprocess.run(cmd, cwd=cwd, capture_output=True, timeout=30, env=env) + if untracked_paths is not None and not untracked_paths: + # Nothing to `add -N`, and the diff only reads the index. + result = subprocess.run(cmd, cwd=cwd, capture_output=True, timeout=30) + else: + with _temp_index(cwd, untracked_paths) as env: + # env is None when there is no index (bare repo / not a repo) + # or no copy slot — diff still runs, just without + # untracked-file support. + result = subprocess.run(cmd, cwd=cwd, capture_output=True, timeout=30, env=env) if result.returncode != 0: debug_log(f"git diff failed: {result.stderr[:200].decode('utf-8', errors='replace')}") return None diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index 00f9d5d6..e8df7a1c 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -97,7 +97,7 @@ from session_state import ( # noqa: E402,F401 load_state, save_state, with_locked_state, ) from gitutil import ( # noqa: E402,F401 - GIT_CMD, apply_safe_git_env, + GIT_CMD, apply_safe_git_env, remove_copies_on_termination, _git_rev_parse_head, _find_git_index, _diff_pathspec, _temp_index, _git_toplevel, _git_dir, _git_rev_list_range, _git_diff_range, _detect_main_branch, _git_reflog_recent_commits, _git_name_only, @@ -2253,6 +2253,7 @@ def main(): """Main hook function.""" debug_log(f"Hook called with args: {sys.argv}") apply_safe_git_env() + remove_copies_on_termination() # Master kill switch — honors ENABLE_SECURITY_REMINDER=0 (legacy) and # SECURITY_GUIDANCE_DISABLE=1 (clearer name, no double negative). Emit diff --git a/plugins/security-guidance/tests/test_git_index_locks.py b/plugins/security-guidance/tests/test_git_index_locks.py index e35855d0..17a877ff 100644 --- a/plugins/security-guidance/tests/test_git_index_locks.py +++ b/plugins/security-guidance/tests/test_git_index_locks.py @@ -30,9 +30,11 @@ def tmproot(tmp_path, monkeypatch): def _leftovers(root): + """Everything left under `root` but the slot files, which stay.""" return sorted( os.path.join(dirpath, f) for dirpath, _, files in os.walk(root) for f in files + if not (f.startswith("slot") and f.endswith(".lock")) ) @@ -43,6 +45,10 @@ def _index_copies_left(root): if os.path.basename(p).startswith(gitutil._TEMP_INDEX_PREFIX)] +def _leftovers_of_copies(root): + return _index_copies_left(root) + + def _index_litter(git_dir): return sorted(n for n in os.listdir(git_dir) if n.startswith("index") and n != "index") @@ -194,21 +200,44 @@ class TestReadOnlyGitLeavesTheRealIndexAlone: (repo / "b.py").write_text("b = 2\n") _make_stat_stale(repo / "app.py") before = _index_sig(repo / ".git") + head = git(repo, "rev-parse", "HEAD").strip() gitutil.apply_safe_git_env() - assert gitutil._git_name_only(str(repo), "HEAD") == {"b.py"} + # app.py: stat changed, content did not. The name list may hold it, + # the review set must not. + assert "b.py" in gitutil._git_name_only(str(repo), "HEAD") + paths, _, _, _, _ = diffstate.compute_v2_review_set(str(repo), head, head) + assert paths == [os.path.join(os.path.realpath(repo), "b.py")] assert _index_sig(repo / ".git") == before assert _leftovers(tmproot) == [] - def test_range_diff_needs_no_index_copy(self, tmp_path, tmproot, monkeypatch): - repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) + def test_diffs_need_no_index_copy(self, tmp_path, tmproot, monkeypatch): + """Every copy is index-sized, so only `add -N` and stash get one.""" + repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n", "b.py": "b = 1\n"}) first = git(repo, "rev-parse", "HEAD").strip() commit_file(repo, "app.py", "x = 2\n") + (repo / "b.py").write_text("b = 2\n") + _make_stat_stale(repo / "app.py") + before = _index_sig(repo / ".git") def no_copy(*a, **kw): - raise AssertionError("range diff copied the index") + raise AssertionError("copied the index") monkeypatch.setattr(gitutil, "_temp_index", no_copy) assert gitutil._git_name_only(str(repo), f"{first}..HEAD") == {"app.py"} + assert "b.py" in gitutil._git_name_only(str(repo), "HEAD") + diff = gitutil.get_git_diff(str(repo), "HEAD", untracked_paths=[]) + assert "+b = 2" in diff and "app.py" not in diff + assert _index_sig(repo / ".git") == before + + def test_untracked_files_still_reach_the_diff(self, tmp_path, tmproot): + repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) + (repo / "new.py").write_text("n = 1\n") + before = _index_sig(repo / ".git") + diff = gitutil.get_git_diff(str(repo), "HEAD", untracked_paths=["new.py"]) + assert "+n = 1" in diff + assert gitutil._git_name_only(str(repo), "HEAD", include_untracked=True) == {"new.py"} + assert _index_sig(repo / ".git") == before + assert _leftovers_of_copies(tmproot) == [] @pytest.mark.skipif(os.name == "nt", reason="uses a /bin/sh git shim") @@ -267,8 +296,7 @@ class TestWholeHook: assert {"stash", "status", "diff", "add"} <= {sub[0] for _, _, sub in calls} assert [c for c in calls if c[0] != "0"] == [] for _, index_file, sub in calls: - if sub[0] in ("stash", "add") or ( - sub[0] == "diff" and not any(".." in a for a in sub)): + if sub[0] in ("stash", "add"): assert index_file.startswith(str(tmproot)), sub assert _index_sig(repo / ".git") == before assert _index_litter(repo / ".git") == [] diff --git a/plugins/security-guidance/tests/test_temp_index_cleanup.py b/plugins/security-guidance/tests/test_temp_index_cleanup.py index f85a0bb2..4ac19ea5 100644 --- a/plugins/security-guidance/tests/test_temp_index_cleanup.py +++ b/plugins/security-guidance/tests/test_temp_index_cleanup.py @@ -24,9 +24,11 @@ def tmproot(tmp_path, monkeypatch): def _leftovers(root): + """Everything left under `root` but the slot files, which stay.""" return sorted( os.path.join(dirpath, f) for dirpath, _, files in os.walk(root) for f in files + if not (f.startswith("slot") and f.endswith(".lock")) ) @@ -164,3 +166,302 @@ class TestPrivateDir: with gitutil._temp_index(str(repo), untracked_paths=[]) as env: assert os.path.dirname(env["GIT_INDEX_FILE"]) == str(tmproot) assert _leftovers(tmproot) == [] + + +def _dead_pid(): + import subprocess + import sys + p = subprocess.Popen([sys.executable, "-c", "pass"]) + p.wait() + return p.pid + + +class TestOwnerGone: + @posix_only + def test_copy_name_carries_the_hook_pid(self, tmp_path, tmproot): + repo = make_repo(tmp_path / "repo") + with gitutil._temp_index(str(repo), untracked_paths=[]) as env: + name = os.path.basename(env["GIT_INDEX_FILE"]) + assert name.startswith(f"security_hook_idx_pid{os.getpid()}_") + assert not gitutil._owner_is_gone(name) + assert not gitutil._owner_is_gone(name + ".lock") + + @posix_only + def test_fresh_copies_of_a_dead_hook_go_at_once(self, tmproot): + private = gitutil._hook_tmpdir() + dead = f"security_hook_idx_pid{_dead_pid()}_abcdefgh" + gone = [_write(os.path.join(d, dead + suffix)) + for d in (private, str(tmproot)) + for suffix in ("", ".lock", ".stash.77")] + keep = [ + _write(os.path.join(private, f"security_hook_idx_pid{os.getpid()}_abcdefgh")), + # Earlier releases: 8 random characters, which may look like a pid. + _write(os.path.join(private, "security_hook_idx_pid1_abc")), + _write(os.path.join(private, "security_hook_idx_12345678")), + _write(os.path.join(str(tmproot), f"unrelated_pid{_dead_pid()}_abcdefgh")), + ] + gitutil._hook_tmpdir() + assert [p for p in gone if os.path.exists(p)] == [] + assert [p for p in keep if not os.path.exists(p)] == [] + + def test_no_process_is_probed_without_getuid(self, tmproot, monkeypatch): + """On Windows os.kill ends the process it is given.""" + monkeypatch.delattr(os, "getuid", raising=False) + + def no_kill(*a): + raise AssertionError("probed a process") + + monkeypatch.setattr(os, "kill", no_kill) + p = _write(str(tmproot / "security_hook_idx_pid999999_abcdefgh")) + gitutil._hook_tmpdir() + assert os.path.exists(p) + + +@pytest.mark.skipif(os.name == "nt", reason="uses signals and a /bin/sh git shim") +class TestHookProcessKilled: + def _start_slow_hook(self, tmp_path, hook_env, repo): + """Start a UserPromptSubmit hook whose `git stash create` hangs, and + return once its index copy exists.""" + import shutil + import subprocess + import sys + import json + from conftest import HOOK_SCRIPT, ups_payload + real_git = shutil.which("git") + bindir = tmp_path / "bin" + bindir.mkdir(exist_ok=True) + shim = bindir / "git" + shim.write_text( + "#!/bin/sh\n" + 'case "$*" in *"stash create"*) [ -n "$SLOW_GIT" ] && exec sleep 60;; esac\n' + f'exec "{real_git}" "$@"\n' + ) + shim.chmod(0o755) + tmproot = tmp_path / "hooktmp" + tmproot.mkdir(exist_ok=True) + env = dict(hook_env) + env["PATH"] = f"{bindir}{os.pathsep}{env['PATH']}" + env["TMPDIR"] = str(tmproot) + env["SLOW_GIT"] = "1" + proc = subprocess.Popen( + [sys.executable, str(HOOK_SCRIPT)], stdin=subprocess.PIPE, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env) + proc.stdin.write(json.dumps(ups_payload(repo)).encode()) + proc.stdin.close() + deadline = time.time() + 30 + while time.time() < deadline and not self._copies(tmproot): + assert proc.poll() is None, "hook exited before copying the index" + time.sleep(0.05) + assert self._copies(tmproot) + return proc, env, tmproot + + def _copies(self, root): + return [p for p in _leftovers(root) + if os.path.basename(p).startswith("security_hook_idx_")] + + def test_terminated_hook_removes_its_copy(self, tmp_path, hook_env, stub_api): + import signal + repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) + (repo / "app.py").write_text("x = 2\n") + proc, env, tmproot = self._start_slow_hook(tmp_path, hook_env, repo) + proc.send_signal(signal.SIGTERM) + assert proc.wait(timeout=30) == 128 + signal.SIGTERM + assert self._copies(tmproot) == [] + + def test_next_run_reclaims_the_copy_of_a_killed_hook(self, tmp_path, hook_env, stub_api): + from conftest import run_hook, ups_payload + repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) + (repo / "app.py").write_text("x = 2\n") + proc, env, tmproot = self._start_slow_hook(tmp_path, hook_env, repo) + proc.kill() + proc.wait(timeout=30) + assert self._copies(tmproot) + env.pop("SLOW_GIT") + run_hook(ups_payload(repo, session_id="s2"), env) + assert self._copies(tmproot) == [] + + +class TestHardLink: + @posix_only + def test_copy_is_a_link_and_git_cannot_change_the_index_through_it(self, tmp_path, tmproot): + repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) + (repo / "new.py").write_text("n = 1\n") + index = repo / ".git" / "index" + before = index.read_bytes() + with gitutil._temp_index(str(repo), untracked_paths=["new.py"]) as env: + copy = env["GIT_INDEX_FILE"] + # `add -N` wrote a new index over the link. + assert os.stat(copy).st_ino != os.stat(index).st_ino + assert open(copy, "rb").read() != before + with gitutil._temp_index(str(repo), untracked_paths=[]) as env: + assert os.stat(env["GIT_INDEX_FILE"]).st_ino == os.stat(index).st_ino + assert index.read_bytes() == before + assert _leftovers(tmproot) == [] + + def test_falls_back_to_a_copy(self, tmp_path, tmproot, monkeypatch): + repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) + index = repo / ".git" / "index" + old = int(time.time()) - 7200 + os.utime(index, (old, old)) + + def no_link(*a, **kw): + raise OSError(18, "Invalid cross-device link") + + monkeypatch.setattr(os, "link", no_link) + with gitutil._temp_index(str(repo), untracked_paths=[]) as env: + copy = env["GIT_INDEX_FILE"] + assert os.stat(copy).st_ino != os.stat(index).st_ino + assert open(copy, "rb").read() == index.read_bytes() + assert int(os.stat(copy).st_mtime) == old + assert _leftovers(tmproot) == [] + + +@posix_only +class TestCopySlots: + def test_only_so_many_copies_at_once(self, tmp_path, tmproot, monkeypatch): + repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) + monkeypatch.setattr(gitutil, "_MAX_LIVE_COPIES", 1) + monkeypatch.setattr(gitutil, "_SLOT_WAIT_S", 0.3) + with gitutil._temp_index(str(repo), untracked_paths=[]) as first: + assert first is not None + with gitutil._temp_index(str(repo), untracked_paths=[]) as second: + assert second is None + with gitutil._temp_index(str(repo), untracked_paths=[]) as again: + assert again is not None + assert _leftovers(tmproot) == [] + + def test_fewer_slots_when_the_disk_is_nearly_full(self, tmproot, monkeypatch): + import collections + import shutil + usage = collections.namedtuple("usage", "total used free") + gb = 1024 ** 3 + index = 350 * 1024 ** 2 + + def free(n): + monkeypatch.setattr(shutil, "disk_usage", lambda p: usage(250 * gb, 0, n)) + + free(200 * gb) + assert gitutil._copy_slots(str(tmproot), index) == gitutil._MAX_LIVE_COPIES + free(10 * gb) + assert gitutil._copy_slots(str(tmproot), index) == 2 + free(5 * gb) + assert gitutil._copy_slots(str(tmproot), index) == 1 + free(0) + assert gitutil._copy_slots(str(tmproot), index) == 1 + free(1 * gb) + assert gitutil._copy_slots(str(tmproot), 1000) == gitutil._MAX_LIVE_COPIES + + def test_waits_for_a_slot(self, tmp_path, tmproot, monkeypatch): + import threading + repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) + monkeypatch.setattr(gitutil, "_MAX_LIVE_COPIES", 1) + monkeypatch.setattr(gitutil, "_SLOT_WAIT_S", 10) + release = threading.Event() + holding = threading.Event() + + def holder(): + with gitutil._temp_index(str(repo), untracked_paths=[]): + holding.set() + release.wait(10) + + t = threading.Thread(target=holder) + t.start() + assert holding.wait(10) + threading.Timer(0.5, release.set).start() + with gitutil._temp_index(str(repo), untracked_paths=[]) as env: + assert env is not None + t.join() + + def test_slot_of_a_killed_hook_is_free(self, tmp_path, tmproot, monkeypatch): + import signal + import subprocess + import sys + monkeypatch.setattr(gitutil, "_MAX_LIVE_COPIES", 1) + monkeypatch.setattr(gitutil, "_SLOT_WAIT_S", 0.3) + private = gitutil._hook_tmpdir() + holder = subprocess.Popen( + [sys.executable, "-c", + "import fcntl, os, sys, time\n" + "fd = os.open(sys.argv[1], os.O_RDWR | os.O_CREAT, 0o600)\n" + "fcntl.flock(fd, fcntl.LOCK_EX)\n" + "print('held', flush=True)\n" + "time.sleep(60)\n", + os.path.join(private, "slot0.lock")], + stdout=subprocess.PIPE) + assert holder.stdout.readline().strip() == b"held" + with gitutil._copy_slot(private) as got: + assert not got + holder.send_signal(signal.SIGKILL) + holder.wait() + with gitutil._copy_slot(private) as got: + assert got + + def test_baseline_falls_back_to_head_without_a_slot(self, tmp_path, tmproot, monkeypatch): + import diffstate + from conftest import git + repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) + (repo / "app.py").write_text("x = 2\n") + head = git(repo, "rev-parse", "HEAD").strip() + monkeypatch.setattr(gitutil, "_MAX_LIVE_COPIES", 1) + monkeypatch.setattr(gitutil, "_SLOT_WAIT_S", 0.3) + private = gitutil._hook_tmpdir() + with gitutil._copy_slot(private) as got: + assert got + assert diffstate.capture_git_baseline(str(repo)) == head + assert diffstate.capture_git_baseline(str(repo)) != head + assert _leftovers(tmproot) == [] + + +class TestStashIndexesLeftInGitDir: + """What releases before 2.0.10 left next to the real index.""" + + def test_old_ones_go_and_nothing_else_does(self, tmp_path, tmproot, monkeypatch): + repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) + git_dir = repo / ".git" + index = (git_dir / "index").read_bytes() + old = [_write(str(git_dir / n)) for n in ("index.stash.123", "index.stash.99999")] + not_ours = [_write(str(git_dir / n)) for n in ( + "index.lock", "index.stash.12.bak", "index.stash.abc", "index.stash.", "myindex.stash.5")] + _advance_clock(monkeypatch, gitutil._TEMP_INDEX_STALE_S + 60) + fresh = _write(str(git_dir / "index.stash.456")) + now = time.time() # the moved clock + os.utime(fresh, (now, now)) + + with gitutil._temp_index(str(repo), untracked_paths=[]): + pass + + assert [p for p in old if os.path.exists(p)] == [] + assert [p for p in not_ours if not os.path.exists(p)] == [] + assert os.path.exists(fresh) + assert (git_dir / "index").read_bytes() == index + + def test_a_directory_or_link_by_that_name_stays(self, tmp_path, tmproot, monkeypatch): + repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) + git_dir = repo / ".git" + target = _write(str(tmp_path / "elsewhere")) + os.mkdir(git_dir / "index.stash.1") + os.symlink(target, git_dir / "index.stash.2") + _advance_clock(monkeypatch, gitutil._TEMP_INDEX_STALE_S + 60) + + with gitutil._temp_index(str(repo), untracked_paths=[]): + pass + + assert os.path.isdir(git_dir / "index.stash.1") + assert os.path.islink(git_dir / "index.stash.2") + assert os.path.exists(target) + + def test_linked_worktree_has_its_own(self, tmp_path, tmproot, monkeypatch): + from conftest import git + repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) + wt = tmp_path / "wt" + git(repo, "worktree", "add", "-q", str(wt), "-b", "side") + wt_git_dir = repo / ".git" / "worktrees" / "wt" + mine = _write(str(wt_git_dir / "index.stash.7")) + main = _write(str(repo / ".git" / "index.stash.7")) + _advance_clock(monkeypatch, gitutil._TEMP_INDEX_STALE_S + 60) + + with gitutil._temp_index(str(wt), untracked_paths=[]): + pass + + assert not os.path.exists(mine) + assert os.path.exists(main) |
