From d952c4acfce1687ebafd7981c31b336ccd34c8b3 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 01:29:37 +0000 Subject: [PATCH] deploy: build only the deployed target's package, not every target (#12738) The registry JSON named each target's store path with string context, so building the deploy CLI realized all 14 target packages (mcpx's check phase included) before the CLI existed. The registry now names store paths without depending on them, and the CLI carries a name -> .drv map (DEPLOY_TARGET_DRVS) whose .drv files stay in its closure. A real deploy realizes its own target's package from that drv when the path is not in the store yet, and fails before touching the profile if the build produces nothing. Refs #12738 Co-Authored-By: Claude Opus 5.5 --- lib/default.nix | 9 ++ pkgs/deploy/default.nix | 22 ++++- pkgs/deploy/deploy.py | 41 +++++++- pkgs/deploy/test_deploy_lazy_targets.py | 125 ++++++++++++++++++++++++ 4 files changed, 193 insertions(+), 4 deletions(-) create mode 100644 pkgs/deploy/test_deploy_lazy_targets.py diff --git a/lib/default.nix b/lib/default.nix index 4d8f5666e9..d5ca880ab9 100644 --- a/lib/default.nix +++ b/lib/default.nix @@ -1646,6 +1646,15 @@ let python3 ${../pkgs/deploy/test_argv.py} ${../pkgs/deploy/deploy.py} mkdir -p $out ''; + deploy-lazy-targets = + pkgs.runCommandLocal "check-deploy-lazy-targets" + { + nativeBuildInputs = [ pkgs.python3 ]; + } + '' + python3 ${../pkgs/deploy/test_deploy_lazy_targets.py} ${../pkgs/deploy/deploy.py} + mkdir -p $out + ''; deploy-argv-property = pkgs.runCommandLocal "check-deploy-argv-property" { diff --git a/pkgs/deploy/default.nix b/pkgs/deploy/default.nix index abc0e9978e..7826f0e434 100644 --- a/pkgs/deploy/default.nix +++ b/pkgs/deploy/default.nix @@ -58,12 +58,27 @@ let messageBridge = callPackage ../../pkgs/message-bridge/worker/package.nix { }; }; }; - jsonDefinitions = lib.mapAttrs (name: defn: defn // { package = "${defn.package}"; }) definitions; + # The registry names each target's store path without depending on it + # (code#12738): string context would make building the CLI realize every + # target package, check phases included, before `deploy` itself exists. + # The CLI builds a target's package only when that target is deployed, + # from the derivation recorded in targetDrvsJson. + jsonDefinitions = lib.mapAttrs ( + name: defn: defn // { package = builtins.unsafeDiscardStringContext "${defn.package}"; } + ) definitions; + # name -> .drv path. unsafeDiscardOutputDependency keeps the .drv files in + # the CLI's closure (so `nix-store --realise` can build from them) without + # building their outputs. + targetDrvs = lib.mapAttrs (name: defn: builtins.unsafeDiscardOutputDependency defn.package.drvPath) ( + lib.filterAttrs (name: defn: lib.isDerivation defn.package) definitions + ); + registryJson = writeText "deploy-targets.json" (builtins.toJSON jsonDefinitions); + targetDrvsJson = writeText "deploy-target-drvs.json" (builtins.toJSON targetDrvs); in { deployTargets = definitions; - deployTargetsJson = writeText "deploy-targets.json" (builtins.toJSON jsonDefinitions); + deployTargetsJson = registryJson; deploy = runCommand "deploy-0.1.0" @@ -77,6 +92,7 @@ in '' makeWrapper ${python3}/bin/python3 $out/bin/deploy \ --add-flags ${./deploy.py} \ - --set DEPLOY_REGISTRY ${writeText "deploy-targets.json" (builtins.toJSON jsonDefinitions)} + --set DEPLOY_REGISTRY ${registryJson} \ + --set DEPLOY_TARGET_DRVS ${targetDrvsJson} ''; } diff --git a/pkgs/deploy/deploy.py b/pkgs/deploy/deploy.py index fdf6760d38..9ccb06c57b 100644 --- a/pkgs/deploy/deploy.py +++ b/pkgs/deploy/deploy.py @@ -64,7 +64,9 @@ The registry is JSON baked into the package at build time (the Nix expression renders the attrset definitions, replacing each -derivation with its store path). `--registry PATH` (or $DEPLOY_REGISTRY) +derivation with its store path, without depending on it: building the +CLI realizes no target package; a deploy builds its target's package +from the derivation $DEPLOY_TARGET_DRVS records, code#12738). `--registry PATH` (or $DEPLOY_REGISTRY) points the CLI at another registry file, which is how the flake checks exercise the malformed-definition path. `--state-dir PATH` (or $DEPLOY_STATE_DIR) relocates the generation logs, `--profile-base PATH` @@ -1011,9 +1013,46 @@ def _run_step(argv, what): raise ActivationError(f"{what} failed (exit {rc}): {err.strip()}") +def _target_drv(name): + """The .drv path that builds `name`'s package, from the map the + flake package bakes in as $DEPLOY_TARGET_DRVS (code#12738), or None + when no map is configured or it does not name `name`.""" + path = os.environ.get("DEPLOY_TARGET_DRVS") + if not path: + return None + try: + with open(path, encoding="utf-8") as fh: + drvs = json.load(fh) + except (OSError, ValueError): + return None + drv = drvs.get(name) if isinstance(drvs, dict) else None + if isinstance(drv, str) and drv.startswith("/nix/store/") and drv.endswith(".drv"): + return drv + return None + + +def ensure_artifact(name, artifact): + """Build `artifact` from its recorded derivation when it is not in + the store yet. The registry names store paths without depending on + them (code#12738), so a target's package is realized only when that + target is deployed. A path already present, a non-store artifact, or + a target with no recorded derivation is left as it is.""" + if not artifact.startswith("/nix/store/") or os.path.exists(artifact): + return + drv = _target_drv(name) + if drv is None or not _which("nix-store"): + return + _run_step(["nix-store", "--realise", drv], f"build the {name} package") + if not os.path.exists(artifact): + raise ActivationError( + f"build the {name} package: {drv} did not produce {artifact}" + ) + + def install_generation(name, artifact, generation, base=None): """Point the profile link for `name` at a new generation dir whose `current` symlink names `artifact`. Returns the link path.""" + ensure_artifact(name, artifact) base_dir = profile_base(base) gen_dir = os.path.join(base_dir, ".generations", name, str(generation)) os.makedirs(gen_dir, exist_ok=True) diff --git a/pkgs/deploy/test_deploy_lazy_targets.py b/pkgs/deploy/test_deploy_lazy_targets.py new file mode 100644 index 0000000000..e86567aeca --- /dev/null +++ b/pkgs/deploy/test_deploy_lazy_targets.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 +"""Coverage for building a deploy target's package on demand (code#12738). + +Oracle: issue #12738 ask 2. The registry names each target's store path +without depending on it, so building the CLI realizes no target package; +a real deploy builds its own target's package from the derivation that +$DEPLOY_TARGET_DRVS records, and nothing else. + +run_cmd and _which are faked (no nix-store runs); the filesystem effects +(profile link, generation dirs, the drv map) are real, in temp dirs. + +Usage: test_deploy_lazy_targets.py [path-to-deploy.py] +""" + +import importlib.util +import json +import os +import sys +import tempfile +import unittest + +DEPLOY_PATH = ( + sys.argv[1] + if len(sys.argv) > 1 + else os.path.join(os.path.dirname(os.path.abspath(__file__)), "deploy.py") +) +spec = importlib.util.spec_from_file_location("deploy", DEPLOY_PATH) +deploy = importlib.util.module_from_spec(spec) +spec.loader.exec_module(deploy) + +ARTIFACT = "/nix/store/00000000000000000000000000000000-svc-12738-missing" +DRV = "/nix/store/11111111111111111111111111111111-svc-12738.drv" + + +class LazyTargetTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.base = os.path.join(self.tmp.name, "profiles") + self.calls = [] + self.produce = None + self._real_run_cmd = deploy.run_cmd + self._real_which = deploy._which + self._real_env = os.environ.get("DEPLOY_TARGET_DRVS") + + def run(argv): + self.calls.append(list(argv)) + if argv[:2] == ["nix-store", "--realise"] and self.produce: + self.produce() + return 0, "", "" + + deploy.run_cmd = run + deploy._which = lambda tool: tool == "nix-store" + self.drvs_path = os.path.join(self.tmp.name, "drvs.json") + os.environ["DEPLOY_TARGET_DRVS"] = self.drvs_path + + def tearDown(self): + deploy.run_cmd = self._real_run_cmd + deploy._which = self._real_which + if self._real_env is None: + os.environ.pop("DEPLOY_TARGET_DRVS", None) + else: + os.environ["DEPLOY_TARGET_DRVS"] = self._real_env + self.tmp.cleanup() + + def write_drvs(self, drvs): + with open(self.drvs_path, "w", encoding="utf-8") as fh: + json.dump(drvs, fh) + + def realise_calls(self): + return [c for c in self.calls if c[:2] == ["nix-store", "--realise"]] + + def test_missing_artifact_is_built_from_its_recorded_drv(self): + self.write_drvs({"svc": DRV, "other": DRV.replace("svc", "other")}) + with self.assertRaises(deploy.ActivationError) as ctx: + deploy.install_generation("svc", ARTIFACT, 1, self.base) + # The fake build produces nothing, so the deploy fails loudly + # instead of linking a dangling profile. + self.assertIn("did not produce", str(ctx.exception)) + self.assertEqual(self.realise_calls(), [["nix-store", "--realise", DRV]]) + + def test_built_artifact_proceeds_to_the_profile(self): + artifact = os.path.join(self.tmp.name, "svc-out") + self.write_drvs({"svc": DRV}) + + def produce(): + os.makedirs(artifact, exist_ok=True) + + self.produce = produce + # ensure_artifact only acts on store paths; exercise it directly + # with a store-shaped path whose existence check is redirected. + real_exists = deploy.os.path.exists + + def exists(path): + if path == ARTIFACT: + return real_exists(artifact) + return real_exists(path) + + deploy.os.path.exists = exists + try: + deploy.ensure_artifact("svc", ARTIFACT) + finally: + deploy.os.path.exists = real_exists + self.assertEqual(self.realise_calls(), [["nix-store", "--realise", DRV]]) + + def test_present_or_unmapped_artifacts_build_nothing(self): + self.write_drvs({"svc": DRV}) + present = os.path.join(self.tmp.name, "present") + os.makedirs(present) + deploy.ensure_artifact("svc", present) # not a store path + deploy.ensure_artifact("unmapped", ARTIFACT) # no recorded drv + os.environ.pop("DEPLOY_TARGET_DRVS") + deploy.ensure_artifact("svc", ARTIFACT) # no map configured + self.assertEqual(self.realise_calls(), []) + + def test_malformed_drv_maps_are_ignored(self): + for drvs in ("not json", '["svc"]', '{"svc": "/tmp/evil.drv"}', '{"svc": 3}'): + with open(self.drvs_path, "w", encoding="utf-8") as fh: + fh.write(drvs) + self.assertIsNone(deploy._target_drv("svc"), drvs) + deploy.ensure_artifact("svc", ARTIFACT) + self.assertEqual(self.realise_calls(), []) + + +if __name__ == "__main__": + unittest.main(argv=[sys.argv[0]], verbosity=2)