Skip to content

perf(cache): store every deployed file's bytes by lockfile hash (deploy store) - #4846

Merged
Daniel Meppiel (danielmeppiel) merged 7 commits into
mainfrom
danielmeppiel-perf-deploy-store
Nov 23, 2026
Merged

Daniel Meppiel (danielmeppiel) merged 7 commits into
mainfrom
danielmeppiel-perf-deploy-store

Conversation

@danielmeppiel

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

Copy link
Copy Markdown
Collaborator

Description

Lane C, unit S1: the deploy store. Every full install now keeps the exact bytes of each deployed file in the machine cache, keyed by the canonical sha256 that the lockfile already records in deployed_file_hashes. This is the foundation for the deploy-only-what-changed replay (S2, IFP lane C). This PR only writes and verifies the store; nothing reads it yet, and no install output changes.

  • src/apm_cli/cache/deploy_store.py (stdlib only). DeployStore.get(key, *, raw_sha256=None) and put(key, data) under <cache>/deploy_v1/<hex[:2]>/<hex>.
    • Keys are exactly 64 lowercase hex characters (fullmatch), so a key cannot carry a path component (a trailing-newline key was caught by a red-first row).
    • Every read re-hashes the entry; a mismatch is evicted and returned as a miss (None), and callers run the full pipeline.
    • Never follows links: the bucket and shard dirs must be real directories (lstat; Windows reparse points refused); the entry opens with O_NOFOLLOW where available, then fstat S_ISREG plus a link/reparse re-check.
    • Writes: dirs 0700; entries via mkstemp (exclusive, 0600) in the shard dir, then os.replace; temp unlinked on failure.
    • raw_sha256 lets a byte-exact restorer refuse the other CRLF/LF image that shares a line-ending-normalized key.
  • Writer, commit-gated: install/phases/lockfile.compute_deployed_hashes reads each deployed file once and hashes it (the same canonical digest as compute_file_hash, via the new content_hash.canonical_digest), then only STAGES it for the command run. InstallService.run commits the staged files after the install committed: it discards before the pipeline and re-reads and re-verifies each file. A refused or failed install (e.g. a rejected --frozen) therefore stores nothing. A warm install costs one lstat per file.
  • Bounded and clearable ([FEATURE] perf(cache): store every deployed file's bytes by lockfile hash (deploy store, lane C S1) #4854): entries above 4 MiB are never stored. A command that added entries evicts least recently used ones above 256 MiB, down to 80% (a verified read refreshes recency). apm cache clean empties the store through the canonical cleanup owner. An empty or deleted store changes nothing (e2e cell).
  • Owner + guard: owner record deploy-store and guard transport-platform-deploy-store-verified-reads. It pins the bucket name to the owner and requires the verify / no-follow / atomic lines, with a MutationCase that removes the read re-hash.

Issue and approved scope

Issue: Refs #4854 (lane C S1; lands only inside the engine train with S2, judged at the train head).

Human scope-approval comment: the scope record on #4854.

Does this PR complete the issue, or what remains? It completes S1 (the write side + verified read API). The replay consumer is S2 (IFP). W3b's S2 constraints are recorded there: bind any store hit to the verified package and re-check exec-gate admission, never rebuild from a lockfile hash alone, and restore exact bytes (raw_sha256).

GAINS

CI bench run 45080175673 (base 6e110b22 -> 42d36581, tree-10, rtt 30, 3 runners x 3 interleaved pairs, CPU incl. children). Budget was <= +2% CPU on warm installs:

Journey CPU p50 base -> new Paired new/base
install-frozen-warm 2.517 -> 2.534 s 1.004
install-locked-warm 2.252 -> 2.251 s 0.998
install-noop 2.054 -> 2.062 s 1.002
install-warm 2.454 -> 2.442 s 0.997

Within budget (max +0.4% paired). Requests and spawns are unchanged.

Type of change

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

Testing

  • Tested locally

  • All existing tests pass

  • Added tests for new functionality (if applicable)

  • tests/integration/test_deploy_store_lifecycle.py (e2e, tree-10 offline mirror): after apm install every lockfile deployed hash has a store entry that re-hashes to it; a tampered entry is healed by the next full install. Red at main with the writer reverted (FileNotFoundError on the first entry).

  • tests/unit/cache/test_deploy_store.py (17): tamper evicted; mismatched put refused; bad keys (../, uppercase, short, trailing newline, non-hex, empty) refused with nothing created; linked bucket and linked entry refused, target untouched; directory-as-entry; 0600 and no temp left; exact-byte reads; APM_NO_CACHE parsing.

  • Lint mirror clean: pinned ruff check/format, architecture lint, auth-signal lint, complexity ratchet, taxonomy, AQ ratchet.

  • W3b security review at 42d3658: PASS (0 BLOCK); its cheap 5C items folded at ac3b84a. Deferred 5C: the dir_fd open chain (POSIX race hardening) and an orphan .part sweep.

Changelog

  • One fragment per section, changelog.d/<pr>.<section>.md.
  • N/A -- internal-only change (CI, tests, refactor).

Spec conformance (OpenAPM v0.1)

If this PR changes behaviour that an OpenAPM v0.1 req-XXX covers,
confirm the three-step ritual in the
development guide:

  • 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 (apm-spec-waiver in the commit message).

…file hash

Every full install now records each deployed file's exact bytes in
<cache>/deploy_v1/<hex[:2]>/<hex>, keyed by the canonical sha256 the
lockfile records as its deployed_file_hashes value. This is the lane C
deploy-store unit (S1): later commands can rebuild a deployed file from the
lockfile hash alone.

- Keys are exactly 64 lowercase hex characters (fullmatch), so no path.
- Every read re-hashes the entry; a mismatch is evicted and returned as a
  miss. Linked buckets and entries are never followed; only regular files.
- Writes go to an owner-only exclusive temp file, then os.replace; a warm
  install costs one lstat per file (same-size entries are left alone).
- The lockfile phase reads each deployed file once to hash and store it.
- Owner record deploy-store + guard transport-platform-deploy-store-verified-reads
  (frozen inventory + mutation case).

apm-spec-waiver: machine-cache side store only; lockfile, deployed files and every OpenAPM-observable output are unchanged

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

W3b hardening at 42d3658: Windows junctions/reparse points are refused
like symlinks; get(raw_sha256=...) lets a byte-exact restorer reject the
other line-ending image sharing a normalized key; APM_NO_CACHE parses like
get_cache_root.

Co-authored-by: Copilot App <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 22, 2026 22:59
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

Unresolved cache issues can block reads indefinitely on FIFOs, leave deployed data outside cleanup and size reporting, and accept corrupted or digest-mismatched entries.

3 open issues
What changed in this PR

This PR adds the write-side foundation for future incremental deployment replay. Full installs populate a machine-local deploy store keyed by canonical lockfile hashes; no replay consumer or install-output change is introduced.

Changes:

  • Add a deploy store with verified reads, optional exact-byte validation, and atomic writes.
  • Share canonical byte hashing and populate the store during deployed-file hash collection.
  • Register an architecture owner and guard, with store, lifecycle, and mutation coverage.
File Description
tests/​unit/​scripts/​test_architecture_runner.py Adds the deploy-store guard to the rule inventory.
tests/​unit/​cache/​test_deploy_store.py Covers storage, verification, invalid keys, links, and cache settings.
tests/​integration/​test_deploy_store_lifecycle.py Checks install population and repair of length-changing corruption.
tests/​integration/​test_architecture_owner_rule_mutations.py Adds a mutation removing read verification.
src/​apm_cli/​utils/​content_hash.py Exposes canonical hashing for in-memory bytes.
src/​apm_cli/​install/​phases/​lockfile.py Stores deployed bytes while collecting lockfile hashes.
src/​apm_cli/​cache/​deploy_store.py Implements the content-addressed deploy store.
scripts/​architecture_linter/​groups/​transport_platform.py Registers the deploy-store rule group.
scripts/​architecture_linter/​checks/​transport_deploy_store.py Guards bucket ownership and required safety checks.
.apm/​architecture/​owners/​transport-auth-platform.json Declares the deploy-store owner and guard.

Review effort: Balanced

Comment thread src/apm_cli/cache/deploy_store.py Resolved
Comment thread src/apm_cli/cache/deploy_store.py Resolved
Comment thread src/apm_cli/install/phases/lockfile.py Resolved
… bound; cache clean

QL red at c29777a: a refused `install --frozen` stored the changed local
snapshot's bytes, because hashing wrote the store. Hashing now only stages
{path: digest} per command run; InstallService.run commits the staged files
after the install committed (and discards them before the pipeline), each
re-read and re-verified, so a refused or failed install stores nothing.

#4854 conditions: entries above 4 MiB are never stored; a command that
added entries evicts least recently used ones above 256 MiB down to 80%
(a verified read refreshes recency); `apm cache clean` empties the store
through the canonical cleanup owner (cleanup guard consumer); DeployStore
takes the cache root. Cells: size bound, entry bound, clean, staging
contract, bytes changed after hashing, and an e2e that an empty or deleted
store changes nothing. The frozen-local lifecycle oracle after the
SUCCESSFUL accepted install now allows only self-verifying deploy-store
entries holding the accepted deployment; every refused row is unchanged.

Refs #4854

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

Unresolved cache-safety flaws can exhaust memory through unbounded reads and delete files outside the store during eviction through Windows directory junctions.

5 open issues
3 previously missed issues

In code that hasn't changed since last review

Medium severity Reject hard-linked cache entries before reading or refreshing them

src/​apm_cli/​cache/​deploy_store.py:107

Hard-linked entries pass both the regular-file and symlink checks, so a hard link to a correctly hashed file outside the store is returned as a hit, and the later os.utime() also changes that outside file's timestamps. The approved scope on #4854 explicitly requires hard-linked entries to be rejected as misses (#4854 (comment)). Reject descriptors whose link count is not one before reading or refreshing recency, and cover this with a hard-link regression.

Medium severity Verify existing cache entries before accepting same-size files

src/​apm_cli/​cache/​deploy_store.py:140

A same-size entry is not necessarily intact: replacing original\n with tampered\n makes put_file() return True while retaining bytes that do not hash to the key. Subsequent full installs never heal that corruption because they skip get(). Verify the existing entry or atomically replace it before reporting success, and add a same-length tamper/reinstall regression without an intervening get().

Medium severity Publish cache entries only after the lockfile commit succeeds

src/​apm_cli/​install/​service.py:373

The pipeline can return while lockfile writes are still staged in the outer writer scope, so publishing here can leave cache entries from an install whose final lockfile commit fails or is interrupted. Route publication through lockfile_write_authority.after_lockfile_commit, keeping a staged snapshot available until the callback runs rather than relying on memos that lifecycle scripts can clear. Add a regression for a failed final lockfile commit.

Review effort: Balanced

Comment thread src/apm_cli/cache/deploy_store.py Resolved
Comment thread src/apm_cli/cache/deploy_store.py Resolved
…e; cache info

Copilot threads on 9283d91:
- Reads open with O_NONBLOCK (a FIFO is a miss, not a hang), reject
  oversized descriptors and read at most the bound + 1 (an entry grown out
  of band is a miss and is evicted).
- put() verifies the incoming digest first; a same-size existing entry is
  kept only if it still hashes to its key, otherwise it is atomically
  replaced (so the next full install heals same-length damage).
- Eviction scans only key-named entries in their own real shard (Windows
  junctions and linked shards refused; .tmp-*.part and strays untouched);
  the same scan feeds `apm cache info` (deployed entries and size).
- The empty-store e2e ignores .apm-local/installation (a per-run id), and
  an e2e covers install -> cache info -> cache clean --force.

Co-authored-by: Copilot App <[email protected]>
Cold: a refused install leaves deploy_v1 empty. Warm: after a successful
install, a refused install leaves the whole cache byte-identical.

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

Critical cache-safety flaws remain: entries can be published before lockfile commit succeeds, cleanup can delete files through Windows junctions, and hard-linked cache entries can read and alter outside files.

No open issues 🎉

3 previously missed issues

In code that hasn't changed since last review

High severity Treat hard-linked cache entries as misses

src/​apm_cli/​cache/​deploy_store.py:82

A hard link to an outside file with the expected digest passes these checks, so get() returns its bytes and updates the outside inode's mtime. This also violates the approved scope on #4854, which requires hard-linked entries to be misses. Reject descriptors with st_nlink > 1 before reading, and add a regression that verifies a miss without changing the outside file.

High severity Reject Windows junctions before traversing cache buckets

src/​apm_cli/​cache/​deploy_store.py:268

On Windows, a junction at <cache>/deploy_v1 passes clean_cache_buckets()'s symlink-only check, so apm cache clean --force traverses the outside target and deletes its children. Extend the canonical cleanup owner's bucket validation to reject directory reparse points before traversal, and add a Windows junction regression.

High severity Publish cache entries only after the lockfile commit succeeds

src/​apm_cli/​install/​service.py:373

A successful pipeline result can still have a staged lockfile: the enclosing writer scope commits it only on exit. If that write fails, deployment rollback runs after this call has already published cache entries and possibly evicted existing ones. Register commit_staged through after_lockfile_commit() so a failed commit leaves the store untouched, and cover the final lockfile-write failure.

5 resolved since last review

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 omitted findings raise cache-safety and lifecycle concerns, including external-file mutation and cache publication before durable lockfile commit.

No open issues 🎉

Review effort: Balanced

@danielmeppiel
Daniel Meppiel (danielmeppiel) merged commit 0a0ac21 into main Nov 23, 2026
78 checks passed
@danielmeppiel
Daniel Meppiel (danielmeppiel) deleted the danielmeppiel-perf-deploy-store branch November 23, 2026 14:38
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.

2 participants