Repository navigation
perf(install): import GitPython only when a clone needs it - #4766
Conversation
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>
There was a problem hiding this comment.
🟡 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
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>
There was a problem hiding this comment.
🟡 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
Guard against missing Git attributes during partial imports · New Fall back when GitPython is partially initialized Handle partially initialized GitPython exception modules Test placeholder-to-exception transition in a fresh subprocess Extend the architecture guard to enforce lazy GitPython access · New
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>
…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>
There was a problem hiding this comment.
🔵 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



Description
perf(install): import GitPython only when a clone needs it (L3 imports/boot).
Every
apm install, including a no-op, builds aGitHubPackageDownloaderin the resolve phase.deps/github_downloader.py,bare_cache.py,clone_engine.pyandgit_reference_resolver.pyimported GitPython at module scope. GitPython loads about 60 modules and, at import, itsrefresh()runsgit versionin a subprocess. A no-op install never clones, so this was pure startup cost.This PR makes four changes:
deps/git_lazy.py:git_command_error()returns GitPython'sGitCommandErroroncegit.excis loaded, else a never-raised placeholder. AGitCommandErrorcannot exist before GitPython is imported, soexcept/isinstancechecks behave identically.new_git_command_error()imports GitPython on the raise path only.bind_git_name()bindsgit/Repo/... into a module namespace on first use.github_downloaderandbare_cachekeepgit,Repo,RemoteProgress,GitCommandErrorandGitProgressReporteras module attributes through a PEP 562__getattr__, so the 76 existingpatch("apm_cli.deps.github_downloader.Repo"/".git")seams work unchanged.GitProgressReporter(aRemoteProgresssubclass) is defined on first use.clone_engineandgit_reference_resolverusegit_command_error()in theirexcept/isinstancechecks.git_reference_resolver's ls-remote test seam reads an already-bound or fully importedgitmodule (one another thread is still importing counts as not loaded) instead of importing GitPython to build an unusedGit()object.cli-startup-import-budgetowner rule (registry_delegation.cli_startup_imports) now rejects module-scope GitPython imports in the four transport modules anddeps/git_lazy.py, which joins that owner.tests/integration/test_gitpython_lazy_import.pymutates each module to prove the rule fires.Behavior: identical. Clone paths import GitPython exactly as before (
clone_with_fallbackbinds the realRepo). No auth, integrity, path-security or policy code is touched.Gains (ABAB at exact SHAs)
Journey:
apm installno-op, tree-10 fixture (10 packages, offline mirror viatests/benchmarks/journeys.pyserve_offline, rtt 0), venv CLI. Base84a893b2a586(main) -> new91c3ea1e4f2e(this PR;src/is byte-identical at head43b72c06, 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).-X importtime)git,git.*)git versionsubprocesses from GitPython refreshControls (10 ABAB pairs, CPU p50):
apm --version273 -> 280 ms (+8 ms, noise; GitPython was never on this path),import apm_cli.commands.install720 -> 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
Testing
tests/integration/test_gitpython_lazy_import.py(component, subprocess) pins that building the install downloader leavesgitout ofsys.modules, that the firstGitCommandErrorraised 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.pypins real-error matching and patchable module attributes.Changelog
changelog.d/<pr>.<section>.md, holdingone line: user-visible effect first, 25 words or fewer, ending with
(#PR); breaking changes only under upgrade notes; no Highlights; nonew lines under
## [Unreleased]. Seechangelog.d/README.mdand.github/instructions/changelog.instructions.md.Spec conformance (OpenAPM v0.1)