Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
86e73bd
fix(uninstall): record a failed survivor rebuild as an error so unins…
abhishekacharya200 Nov 25, 2026
53bf83e
test: red-first cells for #5424
danielmeppiel Nov 25, 2026
c754096
fix(uninstall,prune): fold case and NFC spellings of one local direct…
danielmeppiel Nov 25, 2026
bdf9156
docs(changelog): fragment for #5426
danielmeppiel Nov 25, 2026
17f9f22
test: a pre-#5424 lock with two rows for one folded directory upgrades
danielmeppiel Nov 25, 2026
4ae6dd0
fix(install): --frozen reads a pre-#5424 row spelled another way; kee…
danielmeppiel Nov 25, 2026
22fbbba
test(install): the fast path never migrates a legacy approvals.yml (#…
danielmeppiel Nov 25, 2026
70a2d73
fix(install): the fast path reads legacy consent and never migrates i…
danielmeppiel Nov 25, 2026
32764b8
chore: changelog fragment for #5429
danielmeppiel Nov 25, 2026
c0483de
test(install): the consent cell asserts the fast decision it exercises
danielmeppiel Nov 25, 2026
10bc8ef
fix(uninstall): count a failed survivor rebuild exactly once
danielmeppiel Nov 25, 2026
0ae72e3
Merge main 8225ec64 (#5406) into fix-5424-macos-case-alias
danielmeppiel Nov 25, 2026
05e0db8
docs(changelog): name the fragment after its PR (#5422)
danielmeppiel Nov 25, 2026
05eba4d
train: merge #5429 (c0483deb)
danielmeppiel Nov 25, 2026
933f233
test: #5426 cells assert what the CLI leaves behind (AQ003, AQ004)
danielmeppiel Nov 25, 2026
30ad7f8
train: merge #5422 (05e0db81)
danielmeppiel Nov 25, 2026
c1d3509
test(uninstall): classify the rebuild-failure cells as component; cit…
danielmeppiel Nov 25, 2026
f90271f
train: fold #5422 (c1d3509f)
danielmeppiel Nov 25, 2026
9e6c1d9
train: merge #5426 (933f233c)
danielmeppiel Nov 25, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/5422.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- `apm uninstall` now reports a failed survivor rebuild as an error and exits non-zero instead of printing `Uninstall complete`. (closes #4954, #5422)
1 change: 1 addition & 0 deletions changelog.d/5426.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- `apm uninstall` and `apm prune` treat case or Unicode variants of one local directory as one package; `apm install` merges older duplicate lock rows. (#5426)
1 change: 1 addition & 0 deletions changelog.d/5429.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- `apm install` no longer migrates a legacy `approvals.yml` while it decides whether the fast path applies; only a full install migrates it. (#5429)
8 changes: 8 additions & 0 deletions src/apm_cli/commands/uninstall/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -1678,6 +1678,7 @@ def _sync_integrations_after_uninstall(
# Survivors redeploy exactly the selection install deployed (#3760).
selection = effective_dependency_selection(dep_ref)

failures_before = reintegration_diagnostics.failed_package_count
try:
integration_result = integrate_package_primitives(
pkg_info,
Expand All @@ -1703,6 +1704,13 @@ def _sync_integrations_after_uninstall(
f"Best-effort re-integration skipped for {pkg_id}. "
f"{INTEGRATED_FILES_STALE.sentence()}"
)
# Count the failed rebuild once so uninstall exits non-zero (#4954);
# an error the rebuild already recorded for it counts already.
if reintegration_diagnostics.failed_package_count == failures_before:
reintegration_diagnostics.error(
"Could not rebuild the surviving package's integrated files",
package=pkg_id,
)
logger.verbose_detail(
f" Re-integration error: {_reintegration_error_detail(dep_ref, exc)}"
)
Expand Down
87 changes: 81 additions & 6 deletions src/apm_cli/deps/local_identity.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@

from __future__ import annotations

from collections.abc import Callable, Iterable
import os
from collections.abc import Callable, Iterable, Mapping
from dataclasses import replace
from pathlib import Path
from typing import TypeVar
from pathlib import Path, PurePosixPath
from typing import Any, TypeVar

from ..models.dependency.reference import DependencyReference
from ..utils.paths import portable_relpath
from ..utils.paths import portable_relpath, relative_posix, spelling_key, stored_spelling
from ..utils.realpath import resolve_path

_T = TypeVar("_T")

Expand Down Expand Up @@ -45,6 +47,77 @@ def portable_anchor_identity(anchored: Path, base: Path | None) -> str:
return portable_relpath(anchored, base)


def stored_directory(anchored: Path, root: Path | None) -> Path:
"""*anchored* spelled as the volume stores it: one directory, one spelling (#5424).

A case-folding or normalizing volume (macOS, Windows) opens ``F-Pkg`` as
``f-pkg`` and an NFD name as its NFC form, but ``Path.resolve`` keeps the
spelling it was given. Each component below the project *root* takes the
stored entry (:func:`apm_cli.utils.paths.stored_spelling`): an exact entry
always wins, so a path spelled as stored keeps its identity, and a folded
one must be confirmed by ``samefile``, so distinct directories on a
case-sensitive volume never merge. *anchored* is already resolved (no
links); a directory outside *root*, or a missing or ambiguous entry,
keeps *anchored*: nothing outside the project is listed. Cost: one
directory listing per component below *root*, plus one ``samefile`` per
folded component.
"""
if root is None:
return anchored
try:
base = resolve_path(root)
except (OSError, RuntimeError):
return anchored
rest = relative_posix(anchored, base)
if not rest or rest == "." or (os.sep != "\\" and "\\" in rest):
# A POSIX name may hold a literal backslash, which is not a separator.
return anchored
stored = stored_spelling(base, rest)
return base / stored if stored is not None and stored != rest else anchored


def _below_root(anchor: str) -> bool:
"""Whether an ``anchored_local_path`` is project-relative (not an out-of-project path)."""
parts = PurePosixPath(anchor).parts
return (
bool(parts)
and not PurePosixPath(anchor).is_absolute()
and ".." not in parts
and ":" not in parts[0]
)


def locked_spelling(
ref: DependencyReference, locked: Mapping[str, Any], root: Path | None
) -> DependencyReference:
"""*ref* keyed as a pre-#5424 lock row that names its directory another way.

Before :func:`stored_directory`, a transitive row kept the declared
spelling (``vendor/f-pkg`` for a stored ``F-Pkg``). When *ref*'s key is not
locked, a row whose ``anchored_local_path`` has the same caseless key and
is the same directory below *root* (``samefile``) names it, so ``install
--frozen`` accepts such a lock, read-only, until a plain install re-keys
it. A case-sensitive volume never confirms two spellings. Scans the rows
only on a miss.
"""
anchor = ref.anchored_local_path
if not anchor or root is None or ref.get_unique_key() in locked or not _below_root(anchor):
return ref
want = spelling_key(anchor)
for row in locked.values():
legacy = getattr(row, "anchored_local_path", None)
if not legacy or legacy == anchor or spelling_key(legacy) != want:
continue
if not _below_root(legacy):
continue
try:
if os.path.samefile(root / legacy, root / anchor):
return replace(ref, anchored_local_path=legacy)
except OSError:
continue
return ref


def root_local_dirs(
root_refs: Iterable[DependencyReference], consumer_root: Path
) -> dict[Path, DependencyReference]:
Expand All @@ -54,7 +127,7 @@ def root_local_dirs(
if ref.is_local and ref.local_path and ref.replacement is None:
raw = Path(ref.local_path).expanduser()
anchored = raw.resolve() if raw.is_absolute() else (consumer_root / raw).resolve()
dirs.setdefault(anchored, ref)
dirs.setdefault(stored_directory(anchored, consumer_root), ref)
return dirs


Expand All @@ -71,8 +144,10 @@ def transitive_local_identity(
When the root manifest also declares the anchored directory, the edge
takes the root declaration's identity and spelling, however the declaring
package spells its relative path (``../lib`` vs ``./packages/lib``).
Otherwise the edge is keyed by its anchored directory.
Otherwise the edge is keyed by its anchored directory, spelled as the
volume stores it (:func:`stored_directory`, #5424).
"""
anchored = stored_directory(anchored, root)
root_ref = root_local_dirs.get(anchored)
if root_ref is not None:
return replace(sub_dep, repo_url=root_ref.repo_url, local_path=root_ref.local_path)
Expand Down
5 changes: 4 additions & 1 deletion src/apm_cli/install/fast_entry.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,11 @@ def _run(frozen: bool) -> Any:
disposition = InstallService.frozen_disposition(SimpleNamespace(frozen=frozen))
options = {"frozen": disposition.replay}
decide = _decide_only()
from apm_cli.security.executables import speculative_consent

# Deciding only reads: no lifecycle lock (it writes lock state) and no cache upkeep.
with read_only_caches() if decide else lifecycle_operation():
# The fast path never migrates personal consent; the full install does (#5428).
with read_only_caches() if decide else lifecycle_operation(), speculative_consent():
try:
done = diff_apply.try_apply(
options, argv, root, frozen_disposition=disposition, decide_only=decide
Expand Down
7 changes: 4 additions & 3 deletions src/apm_cli/install/local_content_verdict.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,8 @@ def local_content_reasons(
from dataclasses import replace

from apm_cli.deps.apm_resolver import APMDependencyResolver
from apm_cli.deps.local_identity import locked_spelling, transitive_local_identity
from apm_cli.deps.local_identity import root_local_dirs as collect_root_local_dirs
from apm_cli.deps.local_identity import transitive_local_identity
from apm_cli.deps.path_anchoring import (
LocalResolutionError,
build_local_parent_index,
Expand Down Expand Up @@ -179,14 +179,15 @@ def local_content_reasons(
anchored = APMDependencyResolver._compute_dep_source_path(
child, package, source
)
root = apm_package.source_path or package_root
child = transitive_local_identity(
child,
declaring_parent=key,
anchored=anchored,
root=apm_package.source_path or package_root,
root=root,
root_local_dirs=root_local_dirs,
)
queue.append(child)
queue.append(locked_spelling(child, lockfile.dependencies, root))
except (LocalResolutionError, OSError, ValueError) as exc:
reasons.append(
f" - local dependency {declared.local_path!r} cannot be verified: {exc}"
Expand Down
23 changes: 20 additions & 3 deletions src/apm_cli/security/executables.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@

from __future__ import annotations

import contextlib
import fnmatch
import os
import sys
from collections.abc import Collection
from collections.abc import Collection, Iterator
from dataclasses import dataclass, field, replace
from pathlib import Path
from typing import Any
Expand Down Expand Up @@ -1812,6 +1813,22 @@ def _legacy_approvals_path() -> Path:
return get_apm_home() / "approvals.yml"


# A speculative decision (the install fast path, #5428) reads personal consent and
# never migrates it: it runs before its journal, so a later decline could not undo
# the write. The full install (and apm approve) keep migrating.
_SPECULATIVE_CONSENT: list[bool] = []


@contextlib.contextmanager
def speculative_consent() -> Iterator[None]:
"""Read legacy ``approvals.yml`` without migrating it, for the enclosed decision."""
_SPECULATIVE_CONSENT.append(True)
try:
yield
finally:
_SPECULATIVE_CONSENT.pop()


def _migrate_legacy_approvals(
allow: dict[str, dict[str, bool]],
*,
Expand All @@ -1822,8 +1839,7 @@ def _migrate_legacy_approvals(
The legacy file stored a bare ``{package_key: {exec_type: bool}}`` map of
grants. Existing config entries win over legacy entries on conflict.
"""
import contextlib

persist = persist and not _SPECULATIVE_CONSENT
legacy = _legacy_approvals_path()
if not legacy.is_file():
return allow
Expand Down Expand Up @@ -1864,6 +1880,7 @@ def load_user_executables(
allow = dict(section.get("allow") or {})
deny = dict(section.get("deny") or {})

migrate_legacy = migrate_legacy and not _SPECULATIVE_CONSENT
original_allow = {key: dict(value) for key, value in allow.items()}
migrated = _migrate_legacy_approvals(allow, persist=migrate_legacy)
if migrate_legacy and (migrated != original_allow or (allow and "executables" not in cfg)):
Expand Down
17 changes: 17 additions & 0 deletions tests/fixtures/lifecycle_bug_ledger/bugs/5424.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"issue": 5424,
"fixed_in": "Unreleased",
"summary": "On a case- or normalization-folding volume (macOS, Windows), two spellings of one local package directory (E-Pkg and e-pkg, or NFC and NFD names) became two lock rows, so apm uninstall refused to re-anchor the survivor and apm prune kept an orphan. The anchored directory now takes the spelling the volume stores, so the directory is one lock row.",
"failure_modes": [
"outcome"
],
"properties": [
"outcome.status_matches_state"
],
"regression_tests": [
"tests/integration/test_uninstall_local_reanchor_lifecycle.py::test_reanchor_with_a_case_variant_parent_spelling",
"tests/integration/test_uninstall_local_reanchor_lifecycle.py::test_one_lock_row_for_a_case_variant_parent_spelling_and_a_clean_reanchor",
"tests/integration/test_prune_transitive_local_orphan_lifecycle.py::test_install_and_prune_keep_one_row_per_folded_directory",
"tests/unit/deps/test_apm_resolver_helpers.py::TestOneAnchoredDirectoryIsOneDependency::test_spellings_of_one_directory_are_one_node_only_where_the_volume_folds"
]
}
14 changes: 14 additions & 0 deletions tests/fixtures/lifecycle_bug_ledger/bugs/5428.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"issue": 5428,
"fixed_in": "Unreleased",
"summary": "The install fast path migrated a legacy $APM_HOME/approvals.yml into config.json (and deleted it) during its speculative decision, even under APM_INSTALL_FAST_PATH=decide; the fast path now reads legacy consent without migrating it and the full install keeps the migration.",
"failure_modes": [
"transaction"
],
"properties": [
"transaction.failed_command_preserves_state"
],
"regression_tests": [
"tests/integration/test_fast_path_consent.py::test_a_fast_path_decision_never_migrates_a_legacy_approvals_file"
]
}
101 changes: 101 additions & 0 deletions tests/integration/test_fast_path_consent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
"""The install fast path never migrates personal consent (#5428), over the real CLI.

PROMISE: P-INV-I5 -- a command writes only its declared write set: the fast
path's speculative decision reads a legacy ``$APM_HOME/approvals.yml`` and never
folds it into ``config.json`` or deletes it; the full install owns that write.

The real CLI over the tree-10 offline world (a dependency-declared MCP server):
``APM_INSTALL_FAST_PATH=decide`` reports the decision and writes nothing, so
the legacy file and ``config.json`` stay byte-identical; with every fast path
off, the same state migrates (positive control: the legacy file is live).
"""

from __future__ import annotations

import shutil
import subprocess
import sys
import tempfile
from pathlib import Path

import pytest

import apm_cli
from apm_cli.install.fast_entry import DECIDE_EXIT
from tests.fixtures.perf import TREE_RECIPES, build_tree, serve_offline

pytestmark = [
pytest.mark.component,
pytest.mark.integration,
pytest.mark.promise("P-INV-I5"),
]

_NO_HIT = ("CI", "GITHUB_ACTIONS", "TF_BUILD", "BUILD_ID", "GITLAB_CI", "BUILDKITE")
# The console script's own entry (pyproject: apm = apm_cli.entrypoint:main).
_ENTRY = (sys.executable, "-c", "import sys; from apm_cli.entrypoint import main; sys.exit(main())")
_LEGACY = "perf-org/pkg-000: {hooks: true}\n"


@pytest.fixture
def world():
"""``(install, apm_home)`` in a fresh, installed tree-10 project."""
work = Path(tempfile.mkdtemp(prefix="apm-consent-"))
try:
tree = build_tree(TREE_RECIPES["tree-10"], work / "tree")
with serve_offline(tree, work / "world") as served:
project = work / "project"
shutil.copytree(tree.project, project)
env = {k: v for k, v in served.env.items() if k not in _NO_HIT}
env["PYTHONPATH"] = str(Path(apm_cli.__file__).resolve().parents[1])

def install(fast: str) -> subprocess.CompletedProcess:
return subprocess.run(
[*_ENTRY, "install"],
cwd=project,
env=dict(env, APM_INSTALL_FAST_PATH=fast),
capture_output=True,
text=True,
timeout=600,
)

assert install("0").returncode == 0
yield install, Path(served.apm_home)
finally:
shutil.rmtree(work, ignore_errors=True)


def _consent(home: Path) -> tuple[bytes | None, bytes | None]:
return tuple( # type: ignore[return-value]
path.read_bytes() if path.exists() else None
for path in (home / "approvals.yml", home / "config.json")
)


def test_a_fast_path_decision_never_migrates_a_legacy_approvals_file(world) -> None:
install, home = world
(home / "approvals.yml").write_text(_LEGACY, encoding="utf-8")
before = _consent(home)

decided = install("decide")

# The full fast decision was reached (it reads consent on the way); an early
# decline (no lockfile, an error) would leave the files alone for another reason.
assert decided.returncode == DECIDE_EXIT, decided.stdout + decided.stderr
assert "install fast path: no-op (desired state already deployed)" in decided.stderr
_assert_consent(home, before)


def test_the_full_install_still_migrates_a_legacy_approvals_file(world) -> None:
"""Positive control: the legacy file is live, and the full install folds it in."""
install, home = world
(home / "approvals.yml").write_text(_LEGACY, encoding="utf-8")

done = install("0")

assert done.returncode == 0, done.stdout + done.stderr
assert not (home / "approvals.yml").exists()
assert "perf-org/pkg-000" in (home / "config.json").read_text(encoding="utf-8")


def _assert_consent(home: Path, before) -> None:
assert _consent(home) == before, "the fast path migrated personal consent"
Loading
Loading