Skip to content

perf(lockfile): parse each lockfile text once and load it in O(N) - #4735

Merged
Daniel Meppiel (danielmeppiel) merged 10 commits into
mainfrom
danielmeppiel-perf-boot-and-round-trips
Nov 22, 2026
Merged

Daniel Meppiel (danielmeppiel) merged 10 commits into
mainfrom
danielmeppiel-perf-boot-and-round-trips

Conversation

@danielmeppiel

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

Copy link
Copy Markdown
Collaborator

Description

One apm install reads apm.lock.yaml 19 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:

  1. It re-parsed the whole file with the pure-Python bounded loader. Cost is linear in lockfile size, about 7 KB per dependency.
  2. 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.

fixture journey base 899d17b new 52355d3 CPU ratio
tree-10 cold 40.9 (7.86) [27.82] / 14.86 (6.87) [29.34] 20.02 (7.73) [26.15] / 28.71 (6.4) [28.05] 1.0x
tree-10 warm 7.3 (4.43) [27.38] / 6.8 (4.59) [26.88] 5.81 (3.44) [27.83] / 8.79 (3.43) [25.85] 1.3x
tree-10 noop void (3.92) [28.49] / 9.59 (4.42) [26.81] void (2.93) [30.21] / 6.43 (2.74) [27.99] 1.5x
tree-10 frozen void (5.68) [31.49] / 9.95 (5.16) [27.91] void (3.47) [30.41] / 7.64 (3.51) [27.31] 1.6x
tree-50 cold 60.22 (31.12) [24.68] / 47.46 (29.11) [19.97] 78.4 (28.85) [20.96] / 41.04 (27.94) [23.62] 1.1x
tree-50 warm 28.18 (21.95) [29.22] / 36.93 (22.25) [24.60] 19.52 (13.87) [27.16] / 17.56 (13.33) [27.60] 1.6x
tree-50 noop 26.57 (20.35) [26.05] / 23.83 (18.22) [25.00] 15.99 (11.0) [24.23] / 18.86 (10.13) [23.32] 1.8x
tree-50 frozen 31.61 (25.11) [25.81] / 30.21 (23.88) [27.72] 17.64 (11.37) [20.09] / 15.87 (10.89) [25.06] 2.2x
tree-200 cold 239.52 (141.6) [26.08] 165.43 (103.13) [22.22] 1.4x
tree-200 warm 135.81 (119.67) [27.43] 70.49 (48.08) [21.32] 2.5x
tree-200 noop 133.07 (111.11) [21.29] 44.29 (32.27) [20.90] 3.4x
tree-200 frozen void (161.23) [22.47] void (40.66) [35.16] 4.0x

cProfile of one no-op apm install per variant (structural, valid at any load):

fixture variant LockFile.read calls, cumulative s from_lockfile calls _legacy_locator calls profiled total s
tree-10 base 19, 4.43 398 31,650 12.1
tree-10 new 19, 0.61 18 300 8.43
tree-50 base 19, 26.27 1,918 728,250 52.11
tree-50 new 19, 2.98 18 1,500 29.55
tree-200 base 19, 204.05 7,618 11,463,000 315.27
tree-200 new 19, 13.17 18 6,000 137.75

Reading the tables:

  • The win is algorithmic and grows with N. LockFile.read cumulative time drops 7x at N=10, 9x at N=50 and 15x at N=200 (204 s -> 13 s).
  • A no-op install of 200 packages goes from 133 s to 44 s wall (3.0x, load about 21 on both runs).
  • Cold installs gain less (1.0-1.4x CPU): git and copies dominate there. That is tracked separately.

Review follow-ups (d94f458 .. b2813a0)

Copilot review threads, both fixed and resolved:

  1. 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.
code outcome
base 899d17b4 (main) pass
prior head 6e0ae126 fail: RecursionError escapes LockFile.from_yaml (copy.py:127)
fix d94f4589 pass
  1. 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.

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

Re-validated at d94f458:

  • full lint mirror (ruff, 2100-line guard, YAML / relative_to guards, pylint R0801, auth signals, architecture boundaries, complexity / taxonomy / obligation ratchets, check_test_assertions, tm006): clean
  • targeted lockfile / ledger / MCP-IO / yaml_io suites: 407 passed
  • new architecture mutation cases: 9 passed

Issue 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

  • Bug fix
  • New feature
  • Documentation
  • Maintenance / refactor (performance; behaviour unchanged)

Testing

  • Tested locally
  • All existing tests pass (targeted lockfile/ledger/MCP-IO/yaml_io suites: 404 passed; quality baselines + taxonomy: 43 passed)
  • Added tests for new functionality (if applicable)

tests/unit/deps/test_lockfile_read_cost.py (unit, 11 tests) covers:

  • the same text is parsed once (5 reads, 1 parse)
  • 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.
  • N/A -- internal-only change (CI, tests, refactor).

Spec conformance (OpenAPM v0.1)

  • N/A -- this PR does not change OpenAPM-observable behaviour (commits carry apm-spec-waiver:).

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

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

An accepted YAML alias chain can trigger an uncaught RecursionError during copying, requiring a depth-safe fallback and regression coverage.

2 open issues
What changed in this PR

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.

Review effort: Balanced

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

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

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

Low severity 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.

2 resolved since last review

Review effort: Balanced

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

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

An unpublished, low-severity concern about changelog length and user-facing focus requires human judgment about its significance for approval.

No open issues 🎉

Review effort: Balanced

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 the mutation regression does not exercise deep-copy isolation and would still pass if the cached object were returned directly.

No open issues 🎉

Review effort: Balanced

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

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

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.

No open issues 🎉

Review effort: Balanced

@danielmeppiel
Daniel Meppiel (danielmeppiel) merged commit 290a3a6 into main Nov 22, 2026
72 checks passed
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: lockfile is re-parsed ~19x per install with an O(N^2) ledger rebuild

2 participants