From 14fd740af15aa0f1d3116df09322fcf4c51377ff Mon Sep 17 00:00:00 2001 From: Keerthana KT Date: Thu, 26 Nov 2026 14:39:50 +0530 Subject: [PATCH] perf(submodule): query the repository once when listing submodules `Submodule.iter_items`, which backs `Repo.submodules`, `Submodule.list_items`, `Submodule.children` and the walk in `RootModule.update`, issued two loop-invariant repository queries once per section of `.gitmodules`: - A section whose `path` is not an entry of the parent commit's tree fell back to `repo.index` and `index.entry(path)`. `IndexFile.entry` iterates `iter_entries()`, which reads the whole index again, so each such section ran another `git ls-files --stage` (CLI backend) over every index entry. - Every section that did resolve compared its parent commit against `repo.commit()`, resolving `HEAD` again. On the CLI backend that is two `git symbolic-ref` calls plus a `git show-ref` per section. Both answers are the same for every section. `.gitmodules` is untrusted repository content under the project's threat model, so the number of sections is chosen by whoever authored the repository, and the index size is too. For `S` sections and an index of `E` entries, listing therefore cost `O(S*E)` in time and `O(S)` repository operations. The index is now read at most once and `HEAD` resolved at most once, which makes it `O(S+E)` in time and `O(1)` repository operations beyond the per-section bookkeeping. Measured with Git 2.54.0, Python 3.12 and the CLI backend: | `Repo.submodules` on | before | after | | --- | --- | --- | | a superproject whose `HEAD` tree holds 400 submodule gitlinks, all 400 declared | 51.62 s, 1214 Git processes | 0.46 s, 17 Git processes | | 400 declared sections whose paths are absent from `HEAD`, index of 3001 entries | 20.85 s, 419 Git processes | 0.43 s, 15 Git processes | Per-section growth on the 12-section fixture added here, counted through `git._backend.statistics()` with all paths held in the tree: 43 operations before and 10 after on the CLI backend, 44 before and 11 after on Gix, against 10 and 11 respectively for a single section. That is three operations per additional submodule before the change and none after; with the paths staged in the index only, where both queries repeat, it is four. Results are unchanged. `IndexFile.entries` is keyed by path and stage, so `entries.get((path, 0))` selects the same stage 0 entry that `IndexFile.entry(path)` returned, and a missing key takes the same `continue` the previous `KeyError` did. `HEAD` is still resolved only once a section resolves, so a repository whose `.gitmodules` lists nothing that is tracked does not resolve it at all. Adds `tests/fixtures/submodule-many.sh`, a repository with twelve submodule gitlinks and matching sections, and `test_listing_submodules_queries_the_repository_once` in `test/test_submodule.py`. It lists the submodules for twelve sections and for one and asserts the recorded operation counts are equal, parametrized over paths held in the tree, paths staged in the index only, and absent paths. All three cases fail before the change (43 against 10, 55 against 11 and 19 against 8 on the CLI backend; 44 against 11, 56 against 12 and 20 against 9 on Gix) and pass after on both backends. Validated on macOS with Git 2.54.0, Python 3.12 and GixPython 0.4.0: `test/test_submodule.py` passes with `GIT_PYTHON_BACKEND=cli` (482 passed, 6 skipped, 1 xfailed) and, together with `test/test_submodule_no_fetch.py`, with `gix` (553 passed, 5 skipped, 1 xfailed), both `-m "not net"`; so do `test/test_fixture_health.py`, `test/test_cli_process_counts.py`, `test/test_docs.py` and the `Repo.submodules` cases of `test/test_repo.py`. `ruff check`, `ruff format --check`, `mypy` and `shellcheck` are clean, and `basedpyright --warnings` reports only a pre-existing unresolved `ddt` import in `test/test_git.py`. Agent-Model: claude-opus-5 --- git/objects/submodule/base.py | 23 ++++++++++++++--------- test/test_submodule.py | 30 ++++++++++++++++++++++++++++++ tests/fixtures/submodule-many.sh | 17 +++++++++++++++++ 3 files changed, 61 insertions(+), 9 deletions(-) create mode 100644 tests/fixtures/submodule-many.sh diff --git a/git/objects/submodule/base.py b/git/objects/submodule/base.py index 04a5ef2ce..821272bf7 100644 --- a/git/objects/submodule/base.py +++ b/git/objects/submodule/base.py @@ -71,7 +71,7 @@ from git.types import TBD, Commit_ish, PathLike if TYPE_CHECKING: - from git.index import IndexFile + from git.index import IndexEntry, IndexFile from git.objects.commit import Commit from git.refs import Head from git.repo import Repo @@ -2021,6 +2021,10 @@ def iter_items( native = _backend.submodule_config(parser._file_or_files) sections = parser.sections() if native is NotImplemented else [sm_section(name) for name in native] + # Both repository lookups below are the same for every section, so read each + # of them at most once instead of once per section. + entries: Union[Mapping[Tuple[PathLike, int], "IndexEntry"], None] = None + head_commit: Union["Commit", None] = None for sms in sections: n = sm_name(sms) if native is NotImplemented: @@ -2032,20 +2036,19 @@ def iter_items( b = native[n].get(cls.k_head_option, cls.k_head_default) # Get the binsha. - index = repo.index try: rt = pc.tree # Root tree sm = rt[p] except KeyError: - # Try the index, maybe it was just added. - try: - entry = index.entry(p) - sm = Submodule(repo, entry.binsha, entry.mode, entry.path) - except KeyError: + # Try the index, maybe it was just added. One read serves every section. + if entries is None: + entries = repo.index.entries + entry = entries.get((p, 0)) + if entry is None: # The submodule doesn't exist, probably it wasn't removed from the # .gitmodules file. continue - # END handle keyerror + sm = Submodule(repo, entry.binsha, entry.mode, entry.path) # END handle critical error # Make sure we are looking at a submodule object. @@ -2054,7 +2057,9 @@ def iter_items( # Fill in remaining info - saves time as it doesn't have to be parsed again. sm._name = n - if pc != repo.commit(): + if head_commit is None: + head_commit = repo.commit() + if pc != head_commit: sm._parent_commit = pc # END set only if not most recent! sm._branch_path = git.Head.to_full_path(b) diff --git a/test/test_submodule.py b/test/test_submodule.py index 29a3483cc..a0392fcb9 100644 --- a/test/test_submodule.py +++ b/test/test_submodule.py @@ -6,6 +6,7 @@ import os import os.path as osp from pathlib import Path, PurePosixPath +import re import shutil import sys from types import SimpleNamespace @@ -81,6 +82,35 @@ def test_submodule_configuration_preserves_non_utf8_bytes(scenario, name): ) +def _backend_operations(): + """Count repository operations, whichever backend carries them out.""" + return sum(git._backend.statistics().values()) + + +@pytest.mark.parametrize("location", ["in-tree", "in-index", "absent"]) +def test_listing_submodules_queries_the_repository_once(location): + with fixture_repo("submodule-many.sh", write=True) as repo: + config = Path(repo.working_tree_dir, ".gitmodules") + sections = re.findall(r"\[submodule[^[]*", config.read_text()) + assert len(sections) == 12 + paths = ["module%02d" % index for index in range(len(sections))] + if location != "in-tree": + paths = ["%s/%s" % (location, path) for path in paths] + sections = [section.replace("path = module", "path = %s/module" % location) for section in sections] + if location == "in-index": + specs = ["160000,%s,%s" % (repo.head.commit.hexsha, path) for path in paths] + repo.git.update_index("--add", *[argument for spec in specs for argument in ("--cacheinfo", spec)]) + + def list_submodules(count): + config.write_text("".join(sections[:count])) + before = _backend_operations() + assert len(repo.submodules) == (0 if location == "absent" else count) + return _backend_operations() - before + + list_submodules(1) # Warm the caches a first listing fills. + assert list_submodules(12) == list_submodules(1) + + @pytest.mark.skipif(git._backend.name != "gix", reason="requires the native backend") def test_native_submodule_configuration_preserves_non_utf8_values(): path = read_only_fixture("submodule-bytes.sh", "ascii-name") / "repo" / ".gitmodules" diff --git a/tests/fixtures/submodule-many.sh b/tests/fixtures/submodule-many.sh new file mode 100644 index 000000000..9458e7f0f --- /dev/null +++ b/tests/fixtures/submodule-many.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +set -eu +export GIT_AUTHOR_NAME='GitPython Tests' GIT_AUTHOR_EMAIL='tests@example.invalid' +export GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME" GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL" +export GIT_AUTHOR_DATE='2001-01-01T00:00:00 +0000' +export GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE" +git init -q -b master repo +cd repo +git commit --allow-empty -qm 'Initial commit' +oid=$(git rev-parse HEAD) +for index in 0 1 2 3 4 5 6 7 8 9 10 11; do + name=$(printf 'module%02d' "$index") + git update-index --add --cacheinfo "160000,$oid,$name" + printf '[submodule "%s"]\npath = %s\nurl = ../%s\n' "$name" "$name" "$name" >>.gitmodules +done +git add .gitmodules +git commit -qm 'Add submodules'