| """Environment-root resolution for the pipeline's four directory roots. |
| |
| The server exposes four roots (``docs/06_SERVER_RUNBOOK.md`` section 1): |
| |
| EXPLICIT_DATA_ROOT raw/normalized/generated data |
| EXPLICIT_MODEL_ROOT model weights |
| EXPLICIT_RUN_ROOT run artifacts (preflight, predictions, checkpoints) |
| EXPLICIT_CACHE_ROOT venvs and other non-artifact caches |
| |
| Paths in artifacts are always repo-relative or root-relative, never absolute, so |
| outputs reproduce across mounts. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import os |
| from pathlib import Path |
|
|
| ROOT_ENV_VARS = ( |
| "EXPLICIT_DATA_ROOT", |
| "EXPLICIT_MODEL_ROOT", |
| "EXPLICIT_RUN_ROOT", |
| "EXPLICIT_CACHE_ROOT", |
| ) |
|
|
| |
| _FORBIDDEN_ROOT_HINTS = ("/tmp", "/var/tmp") |
|
|
|
|
| class EnvError(RuntimeError): |
| """Raised when a required environment root is missing or invalid.""" |
|
|
|
|
| def repo_root() -> Path: |
| """Return the repository root (the directory containing ``pyproject.toml``).""" |
| return Path(__file__).resolve().parents[2] |
|
|
|
|
| def get_root(name: str) -> Path: |
| """Return the path for an ``EXPLICIT_*`` root, raising if unset.""" |
| value = os.environ.get(name) |
| if not value: |
| raise EnvError(f"{name} is not set") |
| return Path(value).expanduser() |
|
|
|
|
| def data_root() -> Path: |
| return get_root("EXPLICIT_DATA_ROOT") |
|
|
|
|
| def model_root() -> Path: |
| return get_root("EXPLICIT_MODEL_ROOT") |
|
|
|
|
| def run_root() -> Path: |
| return get_root("EXPLICIT_RUN_ROOT") |
|
|
|
|
| def cache_root() -> Path: |
| return get_root("EXPLICIT_CACHE_ROOT") |
|
|
|
|
| def all_roots() -> dict[str, Path]: |
| """Return a dict of every root name to its path (raises if any unset).""" |
| return {name: get_root(name) for name in ROOT_ENV_VARS} |
|
|
|
|
| def missing_roots() -> list[str]: |
| """Return the names of required roots that are unset or empty.""" |
| return [name for name in ROOT_ENV_VARS if not os.environ.get(name)] |
|
|
|
|
| def is_forbidden_root(path: Path) -> bool: |
| """True when ``path`` is /tmp, the user home, or inside the repository.""" |
| resolved = path.resolve() |
| try: |
| resolved.relative_to(repo_root()) |
| return True |
| except ValueError: |
| pass |
| try: |
| home = Path.home() |
| except (RuntimeError, OSError): |
| home = None |
| if home is not None and resolved == home: |
| return True |
| return any( |
| resolved == Path(hint) or str(resolved).startswith(hint.rstrip("/") + "/") |
| for hint in _FORBIDDEN_ROOT_HINTS |
| ) |
|
|