diff --git a/src/agent_env/env/envs/computer/utils/composed.py b/src/agent_env/env/envs/computer/utils/composed.py index bb13d6b6e..3652b20f9 100644 --- a/src/agent_env/env/envs/computer/utils/composed.py +++ b/src/agent_env/env/envs/computer/utils/composed.py @@ -100,8 +100,9 @@ def now() -> str: def stale(result: dict | None) -> bool: """Whether ``result`` was recorded by an agent-env whose composing code differs from this one's, or by one from - before results named it: what it holds may not be what this agent-env composes.""" - return result is not None and result.get("composer") != composition() + before results named it: what it holds may not be what this agent-env composes. Never an image a release published + (``published``): its digest fixes it, and what it's made from pins that release, so no other composer makes it.""" + return result is not None and not result.get("published") and result.get("composer") != composition() @functools.cache diff --git a/src/agent_env/env/envs/computer/utils/composer.py b/src/agent_env/env/envs/computer/utils/composer.py index 61392a2d1..15a39a6bb 100644 --- a/src/agent_env/env/envs/computer/utils/composer.py +++ b/src/agent_env/env/envs/computer/utils/composer.py @@ -34,6 +34,8 @@ from agentenv_protocol.computer.apps import apps_folder from agentenv_protocol.computer.app import BUILD_SETTINGS, SOCKET from agentenv_protocol.computer.platform import PLATFORM_ENV, applies, entry_for +from packaging.requirements import InvalidRequirement, Requirement +from packaging.utils import canonicalize_name from agent_env.artifact.artifacts.computer import LOCAL_IMAGE_PREFIX, ComputerArtifact from agent_env.artifact.artifacts.docker_image import DockerImageArtifact @@ -253,13 +255,20 @@ def _with_containers(env: ComputerEnv, pairs: list[tuple[str, str]]) -> list[tup def _composed(env: ComputerEnv, base: ComputerArtifact, driver: ComputerDriverEnv, form: str, arch: str, builds: builder.Builds, progress: _Progress) -> dict: - """``form`` and ``arch`` built or reused, then probed when it built (gate 3).""" - result = _built(env, base, driver, form, arch, builds, progress) + """``form`` and ``arch`` built or reused, then probed when it built (gate 3). An image a release published that the + record holds unprobed is probed as it is, never built again: no other release's composer makes it.""" + result = _unprobed_published(env, form, arch) or _built(env, base, driver, form, arch, builds, progress) if result["status"] != "unverified": return result return _probed(env, driver, form, arch, result, builds.provider, progress) +def _unprobed_published(env: ComputerEnv, form: str, arch: str) -> dict | None: + """The pair's record, when it's an image a release published that's built but not probed yet.""" + record = env.metadata.get("composed", {}).get(form, {}).get(arch) or {} + return dict(record) if record.get("published") and record.get("status") == "unverified" else None + + def _composed_disk(env: ComputerEnv, base: ComputerArtifact, driver: ComputerDriverEnv, arch: str, container: Future | None, builds: builder.Builds, progress: _Progress) -> dict: """The disk form of ``arch``, once its container, composed now or before, has built: built or reused, then probed @@ -318,11 +327,11 @@ def _composed_vm_bundle(env: ComputerEnv, base: ComputerArtifact, driver: Comput layer = _stage_driver(context, driver, base, {}) apps = [(app, _stage_app(context, app, base, {})) for app in env.composed_apps()] parts = [_part(layer, _services(f"driver-{gate.driver_folder(driver)}", layer.install), - {"MCP_PORT": driver.port}, protocol, False)] + {"MCP_PORT": driver.port}, protocol, False, context)] parts += [_part(staged, dict(zip(gate.programs(app, platform_of(base.os)), [ f"venv/bin/python -m agentenv_protocol.computer.serve_app {shlex.quote(staged.served)}", *(service.command for service in staged.install.services)])), {"ENVIRONMENT_NAME": app.environment_name}, - protocol, True) for app, staged in apps] + protocol, True, context) for app, staged in apps] if (lock := _vm_bundle_lock(env, base, link, parts, context, arch, progress)) is not None: packages.stage_wheels(lock, build, env.stored_id) parts = [replace(part, wheels=tuple(wheel.file for wheel in lock.wheels.get(part.folder, []))) @@ -383,7 +392,7 @@ def _composed_windows_disk(env: ComputerEnv, base: ComputerArtifact, driver: Com parts = [_windows_part(layer, driver_prefix, { program: windows_disk.argv(command, driver_prefix) for program, command in _services(f"driver-{name}", layer.install).items()}, {"MCP_PORT": driver.port}, - protocol)] + protocol, context)] for app in env.composed_apps(): staged = _stage_app(context, app, base, {}) prefix = PureWindowsPath(staged.prefix) @@ -391,7 +400,7 @@ def _composed_windows_disk(env: ComputerEnv, base: ComputerArtifact, driver: Com staged.served] commands = [server, *(windows_disk.argv(service.command, prefix) for service in staged.install.services)] parts.append(_windows_part(staged, prefix, dict(zip(gate.programs(app, platform_of(base.os)), commands)), - {"ENVIRONMENT_NAME": app.environment_name}, protocol)) + {"ENVIRONMENT_NAME": app.environment_name}, protocol, context)) values = env.computer_values() settings = {name: values.get(name, setting.default) for name, setting in base.config.items() if setting.phase == "build"} @@ -494,14 +503,11 @@ async def _provisioned(link: SandboxProvider, source: str, name: str, build: Pat def _part(layer: _Layer, programs: dict[str, str], environment: dict[str, Any], protocol: bool, - app: bool) -> macos_vm_bundle.Part: + app: bool, context: Path) -> macos_vm_bundle.Part: """``layer`` as a VM bundle installs it: its programs, each run directly with its own variables when its service - says so, and a venv's protocol as on Linux: this checkout's source, else an app's pinned to this release, which a - driver's requirements name themselves.""" + says so, and a venv's protocol as on Linux (``_protocol_spec``).""" direct = {service.command: service.environment or {} for service in layer.install.services if service.direct} - extra = "[app]" if app else "" - spec = (f'"$build/context/protocol{extra}"' if protocol else - f"{_PROTOCOL}{extra}=={importlib.metadata.version(_PROTOCOL)}" if app else None) + spec = _protocol_spec(layer, context, '"$build/context/protocol{extra}"' if protocol else None, app) return macos_vm_bundle.Part(layer.folder, layer.prefix, layer.install, {name: (command, direct.get(command)) for name, command in programs.items()}, environment, _venv(layer), spec if _venv(layer) else None, layer.served, layer.steps) @@ -530,7 +536,7 @@ def _composed_omarchy_disk(env: ComputerEnv, base: ComputerArtifact, driver: Com parts = [_omarchy_part(layer, prefix, { program: omarchy_disk.argv(command, prefix) for program, command in _services(f"driver-{name}", layer.install).items()}, {"MCP_PORT": driver.port}, - protocol)] + protocol, context)] for app in env.composed_apps(): staged = _stage_app(context, app, base, {}) prefix = PurePosixPath(staged.prefix) @@ -540,7 +546,7 @@ def _composed_omarchy_disk(env: ComputerEnv, base: ComputerArtifact, driver: Com environment = {"ENVIRONMENT_NAME": app.environment_name, **({PLATFORM_ENV: staged.platform} if staged.platform else {})} parts.append(_omarchy_part(staged, prefix, dict(zip(gate.programs(app, platform_of(base.os)), commands)), - environment, protocol)) + environment, protocol, context)) values = env.computer_values() settings = {name: values.get(name, setting.default) for name, setting in base.config.items() if setting.phase == "build"} @@ -575,24 +581,21 @@ def say(line: str) -> None: def _windows_part(layer: _Layer, prefix: PureWindowsPath, services: dict[str, list[str]], - environment: dict[str, Any], protocol: bool) -> windows_disk.Part: + environment: dict[str, Any], protocol: bool, context: Path) -> windows_disk.Part: """``layer`` as a Windows disk installs it under ``prefix``: its ``services``' argv by name, with ``environment``, - and a venv's protocol as on Linux: this checkout's source, else an app's pinned to this release, which a driver's - requirements name themselves.""" - extra = "[app]" if layer.app else "" - spec = (f"{windows_disk.BUILD}\\context\\protocol{extra}" if protocol else - f"{_PROTOCOL}{extra}=={importlib.metadata.version(_PROTOCOL)}" if layer.app else None) + and a venv's protocol as on Linux (``_protocol_spec``).""" + spec = _protocol_spec(layer, context, f"{windows_disk.BUILD}\\context\\protocol{{extra}}" if protocol else None, + layer.app) return windows_disk.Part(layer.folder, prefix, layer.install, services, environment, (spec,) if spec else (), layer.served, tuple(step for step, _ in layer.steps)) def _omarchy_part(layer: _Layer, prefix: PurePosixPath, services: dict[str, list[str]], environment: dict[str, Any], - protocol: bool) -> omarchy_disk.Part: + protocol: bool, context: Path) -> omarchy_disk.Part: """``layer`` as an Omarchy disk installs it under ``prefix``: its ``services``' argv by name, with ``environment``, - an app's own server, install steps and platform, and a venv's protocol as on Windows (``_windows_part``).""" - extra = "[app]" if layer.app else "" - spec = (f"{omarchy_disk.BUILD}/context/protocol{extra}" if protocol else - f"{_PROTOCOL}{extra}=={importlib.metadata.version(_PROTOCOL)}" if layer.app else None) + an app's own server, install steps and platform, and a venv's protocol as on Linux (``_protocol_spec``).""" + spec = _protocol_spec(layer, context, f"{omarchy_disk.BUILD}/context/protocol{{extra}}" if protocol else None, + layer.app) return omarchy_disk.Part(layer.folder, prefix, layer.install, services, environment, (spec,) if spec else (), layer.served, layer.steps, layer.platform) @@ -622,7 +625,7 @@ def _built(env: ComputerEnv, base: ComputerArtifact, driver: ComputerDriverEnv, layer = _stage_driver(context, driver, base, from_store) apps = [_stage_app(context, app, base, from_store) for app in env.composed_apps()] layers = [layer, *apps] - wants = _wants(layers, _stage_protocol(context)) + wants = _wants(layers, _stage_protocol(context), context) platform, held = f"linux/{arch}", [] def on() -> builder.Builder: @@ -1095,18 +1098,50 @@ def _venv(layer: _Layer) -> bool: return layer.install.python is not None or layer.app -def _wants(layers: list[_Layer], protocol: bool) -> list[packages.Want]: - """What each layer asks a lock for; a venv adds the protocol, for an app with its ``app`` extra: from this checkout's - source when ``protocol``, else an app's pinned to this release, which a driver's requirements name themselves.""" +def _wants(layers: list[_Layer], protocol: bool, context: Path) -> list[packages.Want]: + """What each layer asks a lock for; a venv adds the protocol as ``_protocol_spec`` says, from this checkout's + source when ``protocol``.""" wants = [] for layer in layers: - extra = "[app]" if layer.app else "" - adds = ((f"/ctx/protocol{extra}",) if protocol else - (f"{_PROTOCOL}{extra}=={importlib.metadata.version(_PROTOCOL)}",) if layer.app else ()) - wants.append(packages.Want(layer.folder, layer.install, _venv(layer), adds if _venv(layer) else ())) + spec = _protocol_spec(layer, context, "/ctx/protocol{extra}" if protocol else None, layer.app) + wants.append(packages.Want(layer.folder, layer.install, _venv(layer), (spec,) if spec and _venv(layer) else ())) return wants +def _protocol_spec(layer: _Layer, context: Path, source: str | None, app: bool) -> str | None: + """What ``layer``'s venv, staged in ``context``, adds for the protocol, an app's with its ``app`` extra: the version + its requirements pin exactly, as each env a release ships pins its release's, so an env one release shipped + composes under another; else this checkout's ``source`` (``{extra}`` where the extra goes), when it runs from one; + else, for an app, this release's. A driver's requirements name the protocol themselves.""" + extra = "[app]" if app else "" + if (pinned := _pinned_protocol(context / layer.folder, layer.install)) is not None: + return f"{_PROTOCOL}{extra}=={pinned}" if app else None + if source is not None: + return source.format(extra=extra) + return f"{_PROTOCOL}{extra}=={importlib.metadata.version(_PROTOCOL)}" if app else None + + +def _pinned_protocol(folder: Path, install: Install) -> str | None: + """The one version the requirements ``install`` names in ``folder`` pin the protocol to (``==`` or ``===``, no + wildcard), on no condition: a requirement with a marker may not apply where the venv is built, so it pins nothing.""" + if install.python is None or not (requirements := folder / install.python).is_file(): + return None + for line in requirements.read_text().splitlines(): + line = line.split("#", 1)[0].strip() + if not line or line.startswith("-"): + continue + try: + requirement = Requirement(line) + except InvalidRequirement: + continue + if canonicalize_name(requirement.name) != _PROTOCOL or requirement.marker is not None: + continue + for spec in requirement.specifier: + if spec.operator in ("==", "===") and "*" not in spec.version: + return spec.version + return None + + def _computer(env: ComputerEnv, base: ComputerArtifact, built: dict[str, str], disks: dict[str, str], bundles: dict[str, str]) -> dict | None: """Write the env's computer over the images ``built``, by arch, joined into one index in the env's image store, signed diff --git a/tst/unit/env/envs/test_computer_env.py b/tst/unit/env/envs/test_computer_env.py index de6aca215..2362d4a4c 100644 --- a/tst/unit/env/envs/test_computer_env.py +++ b/tst/unit/env/envs/test_computer_env.py @@ -15,7 +15,7 @@ import shutil import subprocess import urllib.parse -from pathlib import Path +from pathlib import Path, PurePosixPath, PureWindowsPath from types import SimpleNamespace from unittest.mock import AsyncMock @@ -54,7 +54,7 @@ from agent_env.env.envs.computer.env import COMPUTER_TOOLS, ComputerEnv from agent_env.env.envs.computer import app_env from agent_env.env.envs.computer.app_env import ComputerAppEnv -from agent_env.env.envs.computer.utils.install import Install, Service +from agent_env.env.envs.computer.utils.install import Install, MacInstall, Service, WindowsInstall from agent_env.env.envs.computer.driver_env import ComputerDriverEnv, KnownFailure from agent_env.plugins._bundles import ALIASES_FILE, InstalledBundle, installed_aliases from agent_env import providers @@ -543,14 +543,109 @@ def test_a_probe_ended_by_a_dropped_connection_runs_again_on_a_fresh_boot_and_on ({"status": "building"}, {"status": "failed", "stage": "build"}, True), ({"status": "building"}, {"status": "ready", "composer": "sha256:another"}, True), ({"status": "failed", "stage": "build"}, {"status": "ready", "composer": None}, True), + ({"status": "failed", "stage": "resolve"}, {"status": "ready", "composer": "sha256:another", "published": True}, + False), + ({"status": "building"}, {"status": "unverified", "composer": "sha256:another", "published": True}, False), ], ids=["unprobed-over-ready", "build-failure-over-built", "building-over-built", "probe-failure-over-unprobed", "probe-failure-over-ready", "ready-over-probe-failure", "building-over-build-failure", - "building-over-another-composers-ready", "build-failure-over-a-ready-no-composer-named"]) + "building-over-another-composers-ready", "build-failure-over-a-ready-no-composer-named", + "resolve-failure-over-another-composers-published-ready", "building-over-another-composers-published-unprobed"]) def test_a_result_takes_a_pairs_place_only_when_it_got_at_least_as_far(result, stored, replaces): mine = {"composer": composed.composition()} assert (composed._rank({**mine, **result}) >= composed._rank({**mine, **stored})) is replaces +def _recorded_by_another_composer(env, **changes): + """``env``, its arm64 container's record as another agent-env's composer left it, with ``changes``.""" + record = env.metadata["composed"] + record["container"]["arm64"] = {**record["container"]["arm64"], "composer": "sha256:another", **changes} + env.metadata = {**env.metadata, "composed": record} + return env + + +@pytest.mark.parametrize("published", [True, False], ids=["a-release-published-it", "composed-by-a-user"]) +def test_a_ready_build_another_composer_recorded_is_composed_again_unless_a_release_published_it(base, driver, docker, + published): + env = _recorded_by_another_composer(Env.get(_put(base, driver).id), **({"published": True} if published else {})) + + assert (("container", "arm64") in composer.pending(env)) is not published + assert (("container", "arm64") in [(form, arch) for form, arch, _ in env.deployable_builds()]) is published + assert env.build_statuses()["container/arm64"] == ("ready" if published else "ready, by another composer") + + +def test_an_unprobed_image_a_release_published_is_probed_as_it_is_under_another_composer(base, driver, docker): + env = _recorded_by_another_composer(Env.get(_put(base, driver).id), status="unverified", published=True) + image = env.metadata["composed"]["container"]["arm64"]["image"] + builds, resolves = len(docker.builds), len(docker.resolved) + + composer.compose(env, [("container", "arm64")]) + + probed = Env.get(env.id).metadata["composed"]["container"]["arm64"] + assert (probed["status"], probed["image"], probed["published"]) == ("ready", image, True) + assert (len(docker.builds), len(docker.resolved)) == (builds, resolves) + + +PINNED = "agentenv-framework-protocol[app]==0.1.597" +RELEASE = f"agentenv-framework-protocol[app]=={importlib.metadata.version('agentenv-framework-protocol')}" + + +@pytest.mark.parametrize("requirements, added", [ + ("agentenv-framework-protocol[app]==0.1.597\n", PINNED), + ("# shipped by a release\nAgentenv_Framework.Protocol[app] === 0.1.597 # its own\nav>=17\n", PINNED), + ("agentenv-framework-protocol==0.1.597\n", PINNED), + ("agentenv-framework-protocol[app]==0.1.597; sys_platform == 'darwin'\n", RELEASE), + ("agentenv-framework-protocol[app]>=0.1.547\nav>=17\n", RELEASE), + ("agentenv-framework-protocol[app]==0.1.*\n", RELEASE), + ("-r more.txt\nav>=17\n", RELEASE), +], ids=["pinned", "pinned-by-another-spelling", "pinned-without-the-app-extra", "pinned-on-a-condition", "a-floor", + "a-wildcard", "not-named"]) +def test_an_apps_venv_adds_its_protocol_at_the_version_its_requirements_pin_else_at_this_release( + base, driver, docker, tmp_path, requirements, added): + mail = _app(base, driver, tmp_path / "mail", compose=False, + extra={"requirements.txt": requirements, "more.txt": "av>=17\n"}) + + _put(base, driver, apps=[mail]) + + assert {tuple(layer["add"]) for _, request in docker.resolved for layer in request["python"] + if layer["name"] != "driver"} == {(added,)} + + +def test_a_checkout_adds_its_own_protocol_only_to_the_venvs_that_dont_pin_one(base, driver, docker, tmp_path, + monkeypatch): + monkeypatch.setattr(composer, "_protocol_source", lambda: _protocol_checkout(tmp_path)) + mail = _app(base, driver, tmp_path / "mail", compose=False, extra={"requirements.txt": f"{PINNED}\n"}) + + _put(base, driver, apps=[mail]) + + assert {layer["name"]: tuple(layer["add"]) for _, request in docker.resolved for layer in request["python"]} == { + "driver": ("/ctx/protocol",), **{name: (PINNED,) for name in { + layer["name"] for _, request in docker.resolved for layer in request["python"]} - {"driver"}}} + + +@pytest.mark.parametrize("form", ["vm_bundle", "windows", "omarchy"]) +@pytest.mark.parametrize("requirements, source, added", [ + (f"{PINNED}\n", False, PINNED), + (f"{PINNED}\n", True, PINNED), + ("av>=17\n", False, RELEASE), +], ids=["pinned", "pinned-in-a-checkout", "not-pinned"]) +def test_each_disk_and_bundle_form_adds_an_apps_protocol_as_a_container_does(tmp_path, form, requirements, source, + added): + (tmp_path / "apps" / "mail").mkdir(parents=True) + (tmp_path / "apps" / "mail" / "requirements.txt").write_text(requirements) + install = {"vm_bundle": MacInstall, "windows": WindowsInstall}.get(form, Install).model_validate({ + "python": "requirements.txt", "services": [{"name": "imap", "command": "venv/bin/python imap.py"}]}) + layer = composer._Layer("apps/mail", "/opt/mail", install, "app-mail.conf", "@local/~/kit/mail", app=True, + served="app.py:Mail") + if form == "vm_bundle": + spec = composer._part(layer, {}, {}, source, True, tmp_path).protocol + elif form == "windows": + (spec,) = composer._windows_part(layer, PureWindowsPath("C:/apps/mail"), {}, {}, source, tmp_path).wants + else: + (spec,) = composer._omarchy_part(layer, PurePosixPath("/opt/mail"), {}, {}, source, tmp_path).wants + + assert spec == added + + def test_the_composers_digest_changes_with_a_files_bytes_and_with_its_executable_bit_alone(tmp_path, monkeypatch): (tmp_path / "prepare.sh").write_text("echo hi\n") (tmp_path / "README.md").write_text("docs")