diff --git a/src/agent_env/providers/sandbox_providers/host_images.py b/src/agent_env/providers/sandbox_providers/host_images.py index 55b4019fc..180fee327 100644 --- a/src/agent_env/providers/sandbox_providers/host_images.py +++ b/src/agent_env/providers/sandbox_providers/host_images.py @@ -4,7 +4,8 @@ under the image's name, labeled with the sources it was built from, and built again only when those change, so a later deploy, a parallel one or another run finds it. A VM on this machine starts with no build cache, so it loads a saved copy of that build, kept once per sources. Neither is a store version: the image is its build context. An image a -registry publishes is pulled here by its digest, and built from its build context only when it can't be. +registry publishes is pulled here by its digest, unless Docker holds it by that digest already, and built from its build +context only when it can't be. """ from __future__ import annotations @@ -49,11 +50,19 @@ def holds(image_name: str, image_sources: str | None) -> bool: return image_sources is not None and _built_from(image_name) == image_sources -def holds_digest(image: DockerImageArtifact) -> bool: - """Whether this machine's Docker holds ``image``, one with an ``image_digest``, under its name as the image that - digest names: pulled by it, or built here from the image's sources. A tag can name another image than the one a - version records, so holding its name isn't enough.""" - return image.image_digest in _repo_digests(image.image_name) or held(image) +def named_if_held(image: DockerImageArtifact) -> bool: + """Whether this machine's Docker holds ``image``, one with an ``image_digest``, as that digest names it, under its + name (``_holds_under_name``) or by the digest alone, as ``docker pull @`` leaves an image, which it + then names with ``image_name`` over whatever that name held, so a container started by the name runs it.""" + if _holds_under_name(image): + return True + if image.image_digest not in _repo_digests(image.pinned_name): + return False + if present(image.image_name): + logger.warning("%s named another image than the one it's pinned to, %s; it now names the pinned one", + image.image_name, image.image_digest) + _tag(image) + return True def present(image_name: str) -> bool: @@ -146,14 +155,14 @@ def pull_lock(image_name: str) -> str: def pull(image: DockerImageArtifact) -> None: """Have this machine's Docker hold ``image``, one with an ``image_digest``, under its name, unless it already holds - it (``holds_digest``): pulled by its digest, or, when that fails, built from its build context. Raises RuntimeError + it (``named_if_held``): pulled by its digest, or, when that fails, built from its build context. Raises RuntimeError when it can't be pulled or built.""" with holding_locks([pull_lock(image.pinned_name)]): - if holds_digest(image): + if named_if_held(image): return pulled = subprocess.run(["docker", "pull", image.pinned_name], capture_output=True, text=True, errors="replace") if pulled.returncode == 0: - subprocess.run(["docker", "tag", image.pinned_name, image.image_name], capture_output=True, check=True) + _tag(image) return why = (pulled.stderr.strip().splitlines() or [f"docker pull exited {pulled.returncode}"])[-1] if not image.buildable: @@ -162,6 +171,18 @@ def pull(image: DockerImageArtifact) -> None: build(image) +def _holds_under_name(image: DockerImageArtifact) -> bool: + """Whether this machine's Docker holds ``image``, one with an ``image_digest``, under its name as the image that + digest names: pulled by it, or built here from the image's sources. A tag can name another image than the one a + version records, so holding its name isn't enough, and an image held by the digest alone isn't under its name.""" + return image.image_digest in _repo_digests(image.image_name) or held(image) + + +def _tag(image: DockerImageArtifact) -> None: + """Name the image Docker holds by ``image``'s digest with ``image``'s name, where a deploy finds it.""" + subprocess.run(["docker", "tag", image.pinned_name, image.image_name], capture_output=True, check=True) + + async def pull_here(image: DockerImageArtifact) -> None: """``pull`` off the event loop.""" await asyncio.to_thread(pull, image) diff --git a/src/agent_env/providers/sandbox_providers/local_docker/provider.py b/src/agent_env/providers/sandbox_providers/local_docker/provider.py index 38bf79149..1ea86103a 100644 --- a/src/agent_env/providers/sandbox_providers/local_docker/provider.py +++ b/src/agent_env/providers/sandbox_providers/local_docker/provider.py @@ -42,7 +42,8 @@ from agent_env import config from agent_env.attribution import Attribution from agent_env.config.paths import state_root -from agent_env.providers.sandbox_providers.host_images import build_here, built_here, host_platform, present, pull_here +from agent_env.providers.sandbox_providers.host_images import (build_here, built_here, host_platform, named_if_held, + present, pull_here) from agent_env.providers.sandbox_providers.disk_launcher import RESET, UNRESETTABLE, forward, reset_input, unresettable from agent_env.providers.sandbox_providers.local_docker.cli import DockerFailed, docker from agent_env.providers.sandbox_providers.local_docker.disk import KVM, kvm_platforms, launcher_args, machine_for @@ -275,9 +276,10 @@ def _held(self, image_name: str) -> bool: and present(image_name)) async def pull_published(self, artifacts: list) -> list: - """Pull each published image but one this machine's Docker already holds under its name, so a run after the - first needs no registry.""" - held = await asyncio.gather(*(asyncio.to_thread(present, artifact.image_name) for artifact in artifacts)) + """Pull each published image but one this machine's Docker already holds as its digest names it + (``named_if_held``), so a run after the first needs no registry; one whose name holds another image is pulled + over it.""" + held = await asyncio.gather(*(asyncio.to_thread(named_if_held, artifact) for artifact in artifacts)) return await super().pull_published([artifact for artifact, here in zip(artifacts, held) if not here]) def host_port(self, port: int) -> int: diff --git a/tst/unit/providers/sandbox_providers/host_images_test.py b/tst/unit/providers/sandbox_providers/host_images_test.py index 77d3dd075..6d44b87f4 100644 --- a/tst/unit/providers/sandbox_providers/host_images_test.py +++ b/tst/unit/providers/sandbox_providers/host_images_test.py @@ -227,6 +227,7 @@ def run(argv, **kwargs): return subprocess.CompletedProcess(argv, int(failed), "", "Error response from daemon: denied" if failed else "") monkeypatch.setattr(host_images, "_repo_digests", lambda name: (pulled_by or {}).get(name, set())) + monkeypatch.setattr(host_images, "present", lambda name: name in (pulled_by or {})) monkeypatch.setattr(host_images.subprocess, "run", run) return ran @@ -249,6 +250,41 @@ def test_a_published_image_docker_holds_by_its_digest_isnt_pulled_again(local_st assert ran == [] and docker[0] == [] +@pytest.mark.parametrize("pulled_by, held, tagged", [ + ({_PUBLISHED_REF: {_PUBLISHED_DIGEST}}, True, False), + ({_PINNED: {_PUBLISHED_DIGEST}}, True, True), + ({_PINNED: {_PUBLISHED_DIGEST}, _PUBLISHED_REF: {"sha256:" + "d" * 64}}, True, True), + ({_PUBLISHED_REF: {"sha256:" + "d" * 64}}, False, False), + ({}, False, False), +], ids=["under-its-name", "by-its-digest-alone", "by-its-digest-its-name-on-another", "its-name-on-another", "absent"]) +def test_an_image_is_held_as_its_digest_names_it_and_named_when_held_by_the_digest_alone(local_stores, context, docker, + monkeypatch, caplog, pulled_by, + held, tagged): + """A name moved off another image says so: a container started by it will run something else than before.""" + ran = _docker_cli(monkeypatch, pulled_by=pulled_by) + + with caplog.at_level(logging.WARNING): + assert host_images.named_if_held(_published(context)) is held + + assert ran == ([["tag", _PINNED, _PUBLISHED_REF]] if tagged else []) + moved = f"{_PUBLISHED_REF} named another image than the one it's pinned to, {_PUBLISHED_DIGEST}" + assert (moved in caplog.text) is (tagged and _PUBLISHED_REF in pulled_by) + + +@pytest.mark.parametrize("named", [False, True], ids=["untagged", "tag-names-another-image"]) +def test_a_published_image_docker_holds_by_its_digest_alone_is_named_not_pulled_or_built(local_stores, context, docker, + monkeypatch, named): + """``docker pull @`` leaves the image with no tag: it's still the one the digest names, so a registry + this machine can't log in to isn't asked for it, nor is it built in its place.""" + pulled_by = {_PINNED: {_PUBLISHED_DIGEST}} | ({_PUBLISHED_REF: {"sha256:" + "d" * 64}} if named else {}) + ran = _docker_cli(monkeypatch, pulled_by=pulled_by, pull_fails=True) + + host_images.pull(_published(context)) + + assert ran == [["tag", _PINNED, _PUBLISHED_REF]] + assert docker[0] == [] + + def test_a_published_image_built_here_from_its_sources_isnt_pulled(local_stores, context, docker, monkeypatch): ran = _docker_cli(monkeypatch) image = _published(context) diff --git a/tst/unit/providers/sandbox_providers/local_sandbox_test.py b/tst/unit/providers/sandbox_providers/local_sandbox_test.py index 34cf4a94d..194bf4998 100644 --- a/tst/unit/providers/sandbox_providers/local_sandbox_test.py +++ b/tst/unit/providers/sandbox_providers/local_sandbox_test.py @@ -1437,10 +1437,11 @@ def fail(*args): @pytest.mark.asyncio async def test_the_local_provider_pulls_only_the_published_images_its_docker_doesnt_hold(monkeypatch, tmp_path): - """So a run after the first needs no registry.""" + """So a run after the first needs no registry; held means as the image's digest names it, not under its name.""" images = [DockerImageArtifact(id=name, description="d", image_name=f"ghcr.io/team/{name}:src-1", image_digest="sha256:" + "9" * 64) for name in ("held", "new")] - monkeypatch.setattr(ls, "present", lambda image_name: image_name.startswith("ghcr.io/team/held:")) + monkeypatch.setattr(ls, "named_if_held", lambda image: image.id == "held") + monkeypatch.setattr(ls, "present", lambda image_name: True) asked = [] async def pull_published(self, artifacts):