Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
7 changes: 4 additions & 3 deletions .apm/architecture/owners/contracts-tooling.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
{
"id": "dependency-identity-materialization",
"decision": "Dependency comparison identity and policy casing vs display-cased materialization path; host-bound exact policy require identity (required_package_policy_hosts), resolved once by policy/matcher.py DependencyPolicyIndex.find for the manifest and, via the matched dependency's unique key, the lockfile; distinct remote packages never share one materialization directory (MaterializationSlots, before fetch); root-owned exact source replacement and original ownership; embedded git URL subpath validation; the anchor a relative local_path resolves against (the declaring package at every scope; a root-declared relative path at user scope is refused)",
"owner": "models/dependency/identity.py + materialization.py + replacement.py (typed root binding and clean selected-source projection) + object_fields.py (alias validation) + deps/apm_resolver.py (remote source-coordinate anchoring) + DependencyReference (_check_no_embedded_subpath consumes core/host_providers.py) + install/plan.py (root intent comparison; update plans compare the ref the lockfile records) + install/phases/lockfile.py (including empty-graph root intent persistence) + deps/path_anchoring.py local_dep_base_dir (local_path anchor: it decides which directory a relative dependency path names, so it is the local half of materialization identity)",
"owner": "models/dependency/identity.py + materialization.py + replacement.py (typed root binding and clean selected-source projection) + object_fields.py (alias validation) + deps/apm_resolver.py (remote source-coordinate anchoring) + DependencyReference (_check_no_embedded_subpath consumes core/host_providers.py) + install/plan.py (root intent comparison; update plans compare the ref the lockfile records) + install/phases/lockfile.py (including empty-graph root intent persistence) + deps/path_anchoring.py local_dep_base_dir (local_path anchor: it decides which directory a relative dependency path names, so it is the local half of materialization identity) + deps/local_identity.py transitive_local_identity (one anchored directory is one dependency: the node key of a declared local edge for install, the --frozen verdict and the reachability walk, #4731)",
"selectors": [
"src/apm_cli/models/dependency/identity.py",
"src/apm_cli/models/dependency/materialization.py",
Expand All @@ -64,9 +64,10 @@
"src/apm_cli/install/presentation/resolution.py",
"src/apm_cli/install/helpers/no_work.py",
"src/apm_cli/install/plan.py",
"src/apm_cli/deps/path_anchoring.py"
"src/apm_cli/deps/path_anchoring.py",
"src/apm_cli/deps/local_identity.py"
],
"guards": ["contracts-tooling-dependency-identity", "contracts-tooling-local-path-anchor", "contracts-tooling-policy-identity", "contracts-tooling-source-replacements", "contracts-tooling-update-plan-recorded-ref"]
"guards": ["contracts-tooling-dependency-identity", "contracts-tooling-local-identity", "contracts-tooling-local-path-anchor", "contracts-tooling-policy-identity", "contracts-tooling-source-replacements", "contracts-tooling-update-plan-recorded-ref"]
},
{
"id": "native-lifecycle-evidence",
Expand Down
13 changes: 8 additions & 5 deletions CONFORMANCE.json
Original file line number Diff line number Diff line change
Expand Up @@ -1012,14 +1012,17 @@
]
},
{
"behavioral_tests": [],
"behavioral_tests": [
"tests/spec_conformance/test_local_path_identity_reqs.py::test_consumer_recognises_two_relative_spellings_of_one_local_path"
],
"conformance_class": "consumer",
"id": "req-mf-016",
"keyword": "MUST",
"section": "4.3.5",
"status": "skipped",
"test_count": 1,
"status": "active",
"test_count": 2,
"tests": [
"tests/spec_conformance/test_local_path_identity_reqs.py::test_consumer_recognises_two_relative_spellings_of_one_local_path",
"tests/spec_conformance/test_manifest_reqs.py::test_consumer_rejects_absolute_paths_in_apm_source"
],
"waivers": [
Expand Down Expand Up @@ -3350,9 +3353,9 @@
"spec_version": "v0.1.1",
"summary_by_class": {
"consumer": {
"active": 110,
"active": 111,
"partial": 1,
"skipped": 3,
"skipped": 2,
"text-only": 3,
"unbound": 0,
"xfail": 0
Expand Down
4 changes: 2 additions & 2 deletions CONFORMANCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ APM implements the proposed staged-replacement recovery capability (req-lk-023).
| Class | Active | Partial | Skipped | Xfail | Text-only | Unbound |
|-------|-------:|--------:|--------:|------:|----------:|--------:|
| Producer | 9 | 0 | 0 | 0 | 3 | 0 |
| Consumer | 110 | 1 | 3 | 0 | 3 | 0 |
| Consumer | 111 | 1 | 2 | 0 | 3 | 0 |
| Registry | 0 | 0 | 0 | 0 | 1 | 0 |
| Governance | 22 | 0 | 0 | 0 | 0 | 0 |

Expand Down Expand Up @@ -97,7 +97,7 @@ APM implements the proposed staged-replacement recovery capability (req-lk-023).
| [req-mf-013](docs/src/content/docs/specs/openapm-v0.1.md#req-mf-013) | MUST | 4.5 | consumer | active | 2 / 3 | - |
| [req-mf-014](docs/src/content/docs/specs/openapm-v0.1.md#req-mf-014) | MUST | 4.2.3 | producer | active | 1 / 2 | - |
| [req-mf-015](docs/src/content/docs/specs/openapm-v0.1.md#req-mf-015) | MUST | 4.2.3 | producer | active | 2 / 3 | - |
| [req-mf-016](docs/src/content/docs/specs/openapm-v0.1.md#req-mf-016) | MUST | 4.3.5 | consumer | skipped | 0 / 1 | - |
| [req-mf-016](docs/src/content/docs/specs/openapm-v0.1.md#req-mf-016) | MUST | 4.3.5 | consumer | active | 1 / 2 | - |
| [req-mf-017](docs/src/content/docs/specs/openapm-v0.1.md#req-mf-017) | MUST | 4.7 | producer | active | 11 / 12 | - |
| [req-mf-018](docs/src/content/docs/specs/openapm-v0.1.md#req-mf-018) | MUST | 4.6.1 | consumer | active | 5 / 6 | - |
| [req-mf-019](docs/src/content/docs/specs/openapm-v0.1.md#req-mf-019) | MUST | 4.2.4 | consumer | active | 1 / 2 | - |
Expand Down
1 change: 1 addition & 0 deletions changelog.d/4739.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- `apm install --frozen` and `apm audit --ci` accept a monorepo library referenced as `./packages/lib` from the root and `../lib` from a sibling. (closes #4731, #4739)
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
root, or nothing (a root-declared relative path at user scope). The guard is
closed-world: no other function may combine a user-scope test with an
``is_absolute()`` test on a ``local_path``, nor restate the refusal text, and the three install
consumers must call the owner.
consumers must call the owner. ``deps/local_identity.transitive_local_identity``
likewise owns the node key of a declared local edge (#4731).
"""

from __future__ import annotations
Expand Down Expand Up @@ -111,6 +112,75 @@ def check_local_path_anchor(provider: FactsProvider) -> tuple[Violation, ...]:
return tuple(findings)


IDENTITY_RULE = "contracts-tooling-local-identity"
IDENTITY_OWNER = "src/apm_cli/deps/local_identity.py"
IDENTITY_SYMBOL = "transitive_local_identity"
_ANCHOR_HELPERS = frozenset({"portable_anchor_identity", "_portable_anchor_identity"})
_ANCHOR_DELEGATE = ("src/apm_cli/deps/apm_resolver.py", "_portable_anchor_identity")
IDENTITY_CONSUMERS = {
"src/apm_cli/deps/apm_resolver.py": "APMDependencyResolver.build_dependency_tree",
"src/apm_cli/install/local_content_verdict.py": "local_content_reasons",
"src/apm_cli/deps/reachability.py": "compute_forward_reachable_keys",
}


def _called_name(call: ast.Call) -> str | None:
if isinstance(call.func, ast.Name):
return call.func.id
if isinstance(call.func, ast.Attribute):
return call.func.attr
return None


def _calls(node: ast.AST, names: frozenset[str]) -> bool:
return any(
isinstance(item, ast.Call) and _called_name(item) in names for item in ast.walk(node)
)


def _anchor_bypasses(provider: FactsProvider) -> list[Violation]:
"""Only the identity owner may turn an anchored directory into a node key."""
findings: list[Violation] = []
for path in _python_paths(provider, _SRC_PREFIX):
if path == IDENTITY_OWNER:
continue
index = provider.tree_index(path)
if index is None or index.root is None:
continue
for node in index.functions():
if (path, getattr(node, "name", "")) == _ANCHOR_DELEGATE:
continue
body = ast.Module(body=node.body, type_ignores=[])
if _calls(body, _ANCHOR_HELPERS):
findings.append(
_summary(
IDENTITY_RULE,
path,
f"{node.name} derives a local anchored identity; "
f"call {IDENTITY_SYMBOL} ({IDENTITY_OWNER})",
)
)
return findings


def check_local_identity(provider: FactsProvider) -> tuple[Violation, ...]:
"""One anchored directory is one dependency, keyed only by the identity owner."""
findings = _anchor_bypasses(provider)
for path, symbol in IDENTITY_CONSUMERS.items():
facts, failures = checked_facts(provider, path, IDENTITY_RULE, require_python=True)
findings.extend(failures)
if facts is None or facts.tree_index is None:
continue
function = facts.tree_index.function(symbol)
if function is None or not _calls(function, frozenset({IDENTITY_SYMBOL})):
findings.append(
_summary(
IDENTITY_RULE, path, f"{symbol} must key local edges via {IDENTITY_SYMBOL}"
)
)
return tuple(findings)


RULES = (
Rule(
id=RULE,
Expand All @@ -119,4 +189,11 @@ def check_local_path_anchor(provider: FactsProvider) -> tuple[Violation, ...]:
description="Relative local paths anchor on the declaring package via one owner.",
check=check_local_path_anchor,
),
Rule(
id=IDENTITY_RULE,
group="contracts_tests",
guard_ids=(IDENTITY_RULE,),
description="One anchored local directory is one dependency, keyed by one owner.",
check=check_local_identity,
),
)
75 changes: 47 additions & 28 deletions src/apm_cli/deps/apm_resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
from ..models.dependency.subsets import EdgeSelection, merge_edge_selections
from ..models.validation import PackageType, detect_package_type, validate_apm_package
from ..utils.path_security import PathTraversalError, ensure_path_within, validate_path_segments
from ..utils.paths import portable_relpath
from ._shared import MarketplaceManifestMaterializationError, materialize_marketplace_manifest
from .dependency_graph import (
CircularRef,
Expand All @@ -40,6 +39,8 @@
ImmutableRequirements,
ReferenceResolver,
)
from .local_identity import portable_anchor_identity, transitive_local_identity
from .local_identity import root_local_dirs as collect_root_local_dirs

if TYPE_CHECKING:
from .lockfile import LockFile
Expand Down Expand Up @@ -499,28 +500,8 @@ def _is_absolute_local_path(local_path: str) -> bool:

@staticmethod
def _portable_anchor_identity(anchored: Path, base: Path | None) -> str:
"""Return a machine-independent identity string for a resolved local dep.

``anchored`` is the absolute, resolved on-disk location of a local
package. The returned value is the package's stable identity only --
it feeds the ``local:`` cycle key, the lockfile
``dependencies[].anchored_local_path`` field, and (via that same owner
identity) the deployment-ledger owner rows. It is never re-opened as a
filesystem path.

A lockfile is a committed, cross-machine artifact, so this identity
MUST NOT carry a developer's home directory or any absolute prefix.
Packages inside ``base`` (the project root) are recorded relative to
it in forward-slash POSIX form -- matching how directly-declared local
owners already serialize -- which keeps a regenerated lockfile
deterministic across machines and CI. Packages outside ``base`` (or
when ``base`` is unknown) fall back to the resolved absolute POSIX
path: such out-of-project local deps are inherently non-committable,
and the fallback preserves a unique identity without inventing one.
"""
if base is None:
return anchored.resolve().as_posix()
return portable_relpath(anchored, base)
"""Delegate to :func:`apm_cli.deps.local_identity.portable_anchor_identity`."""
return portable_anchor_identity(anchored, base)

def _remote_source_paths_for_parent(
self,
Expand Down Expand Up @@ -965,6 +946,9 @@ def build_dependency_tree(
queued_keys.add(key)
# If already queued as prod, prod wins — skip

root_local_dirs = collect_root_local_dirs(
[item[0] for item in processing_queue], consumer_root
)
if self._reject_nested_root_declarations(
tree, [item[0] for item in processing_queue], modules_dir
):
Expand Down Expand Up @@ -1037,7 +1021,15 @@ def build_dependency_tree(
and dep_ref.get_unique_key() not in self._scoped_rechecked
and existing_node.get_id() not in scheduled_nodes
):
work_items.append((existing_node, dep_ref, parent_node, is_dev))
# Recheck the node at its own anchor, not this edge's (#4731).
work_items.append(
(
existing_node,
existing_node.dependency_ref,
existing_node.parent,
is_dev,
)
)
scheduled_nodes.add(existing_node.get_id())
continue

Expand Down Expand Up @@ -1179,12 +1171,12 @@ def build_dependency_tree(
if local_path.is_absolute()
else (node.package.source_path / local_path).resolve()
)
sub_dep = replace(
sub_dep = transitive_local_identity(
sub_dep,
declaring_parent=node.get_id(),
anchored_local_path=self._portable_anchor_identity(
anchored, root_package.source_path
),
anchored=anchored,
root=root_package.source_path,
root_local_dirs=root_local_dirs,
)
ancestor: DependencyNode | None = node
while ancestor is not None:
Expand Down Expand Up @@ -1231,9 +1223,36 @@ def build_dependency_tree(
processing_queue.append((sub_dep, node.depth + 1, node, is_dev))
queued_keys.add(queue_key)

self._propagate_production(tree)
self._apply_edge_selections(tree)
return tree

def _propagate_production(self, tree: DependencyTree) -> None:
"""Mark every node a production node declares production (prod wins over dev).

Follows materialized children and every recorded declaring edge, so a
node first loaded as dev (a root devDependency a production sibling also
declares) promotes its whole subtree, including children whose edges the
queue dedup dropped, independent of declaration order (#4731).
"""
declared: dict[int, list[str]] = {}
for key, parents in self._edge_parents.items():
for parent in parents:
declared.setdefault(id(parent), []).append(key)
by_key: dict[str, list[DependencyNode]] = {}
for node in tree.nodes.values():
by_key.setdefault(node.dependency_ref.get_unique_key(), []).append(node)
pending = [node for node in tree.nodes.values() if not node.is_dev]
while pending:
node = pending.pop()
declared_children = (
c for key in declared.get(id(node), ()) for c in by_key.get(key, ())
)
for child in [*node.children, *declared_children]:
if child.is_dev:
child.is_dev = False
pending.append(child)

@staticmethod
def _reject_nested_root_declarations(
tree: DependencyTree,
Expand Down
80 changes: 80 additions & 0 deletions src/apm_cli/deps/local_identity.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
"""The one owner of a local dependency's node identity (#4731).

A relative ``local_path`` names a directory; one directory is one dependency.
The install resolver, the ``--frozen`` local-content verdict and the
reachability walk behind ``audit --ci``, ``uninstall`` and ``prune`` all key a
declared local edge through :func:`transitive_local_identity`, so they agree
on one lockfile row per anchored directory.
"""

from __future__ import annotations

from collections.abc import Iterable
from dataclasses import replace
from pathlib import Path

from ..models.dependency.reference import DependencyReference
from ..utils.paths import portable_relpath


def portable_anchor_identity(anchored: Path, base: Path | None) -> str:
"""Return a machine-independent identity string for a resolved local dep.

``anchored`` is the absolute, resolved on-disk location of a local
package. The returned value is the package's stable identity only --
it feeds the ``local:`` cycle key, the lockfile
``dependencies[].anchored_local_path`` field, and (via that same owner
identity) the deployment-ledger owner rows. It is never re-opened as a
filesystem path.

A lockfile is a committed, cross-machine artifact, so this identity
MUST NOT carry a developer's home directory or any absolute prefix.
Packages inside ``base`` (the project root) are recorded relative to
it in forward-slash POSIX form -- matching how directly-declared local
owners already serialize -- which keeps a regenerated lockfile
deterministic across machines and CI. Packages outside ``base`` (or
when ``base`` is unknown) fall back to the resolved absolute POSIX
path: such out-of-project local deps are inherently non-committable,
and the fallback preserves a unique identity without inventing one.
"""
if base is None:
return anchored.resolve().as_posix()
return portable_relpath(anchored, base)


def root_local_dirs(
root_refs: Iterable[DependencyReference], consumer_root: Path
) -> dict[Path, DependencyReference]:
"""Map each root-declared local package's resolved directory to its ref."""
dirs: dict[Path, DependencyReference] = {}
for ref in root_refs:
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)
return dirs


def transitive_local_identity(
sub_dep: DependencyReference,
*,
declaring_parent: str,
anchored: Path,
root: Path | None,
root_local_dirs: dict[Path, DependencyReference],
) -> DependencyReference:
"""Return the node identity of a local edge a package declares.

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.
"""
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)
return replace(
sub_dep,
declaring_parent=declaring_parent,
anchored_local_path=portable_anchor_identity(anchored, root),
)
Loading
Loading