You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
perf(lockfile): parse each lockfile text once and load it in O(N) - #4735
One apm install reads apm.lock.yaml19 times (14 call sites, for example install.py, pipeline.py x3, security/executables.py x3, MCP integration x3, the plugin phases and skill ownership). Every read did two expensive things:
It re-parsed the whole file with the pure-Python bounded loader. Cost is linear in lockfile size, about 7 KB per dependency.
It rebuilt the legacy deployment-ledger projection once per dependency row: _from_validated_data -> add_dependency -> invalidate_legacy_projection -> from_lockfile (x2) over every row added so far. That is O(N^2), and the result was discarded because the load sets the ledger once at the end.
The fix changes no check:
Parse once per text.LockFile.from_yaml calls parse_lockfile_text (deps/lockfile_container.py). It memoizes only the bounded YAML parse, keyed by the exact text plus the parser function's identity. It is a bounded LRU of 4 and deep-copies out. Container validation and LockFile construction still run on every read, and failed parses are not cached. A write followed by a read parses the new text, because the key is the content.
O(N) load. During a load, per-row projection is skipped unless a row could make it observable: a URI receipt (by the codec's own _legacy_locator) or a reserved owner key (valid_owner_keys, e.g. local-bundle provenance). Those rows keep the exact per-row path. The verdict belongs to the ledger codec: DeploymentLedgerCodec.load_observes_per_row_projection. Its implementation is the RowProjection base in core/legacy_lock_evidence.py, an existing selector of the deployment-provenance owner, because deployment_ledger.py sits at the 2100-line cap. The install-deployment-provenance-state guard requires the loader to delegate to it and rejects a hardcoded project_ledger=False.
Deep alias chains. If deepcopy of a memoized parse hits the recursion limit, the text is dropped from the memo and gets a fresh bounded parse, exactly what main returns.
Why not one deferred rebuild at the end of the load? It is not equivalent. With URI receipts, a mid-load _rebuild_from_legacy keeps active_owner on the first claimant (previous.active_owner in record.owners). Measured on three deps sharing copilot-mcp://srv: per-row gives owner/a, a single deferred rebuild gives owner/c, and this PR gives owner/a. A test pins this.
Evidence
Offline mirror from the perf fixtures harness (rtt 0, zero requests on no-op, warm and frozen). Variants were run from frozen worktrees at exact SHAs: base = 899d17b4 (main), new = 52355d36 (main + this change). The later commits on this branch only move the decision helper and rework tests; behaviour is identical and the equivalence tests cover it.
Each cell: wall s (user+sys CPU s incl. git children) [1-min load]. Base and new ran back to back per journey (ABAB). A wall is shown only when BOTH runs of the pair had load < 30; otherwise void.
Deep alias chain vs deepcopy. Test: test_merge_reordered_alias_chain_loads_like_a_fresh_parse. A merge key puts deep first, so deepcopy enters a 1,200-level alias chain at once.
Second authority. The predicate moved onto DeploymentLedgerCodec. It is guarded by install-deployment-provenance-state and proven by test_lockfile_load_row_projection_routes_through_ledger_codec, which covers three bypass mutations: the loader re-derives the verdict, the loader hardcodes the skip, and the codec re-derives the URI locator.
Later Copilot overviews: the two disk tests moved to a component module; the changelog line now leads with the user effect in 25 words; and a direct parse_lockfile_text isolation test was added, because LockFile construction copies lists and the LockFile-level test could not catch a dropped deep copy.
each memoized parse is a private copy; this test fails if the deep copy is dropped
ledger projection does not scale with rows (at most 1 from_lockfile for 30 rows)
the load equals the per-row projection on project and :// fixtures, with and without deployments rows
the first-claimant owner is kept
a reserved-owner row still fails the load as before
a merge-reordered alias chain loads as on main
tests/unit/deps/test_lockfile_reread_on_disk.py (component, 2 tests) covers write-then-read returning the new data, and mutating a returned LockFile leaving both the next read and the file unchanged. Both assert on-disk state.
The tests observe calls with a sys.setprofile hook rather than patching owners. Against base 899d17b4, exactly the 3 cost tests fail (parses == 5, projections == 60/61) and the 8 behaviour tests pass.
Lint mirror on the merge with main: ruff check and format, the 2100-line file guard, pylint R0801, auth signals, architecture boundaries, complexity, taxonomy and obligation ratchets, and check_test_assertions are all clean.
Related finding, filed with QL: tests/test_lockfile.py is outside every CI selection. Its test_write_parses_legacy_lockfile_once fails on main (3 == 1, independent of this PR), which is why this PR's tests live under tests/unit.
Changelog
One fragment per section, changelog.d/4735.changed.md.
One install reads apm.lock.yaml about 19 times. Each read re-parsed the
whole file with the pure-Python bounded loader and rebuilt the legacy
deployment-ledger projection once per dependency row (O(N^2)), only for
the load to replace it at the end.
- LockFile.from_yaml routes through parse_lockfile_text: the bounded parse
is memoized by exact text (bounded LRU, deep copy out); container
validation and construction still run on every read.
- The per-row projection is skipped during a load unless a row can carry
a URI receipt or local-bundle provenance
(DeploymentLedgerCodec.load_observes_per_row_projection); those keep the
exact per-row path.
apm-spec-waiver: performance-only change; lockfile parse and load results are identical, no OpenAPM-observable behaviour changes
Co-authored-by: Copilot App <[email protected]>
tests/test_lockfile.py is outside every CI selection (tests/unit,
tests/test_console.py, tests/red_team, tests/fixtures/policy).
Co-authored-by: Copilot App <[email protected]>
…h, in tests
- Move the load-time projection decision into deps/lockfile_container.py
(deployment_ledger.py and lockfile.py stay within the 2100-line guard);
reserved owners come from DeploymentLedgerCodec.valid_owner_keys, so
local-bundle provenance still routes through the codec.
- Tests: mark the module unit, assert on-disk state for the two file
tests, count calls with a profile hook instead of patching owners, build
the equivalence reference through the public per-row path, and pin the
first-claimant owner and the reserved-owner failure.
apm-spec-waiver: performance-only change; lockfile parse and load results are identical, no OpenAPM-observable behaviour changes
Co-authored-by: Copilot App <[email protected]>
This PR addresses #4733’s lockfile-read bottleneck by reusing parsed YAML and avoiding quadratic ledger reconstruction where per-row projection is unnecessary.
Changes:
Adds a bounded, content-keyed parse cache with private copies for callers.
Skips redundant ledger projection while retaining the existing path for URI receipts and reserved owners.
Adds performance and behavior regression tests plus a changelog entry.
File
Description
tests/unit/deps/test_lockfile_read_cost.py
Tests parse reuse, read isolation, projection cost, and ownership preservation.
src/apm_cli/deps/lockfile.py
Integrates cached parsing and conditional per-row ledger projection.
src/apm_cli/deps/lockfile_container.py
Implements the parse cache and projection-observability predicate.
changelog.d/4735.changed.md
Documents the lockfile-read performance improvement.
…lias copies
Review follow-ups on #4735:
- DeploymentLedgerCodec.load_observes_per_row_projection (RowProjection in
core/legacy_lock_evidence.py, an owner selector) decides when a load may
skip per-row legacy projection, through the codec's own _legacy_locator
and valid_owner_keys; the loader delegates to it. The
install-deployment-provenance-state guard now requires that delegation
and rejects a hardcoded project_ledger=False, with mutation tests.
- parse_lockfile_text falls back to a fresh bounded parse (and does not
memoize the text) when deepcopy hits the recursion limit, so a
merge-reordered alias chain the bounded loader accepts loads as on main.
apm-spec-waiver: performance-only change; lockfile parse and load results are identical, no OpenAPM-observable behaviour changes
Co-authored-by: Copilot App <[email protected]>
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
The module-level unit marker misclassifies two filesystem tests; they should move to a component-marked module while preserving the promise marker.
No open issues 🎉
1 previously missed issue
In code that hasn't changed since last review
Move filesystem tests out of the unit-marked module
tests/unit/deps/test_lockfile_read_cost.py:17
The module-level unit marker also classifies the two disk read/write tests at lines 85-119 as pure unit tests, contrary to the filesystem boundary defined in pyproject.toml:217-219. Move those tests into a separate module marked component, preserving the promise marker, so behavioral selections do not misclassify filesystem tests. Keep the in-memory cost and equivalence tests marked unit.
The two tests that write and reread apm.lock.yaml touch the filesystem, so
they move to a component-marked module with the same promise; the pure
from_yaml cases stay unit.
Co-authored-by: Copilot App <[email protected]>
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Human assessment is needed because the mutation regression does not exercise deep-copy isolation and would still pass if the cached object were returned directly.
LockFile construction copies its lists, so a LockFile-level mutation test
cannot catch a memo that hands out the cached object; this test mutates a
parse_lockfile_text result directly and fails if the deep copy is dropped.
Co-authored-by: Copilot App <[email protected]>
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
The supplied evidence does not establish the required green lifecycle_smoke run or QL H8 sign-off for the current head, so a human must verify these landing gates.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
One
apm installreadsapm.lock.yaml19 times (14 call sites, for exampleinstall.py,pipeline.pyx3,security/executables.pyx3, MCP integration x3, the plugin phases and skill ownership). Every read did two expensive things:_from_validated_data -> add_dependency -> invalidate_legacy_projection -> from_lockfile(x2) over every row added so far. That is O(N^2), and the result was discarded because the load sets the ledger once at the end.The fix changes no check:
LockFile.from_yamlcallsparse_lockfile_text(deps/lockfile_container.py). It memoizes only the bounded YAML parse, keyed by the exact text plus the parser function's identity. It is a bounded LRU of 4 and deep-copies out. Container validation andLockFileconstruction still run on every read, and failed parses are not cached. A write followed by a read parses the new text, because the key is the content._legacy_locator) or a reserved owner key (valid_owner_keys, e.g. local-bundle provenance). Those rows keep the exact per-row path. The verdict belongs to the ledger codec:DeploymentLedgerCodec.load_observes_per_row_projection. Its implementation is theRowProjectionbase incore/legacy_lock_evidence.py, an existing selector of the deployment-provenance owner, becausedeployment_ledger.pysits at the 2100-line cap. Theinstall-deployment-provenance-stateguard requires the loader to delegate to it and rejects a hardcodedproject_ledger=False.deepcopyof a memoized parse hits the recursion limit, the text is dropped from the memo and gets a fresh bounded parse, exactly what main returns.Why not one deferred rebuild at the end of the load? It is not equivalent. With URI receipts, a mid-load
_rebuild_from_legacykeepsactive_owneron the first claimant (previous.active_owner in record.owners). Measured on three deps sharingcopilot-mcp://srv: per-row givesowner/a, a single deferred rebuild givesowner/c, and this PR givesowner/a. A test pins this.Evidence
Offline mirror from the perf fixtures harness (rtt 0, zero requests on no-op, warm and frozen). Variants were run from frozen worktrees at exact SHAs: base =
899d17b4(main), new =52355d36(main + this change). The later commits on this branch only move the decision helper and rework tests; behaviour is identical and the equivalence tests cover it.Each cell: wall s (user+sys CPU s incl. git children) [1-min load]. Base and new ran back to back per journey (ABAB). A wall is shown only when BOTH runs of the pair had load < 30; otherwise
void.cProfile of one no-op
apm installper variant (structural, valid at any load):LockFile.readcalls, cumulative sfrom_lockfilecalls_legacy_locatorcallsReading the tables:
LockFile.readcumulative time drops 7x at N=10, 9x at N=50 and 15x at N=200 (204 s -> 13 s).Review follow-ups (d94f458 .. b2813a0)
Copilot review threads, both fixed and resolved:
deepcopy. Test:test_merge_reordered_alias_chain_loads_like_a_fresh_parse. A merge key putsdeepfirst, sodeepcopyenters a 1,200-level alias chain at once.899d17b4(main)6e0ae126RecursionErrorescapesLockFile.from_yaml(copy.py:127)d94f4589Second authority. The predicate moved onto
DeploymentLedgerCodec. It is guarded byinstall-deployment-provenance-stateand proven bytest_lockfile_load_row_projection_routes_through_ledger_codec, which covers three bypass mutations: the loader re-derives the verdict, the loader hardcodes the skip, and the codec re-derives the URI locator.Later Copilot overviews: the two disk tests moved to a component module; the changelog line now leads with the user effect in 25 words; and a direct
parse_lockfile_textisolation test was added, becauseLockFileconstruction copies lists and the LockFile-level test could not catch a dropped deep copy.Re-validated at d94f458:
relative_toguards, pylint R0801, auth signals, architecture boundaries, complexity / taxonomy / obligation ratchets,check_test_assertions, tm006): cleanIssue and approved scope
Issue: Fixes #4733
Human scope-approval comment: scope record for #4733 requested from Intake by PERF VP.
Does this PR complete the issue, or what remains? It completes rt-01 (lockfile re-read cost). Cold-path round-trip items are in the backlog.
Type of change
Testing
tests/unit/deps/test_lockfile_read_cost.py(unit, 11 tests) covers:from_lockfilefor 30 rows)://fixtures, with and withoutdeploymentsrowstests/unit/deps/test_lockfile_reread_on_disk.py(component, 2 tests) covers write-then-read returning the new data, and mutating a returnedLockFileleaving both the next read and the file unchanged. Both assert on-disk state.The tests observe calls with a
sys.setprofilehook rather than patching owners. Against base899d17b4, exactly the 3 cost tests fail (parses == 5,projections == 60/61) and the 8 behaviour tests pass.Lint mirror on the merge with main: ruff check and format, the 2100-line file guard, pylint R0801, auth signals, architecture boundaries, complexity, taxonomy and obligation ratchets, and
check_test_assertionsare all clean.Related finding, filed with QL:
tests/test_lockfile.pyis outside every CI selection. Itstest_write_parses_legacy_lockfile_oncefails on main (3 == 1, independent of this PR), which is why this PR's tests live undertests/unit.Changelog
changelog.d/4735.changed.md.Spec conformance (OpenAPM v0.1)
apm-spec-waiver:).