Repository navigation
fix(cache): retry incomplete promisor checkouts with credentials (#3071) - #3602
Conversation
Git before 2.36 ignores a failed promisor blob fetch during a non-forced checkout and exits 0 with an empty worktree. Since #2722 (0.29.1), sparse subdirectory installs from public-GitHub hosts try anonymous access first; for a private monorepo the cached partial bare let the anonymous attempt pass the network step, so transitive git+path dependencies landed as empty shards and failed "Not a valid APM package" with no credentialed retry. GitCache now probes promisor checkouts with `git ls-files --deleted` after checkout and raises IncompleteCheckoutError (carrying Git stderr so AuthResolver classifies the anonymous rejection and retries with a token). Sparse cache hits and write-dedup hits with missing tracked files are rebuilt, healing shards poisoned by earlier versions. Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Copilot App <[email protected]>
There was a problem hiding this comment.
🟢 Approval recommended
No active review issues remain for the sparse-checkout recovery and credential-fallback changes.
No open issues 🎉
What changed in this PR
Fixes the private-monorepo regression from #3071 by detecting incomplete sparse Git checkouts and allowing the existing credential fallback to retry, including on Git older than 2.36.
Changes:
- Detects missing tracked files before caching a sparse checkout, preserving Git diagnostics for authentication failure classification.
- Rebuilds incomplete cached sparse checkouts automatically.
- Adds regression coverage for credential retries, transitive monorepo dependencies, and cache repair, with supporting documentation.
| File | Description |
|---|---|
tests/unit/cache/test_git_cache_recency.py |
Adjusts the fake shard fixture to preserve recency-validation coverage. |
tests/unit/cache/test_git_cache_materialization.py |
Adds regression tests for incomplete checkouts, cache repair, and transitive credential retries. |
src/apm_cli/cache/git_cache.py |
Detects incomplete sparse checkouts and rebuilds affected cached shards. |
docs/src/content/docs/reference/cli/cache.md |
Documents sparse checkout recovery behavior. |
CHANGELOG.md |
Records the private-monorepo installation fix and automatic cache repair. |
Review effort: Balanced
…1-transitive-git-path-monorepo-de
…orepo-de Resolve git_cache.py against #3603: main replaced the sparse-widen finalizer with materialize_tracked_symlinks. Keep the #3071 completeness probe on cache hits and write-dedup, and run the post-checkout unmaterialized-path probe before link materialization so an empty promisor tree still raises the auth-classifiable IncompleteCheckoutError. Drop the recency test for the removed finalizer, as main did. Co-authored-by: Copilot App <[email protected]>
CI shard 1 (Linux) failed because filelock leaves sibling .lock files next to variant directories; the assertion now counts only variant directories, matching how git_cache prune skips .lock entries. Co-authored-by: Copilot App <[email protected]>
APM Review Panel:
|
| Persona | B | R | N | Takeaway |
|---|---|---|---|---|
| Auth Expert | 0 | 0 | 0 | Auth integration is sound: IncompleteCheckoutError.stderr carries genuine Git auth diagnostics for the classifier; the human-readable phrase does not false-positive; probe env is local-only; no token leakage. |
| Test Coverage Expert | 0 | 1 | 0 | Three integration-with-fixtures tests form a strong regression trap for #3071 (mutation-killed); probe-failure defense-in-depth branch in _sparse_checkout_is_complete lacks a test. |
| Performance Expert | 0 | 2 | 0 | Probe is O(total_index_entries) per sparse cache hit on the warm-install hot path; trade-off is sound for shipping; amortize via config pin as follow-up. |
B = blocking-severity findings, R = recommended, N = nits.
Counts are signal strength, not gates. The maintainer ships.
Top 3 follow-ups
- [Test Coverage Expert] Add parametrized unit test for _sparse_checkout_is_complete probe-failure branch (CalledProcessError / TimeoutExpired / OSError -> returns False) -- Missing regression trap on a secure-by-default surface: if the except clause narrows, a subprocess crash propagates from the cache-hit hot path instead of triggering a graceful rebuild. Evidence outcome: missing; the assertion is straightforward and the merge-worker has queued the fold.
- [Performance Expert] Amortize the sparse-shard completeness probe via a local config pin so healed shards skip subsequent ls-files spawns -- Per-hit O(index) probe is correct for shipping but becomes pure overhead once a shard is healed; config pin eliminates the fork+exec on every warm install for large monorepos (10-30ms at 100K files). Merge-worker has queued the fold.
- [Performance Expert] Tighten the ls-files probe timeout from 60s to ~10s on the cache-hit and write-dedup paths (inside shard_lock) -- A healthy ls-files completes far under 1s; 60s under shard_lock serializes every concurrent consumer of that shard on a pathological hang. TimeoutExpired is already caught as incomplete, so the shorter bound is safe. Merge-worker has queued the fold.
Recommendation
Ship once the three queued folds land (probe-failure unit test, config-pin amortization, tighter probe timeout under shard_lock) and CI greens on the new head. All findings touch code this PR introduces and are confirmed in-scope by the merge-worker. Highest-signal item is the probe-failure regression trap -- it guards a secure-by-default surface with a one-test fix.
Full per-persona findings
Auth Expert
No findings.
Test Coverage Expert
- [recommended] _sparse_checkout_is_complete probe-failure branch (CalledProcessError/TimeoutExpired/OSError -> False) has no regression trap at
tests/unit/cache/test_git_cache_materialization.py
No test exercises the except branch; grep of tests/ found no references to _sparse_checkout_is_complete or _unmaterialized_paths. If a refactor narrowed the except clause, a probe crash would propagate from the cache-hit/write-dedup path instead of rebuilding.
Suggested: Add a parametrized unit test monkeypatching _unmaterialized_paths to raise CalledProcessError/TimeoutExpired/OSError and asserting _sparse_checkout_is_complete returns False.
Proof (missing at):tests/unit/cache/test_git_cache_materialization.py::test_probe_failure_treats_shard_as_incomplete-- proves: A git ls-files --deleted crash on a cached sparse shard triggers a graceful rebuild instead of propagating the subprocess error
Performance Expert
- [recommended] Per-dependency git ls-files spawn on every warm sparse cache hit is permanent overhead for a transient problem; amortize via config pin. at
src/apm_cli/cache/git_cache.py:338
_sparse_checkout_is_complete spawns 'git ls-files --deleted -z' on every warm cache hit for sparse deps (get_checkout, inside shard_lock). Git parses the full index (O(total tracked files), not O(cone)); ~2-5ms for 10K files, ~10-30ms for 100K-file monorepos, plus fork/exec. Once healed, every subsequent warm hit pays the same cost for no benefit. Write-dedup and fresh-checkout probes are cold paths and negligible.
Suggested: After the probe passes, persist a local config pin in the shard's .git/config and skip the probe on later hits; unpinned (legacy, possibly poisoned) shards still get probed. - [recommended] 60s timeout on the ls-files probe inside shard_lock is disproportionate; tighten to ~10s to bound lock hold on failure. at
src/apm_cli/cache/git_cache.py:181
A healthy ls-files completes far under 1s even on huge monorepos. On the cache-hit and write-dedup paths the probe runs inside shard_lock, so a pathological 60s hang serializes every concurrent consumer of that shard. TimeoutExpired is already caught and treated as incomplete, so a shorter bound is safe.
Suggested: Add a timeout parameter; pass ~10s from cache-hit/write-dedup; keep 60s for the fresh-checkout probe.
This panel is advisory. It does not block merge. Re-apply the
panel-review label after addressing feedback to re-run.
Generated by autopilot-pr-review-worker. This comment is AI-generated and may contain errors.
Addresses the PR #3602 panel follow-ups (performance-expert x2, test-coverage-expert). The #3071 ls-files completeness probe ran on every warm sparse cache hit; verified shards now carry a local apm.sparseMaterialization=complete pin and skip the spawn. Shards from 0.29.1+ lack the pin, so they are still probed once and healed or pinned. The cache-hit and write-dedup probe runs inside the shard lock, so it now uses a 10s timeout instead of 60s. New tests trap the pin skip and the probe-failure branch (CalledProcessError, TimeoutExpired, OSError -> rebuild); each was mutation-checked. Co-authored-by: Copilot App <[email protected]>
Addresses the PR #3602 delta-panel follow-ups (performance-expert, test-coverage-expert). The fresh-checkout pin write ran inside the create try block, so a git config failure removed a checkout already verified complete. The pin only lets later hits skip the probe, so the helper now logs and ignores write failures on both call sites. A new test fails pin writes and asserts the checkout lands, stays valid, and is probed again on the next hit; it was mutation-checked. Co-authored-by: Copilot App <[email protected]>
…orepo-de Co-authored-by: Copilot App <[email protected]>
…orepo-de Co-authored-by: Copilot App <[email protected]>
APM Review Panel:
|
| PR | head SHA | CEO stance | iters | folds | defers | Copilot rounds | CI | mergeable | mergeStateStatus | notes |
|---|---|---|---|---|---|---|---|---|---|---|
| #3602 | 2a2013f |
ship_now | 3 | 7 | 1 | 2 | green | MERGEABLE | BLOCKED | pending required review; trial merge with open #3599 is clean |
Convergence
3 outer iterations and 2 Copilot rounds. Final panel stance: ship_now. Ready for maintainer review.
Panel summary
| Persona | B | R | N | Takeaway |
|---|---|---|---|---|
| Auth Expert | 0 | 0 | 0 | Pin-write swallowing cannot affect the IncompleteCheckoutError credential-retry path; no auth concerns in this delta. |
| Test Coverage Expert | 0 | 0 | 0 | Prior delta finding resolved: test_pin_write_failure_keeps_verified_checkout regression-traps both call sites; no new coverage gaps in this delta. |
| Performance Expert | 0 | 0 | 0 | Prior cold-path pin-write finding resolved; guard centralized in _pin_sparse_completeness helper. No new perf concerns in this delta. |
B = blocking-severity findings, R = recommended, N = nits.
Counts are signal strength, not gates. The maintainer ships.
Top 1 follow-ups
- [Test Coverage Expert] Pre-existing: 3 tests in tests/integration/test_git_cache_hermetic.py::TestCreateCheckout fail on plain main (mocked subprocess.run str stdout vs fix(git): materialize package links from Git objects on every host #3603 materialize_tracked_symlinks bytes expectation) -- Out of scope for this PR -- failures reproduce on main without this branch. Noted for backlog visibility; file against fix(git): materialize package links from Git objects on every host #3603 or a follow-up.
Recommendation
All four panel findings across three iterations have been folded and mutation-checked; zero in-scope items remain, and CI is green at the exact head. The one listed follow-up is a pre-existing test breakage on main from #3603, not introduced by this PR.
Full per-persona findings
Auth Expert
No findings.
Test Coverage Expert
No findings.
Performance Expert
No findings.
This panel is advisory. It does not block merge. Re-apply the
panel-review label after addressing feedback to re-run.
Generated by autopilot-pr-review-worker. This comment is AI-generated and may contain errors.
Resolve conflicts with the link-text checkout rewrite (#3599/#3602) in git_cache.py, bare_cache.py, git_env.py and git_sparse.py by taking main's version and re-applying this PR's mechanical text=True -> run_git_text rewrite to the remaining Git text-mode calls. main's new bytes-mode ls-tree/cat-file path in git_sparse stays as is. The sparse regression test now drives main's public apply_sparse_cone, sparse_checkout_active and materialize_tracked_symlinks instead of the removed _tracked_symlinks helper. Co-authored-by: Copilot App <[email protected]>
Clean merge of eight main commits (#3408, #2231, #2602, #3640, #3611, #3645, #3602, #3646); no lockfile or autopilot package conflicts and apm audit --ci passes with no drift. Co-authored-by: sergio-sisternes-epam <[email protected]> Co-authored-by: Copilot App <[email protected]>
Resolve the git_cache.py conflict with #3602 (incomplete promisor checkout retry): keep main's `checkout =` result binding and route it through run_git_text, and route main's new ls-files probe and sparse completeness pin through run_git_text as well. Co-authored-by: Copilot App <[email protected]>
Description
TL;DR
Since 0.29.1,
apm installof a transitivegit:+path:dependency from a private GitHub monorepo can cache an empty sparse checkout, which then failsNot a valid APM package. On Git older than 2.36,git checkoutexits 0 even when the anonymous blob fetch is rejected.GitCachenow detects tracked files missing after a promisor checkout and raises an auth-classifiable error, so the existing anonymous-first fallback retries with credentials. It also rebuilds incomplete shards left in the cache by earlier versions.Note
Root-cause analysis and the
git ls-files --deletedidea come from jiteshjadav-rogers's investigation on the issue. This PR reproduces that analysis with a real Git 2.33 binary, bisects it to #2722, and adds regression tests plus a self-healing cache-hit path. Thanks also to danielle060821 for the earlier reproduction attempts that narrowed the shape.Problem (WHY)
AuthResolver.try_with_fallback(unauth_first=True)for github.com-class hosts. It only retries with a token when the anonymous attempt raises (core/auth.pyunauth-first branch).<shard>__ppartial bare, a transitive sparse checkout needs no network untilgit checkoutlazily fetches blobs. On Git < 2.36, a rejected promisor fetch during a non-forced checkout still exits 0. The result is that HEAD and the index move but the worktree stays empty._create_checkoutonly checked the exit code and HEAD, so the empty shard was landed as valid. Every later run, including the credentialed retry, then got a cache hit on it. Validation reported the barerepo_url, which hid the real cause.Approach (WHAT)
git ls-files --deleted -z. Any missing tracked file raisesIncompleteCheckoutError, the staged directory is removed, and nothing lands.stderr, soAuthResolver.is_public_github_auth_failuresees the anonymous rejection and retries with the resolved token.apm cache clean.Implementation (HOW)
src/apm_cli/cache/git_cache.py: addsIncompleteCheckoutError(RuntimeError)with astderrattribute and the_unmaterialized_paths/_sparse_checkout_is_completehelpers (L167-L203).get_checkoutruns the probe before trusting a sparse hit (L330)._create_checkoutruns it in write-dedup and after a fresh promisor checkout (L931). The resolver,AuthResolver, the auth classifier, and containment checks are untouched.tests/unit/cache/test_git_cache_materialization.py(new): a diamond monorepo fixture (pkg-a -> pkg-b -> pkg-shared, pluspkg-a -> pkg-shared) declared through realgit:+path:manifests. Old-Git behavior is emulated by turning the SHA checkout intoread-tree+update-refwith exit 0 and the anonymous-fetch stderr.tests/unit/cache/test_git_cache_recency.py: no longer changed. fix(git): materialize package links from Git objects on every host #3603 removed_finalize_sparse_checkoutand the recency test that targeted it, so the merge withmaindrops the stub.apm.sparseMaterialization=completepin, so warm cache hits skip thels-filesspawn. Shards from 0.29.1+ lack the pin, so they are probed once and then healed or pinned. The probe under the shard lock uses a 10s timeout. A failed pin write is logged and ignored. On a fresh checkout, the probe runs before fix(git): materialize package links from Git objects on every host #3603'smaterialize_tracked_symlinks.docs/src/content/docs/reference/cli/cache.md: one paragraph on how sparse variants fetch on demand and are discarded or rebuilt when incomplete.Diagrams
Legend: a transitive sparse checkout before and after this PR. The boxed steps are new. Read the
altbranch first.sequenceDiagram participant DL as GitHubPackageDownloader participant AR as AuthResolver participant GC as GitCache participant G as git (< 2.36) DL->>AR: try_with_fallback(unauth_first) AR->>GC: get_checkout(env without token) GC->>G: clone --local from cached __p bare GC->>G: checkout SHA (lazy blob fetch rejected) G-->>GC: exit 0, worktree empty rect rgb(230, 245, 255) GC->>G: ls-files --deleted -z G-->>GC: packages/pkg-shared/apm.yml ... GC-->>AR: raise IncompleteCheckoutError (stderr kept) end alt before this PR GC-->>DL: empty shard landed and cached Note over DL: validate fails - Not a valid APM package else after this PR AR->>AR: is_public_github_auth_failure -> true AR->>GC: get_checkout(env with token) GC-->>DL: complete shard, package validates endTrade-offs
git ls-filesspawn per unverified sparse shard. Shards are probed once and then pinned, so caches poisoned by 0.29.1-0.35.x heal withoutapm cache clean, and warm hits on verified shards spawn nothing. This follows the existing pin-rematerialization precedent.AuthResolverdecide; no checkout-time credential logic. The retry policy stays in its single owner (try_with_fallback). The cache only reports the incomplete state with Git's own diagnostics. A non-auth failure surfaces as an error instead of a silently empty package.git: parentsentinel behavior is out of scope per the approved record. It shares this cache path, so it should benefit, but no sentinel code was changed.Benefits
git:+path:dependencies from private monorepos install on Git < 2.36 without theAPM_NO_CACHE=1workaround.checkouts_v1/, which removes a persistent cache-poisoning vector.apm cache clean).Not a valid APM packageagainst the bare repo URL.Issue and approved scope
Issue: Fixes #3071
Human scope-approval comment: #3071 (comment). This is the canonical
apm-scope:v1record; trusted-copyeligibility.cjsreportsrecord-present. The approval was reconfirmed for this delivery by Daniel Meppiel (@danielmeppiel), the review contact, on 2026-11-12.Does this PR complete the issue, or what remains? It completes the approved scope: it restores declared-subdirectory resolution and validation for nested and transitive Git+path monorepo dependencies. The regression was reproduced before coding (Git 2.33, see Validation), and a consumer/parent/child (diamond) fixture proves the declared subdirectory resolves and validates. Unrelated resolution and containment behavior are unchanged. Separate
git: parentsentinel defects, if any remain, are out of scope per the record.Type of change
Testing
Reproduction before coding (real Git 2.33.0 built from source, HEAD without the fix)
Fixture: the parent sparse install seeds the
__ppartial bare, then the remote rejects blob fetches.Bisect:
git log v0.29.0..v0.29.1 -- src/apm_cli/deps/github_downloader.py→74f05e4c0 fix: authenticate private subdirectory cache (closes #2714) (#2722)introduced_persistent_cache_checkoutwithunauth_first=True.Validation
Note
Local preflight skipped by maintainer instruction (2026-11-12); CI is the gate.
Tests, mutation break, and CI-mirror lint (rebased onto origin/main 1009d4b)
Scenario Evidence
pkg-afrom a private monorepo resolves its transitivegit:+path:deps (pkg-b, thenpkg-shared, plus the diamond edge) from the declared subdirectory, retrying with my token when anonymous blob fetches are rejectedtests/unit/cache/test_git_cache_materialization.py::test_transitive_monorepo_subdirectory_retries_with_credentials(regression-trap for #3071)tests/unit/cache/test_git_cache_materialization.py::test_silent_promisor_checkout_raises_auth_signal_and_lands_nothing(regression-trap for #3071)apm cache cleantests/unit/cache/test_git_cache_materialization.py::test_cached_incomplete_sparse_shard_is_rematerializedtests/unit/cache/test_git_cache_materialization.py::test_verified_sparse_shard_skips_probe_on_hittests/unit/cache/test_git_cache_materialization.py::test_probe_failure_treats_shard_as_incompletetests/unit/cache/test_git_cache_materialization.py::test_pin_write_failure_keeps_verified_checkoutHow to test
uv run --extra dev pytest tests/unit/cache/test_git_cache_materialization.py -q→ 3 passed._unmaterialized_pathsreturn[]→ all 3 fail; revert.PATH: run a private-monorepo diamond install (from the issue) afterapm cache clean→ installs withoutAPM_NO_CACHE=1.Spec conformance (OpenAPM v0.1)
If this PR changes behaviour that an OpenAPM v0.1
req-XXXcovers,confirm the three-step ritual in the
development guide:
docs/src/content/docs/specs/openapm-v0.1.mdupdated(new/changed
<a id="req-XXX"></a>anchor + prose + Appendix Crow).
docs/src/content/docs/specs/manifests/openapm-v0.1.requirements.ymlupdated.
@pytest.mark.req("req-XXX")test undertests/spec_conformance/added or extended.CONFORMANCE.{md,json}regenerated viauv run --extra dev python -m tests.spec_conformance.gen_statementand committed.
Co-authored-by: Copilot [email protected]