Skip to content

Commit 14fd740

Browse files
committed
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
1 parent 1c9ef7d commit 14fd740

3 files changed

Lines changed: 61 additions & 9 deletions

File tree

‎git/objects/submodule/base.py‎

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@
7171
from git.types import TBD, Commit_ish, PathLike
7272

7373
if TYPE_CHECKING:
74-
from git.index import IndexFile
74+
from git.index import IndexEntry, IndexFile
7575
from git.objects.commit import Commit
7676
from git.refs import Head
7777
from git.repo import Repo
@@ -2021,6 +2021,10 @@ def iter_items(
20212021

20222022
native = _backend.submodule_config(parser._file_or_files)
20232023
sections = parser.sections() if native is NotImplemented else [sm_section(name) for name in native]
2024+
# Both repository lookups below are the same for every section, so read each
2025+
# of them at most once instead of once per section.
2026+
entries: Union[Mapping[Tuple[PathLike, int], "IndexEntry"], None] = None
2027+
head_commit: Union["Commit", None] = None
20242028
for sms in sections:
20252029
n = sm_name(sms)
20262030
if native is NotImplemented:
@@ -2032,20 +2036,19 @@ def iter_items(
20322036
b = native[n].get(cls.k_head_option, cls.k_head_default)
20332037

20342038
# Get the binsha.
2035-
index = repo.index
20362039
try:
20372040
rt = pc.tree # Root tree
20382041
sm = rt[p]
20392042
except KeyError:
2040-
# Try the index, maybe it was just added.
2041-
try:
2042-
entry = index.entry(p)
2043-
sm = Submodule(repo, entry.binsha, entry.mode, entry.path)
2044-
except KeyError:
2043+
# Try the index, maybe it was just added. One read serves every section.
2044+
if entries is None:
2045+
entries = repo.index.entries
2046+
entry = entries.get((p, 0))
2047+
if entry is None:
20452048
# The submodule doesn't exist, probably it wasn't removed from the
20462049
# .gitmodules file.
20472050
continue
2048-
# END handle keyerror
2051+
sm = Submodule(repo, entry.binsha, entry.mode, entry.path)
20492052
# END handle critical error
20502053

20512054
# Make sure we are looking at a submodule object.
@@ -2054,7 +2057,9 @@ def iter_items(
20542057

20552058
# Fill in remaining info - saves time as it doesn't have to be parsed again.
20562059
sm._name = n
2057-
if pc != repo.commit():
2060+
if head_commit is None:
2061+
head_commit = repo.commit()
2062+
if pc != head_commit:
20582063
sm._parent_commit = pc
20592064
# END set only if not most recent!
20602065
sm._branch_path = git.Head.to_full_path(b)

‎test/test_submodule.py‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import os
77
import os.path as osp
88
from pathlib import Path, PurePosixPath
9+
import re
910
import shutil
1011
import sys
1112
from types import SimpleNamespace
@@ -81,6 +82,35 @@ def test_submodule_configuration_preserves_non_utf8_bytes(scenario, name):
8182
)
8283

8384

85+
def _backend_operations():
86+
"""Count repository operations, whichever backend carries them out."""
87+
return sum(git._backend.statistics().values())
88+
89+
90+
@pytest.mark.parametrize("location", ["in-tree", "in-index", "absent"])
91+
def test_listing_submodules_queries_the_repository_once(location):
92+
with fixture_repo("submodule-many.sh", write=True) as repo:
93+
config = Path(repo.working_tree_dir, ".gitmodules")
94+
sections = re.findall(r"\[submodule[^[]*", config.read_text())
95+
assert len(sections) == 12
96+
paths = ["module%02d" % index for index in range(len(sections))]
97+
if location != "in-tree":
98+
paths = ["%s/%s" % (location, path) for path in paths]
99+
sections = [section.replace("path = module", "path = %s/module" % location) for section in sections]
100+
if location == "in-index":
101+
specs = ["160000,%s,%s" % (repo.head.commit.hexsha, path) for path in paths]
102+
repo.git.update_index("--add", *[argument for spec in specs for argument in ("--cacheinfo", spec)])
103+
104+
def list_submodules(count):
105+
config.write_text("".join(sections[:count]))
106+
before = _backend_operations()
107+
assert len(repo.submodules) == (0 if location == "absent" else count)
108+
return _backend_operations() - before
109+
110+
list_submodules(1) # Warm the caches a first listing fills.
111+
assert list_submodules(12) == list_submodules(1)
112+
113+
84114
@pytest.mark.skipif(git._backend.name != "gix", reason="requires the native backend")
85115
def test_native_submodule_configuration_preserves_non_utf8_values():
86116
path = read_only_fixture("submodule-bytes.sh", "ascii-name") / "repo" / ".gitmodules"

‎tests/fixtures/submodule-many.sh‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
#!/usr/bin/env bash
2+
set -eu
3+
export GIT_AUTHOR_NAME='GitPython Tests' GIT_AUTHOR_EMAIL='tests@example.invalid'
4+
export GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME" GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"
5+
export GIT_AUTHOR_DATE='2001-01-01T00:00:00 +0000'
6+
export GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"
7+
git init -q -b master repo
8+
cd repo
9+
git commit --allow-empty -qm 'Initial commit'
10+
oid=$(git rev-parse HEAD)
11+
for index in 0 1 2 3 4 5 6 7 8 9 10 11; do
12+
name=$(printf 'module%02d' "$index")
13+
git update-index --add --cacheinfo "160000,$oid,$name"
14+
printf '[submodule "%s"]\npath = %s\nurl = ../%s\n' "$name" "$name" "$name" >>.gitmodules
15+
done
16+
git add .gitmodules
17+
git commit -qm 'Add submodules'

0 commit comments

Comments
 (0)