diff --git a/.dockerignore b/.dockerignore index 575b094162..3b93cecead 100644 --- a/.dockerignore +++ b/.dockerignore @@ -49,6 +49,7 @@ compose/package-cache/npmrc compose/package-cache/apt/*.list inventories/development/tools.rendered.yml +inventories/development/tools.address # Host shell / editor / tooling state accidentally surfaced inside this working copy .ansible diff --git a/.gitignore b/.gitignore index 575b094162..3b93cecead 100644 --- a/.gitignore +++ b/.gitignore @@ -49,6 +49,7 @@ compose/package-cache/npmrc compose/package-cache/apt/*.list inventories/development/tools.rendered.yml +inventories/development/tools.address # Host shell / editor / tooling state accidentally surfaced inside this working copy .ansible diff --git a/cli/administration/deploy/development/env.py b/cli/administration/deploy/development/env.py index c18905faa1..d2f9a923a1 100644 --- a/cli/administration/deploy/development/env.py +++ b/cli/administration/deploy/development/env.py @@ -6,6 +6,13 @@ from utils.distros import distro_names VALID_DISTROS: tuple[str, ...] = distro_names() +TOOLS_LANE_KEYS: tuple[str, ...] = ( + "INFINITO_TOOLS_LIBRETRANSLATE_PORT", + "INFINITO_TOOLS_MODELS_HOST_PATH", + "INFINITO_TOOLS_S1_PORT", + "INFINITO_TOOLS_TRANSLATE_PORT", +) + def compose_file_args() -> list[str]: """Compose `-f` flags shared by up and down flows. @@ -29,13 +36,7 @@ def compose_file_args() -> list[str]: out += ["-f", "compose/gpu.override.yml"] if (os.environ.get("INFINITO_PUBLISH_PORTS") or "").strip().lower() == "false": out += ["-f", "compose/noports.override.yml"] - if all( - (os.environ.get(key) or "").strip() - for key in ( - "INFINITO_TOOLS_LIBRETRANSLATE_PORT", - "INFINITO_TOOLS_MODELS_HOST_PATH", - ) - ): + if all((os.environ.get(key) or "").strip() for key in TOOLS_LANE_KEYS): out += ["-f", "compose/tools.override.yml"] if profile.image_mirror_enabled(): diff --git a/compose/tools.override.yml b/compose/tools.override.yml index 8d2f1f5f5a..fdb49d32b0 100644 --- a/compose/tools.override.yml +++ b/compose/tools.override.yml @@ -50,6 +50,8 @@ services: .env single source of truth}:${INFINITO_TOOLS_LIBRETRANSLATE_PORT:?Run 'make dotenv' to generate the .env single source of truth}" - "${INFINITO_BIND_IP:?Run 'make dotenv' to generate the .env single source of truth}:${INFINITO_TOOLS_TRANSLATE_PORT:?Run 'make dotenv' to generate the .env single source of truth}:${INFINITO_TOOLS_TRANSLATE_PORT:?Run 'make dotenv' to generate the .env single source of truth}" + - "${INFINITO_BIND_IP:?Run 'make dotenv' to generate the .env single source of truth}:${INFINITO_TOOLS_S1_PORT:?Run 'make dotenv' to generate the + .env single source of truth}:${INFINITO_TOOLS_S1_PORT:?Run 'make dotenv' to generate the .env single source of truth}" networks: default: diff --git a/tests/unit/python/cli/administration/deploy/development/test_env_compose_file_args.py b/tests/unit/python/cli/administration/deploy/development/test_env_compose_file_args.py index ff9e5ebf24..edc768191c 100644 --- a/tests/unit/python/cli/administration/deploy/development/test_env_compose_file_args.py +++ b/tests/unit/python/cli/administration/deploy/development/test_env_compose_file_args.py @@ -8,10 +8,16 @@ because an unsatisfied `:?` guard inside one of them aborts the whole stack. from __future__ import annotations import os +import re import unittest from unittest.mock import patch -from cli.administration.deploy.development.env import compose_file_args +from cli.administration.deploy.development.env import ( + TOOLS_LANE_KEYS, + compose_file_args, +) +from utils.cache import PROJECT_ROOT +from utils.cache.files import read_text _LOCAL_PRIMARY = { "GITHUB_ACTIONS": "", @@ -25,6 +31,8 @@ _LOCAL_PRIMARY = { "INFINITO_GPU_COUNT": "0", "INFINITO_TOOLS_LIBRETRANSLATE_PORT": "8097", "INFINITO_TOOLS_MODELS_HOST_PATH": "/var/cache/infinito/core/cache/models", + "INFINITO_TOOLS_S1_PORT": "8096", + "INFINITO_TOOLS_TRANSLATE_PORT": "8101", } _WORKTREE = { @@ -159,5 +167,33 @@ class TestComposeFileArgs(unittest.TestCase): self.assertNotIn("compose/tools.override.yml", compose_file_args()) +class TestToolsLaneGateCoversItsGuards(unittest.TestCase): + def test_every_guard_the_override_adds_is_gated(self) -> None: + """A `:?` guard the gate does not know aborts every compose call. + + The guards compose.yml already carries are satisfied for any stack + that runs at all, so only the ones the lane's override adds on top + can fire against an .env that predates them. INFINITO_IMAGE is the + one exception: the deploy CLI injects it into the process + environment and it never reaches .env, so gating on it would drop + the lane permanently. + """ + guards = re.compile(r"\$\{([A-Z_][A-Z0-9_]*):\?") + shared = set(guards.findall(read_text(PROJECT_ROOT / "compose.yml"))) + override = set( + guards.findall(read_text(PROJECT_ROOT / "compose" / "tools.override.yml")) + ) + added = override - shared - {"INFINITO_IMAGE"} + self.assertEqual( + sorted(added - set(TOOLS_LANE_KEYS)), + [], + "compose/tools.override.yml guards these variables, and " + "compose_file_args layers the file in without checking them, so " + "an .env written before they existed aborts every compose " + "command instead of only dropping the lane. Add them to " + "TOOLS_LANE_KEYS.", + ) + + if __name__ == "__main__": # pragma: no cover unittest.main() diff --git a/tests/unit/python/utils/inventory/test_tools_address.py b/tests/unit/python/utils/inventory/test_tools_address.py new file mode 100644 index 0000000000..3da2030d69 --- /dev/null +++ b/tests/unit/python/utils/inventory/test_tools_address.py @@ -0,0 +1,96 @@ +"""Unit tests for the tools lane's address handoff. + +The host resolves the runner's address and writes it down; a container of the +stack reads the file, because it cannot ask docker and the compose service +name resolves nowhere behind the stack's own CoreDNS. +""" + +from __future__ import annotations + +import json +import subprocess +import unittest +from pathlib import Path +from tempfile import TemporaryDirectory +from unittest.mock import patch + +from utils.inventory import tools +from utils.inventory.tools import ADDRESS, LANE_SERVICE, lane_address, lane_ip + +NETWORKS = { + "infinito-nexus-core_default": {"IPAddress": "172.30.0.9"}, + "store-i18n_default": {"IPAddress": "172.30.5.2"}, +} + + +def _completed(returncode: int, stdout: str) -> subprocess.CompletedProcess: + return subprocess.CompletedProcess(args=[], returncode=returncode, stdout=stdout) + + +class TestLaneIp(unittest.TestCase): + def _run(self, found, env=None) -> str: + environment = {"INFINITO_SUBNET": "172.30.5.0/24", "INFINITO_CONTAINER": "c"} + with ( + patch.object(tools.subprocess, "run", return_value=found), + patch( + "utils.i18n.libretranslate.environment", return_value=env or environment + ), + ): + return lane_ip(Path("/nowhere")) + + def test_the_address_inside_the_stack_subnet_wins(self) -> None: + self.assertEqual(self._run(_completed(0, json.dumps(NETWORKS))), "172.30.5.2") + + def test_a_runner_docker_cannot_describe_answers_empty(self) -> None: + self.assertEqual(self._run(_completed(1, "")), "") + + def test_output_that_is_not_json_answers_empty(self) -> None: + self.assertEqual(self._run(_completed(0, "no such object")), "") + + def test_no_address_in_the_subnet_answers_empty(self) -> None: + other = {"bridge": {"IPAddress": "172.17.0.2"}} + self.assertEqual(self._run(_completed(0, json.dumps(other))), "") + + def test_a_missing_subnet_answers_empty(self) -> None: + self.assertEqual( + self._run( + _completed(0, json.dumps(NETWORKS)), env={"INFINITO_CONTAINER": "c"} + ), + "", + ) + + +class TestLaneAddress(unittest.TestCase): + def setUp(self) -> None: + self.tmp = TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + (self.root / ADDRESS).parent.mkdir(parents=True) + + def _write(self, body: str) -> None: + (self.root / ADDRESS).write_text(body, encoding="utf-8") + + def test_a_written_address_is_read_back(self) -> None: + self._write("172.30.5.2\n") + self.assertEqual(lane_address(self.root), "172.30.5.2") + + def test_a_missing_file_falls_back_to_the_service_name(self) -> None: + self.assertEqual(lane_address(self.root), LANE_SERVICE) + + def test_an_empty_file_falls_back_to_the_service_name(self) -> None: + self._write("\n") + self.assertEqual(lane_address(self.root), LANE_SERVICE) + + def test_remembering_an_unresolvable_address_writes_nothing(self) -> None: + with patch.object(tools, "lane_ip", return_value=""): + tools._remember_address(self.root) + self.assertFalse((self.root / ADDRESS).exists()) + + def test_remembering_a_resolved_address_makes_it_readable(self) -> None: + with patch.object(tools, "lane_ip", return_value="172.30.5.2"): + tools._remember_address(self.root) + self.assertEqual(lane_address(self.root), "172.30.5.2") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/inventory/test_tools_serving.py b/tests/unit/python/utils/inventory/test_tools_serving.py new file mode 100644 index 0000000000..817c3372f5 --- /dev/null +++ b/tests/unit/python/utils/inventory/test_tools_serving.py @@ -0,0 +1,59 @@ +"""Unit tests for utils.inventory.tools.serving.""" + +from __future__ import annotations + +import unittest +from pathlib import Path +from unittest.mock import patch + +from utils.inventory import tools +from utils.inventory.tools import LIBRETRANSLATE_ROLE, S1_ROLE, serving + +ROOT = Path("/nowhere") +ENGINE_LANGUAGES = b'[{"code": "de"}, {"code": "en"}]' + + +class TestServing(unittest.TestCase): + def _run(self, answers: dict[str, bytes | None], roles: tuple[str, ...]) -> bool: + with ( + patch.object(tools, "host_url", lambda root, role, key: f"http://{role}"), + patch.object(tools, "_answers", answers.get), + ): + return serving(ROOT, ["de"], roles) + + def test_engine_alone_does_not_speak_for_system_one(self) -> None: + self.assertFalse( + self._run( + {f"http://{LIBRETRANSLATE_ROLE}/languages": ENGINE_LANGUAGES}, + (LIBRETRANSLATE_ROLE, S1_ROLE), + ) + ) + + def test_both_answering_is_serving(self) -> None: + self.assertTrue( + self._run( + { + f"http://{LIBRETRANSLATE_ROLE}/languages": ENGINE_LANGUAGES, + f"http://{S1_ROLE}/health": b"ok", + }, + (LIBRETRANSLATE_ROLE, S1_ROLE), + ) + ) + + def test_a_role_nobody_asked_for_is_not_probed(self) -> None: + self.assertTrue(self._run({f"http://{S1_ROLE}/health": b"ok"}, (S1_ROLE,))) + + def test_a_missing_language_still_fails_the_engine(self) -> None: + self.assertFalse( + self._run( + { + f"http://{LIBRETRANSLATE_ROLE}/languages": b'[{"code": "en"}]', + f"http://{S1_ROLE}/health": b"ok", + }, + (LIBRETRANSLATE_ROLE, S1_ROLE), + ) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/utils/env/handlers/__init__.py b/utils/env/handlers/__init__.py index 485e38e6c2..f4aec5c164 100644 --- a/utils/env/handlers/__init__.py +++ b/utils/env/handlers/__init__.py @@ -64,6 +64,7 @@ from .infinito.swarm_nfs import export_base as swarm_nfs_export_base from .infinito.swarm_nfs import state_path as swarm_nfs_state_path from .infinito.tools import libretranslate as tools_libretranslate from .infinito.tools import models as tools_models +from .infinito.tools import s1 as tools_s1 from .infinito.tools import translate as tools_translate from .infinito.worker import cpu as worker_cpu from .infinito.worker import fetch as worker_fetch @@ -119,6 +120,7 @@ ORDERED_HANDLERS = [ gpu_count, tools_libretranslate, tools_models, + tools_s1, tools_translate, i18n_tuning, package_cache_heap, diff --git a/utils/env/handlers/infinito/tools/s1.py b/utils/env/handlers/infinito/tools/s1.py new file mode 100644 index 0000000000..f9889afc47 --- /dev/null +++ b/utils/env/handlers/infinito/tools/s1.py @@ -0,0 +1,27 @@ +"""INFINITO_TOOLS_S1_PORT: loopback port the tools runner forwards +to its System One, read from roles/svc-ai-s1/meta/services.yml.""" + +from __future__ import annotations + +import re +from typing import TYPE_CHECKING + +from utils.cache.files import read_text +from utils.roles.mapping import ROLE_FILE_META_SERVICES + +if TYPE_CHECKING: + from utils.env.builder import BuildContext, EnvBuilder + +KEY = "INFINITO_TOOLS_S1_PORT" +COMMENT = "Loopback port the tools runner forwards to its System One." +SERVICES = f"roles/svc-ai-s1/{ROLE_FILE_META_SERVICES}" +HTTP_PORT = re.compile(r"^s1:\n(?:.*\n)*?\s+local:\n\s+http:\s*(\d+)\s*$", re.MULTILINE) + + +def apply(eb: EnvBuilder, ctx: BuildContext) -> None: + services = ctx.repo_root / SERVICES + if not services.is_file(): + return + found = HTTP_PORT.search(read_text(services)) + if found: + eb.setdefault(KEY, found.group(1), comment=COMMENT) diff --git a/utils/inventory/tools.py b/utils/inventory/tools.py index 2fbd9b4ba6..2809dcf1d0 100644 --- a/utils/inventory/tools.py +++ b/utils/inventory/tools.py @@ -40,6 +40,7 @@ from utils.roles.mapping import ROLE_FILE_META_SERVICES TEMPLATE = Path("inventories") / "development" / "tools.yml.j2" RENDERED = Path("inventories") / "development" / "tools.rendered.yml" +ADDRESS = Path("inventories") / "development" / "tools.address" API_KEY = "toolsLaneTestKeyNotASecret0000000000" LIBRETRANSLATE_ROLE = "svc-ai-libretranslate-engine" S1_ROLE = "svc-ai-s1" @@ -59,6 +60,68 @@ def models_dir() -> str: return (os.environ.get(KEY) or "").strip() or default() +def lane_ip(root: Path) -> str: + """Return the runner's address inside the stack's own subnet, or ''. + + Must run on the host: it asks this machine's docker daemon, which the + stack's containers cannot reach. + + The runner answers to several addresses, one per network it was ever + brought up on, and only the one inside ``INFINITO_SUBNET`` is the network + the rest of the stack sits on. + + Args: + root: repository root. + """ + import ipaddress + import json + + from utils.i18n.libretranslate import environment, lane_container + + env = environment(root) + found = subprocess.run( + [ + "docker", + "inspect", + lane_container(env), + "--format", + "{{json .NetworkSettings.Networks}}", + ], + capture_output=True, + text=True, + check=False, + ) + if found.returncode != 0: + return "" + try: + subnet = ipaddress.ip_network(env["INFINITO_SUBNET"]) + networks = json.loads(found.stdout) + except (KeyError, ValueError): + return "" + for entry in networks.values(): + address = (entry or {}).get("IPAddress") or "" + if address and ipaddress.ip_address(address) in subnet: + return address + return "" + + +def lane_address(root: Path) -> str: + """Return the address the stack's containers reach the lane on. + + Args: + root: repository root. + """ + path = root / ADDRESS + if not path.is_file(): + return LANE_SERVICE + return ( + path.read_text( # nocheck: cache-read - every lane bring-up rewrites this file and utils.cache.files.read_text is an lru_cache without mtime invalidation + encoding="utf-8" + ).strip() + or LANE_SERVICE + ) + + def lane_url(root: Path, role: str, service_key: str) -> str: """Return the URL a container of the compose stack reaches a lane service on. @@ -66,9 +129,13 @@ def lane_url(root: Path, role: str, service_key: str) -> str: runner container. The inventory pins ``DOCKER_BIND_HOST=0.0.0.0`` so their ports are open on the runner's own interface, which the group_vars default would not do (see ``inventories/development/tools.yml.j2``). The - runner and the rest of the stack share the compose network, which makes - the runner's service name the address to use. The host instead reaches - only the ports the runner republishes through ``compose/tools.override.yml``. + host instead reaches only the ports the runner republishes through + ``compose/tools.override.yml``. + + The address is the runner's numeric one, written by the bring-up. The + stack's containers resolve names through its CoreDNS, which never learns + a compose service name, so ``tools`` answered nowhere inside them and + every check that asked the lane from there skipped itself instead. Args: root: repository root. @@ -76,11 +143,11 @@ def lane_url(root: Path, role: str, service_key: str) -> str: service_key: key under ``meta/services.yml``. Returns: - ``http://:``. + ``http://:``. """ services = load_yaml(root / "roles" / role / ROLE_FILE_META_SERVICES) port = services[service_key]["ports"]["local"]["http"] - return f"http://{LANE_SERVICE}:{port}" + return f"http://{lane_address(root)}:{port}" def host_url(root: Path, role: str, service_key: str) -> str: @@ -132,27 +199,31 @@ def _base_subtag(code: str) -> str: return code.split("-", 1)[0].strip().lower() -def serving(root: Path, load_only: list[str]) -> bool: - """Return whether the lane's engine already carries everything asked of it. +def serving(root: Path, load_only: list[str], roles: tuple[str, ...]) -> bool: + """Return whether every lane role asked for already answers. - Reachability alone is not enough: the engine answers as soon as it has - booted, with whatever subset of models it found, and a run that then waits - for the rest waits forever. The language set it reports is compared + Reachability alone is not enough for the engine: it answers as soon as it + has booted, with whatever subset of models it found, and a run that then + waits for the rest waits forever. The language set it reports is compared against what the lane pins. - Only the engine is judged. It is the one lane service the runner - republishes to the host, and the expensive one: a deploy reinstalls its - whole model selection and restarts it. The lane is deployed as a unit, so - an engine that carries the full selection is one the deploy already - finished. A sibling that is down anyway reports itself, because each check - states which address failed to answer. + Judging the engine alone made ``make test-oracle`` vacuous: ``make i18n`` + deploys the engine on its own, so a lane whose engine served counted as up + while System One was down, and the oracle suite skipped itself to a green + exit. Every role the caller names is probed, which is why the runner + republishes System One's port too. Args: root: repository root. load_only: the language codes the lane pins. + roles: the application ids the caller wants running. """ import json + if S1_ROLE in roles and _answers(f"{host_url(root, S1_ROLE, 's1')}/health") is None: + return False + if LIBRETRANSLATE_ROLE not in roles: + return True body = _answers( f"{host_url(root, LIBRETRANSLATE_ROLE, 'libretranslate-engine')}/languages" ) @@ -212,6 +283,10 @@ def ensure(root: Path, roles: tuple[str, ...]) -> None: answers, not a lane that was just rebuilt, so one that already answers with everything asked of it is left alone. + Either way the runner's address is written down, because a container of + the stack cannot ask docker for it and the runner takes a new one on + every restart. + Args: root: repository root. roles: application ids to deploy. @@ -222,10 +297,11 @@ def ensure(root: Path, roles: tuple[str, ...]) -> None: """ from utils.i18n.libretranslate import baked_languages, deploy, deploying - if serving(root, baked_languages(root)): + if serving(root, baked_languages(root), roles): print( f"tools lane already serves {', '.join(roles)}; not deploying", flush=True ) + _remember_address(root) return if deploying(root): @@ -236,14 +312,25 @@ def ensure(root: Path, roles: tuple[str, ...]) -> None: ) print(f"tools lane deploying {', '.join(roles)}", flush=True) deploy(root, roles=roles) + _remember_address(root) + + +def _remember_address(root: Path) -> None: + """Write the runner's address where a container of the stack reads it.""" + address = lane_ip(root) + if address: + (root / ADDRESS).write_text(f"{address}\n", encoding="utf-8") def main(argv: list[str] | None = None) -> int: """Bring the lane up for ``make test-oracle``, reporting why when it cannot. - Exits 0 even when the lane stays down, because the checks that need it say - so themselves; a deploy that is already running is a reason to leave the - stack alone, not to fail the target. + Only a deploy that is already running exits 0: it holds the stack this + one would touch, and leaving it alone is the right answer. Every other + way of not bringing the lane up exits 1, including a deploy that crashed + and a deploy that ran and left a role silent. The suite skips itself when + the lane is down, and a skip is a green exit, so a target that returned 0 + here would report a verdict it never reached. Args: argv: application ids, defaulting to every role the lane serves. @@ -251,16 +338,25 @@ def main(argv: list[str] | None = None) -> int: import argparse from utils import PROJECT_ROOT + from utils.i18n.libretranslate import baked_languages default_roles = [LIBRETRANSLATE_ROLE, S1_ROLE] parser = argparse.ArgumentParser(description="Bring the tools lane up.") parser.add_argument("roles", nargs="*", default=default_roles) args = parser.parse_args(argv) roles = tuple(args.roles) or tuple(default_roles) + root = Path(PROJECT_ROOT) try: - ensure(Path(PROJECT_ROOT), roles) - except (RuntimeError, OSError, KeyError, subprocess.CalledProcessError) as down: + ensure(root, roles) + except RuntimeError as held: + print(f"tools lane left alone: {held!r}") + return 0 + except (OSError, KeyError, subprocess.CalledProcessError) as down: print(f"tools lane not brought up: {down!r}") + return 1 + if not serving(root, baked_languages(root), roles): + print(f"tools lane deployed but {', '.join(roles)} still do not all answer") + return 1 return 0