Skip to content

Build AI methods with your coding agent, then run them anywhere: as an MCP for chatbots, as a webapp for people, or via API for your software.

feature/Partial-pipelex-skips-auto-init · L-261004-51cca0 (#1365)

Louis Choquel62b0390ad13b
diff --git a/.badges/tests.json b/.badges/tests.json
index 60a0b3cad..1afc05895 100644
--- a/.badges/tests.json
+++ b/.badges/tests.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"label": "tests",
- "message": "15566",
+ "message": "15623",
"color": "blue",
"cacheSeconds": 300
}
diff --git a/.drift/acks/cli-docs.toml b/.drift/acks/cli-docs.toml
index c498de8df..a1524744d 100644
--- a/.drift/acks/cli-docs.toml
+++ b/.drift/acks/cli-docs.toml
@@ -1,8 +1,8 @@
contract = "cli-docs"
-digest = "sha256:b453fc65605094195a9b7c5eb7db7f52b75144f20fc9cb9958ec1761e133258e"
-reviewed_by = "Louis Choquel"
-reviewed_at = "2026-10-08T01:45:16Z"
-rationale = "real-catch: check_model_cmd.py's --type now takes ModelCheckCategory, the categories GET /v1/models/check answers in, so doc_gen is accepted. docs/tools/cli/agent-cli.md's check-model row now lists the categories, doc_gen included, and says a handle: reference names its handle literally; pipelex/cli/agent_cli/CLAUDE.md's check-model row names ModelCheckCategory and why the listing's ModelCategory differs. docs/tools/cli/validate.md's pointer to check-model is still true."
+digest = "sha256:67e74186129a0a063c16a4f36f412f61ede2624ab6201e489af587f58beed0de"
+reviewed_by = "Claude (Opus 5.5)"
+reviewed_at = "2026-10-08T07:21:15Z"
+rationale = "clean-pass: merged tree of origin/dev into this branch. Dev's check-model change keeps the review recorded on dev, whose doc edits in docs/tools/cli/agent-cli.md and pipelex/cli/agent_cli/CLAUDE.md came through the merge unchanged. This branch's only trigger change is init_config delegating its copy walk to the shared copy_kit_templates, with the same skip lists, overwrite on reset and the same dry-run count, so pipelex init config behaves as before. Re-read docs/tools/cli/init.md (full reset, every target replacing its file, the .gitignore rule) and the init rows of pipelex/cli/agent_cli/CLAUDE.md; none describes anything this changes."
[trigger_files]
"pipelex/cli/__init__.py" = "blob:8b137891791fe96927ad78e64b0aad7bded08bdc"
@@ -84,7 +84,7 @@ rationale = "real-catch: check_model_cmd.py's --type now takes ModelCheckCategor
"pipelex/cli/commands/init/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"
"pipelex/cli/commands/init/backends.py" = "blob:04a1a06f1003ed0c7157ec4ca6c8659e4e09fe6b"
"pipelex/cli/commands/init/command.py" = "blob:f17d58fe1813d4bb9552cc418914ea4aebae2d2a"
-"pipelex/cli/commands/init/config_files.py" = "blob:c13be6b8d2a8b211ce9ef0f4889ee131ffc3d2d8"
+"pipelex/cli/commands/init/config_files.py" = "blob:8d1ea8e03e8117de5264d4bc046e5bc259fb1342"
"pipelex/cli/commands/init/credentials.py" = "blob:a9c3ee9e8bdcc5d0f3148f055ab6e2ff34a940fc"
"pipelex/cli/commands/init/ide_extension.py" = "blob:9f0ec1494c07062246ecc906bc55b7f2cf95c715"
"pipelex/cli/commands/init/routing.py" = "blob:c73927deb99804556cb545cdaa6eabf8d1fc3450"
diff --git a/.drift/acks/config-docs.toml b/.drift/acks/config-docs.toml
index 0396483dc..c27cf5d6e 100644
--- a/.drift/acks/config-docs.toml
+++ b/.drift/acks/config-docs.toml
@@ -1,8 +1,8 @@
contract = "config-docs"
-digest = "sha256:fe956b25829d41bf434d926476489cac06a8c37bb712451d5315f6fcb9bb3711"
-reviewed_by = "Claude (Opus 5.5)"
-reviewed_at = "2026-10-05T16:08:21Z"
-rationale = "real-catch: ensure_global_config_exists now fills the home configuration directory from the kit when it exists but is empty, not only when it is missing; docs/configuration/index.md says so in the PIPELEX_HOME section, and the config_loader docstrings now name the home directory instead of crediting Path.home. No setting, default or load order moved."
+digest = "sha256:86496f1545d0c4bcce6d54f10321cfa29d7c32964eb197d5e06a34a7bcfaf435"
+reviewed_by = "Louis Choquel"
+reviewed_at = "2026-10-07T14:54:43Z"
+rationale = "clean-pass: config_loader.py only gains a comment saying the backends.toml write cannot follow a link, because the return above it made sure nothing stands at that path; the fill still never writes through a link. Re-read the PIPELEX_HOME section of docs/configuration/index.md, which describes only the boot fill and stays accurate; the link-following that pipelex init keeps lives in pipelex/kit/template_copy.py and is described in docs/under-the-hood/init-cli-flows.md. No config model, default, validator or load order moved."
[trigger_files]
"pipelex/cogt/config_cogt.py" = "blob:02f71cb4a6b01aebda59c2e31f262ef9c865e17b"
@@ -13,7 +13,7 @@ rationale = "real-catch: ensure_global_config_exists now fills the home configur
"pipelex/pipelex.toml" = "blob:cb3431d9d8a3265121d730eaef34cfbe5e8c4cbf"
"pipelex/system/configuration/__init__.py" = "blob:8b137891791fe96927ad78e64b0aad7bded08bdc"
"pipelex/system/configuration/config_check.py" = "blob:2d5de29aba3d2ce205d3d82b4623f37b53108332"
-"pipelex/system/configuration/config_loader.py" = "blob:131f611530646e777ba705808ea164f088229fa5"
+"pipelex/system/configuration/config_loader.py" = "blob:7563f68051a568ba90d3209c1966d678078c6de2"
"pipelex/system/configuration/config_model.py" = "blob:83b29dc6e93393c9b98c4353636caf0135c80339"
"pipelex/system/configuration/config_root.py" = "blob:c7d43851270912d17413cfc6a511247d3c7cc160"
"pipelex/system/configuration/config_surface.py" = "blob:dc6c877564254aa97ce0b20fd29118def31c957c"
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 214992573..dfa7244a4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,11 @@
# Changelog
+## [Unreleased]
+
+### Fixed
+
+- **A home configuration directory holding only some files gets the kit's missing ones**: every boot now copies into `~/.pipelex/`, or the directory `PIPELEX_HOME` names, each kit file it lacks, never overwriting one it holds or writing through a symbolic link, so a kit file deleted from it comes back. A directory holding anything at all, such as the `pipelex_service.toml` an earlier release wrote, used to be left as it was, and every boot then failed with "Config files are missing for the inference backend library". The inference files are copied as one unit, only when the directory has no `inference/backends.toml`, each file and kit manifest is written whole or not at all, so a fill cut short is completed by the next boot, and a directory Pipelex cannot write to is read as it is.
+
## [v0.78.0] - 2026-10-08
### Highlights
diff --git a/docs/configuration/index.md b/docs/configuration/index.md
index e5274f253..fea3fe1bf 100644
--- a/docs/configuration/index.md
+++ b/docs/configuration/index.md
@@ -34,7 +34,9 @@ The global layer lives in `~/.pipelex/` unless the `PIPELEX_HOME` environment va
export PIPELEX_HOME=/path/to/ci/pipelex-home
```
-Everything that reads or writes the global layer follows it: its `pipelex.toml` and override files, the inference files and their personal overrides, the credentials in its `.env`, the telemetry configuration, `pipelex init`, `pipelex doctor`, `pipelex update`, `pipelex migrate`, and the agent CLI's `--global` flag. The first boot fills the directory from the kit's templates when it does not exist or is empty, as it does for `~/.pipelex/`, so a fresh `mktemp -d` or an empty volume mount works as it is; a directory with anything in it is left alone. A `~` is expanded, a relative path resolves against the working directory at the moment Pipelex is imported, and an empty value counts as unset.
+Everything that reads or writes the global layer follows it: its `pipelex.toml` and override files, the inference files and their personal overrides, the credentials in its `.env`, the telemetry configuration, `pipelex init`, `pipelex doctor`, `pipelex update`, `pipelex migrate`, and the agent CLI's `--global` flag. A `~` is expanded, a relative path resolves against the working directory at the moment Pipelex is imported, and an empty value counts as unset.
+
+Every boot fills the directory from the kit's templates, as it does `~/.pipelex/`: it creates the directory when it does not exist and copies in each kit file the directory lacks, never overwriting a file that is there or writing through a symbolic link, and leaving a link or a file that stands where the kit has a directory alone with everything under it. Each file is written whole or not at all, so a copy cut short leaves nothing half-written. A fresh `mktemp -d`, an empty volume mount, or a directory holding only a `.env` or a personal override therefore works as it is, and a directory that already holds every kit file is not written at all. The inference files are the one exception: they are copied as a whole, and only when the directory has no `inference/backends.toml`, so a directory with an inference setup of its own keeps it exactly as it is, and `pipelex init` or `pipelex update` is what changes it; `backends.toml` is written last, so a fill cut short part-way is completed by the next boot. A directory Pipelex cannot write to, such as a read-only mount, is read as it is.
It is meant for any process that should not share the machine's settings: a test run or a CI job that commits a configuration of its own, a container, or a checkout that must not read the developer's personal backends. A project's own `.pipelex/` keeps winning over it, exactly as it wins over `~/.pipelex/`.
diff --git a/docs/under-the-hood/init-cli-flows.md b/docs/under-the-hood/init-cli-flows.md
index 0cc8b5dd3..70777eaf9 100644
--- a/docs/under-the-hood/init-cli-flows.md
+++ b/docs/under-the-hood/init-cli-flows.md
@@ -264,6 +264,7 @@ Copies a telemetry template and prints instructions. No interactive prompts. Whi
|--------|---------|
| `pipelex/cli/commands/init/command.py` | Orchestration: `init_cmd()`, `execute_initialization()`, `determine_needs()` |
| `pipelex/cli/commands/init/config_files.py` | Config file copying: `init_config()`, skip lists |
+| `pipelex/kit/template_copy.py` | The kit template walk `init_config()` shares with the first-boot fill, `copy_kit_templates()`, and the atomic writes `copy_file_atomically()` and `write_text_atomically()` |
| `pipelex/cli/commands/init/backends.py` | Backend customization: `customize_backends_config()`, `get_selected_backend_keys()` |
| `pipelex/cli/commands/init/routing.py` | Routing customization: `customize_routing_profile()` |
| `pipelex/cli/commands/init/telemetry.py` | Telemetry setup: `setup_telemetry()` |
@@ -316,7 +317,13 @@ This means a project-level file **wins** over the global one, but only if it act
### Global Config Bootstrap
-`ensure_global_config_exists()` creates the home configuration directory (`~/.pipelex/`, or `PIPELEX_HOME`) with kit template files on first use, and fills it the same way when it exists but is empty (called automatically during `load_config()`). It skips all `GIT_IGNORED_CONFIG_FILES` (files like `pipelex_override.toml`) and `.DS_Store` — these are never part of the bootstrap copy.
+`ensure_global_config_exists()`, called automatically during `load_config()`, lays the kit's template files into the home configuration directory (`~/.pipelex/`, or `PIPELEX_HOME`) wherever they are missing. It creates the directory when it does not exist and copies each kit file the directory lacks, never overwriting one it holds, so a home holding only a retired `pipelex_service.toml`, a `.env` or a personal override boots like a fresh one, and a home holding every kit file is not written at all. A file counts as there when anything stands at its path, a symbolic link included even when its target is gone, and nothing is ever written through a link: where the kit has a directory, a link standing in its place, valid or dangling, or a regular file, is left alone with everything under it, the manifests included. Each file is written under a temporary name beside its destination and renamed into place, so it appears whole or not at all and a copy cut off mid-write leaves no truncated file for later boots to keep. It skips all `GIT_IGNORED_CONFIG_FILES` (files like `pipelex_override.toml`, and `.DS_Store`), which are never part of the bootstrap copy.
+
+The `inference/` directory is one unit, as the inference step of `pipelex init` treats it. It is filled only when `inference/backends.toml` is absent, the same signal `pipelex init` reads as a first-time backend setup, and the deck and backends kit manifests are then stamped for each area that has none; the kit's own `.kit_manifest.json` files are never copied. Because `backends.toml` is that signal, it is written last, after every other inference file and the manifests: a fill cut short part-way, by a full disk or a killed process, leaves it absent, and the next boot completes the fill instead of taking a half-copied directory for a complete one. A home with a `backends.toml` of its own keeps its inference directory exactly as it is, because kit routing profiles, deck or backend files copied beside it could route to, or alias the models of, backends it disables.
+
+A home the process cannot write to, such as a read-only mount or a directory another user owns, is read as it is, and the boot then reports whatever configuration is missing. Any other error that stops a copy is raised.
+
+The copy is `copy_kit_templates()` in `pipelex/kit/template_copy.py`, the same walk `init_config()` copies the configuration files with, so the bootstrap and `pipelex init config` agree on which files a directory receives. Both write each file with `copy_file_atomically()`, which is also how the bootstrap writes `backends.toml`, and the kit manifests are written the same way, through `write_text_atomically()` in the same module, so a manifest cut short leaves no truncated `.kit_manifest.json` for the next boot to keep. The two differ on what already stands at a destination. The bootstrap copies without overwriting, so it keeps every file there and never follows a link. `init_config()` copies with `overwrite=reset`, and every `pipelex init` or `pipelex init config` run passes `reset=True`, as `pipelex-agent init` does, because configuration updates are not supported and there is no flag that keeps the existing files; only the dry run that counts missing files for `pipelex init` and `pipelex doctor` passes `reset=False`, and it writes nothing. Overwriting follows a link as a plain copy does, so the template lands at a linked file's target, written beside it and renamed into place, and the link survives. A configuration file linked from a dotfiles repository, as chezmoi, stow or yadm lay them out, therefore stays linked through a reset.
### Config Loading Chain
diff --git a/pipelex/cli/commands/init/config_files.py b/pipelex/cli/commands/init/config_files.py
index c13be6b8d..8d1ea8e03 100644
--- a/pipelex/cli/commands/init/config_files.py
+++ b/pipelex/cli/commands/init/config_files.py
@@ -1,10 +1,10 @@
"""Configuration files management for the init command."""
-import shutil
from pathlib import Path
from pipelex.cli.exceptions import PipelexCLIError
from pipelex.kit.paths import GIT_IGNORED_CONFIG_FILES, get_kit_configs_dir
+from pipelex.kit.template_copy import copy_kit_templates
from pipelex.migration.gitignore import ensure_config_dir_gitignore
from pipelex.system.configuration.config_loader import config_manager
from pipelex.system.telemetry.telemetry_config import TELEMETRY_CONFIG_FILE_NAME
@@ -40,38 +40,15 @@ def init_config(*, reset: bool = False, dry_run: bool = False, target_dir: Path
ensure_config_dir_gitignore(directory=target_config_dir)
try:
- copied_files: list[str] = []
- existing_files: list[str] = []
-
- def copy_directory_structure(*, src_dir: Path, dst_dir: Path, relative_path: Path | None = None, dry_run: bool = False) -> None:
- """Recursively copy directory structure, handling existing files."""
- for src_item in src_dir.iterdir():
- item = src_item.name
- dst_item = dst_dir / item
- relative_item = (relative_path / item) if relative_path is not None else Path(item)
-
- # Skip git-ignored files and telemetry.toml (created when user is prompted)
- if item in INIT_SKIP_FILES:
- continue
-
- if src_item.is_dir():
- if item in INIT_SKIP_DIRS:
- continue
- if not dry_run:
- dst_item.mkdir(parents=True, exist_ok=True)
- copy_directory_structure(src_dir=src_item, dst_dir=dst_item, relative_path=relative_item, dry_run=dry_run)
- elif dst_item.exists() and not reset:
- existing_files.append(relative_item.as_posix())
- else:
- if not dry_run:
- shutil.copy2(src_item, dst_item)
- copied_files.append(relative_item.as_posix())
-
- copy_directory_structure(src_dir=config_template_dir, dst_dir=target_config_dir, dry_run=dry_run)
-
- if dry_run:
- return len(copied_files)
-
+ # The same walk the first boot fills the home configuration directory with, so the two agree on
+ # which files a directory receives.
+ copied_files = copy_kit_templates(
+ template_dir=config_template_dir,
+ target_dir=target_config_dir,
+ skip_names=INIT_SKIP_FILES | INIT_SKIP_DIRS,
+ overwrite=reset,
+ dry_run=dry_run,
+ )
except OSError as exc:
msg = f"Failed to initialize configuration: {exc}"
raise PipelexCLIError(msg) from exc
diff --git a/pipelex/cogt/models/deck_manifest.py b/pipelex/cogt/models/deck_manifest.py
index 6ac93b02e..277b37d67 100644
--- a/pipelex/cogt/models/deck_manifest.py
+++ b/pipelex/cogt/models/deck_manifest.py
@@ -21,6 +21,7 @@ from __future__ import annotations
import hashlib
import json
+import os
from enum import StrEnum
from pathlib import Path
@@ -28,6 +29,7 @@ from pydantic import BaseModel, ConfigDict, Field
from pipelex.cogt.model_backends.backend import PipelexBackend
from pipelex.kit.paths import get_kit_configs_dir
+from pipelex.kit.template_copy import can_fill_directory, write_text_atomically
from pipelex.tools.misc.file_utils import path_exists
from pipelex.tools.misc.package_utils import get_package_version
@@ -182,13 +184,28 @@ def compute_kit_manifest(*, area: KitManagedArea) -> DeckManifest:
def stamp_kit_manifests(*, inference_dir: Path) -> None:
"""Write both areas' manifests for an ``inference/`` directory whose managed files were just copied from the kit.
- For the installers (``pipelex init``, the first-run materialization), so a later ``pipelex update`` tells a file
- the user edited from one the kit moved on.
+ For the installers that replace every kit file (``pipelex init``, ``pipelex-agent init``), so a later ``pipelex
+ update`` tells a file the user edited from one the kit moved on.
"""
for area in KitManagedArea:
write_manifest(compute_kit_manifest(area=area), installed_dir=inference_dir / area)
+def stamp_missing_kit_manifests(*, inference_dir: Path) -> None:
+ """Write the manifest of each area of an ``inference/`` directory that has none, and leave a recorded one alone.
+
+ For the first boot's fill of the home configuration directory, which copies only the kit files the home lacks:
+ a manifest already there records the install the area's files came from, and it stays the baseline ``pipelex
+ update`` compares against. Nothing is written through a link, the fill's own rule: a manifest path holding a
+ link, even a dangling one, counts as recorded, and an area whose directory is a link or a file is skipped.
+ """
+ for area in KitManagedArea:
+ installed_dir = inference_dir / area
+ if not can_fill_directory(directory=installed_dir) or os.path.lexists(manifest_path(installed_dir)):
+ continue
+ write_manifest(compute_kit_manifest(area=area), installed_dir=installed_dir)
+
+
def manifest_path(installed_dir: Path) -> Path:
return installed_dir / MANIFEST_FILENAME
@@ -212,11 +229,14 @@ def read_manifest(installed_dir: Path) -> DeckManifest | None:
def write_manifest(manifest: DeckManifest, *, installed_dir: Path) -> None:
- """Persist the manifest, creating the area's directory if needed."""
+ """Persist the manifest, creating the area's directory if needed.
+
+ Written whole or not at all: a write cut short leaves no truncated manifest, which a fill would keep as
+ recorded and every boot would then report as stale.
+ """
installed_dir.mkdir(parents=True, exist_ok=True)
payload = manifest.model_dump()
- target = manifest_path(installed_dir)
- target.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+ write_text_atomically(destination=manifest_path(installed_dir), text=json.dumps(payload, indent=2, sort_keys=True) + "\n")
def is_deck_stale_fast(deck_dir: Path) -> bool:
diff --git a/pipelex/kit/template_copy.py b/pipelex/kit/template_copy.py
new file mode 100644
index 000000000..77e76a6dd
--- /dev/null
+++ b/pipelex/kit/template_copy.py
@@ -0,0 +1,125 @@
+"""The one walk that lays the kit's configuration templates into a configuration directory.
+
+`pipelex init` copies the configuration files with it, and the first boot fills the home configuration
+directory with it, so the two agree on which files a directory receives and on what "already there"
+means. It imports nothing but the standard library, because the boot's configuration loader calls it.
+
+A symbolic link is treated according to `overwrite`. Without it, the first boot's mode, a link is never
+followed: one at a file's path is kept, even when it dangles, and the walk never enters a link to a
+directory. With it, the mode `init_config(reset=True)` copies in, a link is followed as a plain copy
+follows it: a linked file's target receives the template and the link survives, so a configuration file
+linked from a dotfiles repository stays linked, and a linked directory is entered. Every run of
+`pipelex init`, `pipelex init config` and `pipelex-agent init` that copies configuration files takes that
+mode, since configuration updates are not supported and they always reset; `init_config` copies without
+`overwrite` only in its dry run, which counts the missing files and writes nothing. Either way a file appears whole or not at all:
+it is written under a temporary name beside the place it lands and renamed into place, so a copy cut short
+by a full disk or a killed process leaves no truncated file behind. The kit manifests the fill stamps are
+written the same way, through `write_text_atomically`.
+"""
+
+import os
+import secrets
+import shutil
+from collections.abc import Callable
+from pathlib import Path, PurePosixPath
+
+
+def can_fill_directory(*, directory: Path) -> bool:
+ """Whether kit files may be laid into this path as a directory, creating it if need be.
+
+ True when nothing stands there or a real directory does. False for a symbolic link of any kind, valid
+ or dangling, since filling it would write wherever it points, and for anything else that is not a
+ directory, such as a file, which creating the directory would fail on: whatever stands there is the
+ user's, with everything under it.
+ """
+ if not os.path.lexists(directory):
+ return True
+ return not directory.is_symlink() and directory.is_dir()
+
+
+def _write_atomically(*, destination: Path, write_temporary: Callable[[Path], object]) -> None:
+ """Have `write_temporary` write a file under a temporary name, then rename it into place.
+
+ A destination that is a symbolic link is followed, as a plain write follows it: the file lands at the
+ link's resolved target and the link survives. A dangling link's target is created when its directory
+ exists, and the write raises `FileNotFoundError` when it does not. A caller that must never write through
+ a link, as the first boot's fill must not, checks for one before calling.
+
+ The temporary file sits in the directory the file lands in, which must exist. It is created exclusively,
+ so nothing already standing at its name is written through, and with the mode a plain write gives a new
+ file, the process umask applied. It is removed when the write fails; only a process killed between the
+ two steps can leave one behind, under a name no reader looks for.
+ """
+ landing = Path(os.path.realpath(destination)) if destination.is_symlink() else destination
+ temporary = landing.with_name(f".{landing.name}.{secrets.token_hex(8)}.partial")
+ os.close(os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o666))
+ try:
+ write_temporary(temporary)
+ temporary.replace(landing)
+ finally:
+ temporary.unlink(missing_ok=True)
+
+
+def copy_file_atomically(*, source: Path, destination: Path) -> None:
+ """Copy a file, with the metadata `shutil.copy2` carries, so that it appears whole or not at all.
+
+ It lands at its destination, or at the target of a link standing there, as `_write_atomically` explains.
+ """
+ _write_atomically(destination=destination, write_temporary=lambda temporary: shutil.copy2(source, temporary))
+
+
+def write_text_atomically(*, destination: Path, text: str) -> None:
+ """Write a text file in UTF-8 so that it appears whole or not at all.
+
+ It lands at its destination, or at the target of a link standing there, as `_write_atomically` explains.
+ """
+ _write_atomically(destination=destination, write_temporary=lambda temporary: temporary.write_text(text, encoding="utf-8"))
+
+
+def copy_kit_templates(
+ *,
+ template_dir: Path,
+ target_dir: Path,
+ skip_names: frozenset[str],
+ overwrite: bool,
+ dry_run: bool = False,
+) -> list[str]:
+ """Mirror a kit template tree into a configuration directory, one file at a time.
+
+ Every file under `template_dir` is copied to the same relative path under `target_dir`, and the
+ directories a copied file needs are created on the way. An entry whose name is in `skip_names`, a file
+ or a directory, is left out at any depth, with everything under it.
+
+ Without `overwrite`, a file the target already holds, a symbolic link included even when it dangles, is
+ kept as it is, and a kit directory whose destination `can_fill_directory` refuses, such as a link or a
+ file standing there, is left out with everything under it: a directory that holds every file is not
+ written at all, and nothing is written through a link. With `overwrite`, every file is written, through
+ a link to its target as `copy_file_atomically` does, and a linked directory is entered. With `dry_run`
+ nothing is written, and the result says what a real run would copy.
+
+ Returns:
+ The paths of the files copied, relative to `template_dir` and in POSIX form, in walk order.
+ """
+ copied: list[str] = []
+
+ def mirror(*, src_dir: Path, relative_dir: PurePosixPath) -> None:
+ for src_item in sorted(src_dir.iterdir()):
+ if src_item.name in skip_names:
+ continue
+ relative_item = relative_dir / src_item.name
+ dst_item = target_dir / relative_item
+ if src_item.is_dir():
+ if overwrite or can_fill_directory(directory=dst_item):
+ mirror(src_dir=src_item, relative_dir=relative_item)
+ continue
+ # `lexists` rather than `exists`: a link is there even when it dangles, and copying through it
+ # would write wherever it points, or fail on every run when that place does not exist.
+ if not overwrite and os.path.lexists(dst_item):
+ continue
+ if not dry_run:
+ dst_item.parent.mkdir(parents=True, exist_ok=True)
+ copy_file_atomically(source=src_item, destination=dst_item)
+ copied.append(relative_item.as_posix())
+
+ mirror(src_dir=template_dir, relative_dir=PurePosixPath())
+ return copied
diff --git a/pipelex/system/configuration/config_loader.py b/pipelex/system/configuration/config_loader.py
index 131f61153..7563f6805 100644
--- a/pipelex/system/configuration/config_loader.py
+++ b/pipelex/system/configuration/config_loader.py
@@ -1,9 +1,11 @@
-import shutil
+import errno
+import os
from pathlib import Path
from typing import Any, TypeVar
from pydantic import BaseModel, ValidationError
+from pipelex.kit.template_copy import can_fill_directory, copy_file_atomically, copy_kit_templates
from pipelex.system.configuration.config_surface import (
PIPELEX_CONFIG_SURFACE_ID,
replay_surface_files_in_memory,
@@ -290,40 +292,74 @@ class ConfigLoader:
return self.resolve_config_file(f"{INFERENCE_DIR_NAME}/{MODEL_DECKS_DIR_NAME}")
def ensure_global_config_exists(self) -> None:
- """Create the home configuration directory with kit template files if it doesn't exist or is empty.
-
- An empty directory is what `mktemp -d` or a fresh volume mount gives for `PIPELEX_HOME`, and it
- holds nothing to keep. A directory with anything in it is left exactly as it is.
+ """Lay the kit's template files into the home configuration directory wherever they are missing.
+
+ Every boot that loads the layered configuration calls this. The directory is created when it does
+ not exist, and each kit file it lacks is copied in, so a home holding only some files (a retired
+ `pipelex_service.toml`, a `.env`, a personal override) boots like a fresh one. A file the home
+ already has is never overwritten, which makes this a no-op on a home that holds every kit file.
+
+ A file is "already there" when anything stands at its path, a symbolic link included even when it
+ dangles, and nothing is ever written through a link: where the kit has a directory, a link to one,
+ valid or dangling, or a file standing in its place is left alone with everything under it. Each
+ file is written under a temporary name and renamed into place, so it appears whole or not at all.
+
+ The inference setup is one unit, as `pipelex init` sets it up: it is laid down only when the home
+ has no `inference/backends.toml`, the file `pipelex init` reads as "inference not set up yet", and
+ each area's kit manifest is then stamped unless one is already there. `backends.toml` is written
+ last, after the other inference files and the manifests, so a fill cut short part-way leaves it
+ absent and the next boot completes the fill. A home that has its own
+ `backends.toml` keeps its inference directory exactly as it is, because the kit's routing profiles,
+ deck and backend files copied beside it could route to, or alias the models of, backends it
+ disables; `pipelex init` and `pipelex update` are what change that directory.
+
+ An existing home this process cannot write to, a read-only mount or a directory another user owns,
+ is read as it is, and the boot names whatever its configuration then lacks. That is the one failure
+ tolerated here: any other error that stops a copy is raised.
"""
- global_dir = self.global_config_dir
- if global_dir.is_dir() and any(global_dir.iterdir()):
- return
-
+ # Imported lazily to avoid a circular import: config_loader is loaded very early.
from pipelex.kit.paths import GIT_IGNORED_CONFIG_FILES, get_kit_configs_dir # ruff: ignore[import-outside-top-level]
- config_template_dir = Path(str(get_kit_configs_dir()))
+ global_dir = self.global_config_dir
global_dir.mkdir(parents=True, exist_ok=True)
-
- def copy_directory_structure(*, src_dir: Path, dst_dir: Path) -> None:
- """Recursively copy directory structure from kit templates."""
- for item in src_dir.iterdir():
- if item.name in GIT_IGNORED_CONFIG_FILES or item.name == ".DS_Store":
- continue
- dst_item = dst_dir / item.name
- if item.is_dir():
- dst_item.mkdir(parents=True, exist_ok=True)
- copy_directory_structure(src_dir=item, dst_dir=dst_item)
- else:
- shutil.copy2(item, dst_item)
-
- copy_directory_structure(src_dir=config_template_dir, dst_dir=global_dir)
-
- # Stamp the kit manifests of the deck and of backends/internal.toml so the boot-time staleness
- # check and `pipelex update` have a baseline.
- # Imported lazily to avoid a circular import — config_loader is loaded very early.
- from pipelex.cogt.models.deck_manifest import stamp_kit_manifests # ruff: ignore[import-outside-top-level]
-
- stamp_kit_manifests(inference_dir=global_dir / "inference")
+ kit_configs_dir = Path(str(get_kit_configs_dir()))
+ kit_inference_dir = kit_configs_dir / INFERENCE_DIR_NAME
+ inference_dir = global_dir / INFERENCE_DIR_NAME
+ backends_file = inference_dir / BACKENDS_FILE_NAME
+ try:
+ copy_kit_templates(
+ template_dir=kit_configs_dir,
+ target_dir=global_dir,
+ skip_names=GIT_IGNORED_CONFIG_FILES | {INFERENCE_DIR_NAME},
+ overwrite=False,
+ )
+ # A link counts as there even when it dangles, as it does in the copy itself, and an inference
+ # directory the fill may not enter, a link or a file, is the user's with everything under it.
+ if os.path.lexists(backends_file) or not can_fill_directory(directory=inference_dir):
+ return
+ # Past the return on purpose: the manifest module pulls in the inference backend chain, which
+ # only a home being filled needs. Lazy at all to avoid a circular import, as above.
+ from pipelex.cogt.models.deck_manifest import MANIFEST_FILENAME, stamp_missing_kit_manifests # ruff: ignore[import-outside-top-level]
+
+ # `backends.toml` is what marks the inference setup as there, so it is left out of the walk and
+ # written last: a fill cut short by a full disk or a killed process leaves it absent, and the next
+ # boot resumes the fill rather than taking a half-copied directory for a complete one. The kit's
+ # own manifests are not templates either: a manifest records one install, so the home's are
+ # written for it rather than copied from whatever the kit's say.
+ copy_kit_templates(
+ template_dir=kit_inference_dir,
+ target_dir=inference_dir,
+ skip_names=GIT_IGNORED_CONFIG_FILES | {MANIFEST_FILENAME, BACKENDS_FILE_NAME},
+ overwrite=False,
+ )
+ stamp_missing_kit_manifests(inference_dir=inference_dir)
+ inference_dir.mkdir(parents=True, exist_ok=True)
+ # Nothing stands at its path, a link included, as the return above made sure, so this cannot
+ # write through one.
+ copy_file_atomically(source=kit_inference_dir / BACKENDS_FILE_NAME, destination=backends_file)
+ except OSError as exc:
+ if not (isinstance(exc, PermissionError) or exc.errno == errno.EROFS):
+ raise
@classmethod
def _override_files_for_dir(cls, config_dir: Path, *, include_run_mode: bool) -> list[Path]:
diff --git a/tests/unit/pipelex/system/configuration/test_home_config_fill.py b/tests/unit/pipelex/system/configuration/test_home_config_fill.py
new file mode 100644
index 000000000..edd40cb85
--- /dev/null
+++ b/tests/unit/pipelex/system/configuration/test_home_config_fill.py
@@ -0,0 +1,405 @@
+"""The first boot lays the kit's configuration into the home configuration directory wherever it is missing.
+
+`ConfigLoader.ensure_global_config_exists` runs on every boot that loads the layered configuration. It
+copies each kit file the home lacks and never overwrites one the home has. The inference setup is one
+unit, laid down only when the home has no `inference/backends.toml`, which is the file `pipelex init`
+reads as "inference not set up yet". Every test points `PIPELEX_HOME` at a directory under `tmp_path`,
+so none of them can reach the developer's own `~/.pipelex`.
+"""
+
+import errno
+import json
+import os
+import shutil
+import subprocess # ruff: ignore[suspicious-subprocess-import]
+import sys
+import textwrap
+from pathlib import Path
+from typing import Any
+
+import pytest
+from pytest_mock import MockerFixture
+
+from pipelex.cogt.models.deck_manifest import MANIFEST_FILENAME, KitManagedArea, compute_kit_manifest
+from pipelex.kit.paths import GIT_IGNORED_CONFIG_FILES, get_kit_configs_dir
+from pipelex.system.configuration.config_loader import ConfigLoader
+from pipelex.system.environment import PIPELEX_HOME_ENV_KEY
+
+_MANIFESTS = frozenset(f"inference/{area}/{MANIFEST_FILENAME}" for area in KitManagedArea)
+
+#: Fill the home `PIPELEX_HOME` names, then say whether that loaded the manifest module.
+_PROBE_MANIFEST_MODULE_IMPORT = textwrap.dedent(
+ """
+ import sys
+
+ from pipelex.system.configuration.config_loader import ConfigLoader
+
+ ConfigLoader().ensure_global_config_exists()
+ print("pipelex.cogt.models.deck_manifest" in sys.modules)
+ """
+)
+
+
+def _kit_files() -> dict[str, bytes]:
+ """Every file a fresh home receives from the kit as it is, by its path relative to the kit's `configs/`.
+
+ The kit's own `.kit_manifest.json` files are not among them: a manifest records one install, so the
+ home's are written for it rather than copied from whatever the kit's say.
+ """
+ kit_dir = Path(str(get_kit_configs_dir()))
+ return {
+ path.relative_to(kit_dir).as_posix(): path.read_bytes()
+ for path in kit_dir.rglob("*")
+ if path.is_file() and not (GIT_IGNORED_CONFIG_FILES | {MANIFEST_FILENAME}).intersection(path.relative_to(kit_dir).parts)
+ }
+
+
+def _files_under(directory: Path) -> dict[str, bytes]:
+ return {path.relative_to(directory).as_posix(): path.read_bytes() for path in directory.rglob("*") if path.is_file()}
+
+
+def _write_files(directory: Path, *, files: dict[str, str]) -> None:
+ for relative_path, content in files.items():
+ target = directory / relative_path
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(content, encoding="utf-8")
+
+
+class TestHomeConfigFill:
+ @pytest.fixture
+ def home(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """The home configuration directory, which each test creates (or not) for itself."""
+ home = tmp_path / "pipelex-home"
+ monkeypatch.setenv(PIPELEX_HOME_ENV_KEY, str(home))
+ return home
+
+ @pytest.mark.parametrize("home_exists", [False, True])
+ def test_an_absent_or_empty_home_receives_the_whole_kit(self, home: Path, home_exists: bool) -> None:
+ if home_exists:
+ home.mkdir()
+
+ ConfigLoader().ensure_global_config_exists()
+
+ installed = _files_under(home)
+ kit_files = _kit_files()
+ assert set(installed) == set(kit_files) | _MANIFESTS
+ assert {path: installed[path] for path in kit_files} == kit_files
+ for area in KitManagedArea:
+ stamped = json.loads((home / "inference" / area / MANIFEST_FILENAME).read_text(encoding="utf-8"))
+ assert stamped == compute_kit_manifest(area=area).model_dump()
+
+ @pytest.mark.parametrize(
+ "unrelated_files",
+ [
+ pytest.param({"pipelex_service.toml": "[agreement]\nterms_accepted = true\n"}, id="retired_service_file"),
+ pytest.param({".env": "OPENAI_API_KEY=sk-test\n"}, id="credentials"),
+ pytest.param({"pipelex_override.toml": "[runtime.log]\ndefault_log_level = 'DEBUG'\n"}, id="personal_override"),
+ pytest.param({"inference/backends_override.toml": "[openai]\nenabled = true\n"}, id="inference_override_only"),
+ ],
+ )
+ def test_a_home_holding_only_unrelated_files_receives_the_whole_kit_beside_them(self, home: Path, unrelated_files: dict[str, str]) -> None:
+ """A home holding only files the kit does not ship boots like a fresh one, and keeps those files."""
+ _write_files(home, files=unrelated_files)
+
+ ConfigLoader().ensure_global_config_exists()
+
+ installed = _files_under(home)
+ kit_files = _kit_files()
+ assert set(installed) == set(kit_files) | _MANIFESTS | set(unrelated_files)
+ assert {path: installed[path] for path in kit_files} == kit_files
+ assert {path: installed[path].decode("utf-8") for path in unrelated_files} == unrelated_files
+
+ @pytest.mark.parametrize(
+ "user_file",
+ [
+ "pipelex.toml",
+ "telemetry.toml",
+ "inference/routing_profiles.toml",
+ "inference/deck/1_llm_deck.toml",
+ "inference/backends/openai.toml",
+ ],
+ )
+ def test_a_kit_file_the_user_changed_is_kept_and_the_rest_is_filled_in(self, home: Path, user_file: str) -> None:
+ user_content = "# the user's own version of this file\n"
+ _write_files(home, files={user_file: user_content})
+
+ ConfigLoader().ensure_global_config_exists()
+
+ installed = _files_under(home)
+ kit_files = _kit_files()
+ assert installed[user_file].decode("utf-8") == user_content
+ assert set(installed) == set(kit_files) | _MANIFESTS
+ assert {path: installed[path] for path in kit_files if path != user_file} == {
+ path: content for path, content in kit_files.items() if path != user_file
+ }
+
+ def test_a_home_with_its_own_backends_keeps_its_inference_directory_whole(self, home: Path) -> None:
+ """Only the inference unit is all-or-nothing: the configuration files beside it are still filled in.
+
+ Copying the kit's routing profiles, deck or backend files beside a `backends.toml` the user set up
+ could route to, or alias models of, backends that file disables, so the inference directory of a
+ home that has one is left exactly as it is.
+ """
+ user_backends = "[anthropic]\nenabled = true\n"
+ _write_files(home, files={"inference/backends.toml": user_backends})
+
+ ConfigLoader().ensure_global_config_exists()
+
+ assert _files_under(home / "inference") == {"backends.toml": user_backends.encode("utf-8")}
+ kit_files = _kit_files()
+ top_level_kit_files = {path: content for path, content in kit_files.items() if not path.startswith("inference/")}
+ assert top_level_kit_files
+ assert {path: content for path, content in _files_under(home).items() if not path.startswith("inference/")} == top_level_kit_files
+
+ def test_a_manifest_already_in_an_area_is_kept_and_the_area_without_one_is_stamped(self, home: Path) -> None:
+ recorded_manifest = json.dumps({"kit_version": "0.0.1", "files": {}}, indent=2, sort_keys=True) + "\n"
+ deck_manifest = f"inference/{KitManagedArea.DECK}/{MANIFEST_FILENAME}"
+ backends_manifest = f"inference/{KitManagedArea.BACKENDS}/{MANIFEST_FILENAME}"
+ _write_files(home, files={deck_manifest: recorded_manifest})
+
+ ConfigLoader().ensure_global_config_exists()
+
+ assert (home / deck_manifest).read_text(encoding="utf-8") == recorded_manifest
+ stamped = json.loads((home / backends_manifest).read_text(encoding="utf-8"))
+ assert stamped == compute_kit_manifest(area=KitManagedArea.BACKENDS).model_dump()
+
+ def test_a_home_holding_every_kit_file_is_not_written(self, home: Path) -> None:
+ loader = ConfigLoader()
+ loader.ensure_global_config_exists()
+ (home / "pipelex.toml").write_text("# edited by the user\n", encoding="utf-8")
+ # A rewrite by `shutil.copy2` would carry the kit file's own timestamp, so pinning every file to
+ # one far from it makes any rewrite visible, even of a file whose content would not change.
+ pinned_ns = 1_000_000_000_000_000_000
+ for path in home.rglob("*"):
+ if path.is_file():
+ os.utime(path, ns=(pinned_ns, pinned_ns))
+ before = {path: (path.read_bytes(), path.stat().st_mtime_ns) for path in home.rglob("*") if path.is_file()}
+
+ loader.ensure_global_config_exists()
+
+ assert {path: (path.read_bytes(), path.stat().st_mtime_ns) for path in home.rglob("*") if path.is_file()} == before
+
+ @pytest.mark.skipif(sys.platform == "win32", reason="POSIX permission bits do not make a Windows directory read-only")
+ @pytest.mark.skipif(sys.platform != "win32" and os.geteuid() == 0, reason="root writes through POSIX permission bits")
+ def test_an_existing_home_the_process_cannot_write_to_is_read_as_it_is(self, home: Path) -> None:
+ """A home mounted read-only, or owned by another user, must not stop a boot over a file it lacks."""
+ ConfigLoader().ensure_global_config_exists()
+ (home / "plxt.toml").unlink()
+ home.chmod(0o555)
+ try:
+ ConfigLoader().ensure_global_config_exists()
+
+ assert not (home / "plxt.toml").exists()
+ finally:
+ home.chmod(0o755)
+
+ @pytest.mark.parametrize(
+ "unwritable_error",
+ [
+ pytest.param(PermissionError(errno.EACCES, "Permission denied"), id="permission_denied"),
+ pytest.param(OSError(errno.EROFS, "Read-only file system"), id="read_only_file_system"),
+ ],
+ )
+ def test_an_error_saying_the_home_cannot_be_written_is_tolerated(self, home: Path, mocker: MockerFixture, unwritable_error: OSError) -> None:
+ mocker.patch.object(shutil, "copy2", side_effect=unwritable_error)
+
+ ConfigLoader().ensure_global_config_exists()
+
+ assert not _files_under(home)
+
+ @pytest.mark.usefixtures("home")
+ def test_any_other_error_that_stops_a_copy_is_raised(self, mocker: MockerFixture) -> None:
+ disk_full = OSError(errno.ENOSPC, "No space left on device")
+ mocker.patch.object(shutil, "copy2", side_effect=disk_full)
+
+ with pytest.raises(OSError, match="No space left on device") as raised:
+ ConfigLoader().ensure_global_config_exists()
+
+ assert raised.value is disk_full
+
+ def test_an_inference_fill_cut_short_is_completed_by_the_next_boot(self, home: Path, mocker: MockerFixture) -> None:
+ """`backends.toml` is what marks the inference setup as there, so a fill that stops part-way must leave it out.
+
+ Written before the rest, it would make every later boot take the half-copied directory for a
+ complete one, and the home would fail on the missing routing profiles or deck forever.
+ """
+ real_copy2 = shutil.copy2
+
+ def copy2_failing_on_one_deck_file(src: Any, dst: Any, **kwargs: Any) -> Any:
+ if Path(src).name == "3_extract_deck.toml":
+ raise OSError(errno.ENOSPC, "No space left on device")
+ return real_copy2(src, dst, **kwargs)
+
+ copy2_patch = mocker.patch.object(shutil, "copy2", side_effect=copy2_failing_on_one_deck_file)
+ with pytest.raises(OSError, match="No space left on device"):
+ ConfigLoader().ensure_global_config_exists()
+ assert not (home / "inference" / "backends.toml").exists()
+ mocker.stop(copy2_patch)
+
+ ConfigLoader().ensure_global_config_exists()
+
+ installed = _files_under(home)
+ kit_files = _kit_files()
+ assert set(installed) == set(kit_files) | _MANIFESTS
+ assert {path: installed[path] for path in kit_files} == kit_files
+
+ @pytest.mark.skipif(sys.platform == "win32", reason="creating a symbolic link takes a privilege Windows does not grant by default")
+ @pytest.mark.parametrize(
+ "kit_file",
+ [
+ "pipelex.toml",
+ "inference/deck/1_llm_deck.toml",
+ "inference/backends.toml",
+ f"inference/{KitManagedArea.DECK}/{MANIFEST_FILENAME}",
+ f"inference/{KitManagedArea.BACKENDS}/{MANIFEST_FILENAME}",
+ ],
+ )
+ @pytest.mark.parametrize("link_target_dir_exists", [False, True])
+ def test_a_dangling_link_where_a_kit_file_goes_is_kept_and_never_written_through(
+ self, home: Path, tmp_path: Path, kit_file: str, link_target_dir_exists: bool
+ ) -> None:
+ """A link is the user's, even one whose target is gone: copying or stamping through it would fail every boot, or write elsewhere."""
+ link_target_dir = tmp_path / "link-target"
+ if link_target_dir_exists:
+ link_target_dir.mkdir()
+ link_target = link_target_dir / "gone.toml"
+ link = home / kit_file
+ link.parent.mkdir(parents=True)
+ link.symlink_to(link_target)
+
+ ConfigLoader().ensure_global_config_exists()
+
+ assert link.is_symlink()
+ assert link.readlink() == link_target
+ assert not link_target.exists()
+ assert link_target_dir.exists() == link_target_dir_exists
+
+ @pytest.mark.skipif(sys.platform == "win32", reason="creating a symbolic link takes a privilege Windows does not grant by default")
+ @pytest.mark.parametrize("kit_directory", ["inference", "inference/deck", "inference/backends"])
+ @pytest.mark.parametrize("entry_kind", ["link_to_a_directory", "dangling_link", "regular_file"])
+ def test_whatever_stands_where_a_kit_directory_goes_is_left_alone_with_everything_under_it(
+ self, home: Path, tmp_path: Path, kit_directory: str, entry_kind: str
+ ) -> None:
+ """The fill never enters a link, valid or dangling, and never replaces a file standing where the kit has a directory.
+
+ Entering a valid link would copy the kit into wherever it points, and a dangling one or a file would
+ make creating the directory fail on every boot. What stands there is the user's, and the rest of the
+ home is still filled.
+ """
+ entry = home / kit_directory
+ entry.parent.mkdir(parents=True)
+ link_target = tmp_path / "elsewhere"
+ match entry_kind:
+ case "link_to_a_directory":
+ link_target.mkdir()
+ entry.symlink_to(link_target, target_is_directory=True)
+ case "dangling_link":
+ entry.symlink_to(link_target, target_is_directory=True)
+ case _:
+ entry.write_text("not a directory\n", encoding="utf-8")
+
+ ConfigLoader().ensure_global_config_exists()
+
+ match entry_kind:
+ case "link_to_a_directory":
+ assert entry.is_symlink()
+ assert entry.readlink() == link_target
+ assert not list(link_target.iterdir())
+ case "dangling_link":
+ assert entry.is_symlink()
+ assert entry.readlink() == link_target
+ assert not link_target.exists()
+ case _:
+ assert entry.read_text(encoding="utf-8") == "not a directory\n"
+ assert (home / "pipelex.toml").read_bytes() == _kit_files()["pipelex.toml"]
+
+ @pytest.mark.parametrize(
+ "cut_file",
+ [
+ "pipelex.toml",
+ "inference/deck/3_extract_deck.toml",
+ "inference/backends.toml",
+ f"inference/{KitManagedArea.DECK}/{MANIFEST_FILENAME}",
+ f"inference/{KitManagedArea.BACKENDS}/{MANIFEST_FILENAME}",
+ ],
+ )
+ def test_a_write_cut_off_mid_way_leaves_no_partial_file_and_the_next_boot_completes_it(
+ self, home: Path, mocker: MockerFixture, cut_file: str
+ ) -> None:
+ """A file appears whole or not at all, copied from the kit or written as a manifest.
+
+ A truncated `backends.toml` would pass for a finished inference setup, and a truncated manifest for a
+ recorded one that the next fill keeps and every boot then reports as stale.
+ """
+ real_copy2 = shutil.copy2
+ real_write_text = Path.write_text
+
+ def copy2_cut_off_mid_write(src: Any, dst: Any, **kwargs: Any) -> Any:
+ if Path(src).as_posix().endswith(f"/configs/{cut_file}"):
+ Path(dst).write_bytes(Path(src).read_bytes()[:16])
+ raise OSError(errno.ENOSPC, "No space left on device")
+ return real_copy2(src, dst, **kwargs)
+
+ def write_text_cut_off_mid_write(path: Path, data: str, *args: Any, **kwargs: Any) -> int:
+ # The written path is the file itself, or a temporary name beside it carrying its name.
+ if path.parent == (home / cut_file).parent and Path(cut_file).name in path.name:
+ real_write_text(path, data[:16], *args, **kwargs)
+ raise OSError(errno.ENOSPC, "No space left on device")
+ return real_write_text(path, data, *args, **kwargs)
+
+ copy2_patch = mocker.patch.object(shutil, "copy2", side_effect=copy2_cut_off_mid_write)
+ write_text_patch = mocker.patch.object(Path, "write_text", autospec=True, side_effect=write_text_cut_off_mid_write)
+ with pytest.raises(OSError, match="No space left on device"):
+ ConfigLoader().ensure_global_config_exists()
+ # Every file left behind is a whole kit file or a whole manifest: nothing truncated, nothing temporary.
+ kit_files = _kit_files()
+ installed = _files_under(home)
+ assert cut_file not in installed
+ assert set(installed) <= set(kit_files) | _MANIFESTS
+ assert {path: content for path, content in installed.items() if path in kit_files} == {
+ path: kit_files[path] for path in installed if path in kit_files
+ }
+ for area in KitManagedArea:
+ manifest = f"inference/{area}/{MANIFEST_FILENAME}"
+ if manifest in installed:
+ assert json.loads(installed[manifest]) == compute_kit_manifest(area=area).model_dump()
+ mocker.stop(copy2_patch)
+ mocker.stop(write_text_patch)
+
+ ConfigLoader().ensure_global_config_exists()
+
+ installed = _files_under(home)
+ assert set(installed) == set(kit_files) | _MANIFESTS
+ assert {path: installed[path] for path in kit_files} == kit_files
+ for area in KitManagedArea:
+ assert json.loads(installed[f"inference/{area}/{MANIFEST_FILENAME}"]) == compute_kit_manifest(area=area).model_dump()
+
+ @pytest.mark.parametrize(
+ ("home_is_filled", "expects_manifest_module"),
+ [
+ pytest.param(True, False, id="filled_home_imports_nothing_more"),
+ pytest.param(False, True, id="control_empty_home_stamps_manifests"),
+ ],
+ )
+ def test_a_filled_home_does_not_import_the_manifest_module(self, home: Path, home_is_filled: bool, expects_manifest_module: bool) -> None:
+ """The manifest module pulls in the inference backend chain, and only a home being filled needs it.
+
+ Asked in a fresh interpreter, because this one imported it long ago. The empty-home control proves the
+ probe sees the import when it happens, so the filled case cannot pass for a probe that sees nothing.
+ """
+ if home_is_filled:
+ ConfigLoader().ensure_global_config_exists()
+ else:
+ home.mkdir()
+
+ result = subprocess.run( # ruff: ignore[subprocess-without-shell-equals-true]
+ [sys.executable, "-c", _PROBE_MANIFEST_MODULE_IMPORT],
+ capture_output=True,
+ text=True,
+ check=False,
+ timeout=120,
+ env={**os.environ, PIPELEX_HOME_ENV_KEY: str(home)},
+ )
+
+ assert result.returncode == 0, f"stdout={result.stdout}\nstderr={result.stderr}"
+ assert result.stdout.strip().splitlines()[-1] == str(expects_manifest_module)
diff --git a/tests/unit/pipelex/system/configuration/test_kit_template_copy.py b/tests/unit/pipelex/system/configuration/test_kit_template_copy.py
new file mode 100644
index 000000000..1997e9920
--- /dev/null
+++ b/tests/unit/pipelex/system/configuration/test_kit_template_copy.py
@@ -0,0 +1,207 @@
+"""`copy_kit_templates`, the one walk `pipelex init` and the first boot both lay the kit's templates down with."""
+
+import sys
+from pathlib import Path
+
+import pytest
+
+from pipelex.kit.template_copy import copy_kit_templates, write_text_atomically
+
+
+def _write_files(directory: Path, *, files: dict[str, str]) -> None:
+ for relative_path, content in files.items():
+ target = directory / relative_path
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(content, encoding="utf-8")
+
+
+def _files_under(directory: Path) -> dict[str, str]:
+ if not directory.exists():
+ return {}
+ return {path.relative_to(directory).as_posix(): path.read_text(encoding="utf-8") for path in directory.rglob("*") if path.is_file()}
+
+
+_TEMPLATES = {
+ "pipelex.toml": "kit pipelex\n",
+ "skipped.toml": "never copied\n",
+ "inference/backends.toml": "kit backends\n",
+ "inference/deck/1_llm_deck.toml": "kit deck\n",
+ "inference/deck/skipped.toml": "never copied either\n",
+ "storage/data.toml": "under a skipped directory\n",
+}
+_SKIP_NAMES = frozenset({"skipped.toml", "storage"})
+
+
+class TestKitTemplateCopy:
+ @pytest.fixture
+ def template_dir(self, tmp_path: Path) -> Path:
+ template_dir = tmp_path / "kit"
+ _write_files(template_dir, files=_TEMPLATES)
+ return template_dir
+
+ @pytest.mark.parametrize(
+ ("existing", "overwrite", "expected_copied", "expected_after"),
+ [
+ pytest.param(
+ {},
+ False,
+ ["inference/backends.toml", "inference/deck/1_llm_deck.toml", "pipelex.toml"],
+ {"pipelex.toml": "kit pipelex\n", "inference/backends.toml": "kit backends\n", "inference/deck/1_llm_deck.toml": "kit deck\n"},
+ id="empty_target_receives_every_file_not_skipped",
+ ),
+ pytest.param(
+ {"inference/backends.toml": "mine\n", "notes.txt": "unrelated\n"},
+ False,
+ ["inference/deck/1_llm_deck.toml", "pipelex.toml"],
+ {
+ "pipelex.toml": "kit pipelex\n",
+ "inference/backends.toml": "mine\n",
+ "inference/deck/1_llm_deck.toml": "kit deck\n",
+ "notes.txt": "unrelated\n",
+ },
+ id="a_file_the_target_holds_is_kept",
+ ),
+ pytest.param(
+ {"inference/backends.toml": "mine\n", "notes.txt": "unrelated\n"},
+ True,
+ ["inference/backends.toml", "inference/deck/1_llm_deck.toml", "pipelex.toml"],
+ {
+ "pipelex.toml": "kit pipelex\n",
+ "inference/backends.toml": "kit backends\n",
+ "inference/deck/1_llm_deck.toml": "kit deck\n",
+ "notes.txt": "unrelated\n",
+ },
+ id="overwrite_replaces_a_kit_file_and_leaves_the_rest",
+ ),
+ ],
+ )
+ def test_copy(
+ self,
+ template_dir: Path,
+ tmp_path: Path,
+ existing: dict[str, str],
+ overwrite: bool,
+ expected_copied: list[str],
+ expected_after: dict[str, str],
+ ) -> None:
+ target_dir = tmp_path / "target"
+ _write_files(target_dir, files=existing)
+
+ copied = copy_kit_templates(template_dir=template_dir, target_dir=target_dir, skip_names=_SKIP_NAMES, overwrite=overwrite)
+
+ assert copied == expected_copied
+ assert _files_under(target_dir) == expected_after
+
+ def test_a_dry_run_writes_nothing_and_reports_what_a_real_run_would_copy(self, template_dir: Path, tmp_path: Path) -> None:
+ target_dir = tmp_path / "target"
+ _write_files(target_dir, files={"pipelex.toml": "mine\n"})
+
+ copied = copy_kit_templates(template_dir=template_dir, target_dir=target_dir, skip_names=_SKIP_NAMES, overwrite=False, dry_run=True)
+
+ assert copied == ["inference/backends.toml", "inference/deck/1_llm_deck.toml"]
+ assert _files_under(target_dir) == {"pipelex.toml": "mine\n"}
+ assert not (target_dir / "inference").exists()
+
+ @pytest.mark.skipif(sys.platform == "win32", reason="creating a symbolic link takes a privilege Windows does not grant by default")
+ @pytest.mark.parametrize(
+ ("overwrite", "expected_linked_content"),
+ [
+ pytest.param(False, "the user's own\n", id="kept_and_never_written_through_without_overwrite"),
+ pytest.param(True, "kit pipelex\n", id="written_through_to_its_target_with_overwrite"),
+ ],
+ )
+ def test_a_link_at_a_file_s_destination_survives(self, template_dir: Path, tmp_path: Path, overwrite: bool, expected_linked_content: str) -> None:
+ """A configuration file linked from a dotfiles repository stays linked.
+
+ The fill, which never overwrites, leaves the link and the file it points to alone; `init_config(reset=True)`,
+ which every `pipelex init` and `pipelex-agent init` copy takes, rewrites the file it points to, whole,
+ and leaves nothing else beside it.
+ """
+ target_dir = tmp_path / "target"
+ target_dir.mkdir()
+ linked_file = tmp_path / "dotfiles" / "pipelex.toml"
+ _write_files(linked_file.parent, files={linked_file.name: "the user's own\n"})
+ (target_dir / "pipelex.toml").symlink_to(linked_file)
+
+ copy_kit_templates(template_dir=template_dir, target_dir=target_dir, skip_names=_SKIP_NAMES, overwrite=overwrite)
+
+ assert (target_dir / "pipelex.toml").is_symlink()
+ assert (target_dir / "pipelex.toml").readlink() == linked_file
+ assert linked_file.read_text(encoding="utf-8") == expected_linked_content
+ assert [path.name for path in linked_file.parent.iterdir()] == ["pipelex.toml"]
+
+ @pytest.mark.skipif(sys.platform == "win32", reason="creating a symbolic link takes a privilege Windows does not grant by default")
+ def test_overwrite_through_a_dangling_link_writes_its_target_when_that_directory_exists(self, template_dir: Path, tmp_path: Path) -> None:
+ """What a plain copy did: the link's target is created, and the link now points at the template."""
+ target_dir = tmp_path / "target"
+ target_dir.mkdir()
+ linked_file = tmp_path / "dotfiles" / "pipelex.toml"
+ linked_file.parent.mkdir()
+ (target_dir / "pipelex.toml").symlink_to(linked_file)
+
+ copy_kit_templates(template_dir=template_dir, target_dir=target_dir, skip_names=_SKIP_NAMES, overwrite=True)
+
+ assert (target_dir / "pipelex.toml").is_symlink()
+ assert linked_file.read_text(encoding="utf-8") == "kit pipelex\n"
+
+ @pytest.mark.skipif(sys.platform == "win32", reason="creating a symbolic link takes a privilege Windows does not grant by default")
+ def test_overwrite_through_a_dangling_link_whose_directory_is_gone_raises(self, template_dir: Path, tmp_path: Path) -> None:
+ """What a plain copy did as well: there is nowhere to write, and the caller is told so."""
+ target_dir = tmp_path / "target"
+ target_dir.mkdir()
+ linked_file = tmp_path / "gone" / "pipelex.toml"
+ (target_dir / "pipelex.toml").symlink_to(linked_file)
+
+ with pytest.raises(FileNotFoundError):
+ copy_kit_templates(template_dir=template_dir, target_dir=target_dir, skip_names=_SKIP_NAMES, overwrite=True)
+
+ assert (target_dir / "pipelex.toml").is_symlink()
+ assert not linked_file.parent.exists()
+
+ @pytest.mark.skipif(sys.platform == "win32", reason="creating a symbolic link takes a privilege Windows does not grant by default")
+ @pytest.mark.parametrize(
+ ("overwrite", "expected_in_linked_directory"),
+ [
+ pytest.param(False, [], id="never_entered_without_overwrite"),
+ pytest.param(True, ["backends.toml", "deck/1_llm_deck.toml"], id="entered_with_overwrite"),
+ ],
+ )
+ def test_a_linked_directory_is_entered_only_with_overwrite(
+ self, template_dir: Path, tmp_path: Path, overwrite: bool, expected_in_linked_directory: list[str]
+ ) -> None:
+ target_dir = tmp_path / "target"
+ target_dir.mkdir()
+ linked_directory = tmp_path / "dotfiles" / "inference"
+ linked_directory.mkdir(parents=True)
+ (target_dir / "inference").symlink_to(linked_directory, target_is_directory=True)
+
+ copy_kit_templates(template_dir=template_dir, target_dir=target_dir, skip_names=_SKIP_NAMES, overwrite=overwrite)
+
+ assert (target_dir / "inference").is_symlink()
+ assert sorted(path.relative_to(linked_directory).as_posix() for path in linked_directory.rglob("*") if path.is_file()) == (
+ expected_in_linked_directory
+ )
+
+ def test_a_copy_leaves_no_temporary_file_behind(self, template_dir: Path, tmp_path: Path) -> None:
+ target_dir = tmp_path / "target"
+
+ copy_kit_templates(template_dir=template_dir, target_dir=target_dir, skip_names=_SKIP_NAMES, overwrite=False)
+
+ assert sorted(path.relative_to(target_dir).as_posix() for path in target_dir.rglob("*") if path.is_file()) == [
+ "inference/backends.toml",
+ "inference/deck/1_llm_deck.toml",
+ "pipelex.toml",
+ ]
+
+ @pytest.mark.skipif(sys.platform == "win32", reason="POSIX permission bits do not apply on Windows")
+ def test_a_text_written_atomically_gets_the_mode_a_plain_write_gives_and_leaves_nothing_beside_it(self, tmp_path: Path) -> None:
+ """A temporary file made private, as `mkstemp` makes one, would leave the renamed manifest readable by its owner only."""
+ plainly_written = tmp_path / "plain.json"
+ plainly_written.write_text("{}\n", encoding="utf-8")
+ atomically_written = tmp_path / "atomic.json"
+
+ write_text_atomically(destination=atomically_written, text="{}\n")
+
+ assert atomically_written.read_text(encoding="utf-8") == "{}\n"
+ assert atomically_written.stat().st_mode == plainly_written.stat().st_mode
+ assert sorted(path.name for path in tmp_path.iterdir()) == ["atomic.json", "plain.json"]
diff --git a/tests/unit/pipelex/system/pipelex_home/test_pipelex_home_readers.py b/tests/unit/pipelex/system/pipelex_home/test_pipelex_home_readers.py
index 36e4c6772..d7a9b824c 100644
--- a/tests/unit/pipelex/system/pipelex_home/test_pipelex_home_readers.py
+++ b/tests/unit/pipelex/system/pipelex_home/test_pipelex_home_readers.py
@@ -100,11 +100,13 @@ class TestEveryReaderFollows:
assert (empty_home / "pipelex.toml").is_file()
assert (empty_home / "inference" / "backends.toml").is_file()
- def test_the_first_boot_leaves_a_relocated_home_with_files_alone(self, relocated: Path) -> None:
+ def test_the_first_boot_keeps_a_relocated_home_s_files_and_fills_in_the_missing_ones(self, relocated: Path) -> None:
+ """The home's own files are kept, a missing kit file is added, and an inference setup of its own stays whole."""
ConfigLoader().ensure_global_config_exists()
assert (relocated / "pipelex.toml").read_text(encoding="utf-8") == "[relocated_marker]\nseen = true\n"
- assert not (relocated / "telemetry.toml").exists()
+ assert (relocated / "telemetry.toml").is_file()
+ assert sorted(path.name for path in (relocated / "inference").iterdir()) == ["backends.toml", "routing_profiles.toml"]
def test_pipelex_init_says_where_it_will_save_the_credentials(self, relocated: Path) -> None:
panel = build_initialization_panel(
diff --git a/tests/unit/pipelex/test_runtime_boot_closure.py b/tests/unit/pipelex/test_runtime_boot_closure.py
index 9bc3a0999..3fc37dd6e 100644
--- a/tests/unit/pipelex/test_runtime_boot_closure.py
+++ b/tests/unit/pipelex/test_runtime_boot_closure.py
@@ -129,19 +129,20 @@ STALE_TELEMETRY_OVERRIDE = 'telemetry_mode = "off"\n'
def _run_booted_runtime(
*,
interpreter_packages: "tuple[str, ...]",
- stale_home: Path | None = None,
+ home: Path,
+ expects_replay: bool = False,
) -> subprocess.CompletedProcess[str]:
"""Boot the kernel layer in a fresh interpreter and return the sweep's verdict.
- With `stale_home`, the subprocess runs with that directory as its home (both spellings, so
- `Path.home()` resolves to it on every platform), and the script additionally requires that the
+ The subprocess runs with `home` as its home directory (both spellings, so `Path.home()` resolves
+ to it on every platform), and every case passes a directory of its own under `tmp_path`. A boot
+ copies into the home configuration directory each kit file it lacks, so a subprocess left on the
+ developer's home would write into their real `~/.pipelex`; `PIPELEX_HOME` cannot move it, since
+ this module unsets the variable. With `expects_replay`, the script additionally requires that the
boot went through the migration replay.
"""
- env: dict[str, str] | None = None
- mode = "healthy"
- if stale_home is not None:
- env = {**os.environ, "HOME": str(stale_home), "USERPROFILE": str(stale_home)}
- mode = "expect-replay"
+ env = {**os.environ, "HOME": str(home), "USERPROFILE": str(home)}
+ mode = "expect-replay" if expects_replay else "healthy"
try:
return subprocess.run( # ruff: ignore[subprocess-without-shell-equals-true]
[sys.executable, "-c", _BOOTED_RUNTIME_SCRIPT, mode, *interpreter_packages],
@@ -157,9 +158,9 @@ def _run_booted_runtime(
class TestBootedKernelLayer:
- def test_the_sweep_still_detects_a_package_the_runtime_boot_really_loads(self) -> None:
+ def test_the_sweep_still_detects_a_package_the_runtime_boot_really_loads(self, tmp_path: Path) -> None:
"""The control: same script, opposite verdict. Without this, every other case is vacuous."""
- result = _run_booted_runtime(interpreter_packages=(CONTROL_PACKAGE_THE_RUNTIME_ALWAYS_LOADS,))
+ result = _run_booted_runtime(interpreter_packages=(CONTROL_PACKAGE_THE_RUNTIME_ALWAYS_LOADS,), home=tmp_path)
assert result.returncode == 1, (
f"treating {CONTROL_PACKAGE_THE_RUNTIME_ALWAYS_LOADS!r} as an interpreter package must fail — "
@@ -170,8 +171,9 @@ class TestBootedKernelLayer:
assert "interpreter module(s)" in result.stdout
assert "runtime boot OK" not in result.stdout
- def test_booting_the_kernel_layer_loads_no_interpreter_module_and_installs_no_interpreter_hub(self) -> None:
- result = _run_booted_runtime(interpreter_packages=INTERPRETER_PACKAGES)
+ def test_booting_the_kernel_layer_loads_no_interpreter_module_and_installs_no_interpreter_hub(self, tmp_path: Path) -> None:
+ """Booted from an empty home, as on a clean machine, so the developer's own configuration cannot steer it."""
+ result = _run_booted_runtime(interpreter_packages=INTERPRETER_PACKAGES, home=tmp_path)
assert result.returncode == 0, (
"booting the kernel layer must load zero interpreter modules and install no InterpreterHub.\n"
"This is the boot-time half of the hub-layering property — see docs/contribute/hub-layering.md "
@@ -186,7 +188,7 @@ class TestBootedKernelLayer:
global_config_dir.mkdir()
(global_config_dir / "telemetry_override.toml").write_text(STALE_TELEMETRY_OVERRIDE, encoding="utf-8")
- result = _run_booted_runtime(interpreter_packages=INTERPRETER_PACKAGES, stale_home=tmp_path)
+ result = _run_booted_runtime(interpreter_packages=INTERPRETER_PACKAGES, home=tmp_path, expects_replay=True)
assert result.returncode == 0, (
"a kernel-layer boot that replays the migration ledger over a stale file must load zero interpreter "
"modules. Exit 3 means the boot never reached the replay, so the fixture has stopped being stale.\n"