File size: 2,521 Bytes
e1ced61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
"""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",
)

# Roots that must never double as a large output 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 unset on some sandboxes
        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
    )