Skip to content

perf(parser-conventional-monorepo): batch changed-file lookups in one pass - #1522

Open
Harouak42 wants to merge 1 commit into
python-semantic-release:masterfrom
Harouak42:perf/monorepo-parser-batched-path-lookups
Open

Harouak42 wants to merge 1 commit into
python-semantic-release:masterfrom
Harouak42:perf/monorepo-parser-batched-path-lookups

Conversation

@Harouak42

Copy link
Copy Markdown

Purpose

Resolves the performance half of #1521: the conventional-monorepo parser pays one
git diff subprocess per commit while ReleaseHistory.from_git_history() walks the
repository's full history, which makes every release run minutes-long in monorepos
with long histories.

Rationale

Commit.stats (GitPython) spawns one git diff <parent> <sha> --numstat --no-renames --raw subprocess per commit, and the monorepo parser triggers it for every non-merge
commit via _has_relevant_changed_files(). On a monorepo with 44,996 commits
(12,910 merge commits, ~32k non-merge commits) this measured 13.6 ms/commit — about
7.5 minutes of subprocess spawns per release, on top of the walk itself.

This change replaces the per-commit lookups with a single batched pass:

  • ConventionalCommitMonorepoParser.prepare_changed_paths(repo) runs one
    git log HEAD --topo-order --no-renames --name-only --format=%x1e%H invocation
    and builds a commit-sha -> filter-match index. The %x1e record separator and
    --name-only output make the parse unambiguous (paths are C-quoted by git when
    they contain special characters, so they cannot collide with record boundaries).
  • ReleaseHistory.from_git_history() calls prepare_changed_paths() when the
    parser provides it (capability check via getattr, no isinstance coupling), so
    the changelog command benefits as well.
  • _has_relevant_changed_files() consults the index first and falls back to the
    original per-commit Commit.stats lookup for any commit missing from the index
    (merge and empty commits, which produce no file entries in git log, plus any
    commit the batch could not classify).

Behavior is preserved exactly:

  • --name-only --no-renames yields the same repo-relative path set as the
    filename column of the git diff --numstat --no-renames output that
    Commit.stats parses (including git's C-quoting of unusual paths), so the
    fnmatch verdicts are identical.
  • Merge commits: git log prints no entries for them by default, so they are
    absent from the index and still resolved through Commit.stats, which diffs a
    merge against its first parent. This keeps ignore_merge_commits = false
    configurations behaving as before.
  • Root commits: git log lists the root commit's files as additions, matching
    the root=True handling in Commit.stats.
  • If the batched pass fails for any reason, the parser logs a warning, leaves the
    index disabled, and every commit goes through the original per-commit path. The
    optimization is fail-open and cannot fail a release.

Measured on the 44,996-commit monorepo (same repo as reported in #1521):

measurement before after
full-history path lookups ~7.5 min (one git diff spawn per commit) 1.5 s (one batched git log)
ReleaseHistory.from_git_history() ~7.5-9 min 6.4 s
semantic-release --noop changelog end to end ~8-10 min 7.2 s

How to test?

New unit tests in tests/unit/semantic_release/commit_parser/test_conventional_monorepo.py:

  • parse results are identical with and without the prepared index, for both
    ignore_merge_commits settings, across a fixture repo covering renames inside
    and outside the package (the --no-renames parity case), a merge commit, an
    empty commit, a squashed multi-commit message, and a non-conventional message;
  • every indexed verdict equals the per-commit Commit.stats verdict;
  • merge and empty commits fall back to Commit.stats and produce the same
    verdict as an unindexed parser;
  • a failing batch leaves the index disabled and parsing still matches the
    unindexed behavior;
  • parsing an indexed commit spawns no git diff/git diff-tree subprocess.

Additionally, against a real 44,996-commit monorepo: per-commit parse
classifications (type, bump, changelog inclusion) were compared for all commits
between stock v10.7.0 and this change and are identical, the resulting
ReleaseHistory summaries are identical, and the rendered CHANGELOG.md output
is byte-identical.

PR Completion Checklist

  • Reviewed & followed the Contributor Guidelines
  • Changes Implemented & Validation pipeline succeeds
  • Commits follow the Conventional Commits standard
    and are separated into the proper commit type and scope (recommended order: test, build, feat/fix, docs)

Refs: #1521 (proposes the same batching fix plus a bounded walk for
mode = "update"; the bounded walk is left as a potential follow-up since it
needs a closer look at the changelog render path).

… pass

The conventional-monorepo parser triggered one git diff subprocess per
commit through GitPython's Commit.stats for every non-merge commit in the
full-history walk of ReleaseHistory.from_git_history(), making release
runs minutes-long on monorepos with long histories (python-semantic-release#1521: 13.6
ms/commit, ~32k non-merge commits, ~10 min per release on a 44,996-commit
monorepo).

Add ConventionalCommitMonorepoParser.prepare_changed_paths(repo), which
builds a commit-sha to path-filter-match index from a single
git log HEAD --topo-order --no-renames --name-only --format=%x1e%H pass,
and have ReleaseHistory.from_git_history() invoke it via a capability
check when the parser provides it (changelog command included).

_has_relevant_changed_files() consults the index and falls back to the
original per-commit stats lookup for commits missing from the index
(merge and empty commits, which git log lists without file entries, so
ignore_merge_commits = false configurations still diff merges against
their first parent). --no-renames --name-only yields the same
repo-relative path keys as the numstat output parsed by Commit.stats,
including git's C-quoting of unusual paths, so filter verdicts are
identical. If the batch fails, the parser logs a warning, disables the
index, and falls back per-commit: the optimization is fail-open.

Measured on the 44,996-commit monorepo from python-semantic-release#1521:
- ReleaseHistory.from_git_history(): 515 s -> 6.4 s (81x)
- per-commit classifications identical for all 44,996 commits
- rendered CHANGELOG.md byte-identical against stock v10.7.0

Refs python-semantic-release#1521

Assisted-by: opencode (openrouter/z-ai/glm-5.3-flash)
@Abedyn

Abedyn commented Dec 6, 2026

Copy link
Copy Markdown

AI disclosure: OpenAI Codex performed this investigation, prepared this comment and patch, and ran the checks below. Posted at the contributor's request.

I found a filename-quoting compatibility edge when testing this PR at da03e68c77911b2b23332d9464575a278beef15b with unreleased GitPython main at 1672a16a5516f99abbf583d24a3541538d0d3921.

That GitPython source unquotes the paths returned by Commit.stats.files, while the batched git log --name-only output retains Git's C quoting. With core.quotePath=true, a commit modifying packages/pkg-a/café.py or packages/pkg-a/مهمة.py is relevant to the package through the per-commit lookup, but the prepared index marks it irrelevant. An unscoped fix: update package then changes from ParsedCommit to ParseError when running from packages/pkg-a with path_filters=(".",).

Both this PR and the GitPython main behavior above are unreleased. The published GitPython 3.2.1 wheel still retains quoted stats paths, even though it reports the same version number as that main checkout. The reproduction therefore needs the exact GitPython source above.

A small conservative follow-up is to leave commits containing any quoted path out of the prepared index. The existing stats fallback then preserves the installed GitPython implementation's semantics. Ordinary paths retain batching; quoted-path commits retain their existing per-commit lookup cost.

I added six real-repository parity cases: plain, accented Latin, and Arabic filenames, each with core.quotePath enabled and disabled. The tests are included in the patch below and use this PR's existing helpers.

Local check Before follow-up After follow-up
Six filename cases with GitPython main 1672a16 4 passed, 2 failed 6 passed
Focused monorepo test file with published GitPython 3.2.1 11 original tests passed 17 tests passed

Environment: Windows 11, Python 3.13.17, Git 2.56.0.windows.4, CLI backend. Ruff 0.6.1 lint and git diff --check passed. ruff format --check flags formatting already present in both files on the untouched PR head; the patch leaves that formatting alone. The patch applies cleanly to the exact PR head above.

To run the six cases, set GIT_PYTHON_BACKEND=cli and put the specified GitPython checkout first on PYTHONPATH, then run:

python -m pytest tests/unit/semantic_release/commit_parser/test_conventional_monorepo.py -k quoted_paths_preserve_per_commit_results -q -o addopts=''

Separately, an eight-commit synthetic process-count check confirmed this PR's ordinary-path batching benefit: 8 diff processes without preparation, versus 1 log process and 0 diffs with preparation, with identical relevance results. This was a process-count check, not a timing benchmark. No large-repository timing, Gix backend comparison, full-suite pass, or end-to-end release is claimed; Gix had no compatible prebuilt Windows wheel, and the broader parser run was stopped before completion. The quoted-path follow-up preserves the published wheel's existing per-commit behavior.

Proposed follow-up patch against da03e68 (implementation and regression tests)
diff --git a/src/semantic_release/commit_parser/conventional/parser_monorepo.py b/src/semantic_release/commit_parser/conventional/parser_monorepo.py
index 1149e23..68d03b1 100644
--- a/src/semantic_release/commit_parser/conventional/parser_monorepo.py
+++ b/src/semantic_release/commit_parser/conventional/parser_monorepo.py
@@ -516,10 +516,10 @@ class ConventionalCommitMonorepoParser(
         every commit in one ``git log --name-only`` invocation and stores only
         the filter-match result for each commit.
 
-        Commits missing from the index (merge commits, empty commits, or commits
-        created after the batch ran) transparently fall back to the per-commit
-        stats lookup. On any failure the index stays disabled and the original
-        behavior is used, so this can never fail a release.
+        Commits missing from the index (merge commits, empty commits, commits with
+        quoted paths, or commits created after the batch ran) transparently fall
+        back to the per-commit stats lookup. On any failure the index stays disabled
+        and the original behavior is used, so this can never fail a release.
         """
         git_root = (
             Path(repo.working_tree_dir or repo.working_dir).absolute().resolve()
@@ -557,6 +557,11 @@ class ConventionalCommitMonorepoParser(
                 # which can diff a merge against its first parent, is used.
                 continue
 
+            # GitPython versions differ in whether Commit.stats unquotes paths.
+            # Keep their per-commit behavior whenever Git quotes a filename.
+            if any(path.startswith('"') for path in changed_paths):
+                continue
+
             index[lines[0]] = self._changed_paths_match(
                 (str(git_root / path) for path in changed_paths),
                 selection_filters,
diff --git a/tests/unit/semantic_release/commit_parser/test_conventional_monorepo.py b/tests/unit/semantic_release/commit_parser/test_conventional_monorepo.py
index 76bba53..61d5833 100644
--- a/tests/unit/semantic_release/commit_parser/test_conventional_monorepo.py
+++ b/tests/unit/semantic_release/commit_parser/test_conventional_monorepo.py
@@ -186,6 +186,29 @@ def test_rename_out_of_package_is_relevant(git_repo: Repo):
     assert parser._changed_paths_index[rename_commit.hexsha] is True
 
 
+@pytest.mark.parametrize("quote_paths", [True, False])
+@pytest.mark.parametrize("filename", ["plain.py", "café.py", "مهمة.py"])
+def test_quoted_paths_preserve_per_commit_results(
+    tmp_path: Path, monkeypatch: pytest.MonkeyPatch, quote_paths: bool, filename: str
+):
+    with Repo.init(tmp_path, initial_branch="main") as repo:
+        with repo.config_writer() as config:
+            config.set_value("user", "name", "pytest")
+            config.set_value("user", "email", "pytest@example.com")
+            config.set_value("core", "quotePath", quote_paths)
+        commit = _commit_files(
+            repo, "fix: update package", {f"{PKG_A}/{filename}": "pass\n"}
+        )
+        monkeypatch.chdir(tmp_path / PKG_A)
+        unindexed_parser = _make_parser(ignore_merge_commits=True)
+        expected = _classify(unindexed_parser, commit)
+
+        indexed_parser = _make_parser(ignore_merge_commits=True)
+        indexed_parser.prepare_changed_paths(repo)
+
+        assert _classify(indexed_parser, commit) == expected
+
+
 def test_merge_commit_falls_back_to_stats(git_repo: Repo):
     """Merge commits are absent from the index and resolved via Commit.stats."""
     parser = _make_parser(ignore_merge_commits=False)

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants