Skip to content

fix(deps): invalidate the manifest parse cache when apm.yml is rewritten, so re-downloads re-stamp - #2627

Merged
Daniel Meppiel (danielmeppiel) merged 17 commits into
microsoft:mainfrom
McNultyyy:fix/2619-stamp-cache
Nov 12, 2026
Merged

Daniel Meppiel (danielmeppiel) merged 17 commits into
microsoft:mainfrom
McNultyyy:fix/2619-stamp-cache

Conversation

@McNultyyy

@McNultyyy McNultyyy commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Originally stacked on #2620; now rebased onto main (post-merge) as a single commit.

Summary

Fixes a pre-existing bug surfaced while verifying #2620 end-to-end: APMPackage.from_apm_yml memoizes per path for the process lifetime, but marketplace-plugin flows rewrite apm.yml twice within a run (synthesis at 0.0.0, then the short-SHA stamp). On a same-process re-download (e.g. integrate's content-hash mismatch pre-check rmtrees and re-acquires), re-synthesis writes a fresh 0.0.0 manifest but from_apm_yml returns the stale stamped instance — stamp_plugin_version's version == "0.0.0" guard skips, and the tree is left unstamped on disk, hashing to a value no lockfile ever recorded.

Observable on current main (#2620 included): apm install --update against a stale lockfile records the unstamped-tree hash, and every subsequent fresh install hard-fails the supply-chain check with a hash matching neither domain. (Empirically reproduced with anthropics/skills.)

Fix

  • invalidate_apm_yml_cache_entry(path), called from every apm.yml rewrite site inside package trees (synthesis, stamp_plugin_version, virtual-file manifests).
  • Cache mutations hold a module lock — the invalidation iterates the dict while parallel pre-download/resolver worker threads insert into it (RuntimeError: dictionary changed size during iteration, reproduced; stress test included).
  • A generation counter makes invalidation a barrier for in-flight parses: a parse that read pre-rewrite bytes skips its cache insert (the caching lives in from_apm_yml; from_mapping stays cache-free).
  • download_package's persistent-cache fast path already routes through stamp_plugin_version since feat(agent-plugins): add a portable v1 foundation #2654 — with the invalidation now inside stamp_plugin_version, that shared implementation also becomes safe on same-process re-downloads.

With this, apm install --update becomes a safe migration path for pre-#2620 Windows lockfiles. Full auto-migration is stacked PR #2628.

🤖 Generated with Claude Code


Closes #3585

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.

Pull request overview

This pull request fixes a same-process re-download bug where APMPackage.from_apm_yml() could return a stale, cached manifest instance after apm.yml was rewritten (notably during marketplace-plugin synthesize + SHA-stamp flows), leading to skipped re-stamping and an on-disk tree hash that no lockfile ever recorded.

Changes:

  • Add invalidate_apm_yml_cache_entry() plus a module lock and a generation barrier to make manifest-cache invalidation safe under concurrent parsing/insertion.
  • Call cache invalidation after every apm.yml rewrite in package-tree flows (plugin synthesis, stamping, virtual-file package manifests).
  • Add unit tests covering invalidation correctness, same-process restamp after resynthesis, concurrent inserts during invalidation, and “in-flight parse cannot re-poison cache” behavior.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
tests/unit/deps/test_stamp_plugin_version.py Adds regression tests for cache invalidation and concurrency/in-flight parse barriers around apm.yml rewrites.
src/apm_cli/models/apm_package.py Implements cache invalidation API, locking around cache mutations, and a generation barrier to prevent stale re-inserts.
src/apm_cli/deps/plugin_parser.py Invalidates from_apm_yml cache after synthesizing apm.yml for marketplace plugins.
src/apm_cli/deps/package_validator.py Invalidates from_apm_yml cache after stamping apm.yml with the short SHA.
src/apm_cli/deps/github_downloader.py Invalidates from_apm_yml cache after writing virtual-file apm.yml manifests (keeps rewrite invariant uniform).

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread src/apm_cli/models/apm_package.py Resolved
McNultyyy added a commit to McNultyyy/apm that referenced this pull request Aug 24, 2026
…es (apm#2619)

Removes the manual migration step the microsoft#2619 core fix left behind.
Lockfiles and warm apm_modules trees recorded by a pre-fix APM on
Windows carry the CRLF-domain content hash of the APM-authored synthetic
files; without migration, upgrading surfaces a misleading
"supply-chain attack" hard failure until the user regenerates.

- Fresh downloads: when the locked hash equals the fresh tree re-hashed
  with ONLY the APM-authored files (synthetic apm.yml, inline
  hooks.json) CRLF-expanded, the difference is provably the benign
  legacy line-ending domain -- accept, warn once, re-record the
  platform-independent hash. The equivalence is as strong as the hash
  itself; genuine tampering still hard-fails (negative-control test).
- Cached installs: legacy CRLF bytes in APM-authored files are
  rewritten to LF BEFORE the hash is re-recorded, so stale CRLF-domain
  hashes stop propagating into regenerated lockfiles. Upstream
  (git-materialized) content is never touched; hooks.json counts as
  APM-authored only when the plugin manifest declares hooks inline, and
  authored paths behind symlinked directories are skipped (mirroring
  compute_package_hash's enumeration, which never descends symlinks).
- Panel follow-up (microsoft#2620): hermetic marketplace-plugin lockfile write +
  `install --frozen` replay tests. The positive replay re-downloads
  through the real synthesize+stamp chain in the same process WITHOUT
  clearing the manifest parse cache -- a direct regression guard for
  the stamping-cache fix -- and a tampered-lockfile negative control
  keeps the frozen supply-chain gate closed.
- The symlinked-parent guard test now models the fresh-tree (LF)
  scenario it protects: an already-CRLF apm.yml CRLF-expands to itself,
  so no override exists and legacy_crlf_hash correctly returns None.

New module apm_cli/install/legacy_crlf.py;
compute_package_hash_with_overrides computes the CRLF-domain equivalent
without mutating the tree. Verified end-to-end against the real
anthropics/skills repro: a pre-fix Windows lockfile installs --frozen
with a one-time warning and converges; a CRLF-ified warm tree
self-heals on the next install; reruns are silent.

Stacked on the manifest-cache stamping fix microsoft#2627 (required: the
mismatch-triggered re-download must re-stamp for the fresh hash to be
canonical). microsoft#2620 is merged; this branch is rebased on main past it.

apm-spec-waiver: one-time migration shim for pre-fix Windows lockfiles -- accepts the provably-benign legacy CRLF-domain content_hash of APM-authored synthetic files once and re-records the canonical hash; content_hash canonical-tree semantics are reserved for OpenAPM v0.2 (v0.1 spec section 5.6 editorial note), so no v0.1 normative contract changes

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HoaTXUT9rARKFG7Dr1qNsv
McNultyyy added a commit to McNultyyy/apm that referenced this pull request Aug 24, 2026
…es (apm#2619)

Removes the manual migration step the microsoft#2619 core fix left behind.
Lockfiles and warm apm_modules trees recorded by a pre-fix APM on
Windows carry the CRLF-domain content hash of the APM-authored synthetic
files; without migration, upgrading surfaces a misleading
"supply-chain attack" hard failure until the user regenerates.

- Fresh downloads: when the locked hash equals the fresh tree re-hashed
  with ONLY the APM-authored files (synthetic apm.yml, inline
  hooks.json) CRLF-expanded, the difference is provably the benign
  legacy line-ending domain -- accept, warn once, re-record the
  platform-independent hash. The equivalence is as strong as the hash
  itself; genuine tampering still hard-fails (negative-control test).
- Cached installs: legacy CRLF bytes in APM-authored files are
  rewritten to LF BEFORE the hash is re-recorded, so stale CRLF-domain
  hashes stop propagating into regenerated lockfiles. Upstream
  (git-materialized) content is never touched; hooks.json counts as
  APM-authored only when the plugin manifest declares hooks inline, and
  authored paths behind symlinked directories are skipped (mirroring
  compute_package_hash's enumeration, which never descends symlinks).
- Panel follow-up (microsoft#2620): hermetic marketplace-plugin lockfile write +
  `install --frozen` replay tests. The positive replay re-downloads
  through the real synthesize+stamp chain in the same process WITHOUT
  clearing the manifest parse cache -- a direct regression guard for
  the stamping-cache fix -- and a tampered-lockfile negative control
  keeps the frozen supply-chain gate closed.
- The symlinked-parent guard test now models the fresh-tree (LF)
  scenario it protects: an already-CRLF apm.yml CRLF-expands to itself,
  so no override exists and legacy_crlf_hash correctly returns None.

New module apm_cli/install/legacy_crlf.py owns the migration semantics
(accept_legacy_crlf_mismatch, converge_warm_tree) so install/sources.py
keeps only compact call sites and stays within its 1000-LOC
architecture budget; compute_package_hash_with_overrides computes the
CRLF-domain equivalent without mutating the tree. Verified end-to-end against the real
anthropics/skills repro: a pre-fix Windows lockfile installs --frozen
with a one-time warning and converges; a CRLF-ified warm tree
self-heals on the next install; reruns are silent.

Stacked on the manifest-cache stamping fix microsoft#2627 (required: the
mismatch-triggered re-download must re-stamp for the fresh hash to be
canonical). microsoft#2620 is merged; this branch is rebased on main past it.

apm-spec-waiver: one-time migration shim for pre-fix Windows lockfiles -- accepts the provably-benign legacy CRLF-domain content_hash of APM-authored synthetic files once and re-records the canonical hash; content_hash canonical-tree semantics are reserved for OpenAPM v0.2 (v0.1 spec section 5.6 editorial note), so no v0.1 normative contract changes

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HoaTXUT9rARKFG7Dr1qNsv
@McNultyyy
McNultyyy force-pushed the fix/2619-stamp-cache branch from 8a5bfc7 to 6ddb751 Compare August 25, 2026 08:53
McNultyyy added a commit to McNultyyy/apm that referenced this pull request Aug 25, 2026
…es (apm#2619)

Removes the manual migration step the microsoft#2619 core fix left behind.
Lockfiles and warm apm_modules trees recorded by a pre-fix APM on
Windows carry the CRLF-domain content hash of the APM-authored synthetic
files; without migration, upgrading surfaces a misleading
"supply-chain attack" hard failure until the user regenerates.

- Fresh downloads: when the locked hash equals the fresh tree re-hashed
  with ONLY the APM-authored files (synthetic apm.yml, inline
  hooks.json) CRLF-expanded, the difference is provably the benign
  legacy line-ending domain -- accept, warn once, re-record the
  platform-independent hash. The equivalence is as strong as the hash
  itself; genuine tampering still hard-fails (negative-control test).
- Cached installs: legacy CRLF bytes in APM-authored files are
  rewritten to LF BEFORE the hash is re-recorded, so stale CRLF-domain
  hashes stop propagating into regenerated lockfiles. Upstream
  (git-materialized) content is never touched; hooks.json counts as
  APM-authored only when the plugin manifest declares hooks inline, and
  authored paths behind symlinked directories are skipped (mirroring
  compute_package_hash's enumeration, which never descends symlinks).
- Panel follow-up (microsoft#2620): hermetic marketplace-plugin lockfile write +
  `install --frozen` replay tests. The positive replay re-downloads
  through the real synthesize+stamp chain in the same process WITHOUT
  clearing the manifest parse cache -- a direct regression guard for
  the stamping-cache fix -- and a tampered-lockfile negative control
  keeps the frozen supply-chain gate closed.
- The symlinked-parent guard test now models the fresh-tree (LF)
  scenario it protects: an already-CRLF apm.yml CRLF-expands to itself,
  so no override exists and legacy_crlf_hash correctly returns None.

New module apm_cli/install/legacy_crlf.py owns the migration semantics
(accept_legacy_crlf_mismatch, converge_warm_tree) so install/sources.py
keeps only compact call sites and stays within its 1000-LOC
architecture budget; compute_package_hash_with_overrides computes the
CRLF-domain equivalent without mutating the tree. Verified end-to-end against the real
anthropics/skills repro: a pre-fix Windows lockfile installs --frozen
with a one-time warning and converges; a CRLF-ified warm tree
self-heals on the next install; reruns are silent.

Stacked on the manifest-cache stamping fix microsoft#2627 (required: the
mismatch-triggered re-download must re-stamp for the fresh hash to be
canonical). microsoft#2620 is merged; this branch is rebased on main past it.

apm-spec-waiver: one-time migration shim for pre-fix Windows lockfiles -- accepts the provably-benign legacy CRLF-domain content_hash of APM-authored synthetic files once and re-records the canonical hash; content_hash canonical-tree semantics are reserved for OpenAPM v0.2 (v0.1 spec section 5.6 editorial note), so no v0.1 normative contract changes

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HoaTXUT9rARKFG7Dr1qNsv
…ten, so re-downloads re-stamp

APMPackage.from_apm_yml memoizes per (path, source_path) for the process
lifetime, assuming manifest bytes never change within a run. Marketplace-
plugin flows break that assumption twice: validation SYNTHESIZES apm.yml
(version 0.0.0) and stamp_plugin_version REWRITES it with the short
commit SHA. On a same-process re-download (e.g. integrate's content-hash
mismatch pre-check rmtrees and re-acquires), re-synthesis writes a fresh
0.0.0 manifest but from_apm_yml returns the STALE stamped instance, so
the stamp guard (version == "0.0.0") skips and the tree is left
unstamped on disk -- recording/verifying a content hash no lockfile ever
contained. Concretely: `apm install --update` against a stale lockfile
records the unstamped-tree hash, and every subsequent fresh install then
hard-fails the supply-chain check.

Fix:
- invalidate_apm_yml_cache_entry(path): drops all cache entries for a
  manifest path; called from every apm.yml rewrite site inside package
  trees (synthesis, stamp_plugin_version, the virtual-file manifest).
- Cache mutations (insert/clear/invalidate) now hold a module lock:
  the invalidation iterates the dict while parallel pre-download and
  resolver worker threads insert into it, which raised "RuntimeError:
  dictionary changed size during iteration" (reproduced under a
  2-thread stress test, included).
- Invalidation is a barrier for in-flight parses: a generation counter
  bumped under the lock makes from_apm_yml skip its insert (still
  returning the parsed result) when an invalidation landed while it was
  reading the file -- otherwise a parse of pre-rewrite bytes could
  re-poison the cache AFTER the invalidation ran.
- The duplicate inline stamp block in download_package's
  persistent-cache fast path now routes through stamp_plugin_version
  (single stamping implementation, invalidation included).

Stacked on microsoft#2620; makes `apm install --update` a safe migration path
for pre-fix Windows lockfiles (full auto-migration follows separately).

Co-Authored-By: Claude Fable 5 <[email protected]>
@McNultyyy
McNultyyy force-pushed the fix/2619-stamp-cache branch from 6ddb751 to 877ed0c Compare August 27, 2026 07:59
McNultyyy added a commit to McNultyyy/apm that referenced this pull request Aug 27, 2026
…es (apm#2619)

Removes the manual migration step the microsoft#2619 core fix left behind.
Lockfiles and warm apm_modules trees recorded by a pre-fix APM on
Windows carry the CRLF-domain content hash of the APM-authored synthetic
files; without migration, upgrading surfaces a misleading
"supply-chain attack" hard failure until the user regenerates.

- Fresh downloads: when the locked hash equals the fresh tree re-hashed
  with ONLY the APM-authored files (synthetic apm.yml, inline
  hooks.json) CRLF-expanded, the difference is provably the benign
  legacy line-ending domain -- accept, warn once, re-record the
  platform-independent hash. The equivalence is as strong as the hash
  itself; genuine tampering still hard-fails (negative-control test).
- Cached installs: legacy CRLF bytes in APM-authored files are
  rewritten to LF BEFORE the hash is re-recorded, so stale CRLF-domain
  hashes stop propagating into regenerated lockfiles. Upstream
  (git-materialized) content is never touched; hooks.json counts as
  APM-authored only when the plugin manifest declares hooks inline, and
  authored paths behind symlinked directories are skipped (mirroring
  compute_package_hash's enumeration, which never descends symlinks).
- Panel follow-up (microsoft#2620): hermetic marketplace-plugin lockfile write +
  `install --frozen` replay tests. The positive replay re-downloads
  through the real synthesize+stamp chain in the same process WITHOUT
  clearing the manifest parse cache -- a direct regression guard for
  the stamping-cache fix -- and a tampered-lockfile negative control
  keeps the frozen supply-chain gate closed.
- The symlinked-parent guard test now models the fresh-tree (LF)
  scenario it protects: an already-CRLF apm.yml CRLF-expands to itself,
  so no override exists and legacy_crlf_hash correctly returns None.

New module apm_cli/install/legacy_crlf.py owns the migration semantics
(accept_legacy_crlf_mismatch, converge_warm_tree) so install/sources.py
keeps only compact call sites and stays within its 1000-LOC
architecture budget; compute_package_hash_with_overrides computes the
CRLF-domain equivalent without mutating the tree. Verified end-to-end against the real
anthropics/skills repro: a pre-fix Windows lockfile installs --frozen
with a one-time warning and converges; a CRLF-ified warm tree
self-heals on the next install; reruns are silent.

Stacked on the manifest-cache stamping fix microsoft#2627 (required: the
mismatch-triggered re-download must re-stamp for the fresh hash to be
canonical). microsoft#2620 is merged; this branch is rebased on main past it.

apm-spec-waiver: one-time migration shim for pre-fix Windows lockfiles -- accepts the provably-benign legacy CRLF-domain content_hash of APM-authored synthetic files once and re-records the canonical hash; content_hash canonical-tree semantics are reserved for OpenAPM v0.2 (v0.1 spec section 5.6 editorial note), so no v0.1 normative contract changes

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HoaTXUT9rARKFG7Dr1qNsv
@sergio-sisternes-epam

Copy link
Copy Markdown
Collaborator

PR triage recommendation

needs-issue

Recommendation only, not merge or scope approval. A responsible
human maintainer must approve. Labels, automated advice, and
silence are not approval.

Linked issue

none -- community PR without an issue

This PR does not Fixes/Closes a same-repo issue, and
closingIssuesReferences is empty. Related context that is not a
linked accepted issue for this change:

Proposed classification

type/bug, area/lockfile

(empty dimensions on this PR; optional allowlisted labels only)

Suggested next action

Please open a new issue that describes the same-process re-download /
unstamped-tree hash failure (repro, expected vs actual, why it is
outside #2619). Wait for a maintainer to accept that issue before
this implementation is treated as in-scope. Do not merge from this
recommendation.

CODEOWNERS for the touched paths: Daniel Meppiel (@danielmeppiel) Sergio Sisternes (@sergio-sisternes-epam)
(already requested; this comment does not add or remove review requests).

Suggested PR comment

Thank you for contributing this pull request. APM starts with an
issue, not an implementation
(https://github.com/microsoft/apm/blob/main/CONTRIBUTING.md).
Please open an issue describing the user problem so a maintainer
can review and accept the scope first. This PR is labelled
status/deferred until that happens.

#2619 is already accepted and closed for the CRLF/LF synthetic
manifest hash bug (#2620). This PR is a separate process-lifetime
manifest-cache / re-stamp bug and is not linked as a fix for an
open accepted issue.

@sergio-sisternes-epam Sergio Sisternes (sergio-sisternes-epam) added triage/recommended Automated advice completed; not human scope approval. status/deferred Not invited for implementation now; no release commitment. type/bug Something does not work as documented. area/lockfile Lockfile schema, per-file provenance, integrity hashes, drift detection. labels Sep 16, 2026
Resolve conflicts: keep main's 3-tuple from_apm_yml cache key and the
extracted materialize_virtual_file_package owner; move the PR's
virtual-manifest cache invalidation into deps/virtual_file.py.

Co-authored-by: McNultyyy <[email protected]>
Co-authored-by: Copilot App <[email protected]>
materialize_marketplace_manifest synthesizes into a staging file and then
os.replace()s the package-tree apm.yml, so the invalidation inside
synthesize_apm_yml_from_plugin only covered the staging path. A
same-process reload could keep serving the pre-replace manifest. Close
the remaining rewrite site so every package-tree apm.yml rewrite drops
its from_apm_yml cache entries (microsoft#3585 scope: same-process
re-acquisition). Mutation-break: removing the call fails the new test.

Co-authored-by: McNultyyy <[email protected]>
Co-authored-by: Copilot App <[email protected]>
Encodes the microsoft#3585 done-when end to end through validate_apm_package,
stamp_plugin_version and compute_package_hash: a same-process re-download
of a marketplace plugin must hash identically to the first download (the
lockfile record) and to a fresh process. Mutation-break: no-op'ing
invalidate_apm_yml_cache_entry leaves the tree at version 0.0.0 and fails.

Co-authored-by: McNultyyy <[email protected]>
Co-authored-by: Copilot App <[email protected]>
@danielmeppiel

Copy link
Copy Markdown
Collaborator

APM Review Panel: ship_with_followups

Community bugfix restores content-hash integrity for same-process marketplace re-downloads via write-through cache invalidation with correct thread safety.

panel-mode=full; personas=python-architect,supply-chain-security-expert,auth-expert,doc-writer,test-coverage-expert,performance-expert,apm-ceo

cc McNultyyy Daniel Meppiel (@danielmeppiel) Sergio Sisternes (@sergio-sisternes-epam) -- a fresh advisory pass is ready for your review.

All six panelists converge: this PR is a clean, well-scoped bugfix with no blocking findings and no dissent on severity. The python-architect confirms the Lock + generation-counter design is sound and the four invalidation call sites cover every known package-tree apm.yml write path. The supply-chain-security-expert calls it security-positive -- it closes a real integrity gap where a stale manifest cache produced a lockfile hash that would fail on any subsequent fresh install. The performance-expert confirms zero regression: mutations are lock-guarded but the hot-path read (dict.get) stays lock-free, and the O(cache_size) invalidation scan is negligible at realistic package counts. The auth-expert confirms the github_downloader.py hunk is comment-only and auth-neutral.

The test-coverage-expert classified the missing virtual_file.py re-materialization cache test as a nit, but its evidence block declares outcome=missing on a secure-by-default surface, so it is weighted above opinion-only nits and leads the follow-ups. The python-architect's static boundary guard (a lint rule ensuring every future package-tree apm.yml writer also calls the invalidation) is the highest-signal scope-crossing item: it spans the architecture owner registry and every writer, so it is correctly tracked separately.

Strategically, this PR reinforces APM's lockfile-integrity promise. Shipping it promptly with the in-scope follow-ups folded rewards a community contributor who diagnosed the bug end to end.

Dissent. No panelist-vs-panelist dissent. Supply-chain and performance independently flagged the same free-threaded Python (PEP 703) GIL-atomicity note -- convergence, not disagreement.

Aligned with: Secure by default: Restores content-hash integrity so lockfile hashes match materialized trees; the generation-counter barrier prevents races between invalidation and in-flight parses. Governed by policy: A mismatched content_hash breaks reproducible installs and audits; this closes that gap for same-process re-downloads. Oss community driven: Community contributor McNultyyy diagnosed and fixed a real integrity bug; scope was accepted in #3585. Pragmatic as npm: Write-through invalidation with a generation counter is the simplest correct fix; no lockfile schema change, no algorithm swap, no migration burden.

Panel summary

Persona B R N Takeaway
Python Architect 0 1 1 Sound write-through cache invalidation with correct thread safety via Lock + generation counter. No blocking issues. One out-of-scope dual-guardrail recommendation.
Supply Chain Security Expert 0 0 1 Security-positive fix: restores content-hash integrity for same-process re-downloads; TOCTOU barrier via generation counter is sound; no integrity regression.
Auth Expert 0 0 0 github_downloader.py hunk is 3 comment-only lines above an existing stamp_plugin_version call; no auth surface touched, auth-neutral confirmed.
Doc Writer 0 0 3 CHANGELOG entry is accurate, in the right section, ASCII only and credited correctly. No doc page contradicts the fix. Two non-blocking nits.
Test Coverage Expert 0 0 1 Bug-fix regression trap and hash-consistency promise are well-defended by new unit tests across all done criteria; only gap is the defensive virtual_file.py invalidation call (nit).
Performance Expert 0 0 3 No perf regression. Lock only guards mutations; hot-path reads are lock-free. O(n) invalidation scan and global generation counter are justified for realistic cache sizes (10-100 entries).

B = blocking-severity findings, R = recommended, N = nits.
Counts are signal strength, not gates. The maintainer ships.

Top 5 follow-ups

  1. [Test Coverage Expert] Add a dedicated cache-invalidation test for materialize_virtual_file_package. -- The other three apm.yml write sites each have a dedicated invalidation test; this one does not. In scope; fold.
  2. [Python Architect] Add a static lint rule ensuring every package-tree apm.yml writer calls invalidate_apm_yml_cache_entry, registered in the architecture owner index. -- A fifth write site added without invalidation would silently re-introduce the bug. Crosses PR scope (lint rule + owner registry); track separately.
  3. [Doc Writer] Amend the CHANGELOG entry with a one-clause upgrade hint (apm install --update re-records an already-mismatched hash) and drop the ambiguous 'again'. -- Users who already locked an unstamped content_hash need a next step. In scope; fold.
  4. [Python Architect] Wrap the concurrent-insert stress test cleanup in try/finally. -- A failing assertion would leak hundreds of cache entries to later tests. In scope; fold.
  5. [Supply Chain Security Expert] Note the GIL-atomicity assumption (lock-free get and generation snapshot) for free-threaded Python, and the over-invalidation cost ceiling. -- Prevents a subtle regression if APM ever targets PEP 703 builds. In scope; fold as comments.

Architecture

classDiagram
    direction TB
    class APMPackage {
        <<Dataclass>>
        +from_apm_yml(path, source_path, create_config) APMPackage$
    }
    class ManifestCache {
        <<Module Singleton>>
        -_apm_yml_cache dict
        -_apm_yml_cache_lock Lock
        -_apm_yml_cache_generation int
        +invalidate_apm_yml_cache_entry(path)
        +clear_apm_yml_cache()
    }
    class synthesize_apm_yml_from_plugin {
        <<IOBoundary>>
    }
    class stamp_plugin_version {
        <<IOBoundary>>
    }
    class materialize_virtual_file_package {
        <<IOBoundary>>
    }
    class materialize_marketplace_manifest {
        <<IOBoundary>>
    }
    class compute_package_hash {
        <<Pure>>
    }
    APMPackage *-- ManifestCache : from_apm_yml reads and inserts
    synthesize_apm_yml_from_plugin ..> ManifestCache : invalidates after write
    stamp_plugin_version ..> ManifestCache : invalidates after write
    materialize_virtual_file_package ..> ManifestCache : invalidates after write
    materialize_marketplace_manifest ..> ManifestCache : invalidates after write
    stamp_plugin_version ..> APMPackage : rewrites version field
    compute_package_hash ..> APMPackage : hashes materialized tree
    class APMPackage:::touched
    class ManifestCache:::touched
    classDef touched fill:#fff3b0,stroke:#d47600
Loading
flowchart TD
    A["apm install --update: same-process re-download"] --> B["synthesize_apm_yml_from_plugin writes apm.yml version 0.0.0"]
    B --> C["invalidate_apm_yml_cache_entry: bump generation, drop path keys"]
    C --> D["APMPackage.from_apm_yml: cache miss, snapshot generation"]
    D --> E["load_yaml reads fresh 0.0.0 bytes"]
    E --> F{"generation unchanged?"}
    F -->|yes| G["insert into cache under lock"]
    F -->|no| H["skip insert, return parsed result"]
    G --> I{"stamp_plugin_version: version == 0.0.0?"}
    H --> I
    I -->|yes| J["rewrite version to short SHA, invalidate again"]
    J --> K["compute_package_hash matches the first download"]
    I -->|no, pre-fix stale cache| M["stamp skipped: tree stays 0.0.0, hash mismatch"]
Loading

Recommendation

The panel converges cleanly with zero blocking findings across six personas. The fix is correct, thread-safe, and security-positive. Fold the in-scope items (virtual-file invalidation test, CHANGELOG upgrade hint, test try/finally cleanup, free-threading comments) and ship. Track the static boundary-guard lint rule as a separate follow-up.


Full per-persona findings

Python Architect

  • [recommended] Missing static boundary guard for invalidation call-site discipline (out of scope for this bugfix) at src/apm_cli/models/apm_package.py:118
    There are now 4 package-tree apm.yml write sites; a 5th added without invalidate_apm_yml_cache_entry would silently re-introduce the bug. No static guard in scripts/lint-architecture-boundaries.sh enforces the call. Out of scope for the bugfix PR but worth tracking.
    Suggested: Follow-up: add a static boundary check ensuring every package-tree apm.yml writer also calls invalidate_apm_yml_cache_entry, and register it in the architecture owner index.
  • [nit] Concurrent-insert stress test cache cleanup is not guarded by try/finally at tests/unit/deps/test_stamp_plugin_version.py
    clear_apm_yml_cache() runs after the assertions; a failing assert leaves hundreds of unique-keyed entries in the module cache for later tests.
    Suggested: Move the cleanup into a finally block or a fixture.

Supply Chain Security Expert

  • [nit] Document GIL-atomicity assumption on generation counter read for free-threaded Python forward-compat at src/apm_cli/models/apm_package.py:855
    generation_snapshot reads outside the lock relying on GIL atomicity; free-threaded Python (PEP 703) would need the lock or atomics here.
    Suggested: Add a short comment alongside the snapshot line.

Auth Expert

No findings.

Doc Writer

  • [nit] Entry does not say what users with an already-mismatched lockfile should do at CHANGELOG.md:28
    A user who already locked an unstamped content_hash will still fail the integrity check on a fresh install after upgrading. The entry gives no next step.
    Suggested: Add one short clause: lockfiles written by affected versions need one apm install --update to re-record the hash.
  • [nit] 'stamp ... again' could be misread at CHANGELOG.md:28
    Reads as if behavior once worked and is restored; the re-download now gets stamped like the first download.
    Suggested: ...stamp the re-materialized tree with the short commit SHA, as the first download does, so the content_hash...
  • [nit] The changelog instructions show a non-ASCII em dash in the credit format at .github/instructions/changelog.instructions.md:19
    Pre-existing. .github/instructions/changelog.instructions.md shows an em dash credit; repo requires ASCII and CHANGELOG uses '-- by Ilya Solovyov (@user) (#PR)'.
    Suggested: Credit external contributors inline: -- by @username (#PR_NUMBER).

Test Coverage Expert

  • [nit] materialize_virtual_file_package invalidation call has no dedicated cache-invalidation test at src/apm_cli/deps/virtual_file.py:67
    The other three apm.yml-rewrite call sites each have a dedicated invalidation test; virtual_file.py has none. Defensive (virtual manifests use 1.0.0), but a one-test analog prevents silent drift.
    Suggested: Call materialize_virtual_file_package twice with different content and assert from_apm_yml returns the second manifest.
    Proof (missing at): tests/unit/deps/test_virtual_file_materialization.py::test_rematerialization_invalidates_cached_virtual_file_manifest -- proves: Same-process re-materialization of a virtual-file package serves the fresh manifest, not a stale cache entry

Performance Expert

  • [nit] invalidate_apm_yml_cache_entry does an O(cache_size) key scan under the lock; a secondary index would make it O(variants) at src/apm_cli/models/apm_package.py:130
    ~20-40 scans * 100 entries * ~100ns = 200-400us per install; negligible. Lock hold ~20us at n=100. Not justified until profiling shows contention on >>100-package installs. No action needed now.
    Suggested: If profiling shows contention, maintain a dict[Path, set[key]] index alongside inserts/clears.
  • [nit] Global generation counter over-invalidation ceiling should be quantified in the inline comment at src/apm_cli/models/apm_package.py:92
    Worst case P in-flight parses skip their insert per invalidation (P extra parses, ~1-5ms each); in practice 1-3 during materialization. Documenting the ceiling protects against adding invalidations to hotter paths.
    Suggested: Append the worst-case cost to the existing comment block.
  • [nit] Lock-free dict.get read relies on CPython GIL atomicity; add a free-threaded Python note at src/apm_cli/models/apm_package.py:89
    Under PEP 703 free-threaded CPython dict.get is not atomic; a one-line note prevents a future subtle regression if APM ever targets nogil builds.
    Suggested: Add a NOTE about free-threaded Python next to the GIL comment.

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.

Every other package-tree apm.yml rewrite site had a dedicated cache
invalidation test; materialize_virtual_file_package did not. Addresses
panel follow-up (test-coverage-expert). Mutation-break: removing the
invalidate call fails the test.

Co-authored-by: McNultyyy <[email protected]>
Co-authored-by: Copilot App <[email protected]>
Move clear_apm_yml_cache() into the finally block so a failing assertion
cannot leak hundreds of cache entries into later tests. Addresses panel
follow-up (python-architect nit).

Co-authored-by: McNultyyy <[email protected]>
Co-authored-by: Copilot App <[email protected]>
The lock-free cache read and generation snapshot rely on the GIL; flag
them for free-threaded CPython. Spell out the over-invalidation cost so
invalidations stay off hot read paths. Addresses panel follow-ups
(supply-chain-security-expert, performance-expert).

Co-authored-by: McNultyyy <[email protected]>
Co-authored-by: Copilot App <[email protected]>
Drop the ambiguous 'again' and tell users with an already-mismatched
lockfile to run apm install --update once. Addresses panel follow-up
(doc-writer).

Co-authored-by: McNultyyy <[email protected]>
Co-authored-by: Copilot App <[email protected]>
@danielmeppiel

Copy link
Copy Markdown
Collaborator

APM Review Panel: ship_now

All in-scope follow-ups are folded and five delta personas report zero new findings; the community fix for re-download content-hash integrity is ready to ship.

panel-mode=delta; personas=python-architect,supply-chain-security-expert,doc-writer,test-coverage-expert,performance-expert,apm-ceo

cc McNultyyy Daniel Meppiel (@danielmeppiel) Sergio Sisternes (@sergio-sisternes-epam) -- a fresh advisory pass is ready for your review.

Material delta since the last advisory (head 289eba8): the four in-scope follow-ups were folded and verified. The test-coverage-expert confirms the virtual-file re-materialization gap is closed by tests/unit/deps/test_virtual_file.py::test_rematerialization_invalidates_cached_manifest (mutation-break verified). The python-architect confirms the try/finally stress-test cleanup and the GIL / PEP 703 and over-invalidation comments are accurate. The supply-chain-security-expert confirms the new CHANGELOG advice (apm install --update once to re-record an unstamped hash) is safe: it is an explicit re-acquisition, not circular trust. The doc-writer confirms the entry follows house style. The performance-expert sees no regression. Two clean merges of main followed, with no conflicts in PR files.

Three items stay out of this PR, each with a boundary note below: a static lint rule plus owner-registry entry for writer invalidation (a guardrail across every apm.yml writer), a pre-existing em dash in an unrelated instructions file, and a secondary index for the invalidation scan (no profiling evidence). None is a regression introduced here.

McNultyyy diagnosed the root cause and supplied the core fix and its concurrency tests; the merge worker added the remaining rewrite-site coverage, the end-to-end hash test and the panel folds on the branch. Shipping it reinforces APM's lockfile-integrity promise.

Aligned with: Secure by default: Same-process marketplace re-downloads now record the stamped content_hash again; the generation barrier keeps in-flight parses from re-poisoning the cache. Governed by policy: Lockfile hashes match the materialized tree, so fresh installs and audits pass; affected lockfiles get an explicit apm install --update path. Oss community driven: Community-diagnosed integrity bug, scope accepted in #3585, landed with folds on the contributor's branch. Pragmatic as npm: Write-through invalidation, no lockfile schema or hash algorithm change, no automatic migration.

Panel summary

Persona B R N Takeaway
Python Architect 0 0 0 All 4 in-scope follow-ups addressed cleanly: virtual_file invalidation test, try/finally cleanup, GIL/PEP-703 + over-invalidation comments, CHANGELOG wording. No new architectural concerns.
Supply Chain Security Expert 0 0 0 Prior GIL/generation-snapshot nit addressed. CHANGELOG --update re-record advice is safe: explicit TOFU re-acquisition, not circular trust; fixes a broken unstamped hash.
Doc Writer 0 0 0 Both prior nits are fixed: again is gone and the --update upgrade hint is in. The #2627 entry is ASCII, ends with -- by Ilya Solovyov (@user) (#PR) and fits the Fixed section length.
Test Coverage Expert 0 0 0 Prior virtual_file invalidation gap closed by test_rematerialization_invalidates_cached_manifest. Delta is comment-only + test-reliability; no new behavioral change, no new gap.
Performance Expert 0 0 0 Both prior nits (over-invalidation cost comment, free-threading PEP 703 note) addressed with accurate wording; secondary-index correctly deferred; no new perf concerns in delta.

B = blocking-severity findings, R = recommended, N = nits.
Counts are signal strength, not gates. The maintainer ships.

Top 1 follow-ups

  1. [Python Architect] Track a static lint rule ensuring every package-tree apm.yml writer calls invalidate_apm_yml_cache_entry, registered in the architecture owner index. -- A future writer without the call would silently re-introduce the stale-cache bug; the rule spans every writer and the owner registry, so it belongs in its own issue.

Folded in this run

  • (scope gap) Merged main: kept the 3-tuple cache key and moved virtual-manifest invalidation into the new deps/virtual_file.py owner -- resolved in 03c3780.
  • (scope gap) Invalidate the cache after materialize_marketplace_manifest replaces the package-tree apm.yml (the staged synthesis only invalidated the stage path) -- resolved in c047fc0.
  • (scope gap) End-to-end regression test: re-download hash == recorded hash == fresh-process hash via validate_apm_package + stamp_plugin_version + compute_package_hash -- resolved in 86796ff.
  • (scope gap) CHANGELOG entry crediting McNultyyy -- resolved in 289eba8.
  • (panel) Virtual-file re-materialization invalidation test -- resolved in 20b4b5b.
  • (panel) Stress-test cache cleanup in finally -- resolved in c1a3e98.
  • (panel) GIL / PEP 703 and over-invalidation cost comments -- resolved in eac1cdd.
  • (panel) CHANGELOG wording and apm install --update re-record hint -- resolved in 3bb6223.

Copilot signals reviewed

  • src/apm_cli/models/apm_package.py -- LEGIT: "single-opcode" overstated dict.get atomicity (resolved in 877ed0c; thread replied and resolved).

Deferred (out-of-scope follow-ups)

  • (panel) Static lint rule + owner-registry entry enforcing invalidation at every package-tree apm.yml writer -- scope boundary: new cross-cutting architecture guardrail over all writers, beyond the [BUG] Re-downloaded marketplace-plugin trees stay unstamped, so lockfile hashes fail on fresh installs #3585 bug fix.
  • (panel) Em dash in .github/instructions/changelog.instructions.md -- scope boundary: pre-existing text in an unrelated instructions file.
  • (panel) Secondary index for the invalidation key scan -- scope boundary: performance optimization without profiling evidence; the persona recommends no action now.

Regression-trap evidence (mutation-break gate)

  • tests/unit/deps/test_stamp_plugin_version.py::test_same_process_redownload_hash_matches_lockfile_and_fresh_install -- deleted the body of invalidate_apm_yml_cache_entry; test FAILED (re-downloaded tree stayed version: 0.0.0); guard restored.
  • tests/unit/deps/test_shared.py::TestValidateAndLoadPackage::test_rematerialization_invalidates_cached_manifest -- deleted the _shared.py invalidate call; test FAILED; guard restored.
  • tests/unit/deps/test_virtual_file.py::test_rematerialization_invalidates_cached_manifest -- deleted the virtual_file.py invalidate call; test FAILED; guard restored.

Lint contract

ruff check and ruff format --check (src/, tests/, architecture-linter scripts) silent; pylint R0801 10.00/10; lint-auth-signals.sh and lint-architecture-boundaries.sh exit 0, on the PR merged with current main.

CI

All 26 checks pass, 2 skipped, at b0d0d5c (fork runs approved; no .github/ changes in this PR's diff); license/cla SUCCESS (after 0 CI fix iterations).

Mergeability status

PR head SHA CEO stance iters folds defers Copilot rounds CI mergeable mergeStateStatus notes
#2627 b0d0d5c ship_now 2 8 3 1 green MERGEABLE BLOCKED pending required review

Recommendation

Every in-scope follow-up from the prior advisory is folded and verified, CI is green at the exact head, and the review thread is resolved. Ship; track the static writer-invalidation guard separately.


Full per-persona findings

Python Architect

No findings.

Supply Chain Security Expert

No findings.

Doc Writer

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.

@danielmeppiel

Copy link
Copy Markdown
Collaborator

APM Review Panel: ship_now

Clean main merge, zero PR-file delta, CI green at the exact head; stance holds.

panel-mode=delta; personas=apm-ceo

cc McNultyyy Daniel Meppiel (@danielmeppiel) Sergio Sisternes (@sergio-sisternes-epam) -- a fresh advisory pass is ready for your review.

The only change since the prior advisory (head b0d0d5c) is a clean merge of main (new head e5e0c68, base 0d214b8). It changes zero lines in the PR's 10 files and brings no src/ changes. CI is green at this head (26 pass, 2 skipped, 0 fail), license/cla passes, no review threads are open, and the owner-evidence gate re-verified with 251 functional tests passing at this exact head. No panelist was re-spawned because no persona's owned files changed in the delta range. The prior stance and the single scope-crossing follow-up carry forward unchanged.

Aligned with: Secure by default: Unchanged: same-process marketplace re-downloads record the stamped content_hash; the generation barrier prevents in-flight cache re-poisoning. Pragmatic as npm: Unchanged: write-through invalidation, no lockfile schema or hash algorithm change, no automatic migration.

Top 1 follow-ups

  1. [Python Architect] Track a static lint rule ensuring every package-tree apm.yml writer calls invalidate_apm_yml_cache_entry, registered in the architecture owner index. -- A future writer without the call would silently re-introduce the stale-cache bug; the rule spans every writer and the owner registry, so it belongs in its own issue.

Mergeability status

PR head SHA CEO stance iters folds defers Copilot rounds CI mergeable mergeStateStatus notes
#2627 e5e0c68 ship_now 2 9 3 1 green MERGEABLE BLOCKED pending required review

Recommendation

Main merge only, zero PR-file delta, full CI green at the exact head. Ship; track the static writer-invalidation guard separately. Folds, Copilot classification, deferrals and mutation-break evidence are in the previous advisory (#2627 (comment)).


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 DIRTY merge state for microsoft#2627; merge applied cleanly, both
CHANGELOG entries from main preserved alongside the microsoft#2627 Fixed entry.

Co-authored-by: Copilot App <[email protected]>
Refresh microsoft#2627 against current main; merge applied cleanly.

Co-authored-by: Copilot App <[email protected]>
Refresh microsoft#2627 against current main; CHANGELOG Fixed entries from both
sides kept (microsoft#2627 entry plus main's microsoft#3637 entry and microsoft#3642 Removed section).

Co-authored-by: Copilot App <[email protected]>
Keep main's microsoft#3600 Fixed entry alongside the microsoft#2627 entry.

Co-authored-by: Copilot App <[email protected]>
…list

Main keeps prepending entries at the top of the Unreleased Fixed list,
which GitHub's merge treats as a conflict with this PR's entry at the
same position. Appending it at the end keeps all entries and avoids the
recurring DIRTY state.

Co-authored-by: Copilot App <[email protected]>
@danielmeppiel

Copy link
Copy Markdown
Collaborator

Merged current main into this branch: pre-resolution head e5e0c68 -> new head c444739 (main at 1a37071). Merge-of-main was used instead of a rebase because the branch history already contains merge-from-main commits.

Conflicting paths resolved (faithful merge of both intents):

No product code or tests were changed by the resolution; the merges brought only main's own changes.

Lint contract at c444739: ruff check and ruff format --check (src/ tests/ plus architecture scripts) both silent; pylint R0801 10.00/10; lint-auth-signals.sh and lint-architecture-boundaries.sh exit 0; no src file over 2100 lines.

Exact-head evidence: owner-touch detection at c444739 reports the same 5 touched owner decisions; the PR's 251 functional tests pass at that head. CI on c444739: 26 pass, 2 skipping, 0 fail.

Post-push mergeability: gh pr view --json mergeStateStatus,mergeable reports BLOCKED / MERGEABLE (BLOCKED reflects the code-owner review + merge-queue ruleset, not a conflict). Push used git push https://github.com/McNultyyy/apm.git HEAD:refs/heads/fix/2619-stamp-cache (plain fast-forward push of merge commits, no force).

Ready for maintainer review.


This comment was generated by an AI agent on behalf of the maintainers. It may contain errors; please verify before acting on it.

@danielmeppiel
Daniel Meppiel (danielmeppiel) merged commit da60139 into microsoft:main Nov 12, 2026
28 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/lockfile Lockfile schema, per-file provenance, integrity hashes, drift detection. status/deferred Not invited for implementation now; no release commitment. triage/recommended Automated advice completed; not human scope approval. type/bug Something does not work as documented.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] Re-downloaded marketplace-plugin trees stay unstamped, so lockfile hashes fail on fresh installs

4 participants