Skip to content

perf(install): normalize each local plugin once; scan non-ASCII text at C speed (#5838 slice 1) - #5839

Open
Daniel Meppiel (danielmeppiel) wants to merge 12 commits into
mainfrom
fix-5838-local-plugin-install-perf
Open

Daniel Meppiel (danielmeppiel) wants to merge 12 commits into
mainfrom
fix-5838-local-plugin-install-perf

Conversation

@danielmeppiel

@danielmeppiel Daniel Meppiel (danielmeppiel) commented Dec 3, 2026 •

Copy link
Copy Markdown
Collaborator

Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: cb648397e813ebbd5629599440778ee465453193

Dimension Assessment Rationale
Change confidence 8/10 ↑ Red-first cells (fresh 14 and re-pass 23, in plain, symlinked and read-only source shapes) fail on main (normalize 28 and 46) and pass at the fix.
↑ Parity cells pin deployed bytes, receipts and lock rows (raw-image digest, package type), green before and after.
↑ AUD SECURITY GO on the ContentScanner half (3,650,702 differential cases, 0 diffs).
↑ AUD SECURITY GO on the reuse half at 924f826 (TOCTOU closed for the raw image); c8ec3603 floor review PASS at 924f826.
↑ Reuse now requires resolve's validated graph node at exactly the recorded destination; mutations removing either check turn unit cells red.
↑ Linux fs budget rows for both plugin journeys come from PR CI lifecycle_smoke at 924f826.
↑ CI at c9e5703: every fs row held on Linux; the only red was calls.copytree (13 vs 10), from a racy counter (shared depth across resolve's parallel copy workers), fixed in bcd7a45: copytree is now exactly 14 / 23 (main 28 / 46), stable across runs.
↑ CI at bcd7a45 caught a real regression (Integration shard 8, test_root_declared_skill_lifecycle_is_bounded): resolve normalizes in a staging dir with an opaque name, and a root-declared skill took that name. Red CI run at bcd7a45: https://github.com/microsoft/apm/actions/runs/47138676579/job/144370830170. Fixed in e619bd4; AUD fold N1 in this head scans every synthesized file (path and content). Red at bcd7a45 src: the e2e, both test_a_root_declared_skill_is_never_named_after_a_staging_slot[user/project] cells and the unit cell; the nested-file cell is red at e619bd4. Mutations on the record line and the scan breadth each turn cells red. The full test_plugin_e2e.py module passes locally (49, with a token, 0 skipped).
↓ CI and tier2 at this head not observed yet; the new path checks add up to 2 realpath calls per reused plugin, inside the 5% slack by estimate, not by a Linux measure.
↓ Normalization outputs (apm.yml, .apm/**) are not digest-bound within one run (AUD Low residual); deferred to slice 8.
Diagnosis confidence 9/10 ↑ Probe traces show the second normalize is install/sources.py:219 (integrate re-copies and re-validates), which matches the analyst's tracer.
Evidence fit 9/10 ↑ The issue's 28 normalize calls for 14 plugins and its per-character scan_text cost both reproduce on a hermetic world of the same shape.

Description

Slice 1 of #5838 (the install-time floor plan). Local multi-plugin apm install -g did every local legacy plugin's work twice, and scanned non-ASCII Markdown one character at a time.

  • Normalize once (install/local_plugin_image.py). Resolve copies a local Claude-style plugin into apm_modules and validation normalizes that image in place. Integrate used to delete it, copy the source again and normalize a second time (install/sources.py:219). Now resolve hashes the raw image of a plain legacy plugin when it copies it, and integrate reuses the image resolve validated: the same bytes, hashed once, normalized once.
    • The fast path is taken only when resolve's graph holds the package, validated, at exactly the recorded apm_modules path, integrate reads that same path, and it finds the apm.yml that resolve's normalization synthesized. A plugin that fails validation is never reused.
    • Normalization names a root-declared skill, and a manifest without a name, after its directory. Resolve normalizes under an opaque staging name, so an image whose synthesized paths or metadata carry that name is normalized again at its destination.
    • Known residual (AUD, Low): files normalization writes (apm.yml, .apm/**) are not digest-bound between resolve and integrate. A reusable seal for them is slice 8's first commit.
    • Follow-up for 0.40 (AUD): normalize at resolve under the destination's logical name, so the staging-name denylist can go.
    • Native Agent Plugins, Codex compatibility manifests, catalog manifests, and any image this run did not produce keep the copy-and-validate path.
    • The audit replay path (drift.py:434) is not hit by install on this world; it normalizes a scratch image for replay only.
  • ContentScanner at C speed. This is 4b1b7d33's fff7c16c, merged unchanged. One regex over the suspicious code points replaces the per-character loop; findings and positions are unchanged. AUD SECURITY GO: 3,650,702 differential cases, 0 diffs, with a negative control that bites.

cost: fresh 14-plugin install -g --target opencode on top of 9 installed (macOS, hermetic world, counters):

Counter main 641743f this PR
normalize_plugin_directory 28 14
copytree (all, cProfile) 184 92
files_written 1,296 921
hashed_bytes 13.9 MB 11.9 MB
stat / lstat 32,368 / 72,392 28,336 / 68,601
scan_text cumulative (cProfile) 296 ms 11 ms
ord() calls 1,184,929 17,758
Python calls (cProfile) 18.5M 15.6M

On re-passing all 23 plugins, normalize goes from 46 to 23. Wall time on the shared host is too noisy to quote.

Linux count-budget rows (tests/perf/count_budgets.json, PR CI lifecycle_smoke, budget = measured + 5%): install-g-14-plugins files_written 783, stat 27,858, lstat 16,956, hashed_bytes 12.5 MB, normalize 14, copytree 14; install-g-23-plugins-repass files_written 602, stat 44,897, normalize 23, copytree 23. The call rows are platform-independent: copytree is counted per thread (main 28 and 46). On main the normalize rows fail (28 and 46); c8ec3603's tracer puts main at about 42% more files written. The validation binding and path checks cost 0 extra reads or hashes, and at most 2 realpath calls per reused plugin.

Issue and approved scope

Issue: Refs #5838 (slice 1 of the floor plan; later slices land as their own PRs)

Human scope-approval comment: #5838 (comment)

Does this PR complete the issue, or what remains? It does not complete the issue. The floor plan's other slices remain: integrate once (2), per-run memos (3), path safety (4), and the rest.

Type of change

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

Testing

  • Tested locally
  • All existing tests pass
  • Added tests for new functionality (if applicable)
promise: P-PERF-count-budgets -- a local multi-plugin install normalizes and copies each plugin once and records what the full path records (source: #5838 scope record)
cell: OP=install SCOPE=user SRC=local PRIM=skill(plugin) TGT=opencode x source shape {plain, symlinked, read-only}   owner: install/local_plugin_image.py (under single-file-package-materialization)
instrument: today test -> tests/integration/test_local_plugin_install_cost.py (new: the counts need the counter hook's new calls table)
oracles: [I1, I7, call counts, byte parity]  decisive: normalize_plugin_directory == 14 (fresh) / 23 (re-pass); copytree == 14 / 23; deployed bytes == source bytes; receipts == file hashes; lock content_hash == raw source digest; package_type marketplace_plugin
failing-before: 429705fd (red-first) -> normalize 28 (fresh), 46 (re-pass), in all 3 shapes
passing-after: 9 passed
guard+mutation: n/a     ledger: n/a (performance)
hints executed: none printed

All local runs went through the host local-test.sh guard, with APM_E2E_TESTS=1:

  • pytest -p no:xdist tests/integration/test_local_plugin_install_cost.py: 9 passed. At 429705f: 6 failed.
  • 43 neighbour modules (local copy, sources, content scanner, normalize): 1,875 passed. The 2 failures in test_sources_materialisation.py were a MagicMock ctx missing the new field; fixed in the stub.
  • pytest tests/unit/install tests/unit/security tests/unit/test_content_scanner*.py: 5,008 passed.
  • Lint mirror, all clean:
    • ruff@0.15.12 check and format;
    • pylint R0801;
    • lint-auth-signals.sh;
    • complexity ratchet, --base-ref 641743fb;
    • taxonomy --changed;
    • assertion and obligation ratchets;
    • lint-architecture-boundaries.sh (the new module is owned under single-file-package-materialization);
    • file length.

Changelog

  • One fragment per section, changelog.d/<pr>.<section>.md, holding
    one line: user-visible effect first, 25 words or fewer, ending with
    (#PR); breaking changes only under upgrade notes; no Highlights; no
    new lines under ## [Unreleased]. See changelog.d/README.md and
    .github/instructions/changelog.instructions.md.
  • N/A -- internal-only change (CI, tests, refactor).

Spec conformance (OpenAPM v0.1)

  • Spec edit: docs/src/content/docs/specs/openapm-v0.1.md updated
    (new/changed <a id="req-XXX"></a> anchor + prose + Appendix C
    row).
  • Manifest edit: docs/src/content/docs/specs/manifests/openapm-v0.1.requirements.yml
    updated.
  • Test edit: a @pytest.mark.req("req-XXX") test under
    tests/spec_conformance/ added or extended.
  • CONFORMANCE.{md,json} regenerated via
    uv run --extra dev python -m tests.spec_conformance.gen_statement
    and committed.
  • N/A -- this PR does not change OpenAPM-observable behaviour. The fix commit carries an apm-spec-waiver: line.

…er loop

scan_text skipped only pure-ASCII text; any other file (one em dash is
enough) went through a Python loop with an ord() and a dict lookup per
character. Match the suspicious codepoints with one precompiled class
built from _CHAR_LOOKUP plus U+FEFF, and compute line and column only for
matches, with C-speed str.count/rfind over the text between them.

Findings, positions, severities and order are unchanged. The new
test_content_scanner_cost.py keeps the former loop as the oracle and
compares it on a table, every suspicious codepoint in six contexts, 300
seeded mixed documents and every codepoint 0..0x10FFFF.

cost: Python work is O(findings), not O(characters); the regex and the
line counting stay O(n) in C. On a 198 KB non-ASCII Markdown corpus with
8 findings: 396,625 -> 70 profiled calls, 16.1 ms -> 1.95 ms.

Refs #5838

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
… (red-first, #5838)

The #5838 world (14 new local Claude-style plugins, 39 skills, 166
non-ASCII Markdown files, 9 already installed) installs with -g for
opencode as plain paths, symlinked paths and read-only directories. The
counter hook gains a calls table (normalize_plugin_directory, top-level
copytree). Main normalizes 28 times; the cells require 14. Parity cells
pin the deployed bytes, receipts and lock rows (raw-image digest,
package type) the copy-and-validate path records.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Resolve copies a local legacy plugin into apm_modules and validation
normalizes that image in place. The integrate phase deleted it, copied
the source again and normalized a second time
(install/sources.py:219 via validate_apm_package). Resolve now hashes
the raw image of a plain legacy plugin when it copies it
(install/local_plugin_image.py), and integrate reuses the image it
validated: same bytes, hashed once, normalized once. Native Agent
Plugins, Codex compatibility manifests, catalog manifests and any image
this run did not produce still take the copy-and-validate path.

Fresh 14 plugins: normalize 28 -> 14, top-level copytree 18 -> 7.
Re-passing 23: normalize 46 -> 23.

apm-spec-waiver: install-internal reuse of an already validated local package image; no OpenAPM requirement changes.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…owner (#5838)

The unit ctx stub carries resolved_local_plugins as InstallContext does.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@danielmeppiel Daniel Meppiel (danielmeppiel) added the full-integration Run the full integration suite (ci-integration.yml) on this PR before merge label Dec 3, 2026
… it and it still hashes the same (#5838)

Resolve records a plain legacy plugin's raw files and digests when it
copies it; the record is kept only when the resolved graph holds a
validated package rooted at that image (keep_validated_local_plugins).
Integrate reuses the image only while it still holds every recorded raw
file with the same digest and adds nothing but the synthesized manifest
and .apm/; any other change re-copies and re-validates. Unit cells cover
an edited, added and linked file and an unvalidated record; an
integration cell installs a plugin whose plugin.json is broken: it
fails and deploys nothing.

The count-budget harness gains the plugins14 journeys
(install-g-14-plugins, install-g-23-plugins-repass) with the calls table
flattened into calls.* rows; fs rows follow from the Linux CI measure.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
- Reuse requires resolve's graph to hold the package at exactly the recorded
  destination, and integrate to read that same path (cost 0).
- Move the record call to one line so install/phases/resolve.py stays at
  its 1001-line budget.
- Add fs budget rows for the plugins14 journeys, measured on Linux PR CI.
- Give the LocalDependencySource ctx stubs a resolved_local_plugins map.

Refs #5838

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@danielmeppiel
Daniel Meppiel (danielmeppiel) marked this pull request as ready for review December 3, 2026 15:09
Copilot AI balanced review requested due to automatic review settings December 3, 2026 15:09
Daniel Meppiel (danielmeppiel) added a commit that referenced this pull request Dec 3, 2026
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Daniel Meppiel (danielmeppiel) added a commit that referenced this pull request Dec 3, 2026
fs.lockfile_reads for the local plugin world, red on #5839's head:
- install-g-14-plugins: 19 -> 13 (budget 14);
- install-g-23-plugins-repass: 24 -> 9 (budget 10).
LockFile.read now builds each document version once per run. Counted
on the same hermetic world (base 19 / 25, head 13 / 9); lstat moves by
about 4% here, inside the 5% slack, so its rows stay.

Refs #5838

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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

Reusing resolved manifests preserves opaque staging-slot names for unnamed plugins instead of their final directory names, breaking normalization parity.

3 open issues
What changed in this PR

Implements the first performance slice of #5838, reducing repeated work in local plugin installation while preserving content-scanner results.

Changes:

  • Reuses validated local plugin images between resolve and integrate.
  • Replaces per-character scanning with regex matching.
  • Adds parity tests, operation counters, and performance budgets.
File Description
tests/​unit/​test_content_scanner_cost.py Tests scanner parity and call costs.
tests/​unit/​install/​test_sources_selection.py Updates context mock.
tests/​unit/​install/​test_sources_materialisation.py Updates context mock.
tests/​unit/​install/​test_local_plugin_image.py Tests image reuse eligibility and tampering.
tests/​quality/​promise-catalog.json Registers scanner performance promise.
tests/​perf/​count_budgets.json Adds plugin installation budgets.
tests/​integration/​test_remaining_modules_coverage.py Updates context mocks.
tests/​integration/​test_perf_count_budgets.py Adds plugin performance journeys.
tests/​integration/​test_local_plugin_install_cost.py Tests normalization counts and installation parity.
tests/​integration/​test_install_sources_classification.py Updates context mock.
tests/​fixtures/​perf/​plugins.py Builds deterministic plugin fixtures.
tests/​fixtures/​perf/​counters.py Supports function-call counters.
tests/​fixtures/​perf/​count_budgets.py Registers journeys and flattens counters.
tests/​benchmarks/​spawn_counter/​sitecustomize.py Instruments copying and normalization.
src/​apm_cli/​utils/​content_hash.py Exposes hashed payload paths.
src/​apm_cli/​security/​content_scanner.py Uses regex-based suspicious-character scanning.
src/​apm_cli/​install/​sources.py Reuses eligible resolved images.
src/​apm_cli/​install/​source_helpers.py Preserves recorded local digests.
src/​apm_cli/​install/​phases/​resolve.py Records reusable plugin images.
src/​apm_cli/​install/​local_plugin_image.py Implements image recording and reuse checks.
src/​apm_cli/​install/​context.py Stores per-run plugin image records.
changelog.d/​5839.fixed.md Documents installation performance improvements.
.apm/​architecture/​owners/​install-deployment.json Registers the image-reuse owner.

Review effort: Balanced

Comment on lines +39 to +42
pkg_type, plugin_json = detect_package_type(image)
if pkg_type != PackageType.MARKETPLACE_PLUGIN:
return False
return not is_codex_compatibility_manifest(image, plugin_json)
"src/apm_cli/deps/github_downloader.py",
"src/apm_cli/install/phases/local_content.py"
"src/apm_cli/install/phases/local_content.py",
"src/apm_cli/install/local_plugin_image.py"
Comment on lines +131 to +135
_copy_depth = [0]

def _copytree(*a, **k):
if _copy_depth[0] == 0:
_bump(_calls, "copytree")
…istic

Resolve copies local packages on parallel workers. The calls table kept
one shared nesting depth and an unlocked increment, so concurrent copies
were counted or dropped at random (9 and 13 on Linux CI for the same
build). Depth is now per thread and increments are locked. Copytree is
exactly one per local plugin: 14 and 23, against 28 and 46 on main.

Refs #5838

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Daniel Meppiel (danielmeppiel) added a commit that referenced this pull request Dec 3, 2026
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Resolve normalizes a local plugin in a staging directory with an opaque
name. Normalization names a root-declared skill, and a manifest without
a name, after the directory it runs in, so reusing that image deployed
the root skill a second time under the staging name. Reuse now refuses
an image whose synthesized paths or metadata carry the staging name;
integrate normalizes it at its destination as before.

Refs #5838

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Daniel Meppiel (danielmeppiel) added a commit that referenced this pull request Dec 3, 2026
Windows CI showed stat signatures cannot tell a same-size in-place
rewrite apart: NTFS mtime ticks are 100 ns and os.stat's st_ctime is
the creation time there; Linux's coarse kernel clock leaves the same
gap within a tick. Per AUD (K1-K4):
- LockFile._read_document reads the text through read_lockfile_text on
  every read (its link and regular-file refusals included) and recalls
  only when the full text is identical; only parse, validation, build
  and adoption are memoized;
- the key also carries adoption's other inputs: whether the path is the
  user scope root, and the home directory;
- the registry YAML memo reads the file each call and reparses only
  when its text changed;
- staged-entry identity, the forget on commit/remove/restore, pickled
  independent copies and the clear at pipeline start are kept.

The plugin journeys' fs.lockfile_reads rows return to #5839's values:
every read now reads the file, and the saving is the build (19 reads
build 5 LockFile objects on the 14-plugin world, 19 on #5839).

cost: one raw read per LockFile.read, as before #5838; no stat calls.

Refs #5838

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Resolve normalizes a local plugin in an opaque staging slot. A
root-declared skill installed at user and project scope deploys once,
under the plugin's name, and is normalized again at its destination.
Red at bcd7a45 (the slot name deployed as a second skill).

Refs #5838

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
The staging-name check read only apm.yml and the top-level .apm
metadata. It now reads every file normalization added, by path and by
content; a file that cannot be read as text still refuses reuse.

Refs #5838

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Daniel Meppiel (danielmeppiel) added a commit that referenced this pull request Dec 3, 2026
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Daniel Meppiel (danielmeppiel) added a commit that referenced this pull request Dec 3, 2026
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

full-integration Run the full integration suite (ci-integration.yml) on this PR before merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants