From 1e804115fcf9e3e5e1b17464ebfed0a3ea6d40f4 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sat, 31 Oct 2026 17:07:54 +0100 Subject: [PATCH] fix(web-app-docs): keep the builder alive through git timeouts and never wipe a healthy mirror fetch() leaked subprocess.TimeoutExpired, which ended the builder thread while it kept the builder lock, so no replica built again. A clone killed at its timeout also left a HEAD that never resolves, and the HEAD-file check ran remote update on it forever. The loop and refs() now catch SubprocessError, fetch() re-clones when HEAD does not resolve, and the clone lands in repo.git.partial and replaces the mirror only after it succeeds. Co-Authored-By: Claude Opus 5.5 --- .../files/python/infinito_docs/build_queue.py | 2 +- .../files/python/infinito_docs/library.py | 17 +++- .../files/infinito_docs/test_build_queue.py | 41 +++++++- .../files/infinito_docs/test_library.py | 94 +++++++++++++++++++ 4 files changed, 147 insertions(+), 7 deletions(-) diff --git a/roles/web-app-docs/files/python/infinito_docs/build_queue.py b/roles/web-app-docs/files/python/infinito_docs/build_queue.py index c001dea022..0e64d68fb4 100644 --- a/roles/web-app-docs/files/python/infinito_docs/build_queue.py +++ b/roles/web-app-docs/files/python/infinito_docs/build_queue.py @@ -195,7 +195,7 @@ class Queue: if time.monotonic() >= next_fetch: try: self.fetch() - except (OSError, subprocess.CalledProcessError) as exc: + except (OSError, subprocess.SubprocessError) as exc: print( f"fetch of {self.repository} failed: {exc}", file=sys.stderr ) diff --git a/roles/web-app-docs/files/python/infinito_docs/library.py b/roles/web-app-docs/files/python/infinito_docs/library.py index c314da4472..0dd6644ae7 100644 --- a/roles/web-app-docs/files/python/infinito_docs/library.py +++ b/roles/web-app-docs/files/python/infinito_docs/library.py @@ -3,6 +3,7 @@ from __future__ import annotations import hashlib import json import re +import shutil import subprocess import threading import time @@ -93,7 +94,7 @@ class Library(Sites, Queue, Builder): ), reverse=True, ) - except subprocess.CalledProcessError: + except subprocess.SubprocessError: head, tags = "", [] with self._lock: self._refs, self._refs_read = (head, tags), time.monotonic() @@ -220,9 +221,11 @@ class Library(Sites, Queue, Builder): return report def fetch(self): - if (self.mirror / "HEAD").is_file(): - self._git("remote", "update", "--prune") - else: + try: + self._git("rev-parse", "--verify", "HEAD") + except subprocess.CalledProcessError: + partial = self.mirror.with_name(f"{self.mirror.name}.partial") + shutil.rmtree(partial, ignore_errors=True) subprocess.run( [ "git", @@ -230,12 +233,16 @@ class Library(Sites, Queue, Builder): "--mirror", "--quiet", self.repository, - str(self.mirror), + str(partial), ], check=True, capture_output=True, timeout=GIT_TIMEOUT_SECONDS, ) + shutil.rmtree(self.mirror, ignore_errors=True) + partial.replace(self.mirror) + else: + self._git("remote", "update", "--prune") self._forget_refs() self.request(LATEST, background=True) self._refresh_stale_sites() diff --git a/tests/unit/python/roles/web-app-docs/files/infinito_docs/test_build_queue.py b/tests/unit/python/roles/web-app-docs/files/infinito_docs/test_build_queue.py index 51c2bd1839..84bc5cf977 100644 --- a/tests/unit/python/roles/web-app-docs/files/infinito_docs/test_build_queue.py +++ b/tests/unit/python/roles/web-app-docs/files/infinito_docs/test_build_queue.py @@ -6,12 +6,20 @@ through :class:`Library`, on the fixture its sibling module owns. from __future__ import annotations +import importlib +import io import json import subprocess import sys +import time import unittest +from contextlib import redirect_stderr +from types import SimpleNamespace +from unittest.mock import patch -from .test_library import LibraryFixture +from .test_library import LibraryFixture, library, timed_out_clone + +build_queue = importlib.import_module("infinito_docs.build_queue") BACKGROUND = "background" @@ -163,5 +171,36 @@ class TestBuilderLock(QueueFixture, unittest.TestCase): self.assertTrue(self.library.acquire_builder()) +class TestBuilderLoop(QueueFixture, unittest.TestCase): + def test_the_builder_outlives_a_fetch_that_times_out(self) -> None: + shelf = library.Library( + str(self.repo), self.data / "fresh", 1, self.package, self.data / "none" + ) + attempts: list = [] + sleeps: list = [] + + class Stop(Exception): + pass + + def sleep(seconds): + sleeps.append(seconds) + if len(sleeps) > 1: + raise Stop + + clock = SimpleNamespace(monotonic=time.monotonic, sleep=sleep) + with ( + patch.object(subprocess, "run", timed_out_clone(attempts)), + patch.object(build_queue, "time", clock), + redirect_stderr(io.StringIO()) as stderr, + self.assertRaises(Stop), + ): + shelf.run_builder(0) + + self.assertEqual(len(attempts), 2, "the next interval must fetch again") + self.assertIn(f"fetch of {self.repo} failed", stderr.getvalue()) + self.assertIn("timed out after", stderr.getvalue()) + self.assertTrue(shelf.servable("latest"), "the builder stopped building") + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/roles/web-app-docs/files/infinito_docs/test_library.py b/tests/unit/python/roles/web-app-docs/files/infinito_docs/test_library.py index 16c5a18eb5..6ab3d5b651 100644 --- a/tests/unit/python/roles/web-app-docs/files/infinito_docs/test_library.py +++ b/tests/unit/python/roles/web-app-docs/files/infinito_docs/test_library.py @@ -265,6 +265,100 @@ class TestLibrary(LibraryFixture): self.assertIsNone(self.library.resolve("latest", "../ref")) self.assertIsNone(self.library.resolve("latest", "/etc/passwd")) + def test_a_ref_read_that_times_out_reads_as_no_mirror(self) -> None: + timeout = subprocess.TimeoutExpired(["git", "rev-parse", "HEAD"], 1) + with patch.object(self.library, "_git", side_effect=timeout): + self.assertEqual(self.library.refs(), ("", [])) + + +def write_killed_clone(killed: Path, url: str) -> None: + """Lay out what ``git clone --mirror`` leaves when killed mid-transfer. + + Args: + killed: the clone's target directory. + url: the repository the clone was fetching. + """ + (killed / "refs").mkdir(parents=True) + (killed / "objects" / "pack").mkdir(parents=True) + (killed / "objects" / "pack" / "tmp_pack_x").write_bytes(b"partial") + (killed / "HEAD").write_text("ref: refs/heads/.invalid\n", encoding="utf-8") + (killed / "config").write_text( + "[core]\n\trepositoryformatversion = 0\n\tbare = true\n" + f'[remote "origin"]\n\turl = {url}\n' + "\tfetch = +refs/*:refs/*\n\tmirror = true\n", + encoding="utf-8", + ) + + +def timed_out_clone(attempts: list, unresolved_head: bool = False): + """Return a ``subprocess.run`` whose first ``git clone`` dies at its timeout. + + Args: + attempts: receives the argv of every clone attempt. + unresolved_head: also fail every ``rev-parse --verify HEAD``. + """ + real_run = subprocess.run + + def run(argv, *args, **kwargs): + if unresolved_head and argv[-3:] == ["rev-parse", "--verify", "HEAD"]: + raise subprocess.CalledProcessError(128, argv) + if argv[:2] != ["git", "clone"]: + return real_run(argv, *args, **kwargs) + attempts.append(argv) + if len(attempts) > 1: + return real_run(argv, *args, **kwargs) + write_killed_clone(Path(argv[-1]), argv[-2]) + raise subprocess.TimeoutExpired(argv, library.GIT_TIMEOUT_SECONDS) + + return run + + +class TestClone(LibraryFixture): + def test_a_clone_killed_at_its_timeout_is_cloned_again(self) -> None: + shelf = library.Library( + str(self.repo), self.data / "fresh", 1, self.package, self.data / "none" + ) + attempts: list = [] + with patch.object(subprocess, "run", timed_out_clone(attempts)): + with self.assertRaises(subprocess.TimeoutExpired): + shelf.fetch() + self.assertEqual(shelf.refs(), ("", [])) + + shelf.fetch() + + self.assertEqual(len(attempts), 2, "a HEAD that never resolves must re-clone") + self.assertEqual(shelf.refs()[0], _git(self.repo, "rev-parse", "HEAD")) + self.assertEqual(shelf.versions(), ["latest", "v1.2.0", "v1.0.0"]) + + def test_a_mirror_wedged_by_an_earlier_killed_clone_is_replaced(self) -> None: + shelf = library.Library( + str(self.repo), self.data / "fresh", 1, self.package, self.data / "none" + ) + write_killed_clone(shelf.mirror, str(self.repo)) + + shelf.fetch() + + self.assertEqual(shelf.refs()[0], _git(self.repo, "rev-parse", "HEAD")) + self.assertFalse(shelf.mirror.with_name("repo.git.partial").exists()) + + def test_a_healthy_mirror_survives_a_re_clone_that_times_out(self) -> None: + shelf = library.Library( + str(self.repo), self.data / "fresh", 1, self.package, self.data / "none" + ) + shelf.fetch() + attempts: list = [] + with patch.object( + subprocess, "run", timed_out_clone(attempts, unresolved_head=True) + ): + with self.assertRaises(subprocess.TimeoutExpired): + shelf.fetch() + + self.assertEqual(len(attempts), 1) + self.assertEqual( + _git(shelf.mirror, "rev-parse", "HEAD"), + _git(self.repo, "rev-parse", "HEAD"), + ) + class TestBeforeTheFirstFetch(unittest.TestCase): def test_latest_is_offered_as_fetching_and_nothing_is_queued(self) -> None: