Skip to content

fix(policy): fetch an org's absent policy once per command run - #4786

Merged
Daniel Meppiel (danielmeppiel) merged 9 commits into
mainfrom
danielmeppiel-perf-policy-absent-memo
Nov 22, 2026
Merged

Daniel Meppiel (danielmeppiel) merged 9 commits into
mainfrom
danielmeppiel-perf-policy-absent-memo

Conversation

@danielmeppiel

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

Copy link
Copy Markdown
Collaborator

Description

An org without a policy repository answers every candidate (.github-private, .github, .apm, _apm) with 404. A 404 is never cached: policy/discovery.py returns outcome="absent" before _write_cache, and only found policies reach the 1 h disk cache. One apm install discovers 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.py adds 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 via ctx.with_resource.
  • policy/discovery.py decorates _fetch_github_contents with memoized_per_invocation, keeping only 404: results. The key is every argument: repo_ref (host + owner + repo) and the file path.

Unchanged:

  • Success responses keep their disk cache.
  • Errors and timeouts are never reused, so fail-closed behaviour is unchanged.
  • Every run still rediscovers policy, so a policy published between runs is found by the next run.
  • Nothing is persisted.

Boundary agreed with #4778 (L5): one memo layer. #4778 will rebase its git remote memo onto core/invocation_memo.py and drop its own scope and cli() hook.

Evidence (GAINS STANDARD)

  1. Journey: apm install on tree-10 whose project git origin is https://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, no apm_modules) and no-op.
  2. SHAs: base 4a1f9fd9e02 (main) -> new 385bf650ed5. Later commits on the branch add tests, the owner record and the changelog only.
  3. ABAB (2 pairs each). CPU = user+sys incl. children, p50. Load was 38-50 on the shared host, so walls are recorded but void; CPU, counts and round trips are load-independent.
journey base CPU p50 new CPU p50 CPU removed requests connects round trips git subprocesses (credential)
no-op 4.75 s (5.04, 4.46) 3.63 s (3.87, 3.39) -24% (1.31x) 16 -> 4 16 -> 4 48 -> 12 22 -> 10 (16 -> 4)
warm-locked 6.48 s (6.57, 6.39) 5.47 s (6.11, 4.82) -16% (1.18x) 24 -> 8 24 -> 8 72 -> 24 43 -> 27 (24 -> 8)
  1. Counts: every removed request is GET api.github.com/repos/<org>/{.github-private,.github,.apm,_apm}/contents/apm-policy.yml -> 404, and each removed request also removes one git credential fill (and the gh auth token lookup behind it).
  2. Wall at real RTT (structural, from removed round trips): no-op -36 RT (about -1.1 s at 30 ms, -3.6 s at 100 ms); warm-locked -48 RT (about -1.4 s at 30 ms, -4.8 s at 100 ms). This is a constant per install, independent of N, so it applies to every install in a github.com repo whose org publishes no policy.
  3. North Star: tree-10 no-op in a github.com repo is now 3.63 s CPU p50 (gap 2.6 s to 1 s); the remainder is integration CPU, tracked separately.
  4. Scaling: the cost is per install, not per dependency, so tree-50 pays the same 16-24 requests at base.

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_ref form; normalizing that is a separate change. policy/discovery.py is at the 2100-line cap.

QL review points

  • (a) Scope lifecycle: cli() opens the scope via ctx.with_resource, and Click closes it when the root context exits. test_the_scope_is_closed_and_cleared_on_exit and test_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.
  • (b) Host in the key: the key is the full repo_ref (host + owner + repo) plus the file path. test_a_404_is_not_reused_for_another_host and ..._for_another_repository prove it.
  • (c) Anonymous vs authenticated 404: the memo wraps _fetch_github_contents, so it stores the outcome of the whole try_with_fallback chain (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_answer shows 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

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

Testing

  • Tested locally
  • All existing tests pass (CI)
  • Added tests for new functionality (if applicable)

tests/unit/policy/test_policy_absent_memo.py (9 tests) drives the real discover_policy against a fake HTTP boundary:

  • an absent policy is fetched once per invocation (six discoveries)
  • outside an invocation every discovery fetches
  • a policy published between runs is found by the next run
  • errors are never reused
  • no cross-repository or cross-host reuse

Red-first: with the decorator removed, test_absent_policy_is_fetched_once_per_invocation fails; with it, all pass.

Changelog

  • changelog.d/4786.fixed.md

Spec conformance (OpenAPM v0.1)

  • N/A -- policy outcomes per run are unchanged (commit carries apm-spec-waiver:).

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]>
Co-authored-by: Copilot App <[email protected]>

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

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

Comment thread src/apm_cli/core/invocation_memo.py Resolved
Comment thread src/apm_cli/core/invocation_memo.py Resolved
…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]>

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

The process-global memo can leak stale 404s across overlapping invocations, while credential-insensitive caching can hide newly accessible policies after credentials change.

3 open issues

Review effort: Balanced

Comment thread src/apm_cli/policy/discovery.py Resolved
…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]>

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

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]>

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

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

Comment thread src/apm_cli/core/invocation_memo.py Resolved
…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]>

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

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]>

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 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

Daniel Meppiel (danielmeppiel) added a commit that referenced this pull request Nov 22, 2026
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]>
@danielmeppiel
Daniel Meppiel (danielmeppiel) merged commit 5944c95 into main Nov 22, 2026
92 of 95 checks passed
@danielmeppiel
Daniel Meppiel (danielmeppiel) deleted the danielmeppiel-perf-policy-absent-memo branch November 22, 2026 19:26
Daniel Meppiel (danielmeppiel) added a commit that referenced this pull request Nov 22, 2026
…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]>
Daniel Meppiel (danielmeppiel) added a commit that referenced this pull request Nov 22, 2026
…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]>
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.

perf: policy discovery repeats 24 uncached 404 lookups per install for orgs without a policy repo

2 participants