Skip to content
Draft
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
1 change: 1 addition & 0 deletions changelog.d/5877.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Local plugin re-passes no longer walk and hash each cached copy a second time; a package changed while install was running now stops install instead of re-copying. (#5877)
22 changes: 21 additions & 1 deletion src/apm_cli/install/deployable_source_plan.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,7 +336,9 @@ def add_direct_matching_files(
):
continue
skill_source_roots.add(portable_relpath(skill_dir, source_root))
for path in tree_files(skill_dir):
skill_files = list(tree_files(skill_dir))
_require_sealed_members(skill_dir, skill_files)
for path in skill_files:
relative = path.relative_to(skill_dir)
if skip_bin and relative.parts[0] == "bin":
continue
Expand Down Expand Up @@ -396,3 +398,21 @@ def copy_ignore(self, directory: str, contents: list[str]) -> list[str]:
continue
ignored.append(name)
return ignored


def _require_sealed_members(skill_dir: Path, files: list[Path]) -> None:
"""Refuse a sealed skill directory whose files are not exactly its verified members (#5838).

A re-pass integrates a sealed image without walking it again; this walk is
the one that would see a member deleted or added after the seal.
"""
import sys

registry = sys.modules.get("apm_cli.utils.sealed_files")
expected = None if registry is None else registry.members_under(skill_dir)
if expected is None:
return
walked = frozenset(portable_relpaths(files, skill_dir))
if walked != expected:
changed = sorted(walked ^ expected)[0]
raise registry.changed_error(skill_dir / changed)
39 changes: 28 additions & 11 deletions src/apm_cli/install/local_plugin_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ class ResolvedLocalPlugin:
destination: Path
# The name the image was normalized under, when it differs from the destination's.
staged_name: str | None = None
# The token of the seal a re-pass verified this image under (#5838 slice 5b).
seal: object | None = None


def _plain_legacy_plugin(dep_ref: Any, image: Path) -> tuple[bool, Path | None]:
Expand Down Expand Up @@ -123,12 +125,14 @@ def reuse_resolved_local_plugin(
every raw file resolve hashed, with the same bytes, and may add only what
normalization writes (the synthesized manifest and ``.apm/``). Anything
else, including a file turned into a link, takes the copy-and-validate path.
An image a re-pass sealed this command, still under that same seal, is taken
without a second walk: a member changed after the seal is refused where it is
planned, scanned or copied.
"""
from apm_cli.core.scope import manifest_file
from apm_cli.install.source_helpers import package_digests
from apm_cli.models.apm_package import APMPackage
from apm_cli.models.validation import PackageType
from apm_cli.utils.content_hash import package_payload_paths
from apm_cli.utils import sealed_files

record = ctx.resolved_local_plugins.pop(dep_key, None)
if record is None or install_path.is_symlink() or not install_path.is_dir():
Expand All @@ -137,24 +141,36 @@ def reuse_resolved_local_plugin(
return None
if not _validated_at(ctx, dep_key, install_path, record.destination):
return None
# An image verified this command and still under that seal is the record's:
# every later reader takes its sealed or verified bytes (#5838 slice 5b).
sealed = record.seal is not None and sealed_files.seal_of(install_path, dep_key) is record.seal
if not sealed and not _still_recorded(ctx, record, install_path):
return None
package = APMPackage.from_apm_yml(manifest_file(install_path), source_path=source_path)
return record.digests, package, PackageType.MARKETPLACE_PLUGIN


def _still_recorded(ctx: Any, record: ResolvedLocalPlugin, install_path: Path) -> bool:
"""Whether *install_path* still holds the raw files and digest *record* hashed."""
from apm_cli.core.scope import manifest_file
from apm_cli.install.source_helpers import package_digests
from apm_cli.utils.content_hash import package_payload_paths

apm_yml = manifest_file(install_path)
if not apm_yml.is_file():
return None
return False
current = package_payload_paths(install_path)
added = current - record.files
synthesized = {apm_yml.name}
if not record.files <= current or any(
path not in synthesized and not path.startswith(".apm/") for path in added
):
return None
return False
if record.staged_name is not None and _names_staging(
install_path, added, apm_yml, record.staged_name
):
return None
if package_digests(ctx, install_path, exclude=added) != record.digests:
return None
package = APMPackage.from_apm_yml(apm_yml, source_path=source_path)
return record.digests, package, PackageType.MARKETPLACE_PLUGIN
return False
return package_digests(ctx, install_path, exclude=added) == record.digests


# -- Re-pass of an unchanged local plugin (#5838 slice 8) ----------------------
Expand Down Expand Up @@ -432,17 +448,18 @@ def reuse_unchanged_local_plugin(
"reinstalled from source"
)
return False
sealed_files.seal_image(
token = sealed_files.seal_image(
install_path,
{
manifest_file(install_path).name: seal.manifest,
_SKILL_SOURCES: seal.receipt,
},
seal.members,
owner=dep_ref.get_display_name(),
key=dep_key,
)
ctx.resolved_local_plugins[dep_key] = ResolvedLocalPlugin(
seal.digests, seal.files, install_path.resolve()
seal.digests, seal.files, install_path.resolve(), seal=token
)
ctx.sealed_local_plugins[dep_key] = seal
return True
Expand Down
13 changes: 11 additions & 2 deletions src/apm_cli/install/primitive_classification.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,14 +117,23 @@ def warn_unrecognized_plugin_schema(diagnostics, package_key: str, install_path:
"""Surface non-fatal plugin schema identification misses."""
if diagnostics is None:
return
from apm_cli.agent_plugins.io import read_json_document
import sys

from apm_cli.agent_plugins.io import decode_json_document, read_json_document
from apm_cli.utils.helpers import find_plugin_json

plugin_json_path = find_plugin_json(install_path)
if plugin_json_path is None or not plugin_json_path.is_file():
return
registry = sys.modules.get("apm_cli.utils.sealed_files") # loaded only by install
# A sealed image's manifest is judged in its verified bytes (#5838).
verified = None if registry is None else registry.read_sealed(plugin_json_path)
try:
document = read_json_document(plugin_json_path)
document = (
read_json_document(plugin_json_path)
if verified is None
else decode_json_document(verified, path=plugin_json_path)
)
except (OSError, ValueError):
return
if not isinstance(document, dict):
Expand Down
38 changes: 5 additions & 33 deletions src/apm_cli/integration/write_seam.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,14 +260,11 @@ def copy2(source: Path, destination: Path) -> Path:

A member of a sealed image (#5838) is copied only from its verified bytes.
"""
from apm_cli.utils.sealed_files import member_digest, sealed

digest = member_digest(source)
if digest is not None:
synthesized = sealed(source)
if synthesized is not None: # a verified synthesized file: its sealed bytes
return _copy2_bytes(source, destination, synthesized)
return _copy2_verified(source, destination, digest)
from apm_cli.utils.sealed_files import read_sealed

verified = read_sealed(source)
if verified is not None: # deploy only the bytes that were verified
return _copy2_bytes(source, destination, verified)
record_before_write(
destination,
follow=True,
Expand All @@ -280,31 +277,6 @@ def copy2(source: Path, destination: Path) -> Path:
return copied


def _copy2_verified(source: Path, destination: Path, digest: str) -> Path:
"""``copy2`` of a sealed image member: deploy only the bytes that were verified (#5838).

The member is read once; those bytes are hashed against *digest* and are
the bytes written, so a swap after verification is either refused here or
never read. The destination is never hashed. Raises
:class:`~apm_cli.utils.sealed_files.SealedImageChangedError` on a mismatch,
before anything is written.
"""
import hashlib

from apm_cli.core.remediation import SEALED_IMAGE_CHANGED
from apm_cli.utils.sealed_files import SealedImageChangedError, sealed_owner

owner = sealed_owner(source)

data = Path(source).read_bytes()
if hashlib.sha256(data).hexdigest() != digest:
raise SealedImageChangedError(
f"The cached copy of {owner} changed while it was being installed; "
f"nothing was recorded. {SEALED_IMAGE_CHANGED.sentence()}"
)
return _copy2_bytes(source, destination, data)


def _copy2_bytes(source: Path, destination: Path, data: bytes) -> Path:
"""``copy2`` that writes *data* (*source*'s verified content) with *source*'s metadata."""
from apm_cli.utils.content_hash import exact_hash_of_bytes
Expand Down
9 changes: 8 additions & 1 deletion src/apm_cli/security/content_scanner.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"""

import re
import sys
import unicodedata
from dataclasses import dataclass
from pathlib import Path
Expand Down Expand Up @@ -274,8 +275,14 @@ def scan_file(path: Path) -> list[ScanFinding]:
Handles encoding errors gracefully — returns an empty list if the
file cannot be decoded as UTF-8 (binary files, etc.).
"""
registry = sys.modules.get("apm_cli.utils.sealed_files") # loaded only by install
# A sealed image member is scanned in the bytes it will be deployed with (#5838).
verified = None if registry is None else registry.read_sealed(path)
try:
content = path.read_text(encoding="utf-8")
if verified is not None:
content = verified.decode("utf-8")
else:
content = path.read_text(encoding="utf-8")
except (UnicodeDecodeError, OSError):
return []
return ContentScanner.scan_text(content, filename=str(path))
Expand Down
85 changes: 82 additions & 3 deletions src/apm_cli/utils/sealed_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,35 @@
_FILES: dict[str, bytes] = {}
_MEMBERS: dict[str, str] = {}
_ROOTS: dict[str, str] = {}
# Root -> (dependency key, the token its seal returned): integrate binds to that object.
_SEALS: dict[str, tuple[str, object]] = {}


class SealedImageChangedError(RuntimeError):
"""A sealed image member changed between its verification and its deployment."""


def changed_error(path: str | Path) -> SealedImageChangedError:
"""The one refusal for sealed member *path*: changed, deleted or added after its seal.

It names the plugin and the member path relative to its image.
"""
from apm_cli.core.remediation import SEALED_IMAGE_CHANGED
from apm_cli.utils.diagnostics import printable_ascii_text

key = _key(path)
with _LOCK:
roots = [root for root in _ROOTS if key.startswith(root + os.sep)]
root = max(roots, key=len) if roots else ""
owner = _ROOTS.get(root, "")
member = key[len(root) + 1 :].replace(os.sep, "/") if root else os.fspath(path)
return SealedImageChangedError(
f"The cached copy of {owner} changed while it was being installed "
f"({printable_ascii_text(member)}); nothing was recorded. "
f"{SEALED_IMAGE_CHANGED.sentence()}"
)


def _key(path: str | Path) -> str:
return os.path.normcase(os.path.normpath(os.path.abspath(os.fspath(path))))

Expand All @@ -43,29 +66,40 @@ def reset() -> None:
_FILES.clear()
_MEMBERS.clear()
_ROOTS.clear()
_SEALS.clear()


def seal_image(
root: str | Path, files: dict[str, bytes], members: dict[str, str], *, owner: str = ""
) -> None:
root: str | Path,
files: dict[str, bytes],
members: dict[str, str],
*,
owner: str = "",
key: str = "",
) -> object:
"""Serve *files* (relative path -> bytes) and bind *members* (relative path -> sha256).

*owner* names the plugin in a refusal.
*owner* names the plugin in a refusal. Returns this seal's token: :func:`seal_of`
answers it for (*root*, *key*) until the image is unsealed or sealed again.
"""
token = object()
with _LOCK:
for base in _forms(root):
_ROOTS[base] = owner or Path(root).name
_SEALS[base] = (key, token)
for relative, data in files.items():
_FILES[_key(os.path.join(base, relative))] = data
for relative, digest in members.items():
_MEMBERS[_key(os.path.join(base, relative))] = digest
return token


def unseal_image(root: str | Path) -> None:
"""Drop every seal under *root*: APM is rewriting or removing that image."""
with _LOCK:
for base in _forms(root):
_ROOTS.pop(base, None)
_SEALS.pop(base, None)
prefix = base + os.sep
for table in (_FILES, _MEMBERS):
for key in [key for key in table if key.startswith(prefix)]:
Expand Down Expand Up @@ -101,3 +135,48 @@ def member_digest(path: str | Path) -> str | None:
if any(key.startswith(root + os.sep) for root in _ROOTS):
return ""
return None


def seal_of(root: str | Path, key: str) -> object | None:
"""The token of the seal on *root* made for *key*, or None."""
with _LOCK:
entry = _SEALS.get(_key(root))
return entry[1] if entry is not None and entry[0] == key else None


def members_under(directory: str | Path) -> frozenset[str] | None:
"""The bound members below *directory*, relative to it, or None when it is not sealed."""
base = _key(directory) + os.sep
with _LOCK:
if not any(base.startswith(root + os.sep) for root in _ROOTS):
return None
return frozenset(
key[len(base) :].replace(os.sep, "/") for key in _MEMBERS if key.startswith(base)
)


def read_sealed(path: str | Path) -> bytes | None:
"""The single reader of a sealed image member: the bytes to scan, parse or copy.

None when *path* is in no sealed image. A synthesized file is served from its
seal; any other member is read once and that buffer is returned only when it
hashes to the member's bound digest. A member changed, deleted or added after
the seal raises :func:`changed_error`; it is never skipped.
"""
import hashlib

digest = member_digest(path)
if digest is None:
return None
synthesized = sealed(path)
if synthesized is not None:
return synthesized
if not digest: # under a sealed image, but no member was verified there
raise changed_error(path)
try:
data = Path(path).read_bytes()
except OSError as exc:
raise changed_error(path) from exc
if hashlib.sha256(data).hexdigest() != digest:
raise changed_error(path)
return data
4 changes: 3 additions & 1 deletion tests/benchmarks/spawn_counter/sitecustomize.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

``APM_PERF_COUNT_CALLS=1`` also counts top-level ``shutil.copytree`` calls and
``normalize_plugin_directory``, ``discover_primitives`` (every primitive discovery)
and ``planned_skill_files`` calls, the install hint's instruction walks
``planned_skill_files``, ``package_payload_paths`` and ``package_digests`` calls, the install hint's instruction walks
(``_parsed_instructions``) and listed directories (``_hint_listing``) and ``Path.home()`` lookups (the ``calls``
table, #5838). They are
engine invariants, not budget rows.
Expand Down Expand Up @@ -158,6 +158,8 @@ def _copytree(*a, **k):
"apm_cli.primitives.discovery": ("discover_primitives",),
"apm_cli.compilation.user_root_context": ("_parsed_instructions", "_hint_listing"),
"apm_cli.integration.skill_preflight": ("planned_skill_files",),
"apm_cli.utils.content_hash": ("package_payload_paths",),
"apm_cli.install.source_helpers": ("package_digests",),
}

class _CallCounter(importlib.abc.MetaPathFinder):
Expand Down
Loading