Skip to content

perf(install): replay a verified no-op install instead of re-running the pipeline - #4775

Closed
Daniel Meppiel (danielmeppiel) wants to merge 16 commits into
mainfrom
danielmeppiel-perf-noop-fast-path
Closed

Daniel Meppiel (danielmeppiel) wants to merge 16 commits into
mainfrom
danielmeppiel-perf-noop-fast-path

Conversation

@danielmeppiel

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

Copy link
Copy Markdown
Collaborator

Description

apm install on an unchanged project (and apm install --frozen with the cache present) runs the whole pipeline and then reports No changes. This PR adds a default-on fast path (APM_INSTALL_FAST_PATH=0 turns it off) that memoizes that answer the way a build system memoizes a step: it replays a recorded no-op only when it can prove that the full pipeline would read the same bytes and reach the same verdicts. Anything unknown or different runs the full pipeline.

How it works (src/apm_cli/install/noop_fast_path.py decides and replays; src/apm_cli/install/noop_recorder.py observes)

Zero cost when off. apm install is decorated with @pipeline_entry.noop_fast_path. That gate decides once, when the command module loads. With APM_INSTALL_FAST_PATH unset (the default), it returns the callback untouched and imports neither fast-path module, so no audit hook, probe or recorder can exist. A fresh-interpreter cell (tests/unit/install/test_noop_fast_path_gate.py) proves both sides.

Status: RESEARCH (draft). CEO ruling: no default-off landing. The fast path is ON by default; APM_INSTALL_FAST_PATH=0 only disables it. This PR lands only after a clean default-on replay hit on the tree-10 no-op, proven by ABAB at exact SHAs, plus the miss path within 3%, all red-first cells, and QL H8. The kill criterion is a hit under 2x, or under 30% of the journey, by the deadline.

Eligibility. Unless APM_INSTALL_FAST_PATH=0, only a plain apm install or apm install --frozen at project scope with an existing lockfile qualifies. Not eligible: packages, --mcp, --update, --refresh, --dry-run, --root, -g, --no-policy, an explicit --policy, or Windows (os.path.exists cannot be observed there).

Record (a full run). The full pipeline runs under an input recorder:

  • sys.addaudithook: every file opened for reading (its SHA-256 is stored), every directory listed (entries with mode/size/mtime/ctime/inode/device/nlink/uid/gid), and every write, rename, link, chmod, subprocess, socket, prompt or sqlite open;
  • os.stat / os.lstat / os.readlink probes, and the results of os.path.realpath. A runtime canary proves that this interpreter's os.path.exists, isdir, lexists, realpath and Path.exists/is_file/resolve reach the hooks; otherwise nothing is recorded;
  • environment variables read, using their values at run start;
  • the command's output.

Each input is snapshotted when it is first observed, together with the referent of a symlink. If any snapshot changes before the stamp is written (a concurrent edit), the stamp is refused.

Stamp (cache root noop_v1/, never in the project). A stamp is written only when the recorded run was itself a no-op:

  • zero writes outside temp paths it created itself (a write to /dev/null does not count);
  • no network and no subprocess, except the policy git remote reads and activity under org-policy discovery (see below);
  • no prompt and no read from an expiring (TTL) cache;
  • a clean exit 0 and exactly one No changes -- install state already up to date summary.

Because that run wrote nothing, its inputs are also its outputs. The first no-op leaves a pending marker. The next no-op records with the live policy view. Later no-ops replay.

Replay. The recorded output is printed again with a freshly measured elapsed time, nothing is written, and the exit code is 0. This happens only when every check below passes, cheapest first:

  1. same argv, cwd, tty state, terminal width and uid;
  2. same environment digest (with APM_INSTALL_FAST_PATH excluded);
  3. the SHA-256 of every recorded file, every directory listing, every probed path and every realpath answer are identical;
  4. same APM code, by a SHA-256 over every source file (or the frozen executable);
  5. LIVE org policy: discover_trust_policy with unchanged cache-freshness rules, routed by the canonical owner classify_project_policy. A blocking or unresolved route, a stale cache, a refresh error or a warning takes the full pipeline. Otherwise the fingerprint (outcome, route, source, digest of the effective policy) must equal the recorded one;
  6. verify_deployed_file_hashes (the canonical lockfile content-hash verifier shared with apm audit and --frozen) reports no drift and no unresolved path.

Miss path. A miss does no live discovery and no hashing; it pays only the recorder. Discovery runs only for a pending invocation (right after a no-op) or when every recorded input already matches.

Cache root not chmodded when unchanged (src/apm_cli/cache/paths.py)

  • _ensure_dir chmodded the cache root to 0o700 on every command, even when it was already 0o700. A same-mode chmod still moves ctime, which made every converged install look changed. The chmod now runs only when the mode differs, so a loosened root is still tightened. Regression cell: test_an_existing_cache_root_is_not_chmodded.

No-op installs no longer write (#4794, src/apm_cli/install/cache_pin.py; this PR is rebased on it)

  • write_marker rewrote every apm_modules/<pkg>/.apm-pin marker on every install, so no install was ever write-free (10 marker rewrites per tree-10 no-op). An existing regular-file marker with identical bytes is now left untouched (0 rewrites); a missing, different or symlinked marker is still (re)written exactly as before. This also removes 10 needless file writes from every warm install.

Equivalence argument

The install command is a deterministic function of what it reads: file bytes, directory listings, path metadata, symlink resolution, the environment, argv/cwd/tty, APM's own code, org policy, and the clock through expiring caches. Everything it writes is either deployment state (project, user-scope targets, lockfile, caches) or output.

  1. File-system inputs. CPython raises an audit event for every open, listdir and scandir. The probe hooks see every stat, lstat, readlink and realpath, and the canary proves this at runtime for the interpreter in use. Replay recomputes each observation from the stamp and compares it exactly, by content hash for every file the run read. Metadata is compared only for paths the run merely stat-ed, which is exactly what the run observed. It is never used instead of content.
  2. Approvals, denials, consent and trust. These are files the full run reads (apm.yml executables, ~/.apm/config.json, ~/.apm/scripts-trust.json), so a grant, revocation or deny changes a recorded hash and forces the full pipeline.
  3. Deployed state. Deployed files are read by the full run (receipt hashes) and are also checked against the lockfile by the canonical verifier on every replay. A tampered or missing file forces the full pipeline.
  4. Org policy. Policy is the one input that depends on the network and the clock. It is re-discovered on every replay with the unchanged freshness rules and routed by the canonical outcome owner. Activity inside discover_policy_with_chain during the recorded run (its network fetch, the gh auth token credential lookup, the git remote reads, and its cache writes) is therefore not recorded as an input. This is acceptable ONLY because the policy fingerprint is re-evaluated live on every replay: a policy whose content changes while every recorded input stays identical is refused (red-first cells below).
  5. Everything else that could vary is refused, not assumed. The stamp is refused for: network outside policy discovery, other subprocesses, prompts, sqlite, expiring caches, writes, dir_fd-relative mutations, paths with .. components, and project or user state inside an interpreter prefix. Inputs are snapshotted at first observation and revalidated right before the stamp is published.
  6. Trust boundary. Stamps live in the user's cache root, the same trust boundary as the cached package contents. A same-user process that can write there can already change what an install deploys.
  7. Idempotence. The stamp is written only after a run that wrote nothing. The state at replay time equals that run's input state, so the full pipeline would repeat that run byte for byte and print the same output.

Issue and approved scope

Issue: Fixes #4770

Human scope-approval comment: #4770 (comment)

Does this PR complete the issue, or what remains? Not yet; this is research until a clean default-on replay is measured on tree-10. CI evidence so far: the replay hit is asserted by the security cells (_converge); the red-first mutation run 45065135368 (Smoke Shard 4 job 137339484000) failed exactly the 6 change cells with the replay cell green, verified by W4; the miss path is +1.2% CPU p50 (ABAB#2). The 1 s target also depends on #4778 / #4786 (per-run memo of policy discovery) and L3's thin install entry (import cost on a hit).

QL H8 bar mapping (perf-signoff-bar.md)

Bar item How it holds Red-first proof
1. Org policy and exec deny/approvals re-evaluated every run live discover_trust_policy + classify_project_policy on every replay; approval/deny stores are recorded inputs lifecycle policy-denies-dependency, policy-denies-executables, user-deny-after-approval, revoked-user-approval (apm.yml + lock byte-identical); unit test_a_changed_org_policy_runs_the_full_install (policy content changes, every recorded input identical)
2. Content hashes of deployed files vs the lock verify_deployed_file_hashes on every replay + SHA-256 of every file the run read lifecycle tampered-deployed-file; unit test_deployed_hash_drift_runs_the_full_install
3. Full pipeline on ANY mismatch the check table returns a reason; any exception or malformed stamp runs the full pipeline lifecycle deleted-deployed-file; unit cells for changed content, a probed path appearing, a removed lockfile, a malformed/unreadable stamp, an instrumentation gap, an input changed during the run
4. Each proven red-first lifecycle cells are differential: a fast-path-ON world vs a fast-path-OFF twin must match exit code, normalized output and installed state; a shortcut that skipped a check would replay No changes and fail the cell tests/lifecycle/security/test_noop_fast_path.py

Gains (GAINS STANDARD)

Journey install-noop, fixture tree-10, offline mirror at 30 ms RTT, ABAB with an identical project copy per side, CPU = user+sys including children (os.wait4).

Run A (base) B (this PR) Result
ABAB#2: 8 pairs, B on the miss path main c969aba: CPU p50 4.414 s f48883f: CPU p50 4.466 s miss-path overhead +1.2% (budget 3%); requests 16 -> 16 on every run; bytes identical after every run; load 31-60
ABAB#1/#3/#4: hit attempts 4.67 / 4.36 / 4.91 s 5.41 / 4.85 / 5.56 s (trace mode on B) no replay yet, so no hit number. Each run found a real cause: #1 a /dev/null write refusal (fixed); #3 gh auth token under policy discovery (fixed); #3 also showed the pipeline rewriting 10 .apm-pin markers per no-op (fixed in #4794); #4 a qualifying run still not stamped (trace now names the reason; follow-up)

Speedup x, % of the no-op removed, and position against 1 s are not claimed, because no clean replay has been measured yet. Wall times are not evidence at host load 30-60. The B CPU in trace mode is inflated by the diagnose recorder, which keeps observing after a refusal. The fast-path modules load only when apm install runs; other commands pay nothing.

Type of change

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

Testing

  • Tested locally (ABAB on the perf harness; lint mirror clean: ruff 0.15.12, pylint R0801, auth signals, complexity ratchet, tm006)
  • All existing tests pass (CI)
  • Added tests for new functionality (if applicable)

Changelog

  • One fragment per section: changelog.d/4775.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.

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

Unsafe stamp validation can replay prior success despite changed policy inputs, changed validation code, or blocked policy components, bypassing required enforcement.

12 open issues
What changed in this PR

This PR adds a verified no-op replay path to apm install, targeting the repeated-install performance goal in #4770. It records eligible full runs and checks their inputs before replaying output. Performance evidence and sign-off remain pending.

Changes:

  • Adds input recording, cached stamps, and replay checks for policy and deployed-file integrity.
  • Hooks replay into install, with disable and trace controls; Windows remains disabled.
  • Adds recorder and lifecycle regression tests, environment-variable documentation, and a changelog entry.
File Description
tests/​unit/​install/​test_noop_fast_path.py Tests recording, invalidation, eligibility, and fallback rules.
tests/​lifecycle/​security/​test_noop_fast_path.py Compares replay with full installs after integrity, consent, and policy changes.
src/​apm_cli/​install/​noop_fast_path.py Implements recording, stamp validation, and output replay.
src/​apm_cli/​commands/​install.py Applies the fast-path decorator to install.
docs/​src/​content/​docs/​reference/​environment-variables.md Documents replay controls and platform limits.
changelog.d/​4775.changed.md Describes the no-op install optimization.

Review effort: Balanced

Comment thread src/apm_cli/install/noop_fast_path.py Resolved
Comment thread src/apm_cli/install/noop_fast_path.py Resolved
Comment thread src/apm_cli/install/noop_fast_path.py Resolved
Comment thread src/apm_cli/install/noop_fast_path.py Resolved
Comment thread src/apm_cli/install/noop_fast_path.py Resolved
Comment thread src/apm_cli/install/noop_fast_path.py Resolved
Comment thread src/apm_cli/install/noop_fast_path.py Resolved
Comment thread src/apm_cli/install/noop_fast_path.py Resolved
Comment thread src/apm_cli/install/noop_fast_path.py Resolved

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 replay-validation flaws can reuse stale output after manifest, approval, or implementation changes, bypassing required dependency installation or updated validation.

14 open issues
1 previously missed issue

In code that hasn't changed since last review

Medium severity Successful Click exits bypass stamp persistence

src/​apm_cli/​install/​noop_fast_path.py:777

Successful real installs do not return from this callback: commands/install.py:1726 calls ctx.exit(outcome.exit_code), which raises Click's Exit even for code 0. Consequently, the recording context unwinds but recording.save() is never reached, so normal and frozen CLI installs never create a stamp and the lifecycle replay assertions cannot pass. Handle a successful Click exit after restoring the recorder, persist the eligible observation, and re-raise the exit; nonzero exits must not be stamped.

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.

🟡 Changes recommended

The no-op fast path can replay stale success after temporary-directory inputs, symlink targets, or security-relevant metadata change, bypassing trust checks the full install would perform.

10 open issues
12 resolved since last review

Review effort: Balanced

Comment thread src/apm_cli/install/noop_fast_path.py Resolved
Comment thread src/apm_cli/install/noop_fast_path.py Resolved
Comment thread src/apm_cli/install/noop_fast_path.py Resolved
Comment thread src/apm_cli/install/noop_fast_path.py Resolved
Comment thread src/apm_cli/install/noop_fast_path.py Resolved

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.

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.

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.

Comment thread src/apm_cli/install/noop_fast_path.py Resolved

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 unconditional posix import breaks Windows test collection, while redundant cache chmod calls change recorded ctime and prevent converged installs from creating replay stamps.

2 open issues
1 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.

🟡 Changes recommended

The unconditional posix import breaks Windows test collection, while redundant cache-root chmods prevent replay convergence and failed pin reads can leave stale markers unchanged.

3 open issues

Review effort: Balanced

Comment thread src/apm_cli/install/cache_pin.py Resolved

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.

Comment thread src/apm_cli/install/noop_fast_path.py Resolved
Comment thread src/apm_cli/install/noop_recorder.py Resolved
Comment thread src/apm_cli/install/noop_fast_path.py Resolved
… check (revert next)

W4 H8 proof: with every replay check but the invocation key disabled, all
six differential change cells must go red in Lifecycle Smoke. Reverted in
the next commit.

Co-authored-by: Copilot App <[email protected]>
At 73273e6 (run 45065135368, Lifecycle Smoke Shard 4 job 137339484000)
all six differential change cells went red and the replay cell stayed
green; unit cells for changed inputs, policy and deployed hashes went red
in Build & Test Shard 2 (job 137339484155).

Co-authored-by: Copilot App <[email protected]>
- Trace names only the program of a refused subprocess (no command line).
- CPython's -1 'no dir_fd' sentinel is not a descriptor.
- Logging handlers bound to the real streams are pointed at the tee while
  recording, so the replayed output includes their lines.
- Listed directories are revalidated by their entries before stamping.
- Interpreter exclusions narrow to stdlib/site-packages paths instead of
  whole prefixes, so project files or local dependencies under a prefix
  are recorded.
- The APM code identity is captured before the recorded run and must be
  unchanged when the stamp is written.
- Replay re-checks the recorded inputs after the live policy and deployed
  hash checks.
- Unit cell: a same-source policy whose rules tighten runs the full install.

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.

Comment thread src/apm_cli/install/noop_fast_path.py Resolved
Comment thread src/apm_cli/install/noop_recorder.py Resolved
Capturing a listed directory's entries raised its own os.scandir audit
event and recursed until RecursionError escaped the audit hook, failing the
advised 'apm install' in J12 with the flag on. Observations now run under a
per-thread re-entrancy guard, and any error while observing refuses the
stamp instead of propagating into the command. Unit cell: a run that lists
directories is recorded, replayed, and a new entry forces a full install.

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

The pending-stamp branch can let source-hashing errors escape the fallback handler, causing an optional optimization to fail an otherwise valid install instead of running the original callback.

4 open issues

Review effort: Balanced

Comment thread src/apm_cli/install/noop_fast_path.py Resolved
- A stamp must carry exactly one elapsed-summary placeholder; an empty or
  summary-less output is no stamp (full install).
- Refuse to stamp when a locked local dependency source resolves under an
  interpreter root whose reads are not recorded (canonical anchoring via
  deps/path_anchoring.resolve_local_dep_dirs).
- A failure while fingerprinting a pending invocation runs the install.
- The audit-hook guard scans every module except the recorder.

apm-spec-waiver: perf research branch, no spec-visible behavior change

Co-authored-by: Copilot App <[email protected]>
CEO ruling: no default-off landing. apm install and --frozen now replay a
verified no-op unless APM_INSTALL_FAST_PATH=0 (0/false/no/off) turns the
fast path off; =trace keeps it on and reports each decision. The fast-path
modules load only when apm install runs, so other commands pay nothing.
Every lifecycle cell now exercises the fast path; the differential security
cells compare it against APM_INSTALL_FAST_PATH=0 (the full pipeline).

apm-spec-waiver: perf research branch; replay output equals the full no-op

Co-authored-by: Copilot App <[email protected]>
@danielmeppiel
Daniel Meppiel (danielmeppiel) marked this pull request as draft November 22, 2026 21:20

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

Trace diagnostics use raw filenames, allowing non-ASCII paths with ASCII stderr to raise UnicodeEncodeError and alter the install outcome; both diagnostics need ascii_safe() protection.

1 open issue
4 resolved since last review

Review effort: Balanced

Comment thread src/apm_cli/install/noop_fast_path.py Resolved
QL ruling on #4775: the first converged repeat of a default-on install
writes its no-op stamp, a derived cache memo. Exempt ONLY added or changed
files under <cache root>/noop_v1 from I2/I5 and the scenario changed sets
(root-scoped; removal stays a violation), and pair it with a fixed-point
oracle in the same four cache-presence cells: once the memo completes, a
further repeat changes zero bytes anywhere, noop_v1 included, exits 0 and
prints the converged output. Two negative rows: a garbage stamp, and a
stamp re-forged to the tampered inputs, must still run the full install.

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

Replay can incorrectly reuse incomplete or stale recordings because audit-hook installation is not verified, actual invocation arguments are ignored, and dependency changes do not invalidate stamps.

9 open issues

Review effort: Balanced

Comment thread src/apm_cli/install/noop_fast_path.py Resolved
Comment thread src/apm_cli/install/noop_fast_path.py Resolved
Comment thread src/apm_cli/install/noop_recorder.py Resolved
Comment thread src/apm_cli/install/noop_fast_path.py Resolved
Comment thread src/apm_cli/install/noop_fast_path.py Resolved
@danielmeppiel
Daniel Meppiel (danielmeppiel) marked this pull request as ready for review November 22, 2026 21:54
- Invocation arguments come from the root group's recorded raw args
  (ctx.meta['apm_raw_args']), never sys.argv; without them nothing replays.
- Loaded module files outside apm_cli (runtime dependencies, stdlib) are
  content-hashed into the stamp and re-verified on replay.
- An audit-event canary proves the recorder hears audit events, so a
  silently refused sys.addaudithook can never qualify a recording.
- Optimization-only policy discovery runs silenced (logging and streams);
  the full pipeline reports its own diagnostics.
- Trace diagnostics go through ascii_safe and can never fail an install.
- Stamps are published through utils/atomic_io.atomic_write_text.
- Cache-presence fixed point: POSIX only, requires a complete (non-pending)
  stamp and the replay diagnostic, and normalizes the policy cache age.

apm-spec-waiver: perf research branch; replay output equals the full no-op

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.

@danielmeppiel

Copy link
Copy Markdown
Collaborator Author

Closed by [PERF] VP v2: KILLED on evidence. CI bench run 45076115380 (base 82f3d22 -> head f7cb3ae, tree-10, rtt 30, 9 interleaved pairs, paired CPU): install-noop 2.78 -> 3.74 s (paired 1.345, 35% slower) and 8 -> 8 spawns, so the fast path never hit. A memoized replay can only hit from the THIRD install onward. The journey users and CI actually run is the first repeat, and CI starts fresh every time. The no-op target moves to a stateless check (desired state from the lockfile vs actual deployed hashes; empty diff = exit), built in the warm/frozen 'deploy only what changed' lane. Branch danielmeppiel-perf-noop-fast-path is kept for its recorder lessons.

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: strict no-op fast path for apm install / --frozen (1 s target)

2 participants