Skip to content

perf(install): import GitPython only when a clone needs it - #4766

Merged
Daniel Meppiel (danielmeppiel) merged 5 commits into
mainfrom
danielmeppiel-perf-boot-imports
Nov 22, 2026
Merged

Daniel Meppiel (danielmeppiel) merged 5 commits into
mainfrom
danielmeppiel-perf-boot-imports

Conversation

@danielmeppiel

@danielmeppiel Daniel Meppiel (danielmeppiel) commented Nov 22, 2026 •

Copy link
Copy Markdown
Collaborator

Description

perf(install): import GitPython only when a clone needs it (L3 imports/boot).

Every apm install, including a no-op, builds a GitHubPackageDownloader in the resolve phase. deps/github_downloader.py, bare_cache.py, clone_engine.py and git_reference_resolver.py imported GitPython at module scope. GitPython loads about 60 modules and, at import, its refresh() runs git version in a subprocess. A no-op install never clones, so this was pure startup cost.

This PR makes four changes:

  • New deps/git_lazy.py: git_command_error() returns GitPython's GitCommandError once git.exc is loaded, else a never-raised placeholder. A GitCommandError cannot exist before GitPython is imported, so except/isinstance checks behave identically. new_git_command_error() imports GitPython on the raise path only. bind_git_name() binds git/Repo/... into a module namespace on first use.
  • github_downloader and bare_cache keep git, Repo, RemoteProgress, GitCommandError and GitProgressReporter as module attributes through a PEP 562 __getattr__, so the 76 existing patch("apm_cli.deps.github_downloader.Repo"/".git") seams work unchanged. GitProgressReporter (a RemoteProgress subclass) is defined on first use.
  • clone_engine and git_reference_resolver use git_command_error() in their except/isinstance checks.
  • git_reference_resolver's ls-remote test seam reads an already-bound or fully imported git module (one another thread is still importing counts as not loaded) instead of importing GitPython to build an unused Git() object.
  • Static guard: the cli-startup-import-budget owner rule (registry_delegation.cli_startup_imports) now rejects module-scope GitPython imports in the four transport modules and deps/git_lazy.py, which joins that owner. tests/integration/test_gitpython_lazy_import.py mutates each module to prove the rule fires.

Behavior: identical. Clone paths import GitPython exactly as before (clone_with_fallback binds the real Repo). No auth, integrity, path-security or policy code is touched.

Gains (ABAB at exact SHAs)

Journey: apm install no-op, tree-10 fixture (10 packages, offline mirror via tests/benchmarks/journeys.py serve_offline, rtt 0), venv CLI. Base 84a893b2a586 (main) -> new 91c3ea1e4f2e (this PR; src/ is byte-identical at head 43b72c06, later commits touch tests only). 6 ABAB pairs, CPU = user+sys including children. Host 1-min load per run: 45, 57, 62, 56, 52, 47, 43, 43, 39, 45, 40, 36 (shared host; wall is noisy, CPU and counts are the signal).

Metric Base 84a893b New 91c3ea1 Delta
CPU p50 (s) 3.059 2.907 -0.152 (-5.0%), 1.05x
CPU min (s) 2.917 2.703 -0.214 (-7.3%)
Paired delta (base - new), 6 pairs median -0.21 s; 6/6 pairs faster
Wall p50 (s, load 36-62) 19.67 18.06 -1.6 (noise-dominated)
Modules imported (-X importtime) 940 869 -71
GitPython modules (git, git.*) 38 0 -38
git version subprocesses from GitPython refresh 1 0 -1
HTTPS connects / requests (whole session incl. setup install) 21 / 41 21 / 41 0

Controls (10 ABAB pairs, CPU p50): apm --version 273 -> 280 ms (+8 ms, noise; GitPython was never on this path), import apm_cli.commands.install 720 -> 720 ms (GitPython loads at downloader construction, not at import).

Share of the whole journey removed: 5.0% of no-op CPU (paired median 7%). North Star: tree-10 no-op now 2.91 s CPU, gap to 1 s = 1.91 s. Scaling: GitPython cost is per-run constant (one import, one git version), so the saving does not grow with tree size; tree-50 not run (10-min slot rule at load 55).

Issue and approved scope

Issue: Refs #4732

Human scope-approval comment: PERF charter on #4732 (CEO re-charter 16:08: tree-10 no-op <= 1 s; boot at or below uv). L3 imports/boot lane, PERF VP GO per PR.

Does this PR complete the issue, or what remains? First L3 slice. Next: lazy package re-exports (apm_cli.utils, apm_cli.commands, apm_cli.bundle, apm_cli.deps.registry, apm_cli.__version__).

Type of change

  • Bug fix
  • New feature
  • Documentation
  • Maintenance / refactor

Testing

  • Tested locally
  • All existing tests pass
  • Added tests for new functionality (if applicable): tests/integration/test_gitpython_lazy_import.py (component, subprocess) pins that building the install downloader leaves git out of sys.modules, that the first GitCommandError raised across the lazy import is still caught, and that the static rule rejects an eager import in each transport module. tests/unit/deps/test_git_lazy.py pins real-error matching and patchable module attributes.

Changelog

  • One fragment per section, changelog.d/<pr>.<section>.md, holding
    one line: user-visible effect first, 25 words or fewer, ending with
    (#PR); breaking changes only under upgrade notes; no Highlights; no
    new lines under ## [Unreleased]. See changelog.d/README.md and
    .github/instructions/changelog.instructions.md.
  • N/A -- internal-only change (CI, tests, refactor).

Spec conformance (OpenAPM v0.1)

  • N/A -- this PR does not change OpenAPM-observable behaviour.

Building the install downloader (every apm install, including a no-op)
imported GitPython at module scope: ~60 modules plus a 'git version'
subprocess from GitPython's import-time refresh. GitPython names stay
patchable module attributes, resolved on first use; except clauses use a
never-raised placeholder until git.exc is loaded, since a GitCommandError
cannot exist before GitPython is imported.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Critical parallel-import races can expose partially initialized GitPython modules, masking failures and bypassing retry or fallback handling, while the test misses the unloaded-to-real-exception transition.

3 open issues
What changed in this PR

This PR reduces install startup overhead by deferring GitPython imports until needed, avoiding that cost when constructing a downloader for a no-op install.

Changes:

  • Adds shared lazy-loading helpers for GitPython names and exceptions.
  • Updates dependency transport modules while preserving patchable module attributes.
  • Adds import-budget and compatibility tests, plus a changelog entry.
File Description
tests/​integration/​test_gitpython_lazy_import.py Tests deferred imports, exception matching, and patchable attributes.
src/​apm_cli/​deps/​github_downloader.py Lazily exposes GitPython names and builds the progress reporter.
src/​apm_cli/​deps/​git_reference_resolver.py Defers exception imports and avoids loading GitPython for the test seam.
src/​apm_cli/​deps/​git_lazy.py Centralizes lazy GitPython access and exception construction.
src/​apm_cli/​deps/​clone_engine.py Uses deferred exception-type lookup in failure handling.
src/​apm_cli/​deps/​bare_cache.py Resolves Repo lazily when cloning.
changelog.d/​4766.changed.md Records the intended install startup improvement.

Review effort: Balanced

Comment thread src/apm_cli/deps/git_lazy.py Resolved
Comment thread src/apm_cli/deps/git_lazy.py Resolved
apm-spec-waiver: perf refactor that defers the GitPython import; no OpenAPM-observable behaviour change.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Concurrent GitPython imports can expose partially initialized modules, causing AttributeError that masks clone failures, bypasses retry handling, and blocks ref resolution.

5 open issues

Review effort: Balanced

- git_command_error()/loaded_git_module() treat a git module another thread
  is still importing as not loaded; the ls-remote seam checks cmd.Git exists.
- The cli-startup-import-budget rule now rejects module-scope GitPython
  imports in the dependency transport modules; deps/git_lazy.py moves to
  that owner. Mutation test per module.
- Component test proves the first failure is caught across the lazy import;
  in-process checks move to a unit test.

apm-spec-waiver: perf refactor that defers the GitPython import; no OpenAPM-observable behaviour change.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Regression coverage is missing for loaded_git_module() ignoring partially initialized modules and prioritizing an explicitly bound test double.

1 open issue
5 resolved since last review

Review effort: Balanced

Comment thread src/apm_cli/deps/git_lazy.py Resolved
…cover partial-import detection

apm-spec-waiver: perf refactor that defers the GitPython import; no OpenAPM-observable behaviour change.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed because the available approval excludes production-code changes and optimizations, leaving this change’s scope authorization unresolved.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

@danielmeppiel
Daniel Meppiel (danielmeppiel) merged commit ac4e44d into main Nov 22, 2026
93 of 100 checks passed
@danielmeppiel
Daniel Meppiel (danielmeppiel) deleted the danielmeppiel-perf-boot-imports branch November 22, 2026 18:56
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