Skip to content

livery.extensions.pytest._observer

livery.extensions.pytest._observer

Pure-stdlib runtime observer hook for recording what a test item reads.

Loaded into every Python process of an observed test item through a .pth file (PTH_NAME) installed in the environment's site-packages. When OBSERVER_VARIABLE is unset the .pth file imports nothing and costs a single environment lookup. When armed, start() attaches a coarse sys.addaudithook (file opens, directory listings, subprocess spawns) and an atexit flush that records imported first-party modules and top-level import names without importing pathlib, dataclasses, importlib.metadata, livery.workshop, or pytest.

Classes:

Name Description
RawReads

Collected reads across a test item's process tree, ready for ItemReadSet.

Functions:

Name Description
ensure_pth

Idempotently install PTH_NAME into site_packages (or active purelib).

normalize_repo_path

Normalize raw to a canonical POSIX path relative to root, or None.

start

Arm the observer for this process when OBSERVER_VARIABLE is set.

collect_raw_reads

Merge every process trace in out_dir into one RawReads for item.

Attributes:

Name Type Description
TYPE_CHECKING
OBSERVER_VARIABLE
PTH_NAME
PTH_CONTENT

TYPE_CHECKING module-attribute

TYPE_CHECKING = False

OBSERVER_VARIABLE module-attribute

OBSERVER_VARIABLE = 'LIVERY_OBSERVER'

PTH_NAME module-attribute

PTH_NAME = 'z1_livery_pytest_observer.pth'

PTH_CONTENT module-attribute

PTH_CONTENT = f'import os; os.getenv("{OBSERVER_VARIABLE}") and __import__("livery.extensions.pytest._observer", fromlist=["start"]).start()\n'

RawReads

RawReads(*, files: dict[str, str], absent: tuple[str, ...], dirs: dict[str, str], dists: dict[str, str], native_tools: tuple[str, ...], unrecorded: bool)

Collected reads across a test item's process tree, ready for ItemReadSet.

Attributes:

Name Type Description
__slots__
files
absent
dirs
dists
native_tools
unrecorded
Source code in packages/extensions/pytest/src/livery/extensions/pytest/_observer.py
def __init__(
    self,
    *,
    files: dict[str, str],
    absent: tuple[str, ...],
    dirs: dict[str, str],
    dists: dict[str, str],
    native_tools: tuple[str, ...],
    unrecorded: bool,
) -> None:
    self.files = files
    self.absent = absent
    self.dirs = dirs
    self.dists = dists
    self.native_tools = native_tools
    self.unrecorded = unrecorded

__slots__ class-attribute instance-attribute

__slots__ = ('absent', 'dirs', 'dists', 'files', 'native_tools', 'unrecorded')

files instance-attribute

files = files

absent instance-attribute

absent = absent

dirs instance-attribute

dirs = dirs

dists instance-attribute

dists = dists

native_tools instance-attribute

native_tools = native_tools

unrecorded instance-attribute

unrecorded = unrecorded

ensure_pth

ensure_pth(site_packages: Path | None = None) -> Path

Idempotently install PTH_NAME into site_packages (or active purelib).

Source code in packages/extensions/pytest/src/livery/extensions/pytest/_observer.py
def ensure_pth(site_packages: Path | None = None) -> Path:
    """Idempotently install `PTH_NAME` into *site_packages* (or active purelib)."""
    from pathlib import Path

    if site_packages is not None:
        target_dir = site_packages
    else:
        import sysconfig

        target_dir = Path(sysconfig.get_path("purelib"))
    target = target_dir / PTH_NAME
    if target.is_file() and target.read_text(encoding="utf-8") == PTH_CONTENT:
        return target
    target_dir.mkdir(parents=True, exist_ok=True)
    tmp = target_dir / f".{PTH_NAME}.{os.getpid()}.tmp"
    tmp.write_text(PTH_CONTENT, encoding="utf-8")
    os.replace(tmp, target)
    return target

normalize_repo_path

normalize_repo_path(raw: str | bytes | PathLike[str] | PathLike[bytes], root: Path, *, windows: bool | None = None, real_case: Callable[[Path], Path] | None = None, allow_root: bool = False) -> str | None

Normalize raw to a canonical POSIX path relative to root, or None.

Drops Windows \\?\ prefixes, compares drive letters and paths case-insensitively on Windows, treats Windows junctions like symlinks, recovers on-disk case when present, and returns None for paths outside root or under ignored cache/VCS directories.

Source code in packages/extensions/pytest/src/livery/extensions/pytest/_observer.py
def normalize_repo_path(
    raw: str | bytes | os.PathLike[str] | os.PathLike[bytes],
    root: Path,
    *,
    windows: bool | None = None,
    real_case: Callable[[Path], Path] | None = None,
    allow_root: bool = False,
) -> str | None:
    r"""Normalize *raw* to a canonical POSIX path relative to *root*, or ``None``.

    Drops Windows ``\\?\`` prefixes, compares drive letters and paths
    case-insensitively on Windows, treats Windows junctions like symlinks,
    recovers on-disk case when present, and returns ``None`` for paths
    outside *root* or under ignored cache/VCS directories.
    """
    from pathlib import PosixPath, PureWindowsPath, WindowsPath

    text = os.fsdecode(raw)
    if not text:
        return None
    is_win = (
        windows
        if windows is not None
        else (_HOST_IS_NT or _looks_windows(text) or _looks_windows(str(root)))
    )
    cleaned = _strip_windows_prefix(text)
    root_text = _strip_windows_prefix(str(root))

    if is_win and not _HOST_IS_NT:
        win_root = PureWindowsPath(root_text)
        win_raw = PureWindowsPath(cleaned)
        if not win_raw.is_absolute():
            win_raw = win_root / win_raw
        return _relative_from_parts(
            _win_norm_parts(win_raw),
            _win_norm_parts(win_root),
            case_insensitive=True,
            allow_root=allow_root,
        )

    host_path = WindowsPath if _HOST_IS_NT else PosixPath
    candidate = host_path(cleaned)
    if not candidate.is_absolute():
        candidate = host_path.cwd() / candidate
    resolved_root = _resolve_with_junctions(host_path(root_text))
    resolved_path = _resolve_with_junctions(candidate)
    if real_case is not None:
        resolved_path = real_case(resolved_path)
    return _relative_from_parts(
        resolved_path.parts,
        resolved_root.parts,
        case_insensitive=is_win,
        allow_root=allow_root,
    )

start

start() -> bool

Arm the observer for this process when OBSERVER_VARIABLE is set.

Source code in packages/extensions/pytest/src/livery/extensions/pytest/_observer.py
def start() -> bool:
    """Arm the observer for this process when `OBSERVER_VARIABLE` is set."""
    global _ACTIVE
    if _ACTIVE:
        return False
    config_path = os.environ.get(OBSERVER_VARIABLE, "").strip()
    if not config_path:
        return False
    try:
        with open(config_path, encoding="utf-8") as handle:
            config = json.load(handle)
    except (OSError, ValueError):
        return False
    if not isinstance(config, dict):
        return False
    root_raw = config.get("root")
    out_raw = config.get("out")
    if not isinstance(root_raw, str) or not isinstance(out_raw, str):
        return False
    if not os.path.isdir(out_raw):
        return False
    observer = _ProcessObserver(root_raw, out_raw)
    _ACTIVE = True
    observer.write_alive()
    sys.addaudithook(observer.audit)
    atexit.register(observer.flush)
    return True

collect_raw_reads

collect_raw_reads(out_dir: Path, root: Path, item: str) -> RawReads

Merge every process trace in out_dir into one RawReads for item.

Source code in packages/extensions/pytest/src/livery/extensions/pytest/_observer.py
def collect_raw_reads(out_dir: Path, root: Path, item: str) -> RawReads:
    """Merge every process trace in *out_dir* into one `RawReads` for *item*."""
    import hashlib

    procs: list[dict[str, Any]] = []
    alive_pids: set[int] = set()
    for flag in sorted(out_dir.glob("alive-*-*.flag")):
        parts = flag.stem.split("-")
        if len(parts) == 3 and parts[1].isdigit() and parts[2].isdigit():
            alive_pids.add(int(parts[1]))
    for trace in sorted(out_dir.glob("proc-*-*.json")):
        try:
            data = json.loads(trace.read_text(encoding="utf-8"))
        except (OSError, ValueError):
            continue
        if isinstance(data, dict):
            procs.append(data)
            pid = int(data.get("pid", 0))
            if pid:
                alive_pids.add(pid)

    all_files: set[str] = set()
    all_dirs: set[str] = set()
    all_dists: dict[str, str] = {}
    all_tops: set[str] = set()
    all_tools: set[str] = set()
    unrecorded = not procs
    total_spawned = 0
    for proc in procs:
        all_files.update(str(p) for p in proc.get("files", ()))
        all_dirs.update(str(d) for d in proc.get("dirs", ()))
        raw_tops = proc.get("imported-tops")
        if isinstance(raw_tops, list):
            all_tops.update(str(t) for t in raw_tops)
        all_tools.update(str(t) for t in proc.get("native-tools", ()))
        if proc.get("lost-child-hook"):
            unrecorded = True
        total_spawned += int(proc.get("spawned-python-children", 0))
    if all_tops:
        by_top = _dist_versions_by_top()
        for top in sorted(all_tops):
            for norm, ver in by_top.get(top, ()):
                all_dists.setdefault(norm, ver)
        if all_dists:
            all_dists = _expand_dist_closure(all_dists, _dist_dependency_graph())
    # Every spawned Python child must register in out_dir (counting by distinct
    # alive PIDs rather than direct PPID so Windows venv launcher shims do not
    # break the parent-child link).
    if total_spawned > 0 and len(alive_pids) < 1 + total_spawned:
        unrecorded = True

    norm_item = item.replace("\\", "/").lstrip("./")
    all_files.add(norm_item)

    present_files: dict[str, str] = {}
    absent_files: list[str] = []
    for rel in sorted(all_files):
        full = root / rel
        if full.is_file():
            present_files[rel] = hashlib.sha256(full.read_bytes()).hexdigest()
        elif not full.exists():
            absent_files.append(rel)

    dir_digests = {rel: _dir_digest(root, rel) for rel in sorted(all_dirs)}
    return RawReads(
        files=present_files,
        absent=tuple(absent_files),
        dirs=dir_digests,
        dists=dict(sorted(all_dists.items())),
        native_tools=tuple(sorted(all_tools)),
        unrecorded=unrecorded,
    )