Repository navigation
fix(policy): fetch an org's absent policy once per command run - #4786
Conversation
An org without a policy repository answers every candidate (.github-private, .github, .apm, _apm) with 404, and a 404 is never cached (only found policies reach the 1 h disk cache). One `apm install` discovers policy about six times (commit gate, trust routing, project classification), so it repeated 4 GETs, 4 new TLS connections and 4 token lookups (gh auth token, git credential fill) six times: 24 requests and 72 round trips per install. The GitHub Contents 404 is now reused within one command run: - core/invocation_memo.py: a per-invocation memo scope (stdlib only, shared by worker threads, absent outside a scope); cli() opens one scope per command. - policy/discovery.py: _fetch_github_contents keeps only "404:" results. Success responses keep their disk cache, errors and timeouts are never reused, and every run still rediscovers policy, so freshness and fail-closed behaviour are unchanged. apm-spec-waiver: performance-only change; policy discovery outcomes per run are unchanged, no OpenAPM-observable behaviour changes Co-authored-by: Copilot App <[email protected]>
…owner record Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Copilot App <[email protected]>
There was a problem hiding this comment.
🟡 Changes recommended
Overlapping invocation scopes can leak stale policy 404 results into later calls, and concurrent cache misses can trigger duplicate fetches.
2 open issues
What changed in this PR
This PR reduces repeated GitHub policy lookups for organizations without a policy repository by adding invocation-local reuse of 404 responses to APM’s policy discovery.
Changes:
- Adds a shared memo facility with scope managed by the root CLI.
- Memoizes GitHub Contents 404 results while leaving success caching and error retries unchanged.
- Adds regression coverage, updates the architecture owner record, and documents the performance improvement.
| File | Description |
|---|---|
tests/unit/policy/test_policy_absent_memo.py |
Tests reuse, scope lifetime, retries, and repository/host separation. |
src/apm_cli/policy/discovery.py |
Applies invocation-local memoization to GitHub policy 404s. |
src/apm_cli/core/invocation_memo.py |
Introduces memo scopes and a reusable decorator. |
src/apm_cli/cli.py |
Opens a memo scope for each command invocation. |
changelog.d/4786.fixed.md |
Records reduced policy requests during installation. |
.apm/architecture/owners/contracts-tooling.json |
Records ownership of invocation-local policy memoization. |
Review effort: Balanced
…ed per-command scope The reused 404 is the auth chain's outcome (the recorded request carried the token); the scope is cleared on exit; two CLI invocations each start with an empty memo. Co-authored-by: Copilot App <[email protected]>
…sses fetch once Review follow-up on #4786: any overlap of invocation scopes turns memoization off until the last scope exits, so no invocation reads another's memo and nothing survives the scopes; same-key calls run under a per-key lock so concurrent workers that miss together fetch once, while rejected results still retry. Regression tests for out-of-order exit and concurrent misses. Co-authored-by: Copilot App <[email protected]>
There was a problem hiding this comment.
🔵 Needs a closer look
Cached anonymous 404s survive credential changes during pre-install scripts, allowing installation to bypass an existing private policy; cache invalidation and regression coverage are needed.
1 open issue
2 resolved since last review
Review effort: Balanced
A pre-install script runs user code mid-command and may refresh stored credentials or change the git remote; a policy 404 seen before it must not mask a policy the refreshed credentials can now read. The lifecycle runner now drops every invocation memo after command scripts run (http scripts cannot change local credentials). Regression test fails without the hook. Co-authored-by: Copilot App <[email protected]>
There was a problem hiding this comment.
🟡 Changes recommended
A critical invalidation race lets lookups waiting on an old memo return stale results after it is cleared or an overlapping scope starts, requiring a current-memo check and regression coverage.
1 open issue
1 resolved since last review
Review effort: Balanced
…tured ones Forget runs in a finally around each command script (success, failure or raise), and it clears every named memo in place so a reference captured before the script sees nothing after it. Tests: a failing and a passing post-install script both empty a pre-captured memo; red with the hook replaced by pass. Co-authored-by: Copilot App <[email protected]>
… an invalidation A generation counter bumps on every scope change and forget; a memoized call reads or publishes only if its captured generation is still current, so a waiter refetches and a fetch that straddles an invalidation does not publish. Regression test fails on the previous module. Co-authored-by: Copilot App <[email protected]>
There was a problem hiding this comment.
🟡 Changes recommended
A reproduced invalidation race lets an in-flight fetch repopulate a detached memo and return a stale 404 to a waiting caller, bypassing the lifecycle-script credential-refresh boundary.
1 open issue
1 resolved since last review
Review effort: Balanced
The lifecycle command-script tests spawn real processes, so they move from tests/unit to tests/integration/policy as a component module and assert the script's durable marker file. Pure memo tests stay unit. Removing the forget in the script finally fails all three. Co-authored-by: Copilot App <[email protected]>
There was a problem hiding this comment.
🔵 Needs a closer look
Human assessment is needed because watch-mode caching can cause recompiles to bypass newly published blocking policies, creating a critical policy-enforcement risk.
No open issues 🎉
1 resolved since last review
Review effort: Balanced
Org policy discovery runs several times in one install (preflight, policy gate, target check, MCP) and each shelled out to git remote: 8 subprocesses on a tree-10 no-op. policy/_remote.py::_git now answers repeats within one CLI invocation from core/invocation_memo (#4786), failures included; outside a command run every read is live. apm-spec-waiver: memoizes an identical subprocess read within one command run; no OpenAPM-observable behaviour changes Co-authored-by: Copilot App <[email protected]>
…s root The per-invocation key is the absolute path without collapsing '..' (which abspath would do before symlinks resolve), and git keeps the caller's own cwd. Lifecycle scripts already drop every invocation memo after they run (core/lifecycle_scripts.py, #4786), so a pre-install script that switches origin is seen by the later policy gate. Tests: component marker; the next-run freshness read happens inside a new scope; a '..' path through a symlink is a distinct key. Co-authored-by: Copilot App <[email protected]>
…s root The per-invocation key is the absolute path without collapsing '..' (which abspath would do before symlinks resolve), and git keeps the caller's own cwd. Lifecycle scripts already drop every invocation memo after they run (core/lifecycle_scripts.py, #4786), so a pre-install script that switches origin is seen by the later policy gate. Tests: component marker; the next-run freshness read happens inside a new scope; a '..' path through a symlink is a distinct key. Co-authored-by: Copilot App <[email protected]>



Description
An org without a policy repository answers every candidate (
.github-private,.github,.apm,_apm) with 404. A 404 is never cached:policy/discovery.pyreturnsoutcome="absent"before_write_cache, and only found policies reach the 1 h disk cache. Oneapm installdiscovers policy about six times (commit gate, trust routing, project classification). For every project whose git origin is on github.com, it therefore repeated 4 GETs, 4 new TLS connections and 4 token lookups (gh auth token,git credential fill) six times: 24 requests and 72 round trips per install, about 2.2 s at 30 ms RTT and about 7 s at 100 ms.This PR reuses the GitHub Contents 404 within one command run:
core/invocation_memo.pyadds a per-invocation memo scope. It is stdlib-only, so it adds no CLI import cost; it is shared by worker threads; and outside a scope it is absent, so library callers and tests see no memo.cli()opens one scope per command viactx.with_resource.policy/discovery.pydecorates_fetch_github_contentswithmemoized_per_invocation, keeping only404:results. The key is every argument:repo_ref(host + owner + repo) and the file path.Unchanged:
Boundary agreed with #4778 (L5): one memo layer. #4778 will rebase its
git remotememo ontocore/invocation_memo.pyand drop its own scope andcli()hook.Evidence (GAINS STANDARD)
apm installon tree-10 whose project git origin ishttps://github.com/perf-org/consumer.git(the realistic case), with an offline mirror at rtt 30 whose org has no policy repo. Measured: warm-locked (lockfile + cache, noapm_modules) and no-op.4a1f9fd9e02(main) -> new385bf650ed5. Later commits on the branch add tests, the owner record and the changelog only.GET api.github.com/repos/<org>/{.github-private,.github,.apm,_apm}/contents/apm-policy.yml -> 404, and each removed request also removes onegit credential fill(and thegh auth tokenlookup behind it).Known residue (follow-up, not in this PR): warm-locked still makes 8 requests, not 4. One discovery path keys the same org with a different
repo_refform; normalizing that is a separate change.policy/discovery.pyis at the 2100-line cap.QL review points
cli()opens the scope viactx.with_resource, and Click closes it when the root context exits.test_the_scope_is_closed_and_cleared_on_exitandtest_each_cli_invocation_gets_a_fresh_scope_closed_at_exit(two CliRunner calls in one interpreter each see an empty memo; none remains after) prove it.repo_ref(host + owner + repo) plus the file path.test_a_404_is_not_reused_for_another_hostand..._for_another_repositoryprove it._fetch_github_contents, so it stores the outcome of the wholetry_with_fallbackchain (unauth_first=False), never a single attempt. Every call uses the same resolver and inputs, and within one command the credential sources (process env, gh CLI, git helpers) do not change, so no later call in the same command can hold a different credential.test_the_reused_404_is_the_authenticated_answershows the memoized 404 came from the request that carried the token.Issue and approved scope
Fixes #4782
Human scope-approval comment: scope record on #4782 (regent-ruled, accepted; 0.38.0 bug).
Does this PR complete the issue, or what remains? Completes #4782. ADO and GitLab policy fetchers are out of scope.
Type of change
Testing
tests/unit/policy/test_policy_absent_memo.py(9 tests) drives the realdiscover_policyagainst a fake HTTP boundary:Red-first: with the decorator removed,
test_absent_policy_is_fetched_once_per_invocationfails; with it, all pass.Changelog
changelog.d/4786.fixed.mdSpec conformance (OpenAPM v0.1)
apm-spec-waiver:).