Skip to content

livery.extensions.python._backend

livery.extensions.python._backend

Build, version, publish and test a python distribution: the python extension's code.

The python extension's answers and steps call the functions here, so a package whose set holds python builds, stamps, publishes and runs its tests through them. The suites of every package a run judges run in one pytest call.

Functions:

Name Description
public_modules

The modules that declare package's public API.

module_for

The package's importable module, read from its src tree.

current_version

The version the package's pyproject.toml declares.

stamp_version

Where a Python package's version lives, ready to stamp.

stamp

Write version and raise package's floors in its manifests; the files changed.

raise_floors

Raise each requirement on a member released with package; the files changed.

test

Run package's tests: its suite, or the files in selection alone.

examples_of

The example files package ships under docs/examples/, sorted.

run_examples

Run package's documentation examples, one test per file; arguments to pytest.

runner_shaped

env with the runner's variables set, as the check legs see the suite.

run_test

Run the suites of packages in one pytest call, pytest_args unchanged.

speed_lines

Each package's summed test time; on a check leg, beside its mark there.

module_roots

The import prefixes package owns.

root_marks

The files that mark an importable root under src, shallowest first.

scripts

The scripts package's pyproject.toml names under [project.scripts].

run_script

Start the script name from the workspace's environment; its exit code.

plugin_hosts

Each module package names in a plugin group, to the programs that load it.

plugin_reaches

Each changed path pytest loads as a plugin, to why, and every member pytest runs.

plugin_modules

The modules package declares as footman task entry points.

references

What each python source of package references, one record per file.

declared_requirements

The package's declared dependencies, name to constraint text.

declared_test_requirements

The package's test extra, name to constraint text.

declare_requirement

Add <dependency>>=<floor> to the project's dependencies; the files changed.

declare_test_requirement

Write <dependency>>=<floor> into the test extra; the files changed.

module_docs_dir

Where package's wheel-embedded _docs lives; None without a module.

materialise_module_docs

Copy the package's docs/ into its wheel-embedded _docs, whole.

module_docs

The wheel-embedded _docs, in the source tree for one build alone.

build

Build package's wheel and sdist into its dist/; the dist dir.

publish_artifact

Upload dist/* to the python index: python's publish step calls it.

publish_wheels

Upload dist/*; False when everything was already published.

isolated_test

Test package's built wheel in a fresh venv at resolution; what it got.

verify

Install package's released version alone and run its tests at tree.

run_isolated_test

Install the built wheel into a fresh venv and test the installed copy.

Attributes:

Name Type Description
EXTENSION
PURE_TAG
RUNNER_VARIABLES
COVERAGE_CONFIG
METER
PREVIEW Query[Callable[[Path, tuple[Package, ...]], None] | None]
RUNNER_DISTRIBUTION
PLUGIN_GROUPS Mapping[str, str]
PYTEST
PYTEST_STEPS
TEST_EXTRA
RESOLUTIONS dict[str, tuple[str, bool]]

EXTENSION module-attribute

EXTENSION = 'python'

PURE_TAG module-attribute

PURE_TAG = '-none-any.whl'

RUNNER_VARIABLES module-attribute

RUNNER_VARIABLES = ('CI', 'GITHUB_ACTIONS')

COVERAGE_CONFIG module-attribute

COVERAGE_CONFIG = '.coveragerc'

METER module-attribute

METER = 'COVERAGE_PROCESS_START'

PREVIEW module-attribute

PREVIEW: Query[Callable[[Path, tuple[Package, ...]], None] | None] = Query('python.test.preview')

RUNNER_DISTRIBUTION module-attribute

RUNNER_DISTRIBUTION = 'livery-footman'

PLUGIN_GROUPS module-attribute

PLUGIN_GROUPS: Mapping[str, str] = {'footman.tasks': RUNNER_DISTRIBUTION, 'footman.builtin': RUNNER_DISTRIBUTION, 'pytest11': 'pytest'}

PYTEST module-attribute

PYTEST = 'pytest'

PYTEST_STEPS module-attribute

PYTEST_STEPS = ('test.pytest', 'examples.pytest')

TEST_EXTRA module-attribute

TEST_EXTRA = 'test'

RESOLUTIONS module-attribute

RESOLUTIONS: dict[str, tuple[str, bool]] = {'floor': ('lowest-direct', False), 'latest': ('highest', False), 'head': ('highest', True)}

public_modules

public_modules(package: Package) -> tuple[str, ...]

The modules that declare package's public API.

A root that is a regular package, or a single module, is its own declaration. A public package beneath a root keeps its own import path and is declared in the root's __init__ as well, imported for the checkers alone and listed in __all__: the verifier follows the declaration into it, reading the py.typed at the distribution's root. A namespace root, one with no __init__, declares nothing; a package with no src tree is its distribution name's module.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def public_modules(package: Package) -> tuple[str, ...]:
    """The modules that declare *package*'s public API.

    A root that is a regular package, or a single module, is its own
    declaration. A public package beneath a root keeps its own import
    path and is declared in the root's ``__init__`` as well, imported
    for the checkers alone and listed in ``__all__``: the verifier
    follows the declaration into it, reading the ``py.typed`` at the
    distribution's root. A namespace root, one with no ``__init__``,
    declares nothing; a package with no src tree is its distribution
    name's module.
    """
    src = package.directory / "src"
    if not src.is_dir():
        return (module_for(package),)
    modules: list[str] = []
    for root in module_roots(package) or (module_for(package),):
        directory = src.joinpath(*root.split("."))
        if (directory / "__init__.py").is_file() or directory.with_suffix(
            ".py"
        ).is_file():
            modules.append(root)
    return tuple(modules)

module_for

module_for(package: Package) -> str

The package's importable module, read from its src tree.

The single-directory chain under src/ down to the first directory carrying python files is the module (src/livery/forge is livery.forge). Deriving it from the distribution name guessed wrong the moment a member's own name carried a hyphen: loop-echo under a workspace prefix became loop.echo, a module that does not exist. A package without a src tree, or whose src/ holds no single directory to start the chain, falls back to the dist-name spelling, underscores for hyphens beyond the namespace dot.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def module_for(package: Package) -> str:
    """The package's importable module, read from its src tree.

    The single-directory chain under ``src/`` down to the first
    directory carrying python files is the module
    (``src/livery/forge`` is ``livery.forge``). Deriving it from the
    distribution name guessed wrong the moment a member's own name
    carried a hyphen: ``loop-echo`` under a workspace prefix became
    ``loop.echo``, a module that does not exist. A package without a
    src tree, or whose ``src/`` holds no single directory to start the
    chain, falls back to the dist-name spelling, underscores for
    hyphens beyond the namespace dot.
    """
    src = package.directory / "src"
    if src.is_dir():
        parts: list[str] = []
        node = src
        while True:
            dirs = [d for d in node.iterdir() if d.is_dir() and d.name.isidentifier()]
            has_py = any(f.suffix == ".py" for f in node.iterdir() if f.is_file())
            if parts and (has_py or len(dirs) != 1):
                return ".".join(parts)
            if len(dirs) != 1:
                break
            node = dirs[0]
            parts.append(node.name)
    head, _, tail = package.name.partition("-")
    if not tail:
        return head
    return head + "." + tail.replace("-", "_")

current_version

current_version(package: Package) -> str

The version the package's pyproject.toml declares.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def current_version(package: Package) -> str:
    """The version the package's ``pyproject.toml`` declares."""
    data = tomllib.loads((package.directory / "pyproject.toml").read_text("utf-8"))
    return str(data.get("project", {}).get("version", "0.0.0"))

stamp_version

stamp_version(package: Package) -> _Stamper

Where a Python package's version lives, ready to stamp.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def stamp_version(package: Package) -> _Stamper:
    """Where a Python package's version lives, ready to stamp."""
    return _Stamper(package)

stamp

stamp(package: Package, version: str, floors: Mapping[str, str]) -> list[str]

Write version and raise package's floors in its manifests; the files changed.

The version goes into pyproject.toml and every __version__ (stamp_version), and each requirement on one of floors, the members released with package, takes that member's version (raise_floors). Each file once, relative to the package's directory.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def stamp(package: Package, version: str, floors: Mapping[str, str]) -> list[str]:
    """Write *version* and raise *package*'s floors in its manifests; the files changed.

    The version goes into ``pyproject.toml`` and every ``__version__``
    (`stamp_version`), and each requirement on one of *floors*, the
    members released with *package*, takes that member's version
    (`raise_floors`). Each file once, relative to the package's
    directory.
    """
    changed = stamp_version(package).stamp(version)
    changed += raise_floors(package, floors)
    return list(dict.fromkeys(changed))

raise_floors

raise_floors(package: Package, floors: Mapping[str, str]) -> list[str]

Raise each requirement on a member released with package; the files changed.

floors names each such member by its path, to the version it releases at. A requirement on its distribution in pyproject.toml, "<name>>=<floor>" wherever the file declares it (its dependencies, its extras, its groups), takes that version. Empty for no floors, and for a pyproject that names none of them.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def raise_floors(package: Package, floors: Mapping[str, str]) -> list[str]:
    """Raise each requirement on a member released with *package*; the files changed.

    *floors* names each such member by its path, to the version it
    releases at. A requirement on its distribution in
    ``pyproject.toml``, ``"<name>>=<floor>"`` wherever the file
    declares it (its dependencies, its extras, its groups), takes that
    version. Empty for no floors, and for a pyproject that names none of
    them.
    """
    if not floors:
        return []
    from livery.workshop import discover_packages

    names = {
        member.name: floors[member.path]
        for member in discover_packages(package.root)
        if member.path in floors and member.path != package.path
    }
    pyproject = package.directory / "pyproject.toml"
    text = original = pyproject.read_text("utf-8")
    for name, version in names.items():
        text = re.sub(
            rf'("{re.escape(name)}\s*>=\s*)[0-9][^"]*(")',
            rf"\g<1>{version}\g<2>",
            text,
        )
    if text == original:
        return []
    pyproject.write_text(text, encoding="utf-8")
    return ["pyproject.toml"]

test

test(package: Package, root: Path, *, selection: tuple[str, ...] = (), arguments: tuple[str, ...] = ()) -> None

Run package's tests: its suite, or the files in selection alone.

arguments go to pytest after the workshop's own.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def test(
    package: Package,
    root: Path,
    *,
    selection: tuple[str, ...] = (),
    arguments: tuple[str, ...] = (),
) -> None:
    """Run *package*'s tests: its suite, or the files in *selection* alone.

    *arguments* go to pytest after the workshop's own.
    """
    files = tuple(f"{package.path}/{path}" for path in selection)
    run_test(
        *arguments,
        packages=(package,),
        root=root,
        selection={package.path: files} if files else None,
    )

examples_of

examples_of(package: Package) -> list[Path]

The example files package ships under docs/examples/, sorted.

A conftest.py there is the package's setup around them, never an example.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def examples_of(package: Package) -> list[Path]:
    """The example files *package* ships under ``docs/examples/``, sorted.

    A ``conftest.py`` there is the package's setup around them, never
    an example.
    """
    base = package.directory / "docs" / "examples"
    if not base.is_dir():
        return []
    return sorted(path for path in base.rglob("*.py") if path.name != "conftest.py")

run_examples

run_examples(package: Package, root: Path, files: tuple[str, ...] = (), arguments: tuple[str, ...] = ()) -> None

Run package's documentation examples, one test per file; arguments to pytest.

Pytest over the package's docs/examples/ directory, or over files alone when every one of them is an example, whose files the workshop's examples plugin collects (livery.workshop.is_example), from the workspace root so the workspace's pytest configuration applies. A named file that is no example, the examples' conftest.py, is every example's setup, so the whole directory runs. Captured and printed on a red exit, so a runner's log carries the failing example's file and line; a package without examples says so and passes.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def run_examples(
    package: Package,
    root: Path,
    files: tuple[str, ...] = (),
    arguments: tuple[str, ...] = (),
) -> None:
    """Run *package*'s documentation examples, one test per file; *arguments* to pytest.

    Pytest over the package's ``docs/examples/`` directory, or over
    *files* alone when every one of them is an example, whose files
    the workshop's examples plugin collects
    ([livery.workshop.is_example][]), from the workspace root so
    the workspace's pytest configuration applies. A named file that is
    no example, the examples' ``conftest.py``, is every example's
    setup, so the whole directory runs. Captured and printed on a red
    exit, so a runner's log carries the failing example's file and
    line; a package without examples says so and passes.
    """
    from livery.workshop import is_example

    if not examples_of(package):
        print(f"  examples: {package.path} has none")
        return
    named = tuple(name for name in files if is_example(Path(name)))
    targets = (
        named
        if files and len(named) == len(files)
        else (f"{package.path}/docs/examples",)
    )
    result = pytest.opts(in_process=False, cwd=root, nofail=True)(*targets, *arguments)
    if result.code != 0:
        print(result.stdout, end="")
        print(result.stderr, end="")
        fail(f"examples of {package.path}: pytest exited {result.code}")

runner_shaped

runner_shaped(env: Mapping[str, str]) -> dict[str, str]

env with the runner's variables set, as the check legs see the suite.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def runner_shaped(env: Mapping[str, str]) -> dict[str, str]:
    """*env* with the runner's variables set, as the check legs see the suite."""
    return {**env, **dict.fromkeys(RUNNER_VARIABLES, "true")}

run_test

run_test(*pytest_args: str, packages: tuple[Package, ...], root: Path, selection: Mapping[str, tuple[str, ...]] | None = None, point: str = '', measured: bool = False) -> None

Run the suites of packages in one pytest call, pytest_args unchanged.

The call collects each package's own test directory, the workspace's own tests when their unit is among packages, and nothing else, so a package a run leaves out is never collected; selection names, per package path, the test files that stand for the package's directory. point selects that CI point's tests, through the workshop's points plugin. A measured run measures coverage over the namespace the configuration names: inside CI the tests run metered for the gate job's union, and on a machine the run prints the preview a listed extension answers python.test.preview with (livery.extensions.python._backend.PREVIEW), the coverage extension's figure beside each floor, or none. A run that is not measured runs no meter and prints no preview. A machine's run sets the runner's variables (RUNNER_VARIABLES), so the suite is judged the way the legs judge it. With no test directory among the packages no pytest starts, since one handed no path would collect the whole configuration.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def run_test(
    *pytest_args: str,
    packages: tuple[Package, ...],
    root: Path,
    selection: Mapping[str, tuple[str, ...]] | None = None,
    point: str = "",
    measured: bool = False,
) -> None:
    """Run the suites of *packages* in one pytest call, *pytest_args* unchanged.

    The call collects each package's own test directory, the
    workspace's own tests when their unit is among *packages*, and
    nothing else, so a package a run leaves out is never collected;
    *selection* names, per package path, the test files that stand for
    the package's directory. *point* selects that CI point's tests,
    through the workshop's points plugin. A *measured* run measures
    coverage over the namespace the configuration names: inside CI the
    tests run metered for the gate job's union, and on a machine the
    run prints the preview a listed extension answers
    ``python.test.preview`` with
    ([livery.extensions.python._backend.PREVIEW][]), the coverage
    extension's figure beside each floor, or none. A run that is not
    measured runs no meter and prints no preview. A machine's run sets
    the runner's variables (`RUNNER_VARIABLES`), so the suite is judged
    the way the legs judge it. With no test directory among the
    packages no pytest starts, since one handed no path would collect
    the whole configuration.
    """
    from livery.workshop import WORKSPACE_TESTS

    if point:
        pytest_args = (*pytest_args, f"--workshop-point={point}")
    chosen = selection or {}
    picked: list[str] = []
    for package in packages:
        # The workspace's own tests are a unit whose directory is its
        # own: the leg stores them keyed by the whole tree.
        unit = package.path == WORKSPACE_TESTS
        tests = package.directory if unit else package.directory / "tests"
        if tests.is_dir():
            own = package.path if unit else f"{package.path}/tests"
            picked.extend(chosen.get(package.path) or (own,))
    dirs = tuple(picked)
    if not dirs:
        names = ", ".join(package.path for package in packages)
        print(f"  tests: no test directory in {names}; nothing to collect")
        return
    from livery.workshop import SPEED_FILE_VARIABLE, ci_run

    run = ci_run()
    with tempfile.TemporaryDirectory() as scratch:
        # The workshop's speed plugin sums each package's test time
        # into this file; the sums print beside the marks afterwards,
        # on a red run too.
        sums = Path(scratch) / "speed.json"
        env = {**os.environ, SPEED_FILE_VARIABLE: str(sums)}
        try:
            if run is not None:
                # Inside CI a measured run meters the tests, and only
                # them. Coverage's own subprocess variable is armed in
                # pytest's environment, never in the gate's own, so
                # every python the tests start inherits it (the xdist
                # workers, the runner's children a test spawns in a
                # fixture workspace) and the driver that decides what
                # to run records nothing: a line counts only when a
                # test reached it, whatever the gate ran around the
                # tests. The test extension's pytest plugin names each
                # test's context in that run, the leg splits the one
                # run's data per suite, and the floors are judged
                # once, on the union, in the gate job. Captured, and
                # printed on a red exit: the job's log is the run's
                # evidence and nothing else in a runner shows a red
                # test's words. Captured rather than streamed because a
                # captured child gets its own hidden console on Windows,
                # where a streamed one shares the runner's and a control
                # event a worker raises would interrupt the runner too.
                armed = {**env, METER: str(root / COVERAGE_CONFIG)} if measured else env
                result = pytest.opts(in_process=False, env=armed, nofail=True)(
                    *dirs, *pytest_args
                )
                if result.code != 0:
                    print(result.stdout, end="")
                    print(result.stderr, end="")
                    fail(f"pytest exited {result.code}")
            else:
                # Bare --cov on a measured run: the measured source is
                # the configuration's `[run] source`, the namespace the
                # render derived, never a spelled module. The runner's
                # variables are set, so a test that reads them is
                # judged here as on the leg.
                metered = ("--cov", "--cov-report=") if measured else ()
                pytest.opts(in_process=False, env=runner_shaped(env))(
                    *dirs, *metered, *pytest_args
                )
        finally:
            for line in speed_lines(root, sums, leg=run.leg if run else ""):
                print(line)
    if run is None and measured:
        from livery.workshop import answer

        preview = answer(root, PREVIEW)
        if preview is not None:
            preview(root, packages)

speed_lines

speed_lines(root: Path, sums: Path, *, leg: str = '') -> list[str]

Each package's summed test time; on a check leg, beside its mark there.

sums is the file the speed plugin wrote; no file means the plugin did not run. With leg the run is a check leg's, and each line carries the package's mark on that leg or says there is none; an unreadable store says so once and the times still print. Without leg the run is a machine's: the times print alone, since the marks are judged on the CI legs and a machine's clock is not one of them, and nothing here reads the store.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def speed_lines(root: Path, sums: Path, *, leg: str = "") -> list[str]:
    """Each package's summed test time; on a check leg, beside its mark there.

    *sums* is the file the speed plugin wrote; no file means the
    plugin did not run. With *leg* the run is a check leg's, and each
    line carries the package's mark on that leg or says there is
    none; an unreadable store says so once and the times still print.
    Without *leg* the run is a machine's: the times print alone,
    since the marks are judged on the CI legs and a machine's clock
    is not one of them, and nothing here reads the store.
    """
    from livery.workshop import speed_marks

    if not sums.is_file():
        return []
    try:
        loaded = json.loads(sums.read_text("utf-8"))
    except (OSError, ValueError):
        return []
    if not isinstance(loaded, dict) or not loaded:
        return []
    current: dict[tuple[str, str], SpeedMark] | None = None
    lines: list[str] = []
    if leg:
        current, why = speed_marks(root)
        if current is None:
            lines.append(f"  speed marks: not read ({why})")
    for package, data in sorted(loaded.items()):
        if not isinstance(data, dict):
            continue
        seconds = float(data.get("seconds", 0.0))
        tests = int(data.get("tests", 0))
        if not leg:
            beside = "judged on the CI legs"
        elif current is None:
            beside = "mark unknown"
        else:
            mark = current.get((str(package), leg))
            beside = (
                f"mark {mark.seconds:.1f}s on {leg}"
                if mark is not None
                else f"no mark on {leg}"
            )
        lines.append(f"  speed {package}: {seconds:.1f}s over {tests} tests ({beside})")
    return lines

module_roots

module_roots(package: Package) -> tuple[str, ...]

The import prefixes package owns.

The build backend's module-name where the manifest declares one, since that is what the wheel ships. Otherwise each topmost directory under src holding an __init__.py on its branch, which finds nothing under a namespace root, one with no public names. Never derived from the distribution name: three distributions share the livery.toolroom namespace, so a transformed name would attribute two of them to the third. A package with no python source owns nothing.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def module_roots(package: Package) -> tuple[str, ...]:
    """The import prefixes *package* owns.

    The build backend's ``module-name`` where the manifest declares
    one, since that is what the wheel ships. Otherwise each topmost
    directory under ``src`` holding an ``__init__.py`` on its branch,
    which finds nothing under a namespace root, one with no public
    names. Never derived
    from the distribution name: three distributions share the
    ``livery.toolroom`` namespace, so a transformed name would
    attribute two of them to the third. A package with no python
    source owns nothing.
    """
    src = package.directory / "src"
    if not src.is_dir():
        return ()
    declared = _declared_modules(package)
    if declared:
        return declared
    roots: list[str] = []
    for init in root_marks(src):
        dotted = ".".join(init.relative_to(src).parts[:-1])
        if not dotted:
            continue
        if any(dotted == root or dotted.startswith(root + ".") for root in roots):
            continue
        roots.append(dotted)
    return tuple(sorted(roots))

root_marks

root_marks(src: Path) -> list[Path]

The files that mark an importable root under src, shallowest first.

A root carries an __init__.py; the topmost on a branch is that branch's root. A namespace, one with no __init__.py, marks nothing.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def root_marks(src: Path) -> list[Path]:
    """The files that mark an importable root under *src*, shallowest first.

    A root carries an ``__init__.py``; the topmost on a branch is that
    branch's root. A namespace, one with no ``__init__.py``, marks
    nothing.
    """
    return sorted(src.rglob("__init__.py"), key=lambda path: (len(path.parts), path))

scripts

scripts(package: Package) -> tuple[str, ...]

The scripts package's pyproject.toml names under [project.scripts].

Each by the name its installation puts on PATH, in the file's order; empty for a package without the file or the table.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def scripts(package: Package) -> tuple[str, ...]:
    """The scripts *package*'s ``pyproject.toml`` names under ``[project.scripts]``.

    Each by the name its installation puts on PATH, in the file's
    order; empty for a package without the file or the table.
    """
    pyproject = package.directory / "pyproject.toml"
    if not pyproject.is_file():
        return ()
    data = tomllib.loads(pyproject.read_text("utf-8"))
    return tuple(str(name) for name in data.get("project", {}).get("scripts", {}))

run_script

run_script(package: Package, root: Path, name: str, arguments: tuple[str, ...]) -> int

Start the script name from the workspace's environment; its exit code.

The script is the one fm sync installs into the .venv at root, started with arguments and the console shared.

Raises:

Type Description
Failed

when the environment holds no script of that name, naming the directory and the verb that installs it.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def run_script(
    package: Package, root: Path, name: str, arguments: tuple[str, ...]
) -> int:
    """Start the script *name* from the workspace's environment; its exit code.

    The script is the one ``fm sync`` installs into the ``.venv`` at
    *root*, started with *arguments* and the console shared.

    Raises:
        Failed: when the environment holds no script of that name,
            naming the directory and the verb that installs it.
    """
    from livery.workshop import scripts_dir

    directory = scripts_dir(root / ".venv")
    script = directory / (f"{name}.exe" if sys.platform == "win32" else name)
    if not script.is_file():
        fail(
            f"{package.path}: {directory} holds no script {name};"
            f" `{footman.prog()} sync` installs the workspace's packages there"
        )
    return footman.run([str(script), *arguments], capture=False, nofail=True).code

plugin_hosts

plugin_hosts(package: Package) -> dict[str, frozenset[str]]

Each module package names in a plugin group, to the programs that load it.

Read from the [project.entry-points] tables of the package's pyproject.toml, for the groups PLUGIN_GROUPS names, each program by its distribution. A module under one of these modules is loaded with it. Empty for a package that names none.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def plugin_hosts(package: Package) -> dict[str, frozenset[str]]:
    """Each module *package* names in a plugin group, to the programs that load it.

    Read from the ``[project.entry-points]`` tables of the package's
    ``pyproject.toml``, for the groups ``PLUGIN_GROUPS`` names, each
    program by its distribution. A module under one of these modules
    is loaded with it. Empty for a package that names none.
    """
    pyproject = package.directory / "pyproject.toml"
    if not pyproject.is_file():
        return {}
    return _hosts_in(pyproject.read_text("utf-8"))

plugin_reaches

plugin_reaches(changes: Changes) -> dict[str, tuple[str, tuple[str, ...]]]

Each changed path pytest loads as a plugin, to why, and every member pytest runs.

pytest loads every module a member's pyproject.toml names in a group PLUGIN_GROUPS gives it into every session it starts, so a change to one reaches every member a step of PYTEST_STEPS runs pytest over. A changed path widens when it is such a module, or a file under such a package, as the working tree names them; when the change removed it and changes' earlier tree named it; and when it is a member's pyproject.toml whose plugins for pytest differ from the earlier tree's. Empty when no changed path widens.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def plugin_reaches(changes: Changes) -> dict[str, tuple[str, tuple[str, ...]]]:
    """Each changed path pytest loads as a plugin, to why, and every member pytest runs.

    pytest loads every module a member's ``pyproject.toml`` names in a
    group `PLUGIN_GROUPS` gives it into every session it starts, so a
    change to one reaches every member a step of `PYTEST_STEPS` runs
    pytest over. A changed path widens when it is such a module, or a
    file under such a package, as the working tree names them; when
    the change removed it and *changes*' earlier tree named it; and
    when it is a member's ``pyproject.toml`` whose plugins for pytest
    differ from the earlier tree's. Empty when no changed path widens.
    """
    from livery.extensions.python._parse import dotted_name
    from livery.workshop import discover_packages

    packages = discover_packages(changes.root)
    removed = frozenset(changes.removed())
    # Each manifest is read once, however many of its package's paths changed.
    named: dict[tuple[str, bool], frozenset[str]] = {}

    def plugins(package: Package, *, earlier: bool) -> frozenset[str]:
        key = (package.path, earlier)
        if key not in named:
            if earlier:
                text = changes.text_before(f"{package.path}/pyproject.toml")
            else:
                manifest = package.directory / "pyproject.toml"
                text = manifest.read_text("utf-8") if manifest.is_file() else ""
            named[key] = _pytest_plugins(text)
        return named[key]

    widened: dict[str, str] = {}
    for path in changes.paths:
        package = next((p for p in packages if path.startswith(f"{p.path}/")), None)
        if package is None:
            continue
        relative = path[len(package.path) + 1 :]
        if relative == "pyproject.toml":
            if plugins(package, earlier=True) != plugins(package, earlier=False):
                widened[path] = "the plugins it names for pytest changed"
            continue
        if not relative.startswith("src/"):
            continue
        module = dotted_name(Path(relative), Path("src"))
        held = _plugin_of(module, plugins(package, earlier=False))
        if held:
            widened[path] = _loaded(module, held, now=True)
            continue
        if path in removed:
            held = _plugin_of(module, plugins(package, earlier=True))
            if held:
                widened[path] = _loaded(module, held, now=False)
    if not widened:
        return {}
    suites = _pytest_members(packages)
    return {path: (why, suites) for path, why in widened.items()}

plugin_modules

plugin_modules(package: Package) -> tuple[str, ...]

The modules package declares as footman task entry points.

A module the runner loads as a plugin has the runner present by construction, and whatever the extension stack mounts with it, so its imports of either are not dependencies of the distribution. The fact lives in the package's own metadata; nothing here needs to be told a second time.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def plugin_modules(package: Package) -> tuple[str, ...]:
    """The modules *package* declares as footman task entry points.

    A module the runner loads as a plugin has the runner present by
    construction, and whatever the extension stack mounts with it, so its
    imports of either are not dependencies of the distribution. The
    fact lives in the package's own metadata; nothing here needs to
    be told a second time.
    """
    return tuple(
        module
        for module, programs in plugin_hosts(package).items()
        if RUNNER_DISTRIBUTION in programs
    )

references

references(package: Package) -> tuple[SourceReferences, ...]

What each python source of package references, one record per file.

Every .py file under src, then under tests, in path order, read through the layering phase's one parse, so a file another rule also reads is parsed once per gate; a file that does not parse is left out, since the syntax gate names it. A source under src is referenced by its dotted path, and a test by nothing. Two of python's conventions account for a name: each name a module the package declares as a footman task entry point references, since the runner that loads the module brings what it imports, and each name of a sibling one of its optional extras names, since an extra is a declaration of its own.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def references(package: Package) -> tuple[SourceReferences, ...]:
    """What each python source of *package* references, one record per file.

    Every ``.py`` file under ``src``, then under ``tests``, in path
    order, read through the layering phase's one parse, so a file
    another rule also reads is parsed once per gate; a file that does
    not parse is left out, since the syntax gate names it. A source
    under ``src`` is referenced by its dotted path, and a test by
    nothing. Two of python's conventions account for a name: each
    name a module the package declares as a footman task entry point
    references, since the runner that loads the module brings what it
    imports, and each name of a sibling one of its optional extras
    names, since an extra is a declaration of its own.
    """
    from livery.extensions.python._parse import dotted_name, parsed_source

    plugins = plugin_modules(package)
    around, named = _extra_siblings(package)
    records: list[SourceReferences] = []
    for area in ("src", "tests"):
        base = package.directory / area
        if not base.is_dir():
            continue
        for source in sorted(base.rglob("*.py")):
            parsed = parsed_source(source)
            if parsed is None:
                continue
            module = dotted_name(source, base) if area == "src" else ""
            names = dict.fromkeys(reference.name for reference in parsed.references)
            loaded = bool(module) and any(
                module == plugin or module.startswith(plugin + ".")
                for plugin in plugins
            )
            accounted = tuple(
                name for name in names if loaded or around.owner_of(name) in named
            )
            relative = source.relative_to(package.directory).as_posix()
            records.append(
                SourceReferences(
                    path=f"{package.path}/{relative}",
                    module=module,
                    references=parsed.references,
                    accounted=accounted,
                )
            )
    return tuple(records)

declared_requirements

declared_requirements(package: Package) -> dict[str, str]

The package's declared dependencies, name to constraint text.

Read from [project.dependencies]; the layering lint compares these against the contract's build and runtime edges.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def declared_requirements(package: Package) -> dict[str, str]:
    """The package's declared dependencies, name to constraint text.

    Read from ``[project.dependencies]``; the layering lint compares
    these against the contract's build and runtime edges.
    """
    project = _project_table(package)
    return _constraints(project.get("dependencies", []))

declared_test_requirements

declared_test_requirements(package: Package) -> dict[str, str]

The package's test extra, name to constraint text.

Read from [project.optional-dependencies] test; the layering lint compares these against the contract's test edges. Empty for a package that declares no such extra.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def declared_test_requirements(package: Package) -> dict[str, str]:
    """The package's ``test`` extra, name to constraint text.

    Read from ``[project.optional-dependencies] test``; the layering
    lint compares these against the contract's test edges. Empty for a
    package that declares no such extra.
    """
    extras = _project_table(package).get("optional-dependencies") or {}
    return _constraints(extras.get(TEST_EXTRA) or [])

declare_requirement

declare_requirement(package: Package, dependency: Package, floor: str) -> list[str] | None

Add <dependency>>=<floor> to the project's dependencies; the files changed.

The python extension's requirement writer, its answer to the requirement-writers query. It takes a sibling whose set holds python, which the pyproject names as a distribution, and returns None for any other sibling, which it leaves to another writer of the package's set. A text edit that keeps the manifest's formatting: the entry joins the existing list, one per line, or opens the list when the project declares none. Already declared, whatever the constraint, means nothing to write. A manifest without a [project] table refuses naming it.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def declare_requirement(
    package: Package, dependency: Package, floor: str
) -> list[str] | None:
    """Add ``<dependency>>=<floor>`` to the project's dependencies; the files changed.

    The python extension's requirement writer, its answer to the
    ``requirement-writers`` query. It takes a sibling whose set holds
    python, which the pyproject names as a distribution, and returns
    None for any other sibling, which it leaves to another writer of
    the package's set. A text edit that keeps the manifest's
    formatting: the entry joins the existing list, one per line, or
    opens the list when the project declares none. Already declared,
    whatever the constraint, means nothing to write. A manifest without
    a ``[project]`` table refuses naming it.
    """
    import re as _re

    from livery.workshop import extension_set

    if EXTENSION not in extension_set(dependency):
        return None
    pyproject = package.directory / "pyproject.toml"
    if dependency.name in declared_requirements(package):
        return []
    text = pyproject.read_text("utf-8")
    entry = f'    "{dependency.name}>={floor}",\n'
    listed = _re.search(r"^dependencies = \[(.*?)^\]", text, flags=_re.M | _re.S)
    inline = _re.search(r"^dependencies = \[(.*)\]$", text, flags=_re.M)
    if listed is not None:
        head, tail = text[: listed.end() - 1], text[listed.end() - 1 :]
        text = head + entry + tail
    elif inline is not None:
        items = [item.strip() for item in inline.group(1).split(",") if item.strip()]
        lines = "".join(f"    {item},\n" for item in items) + entry
        text = (
            text[: inline.start()]
            + f"dependencies = [\n{lines}]"
            + text[inline.end() :]
        )
    else:
        header = _re.search(r"^\[project\]\n", text, flags=_re.M)
        if header is None:
            fail(f"{pyproject} has no [project] table to declare a dependency in")
        text = (
            text[: header.end()]
            + f"dependencies = [\n{entry}]\n"
            + text[header.end() :]
        )
    pyproject.write_text(text, encoding="utf-8")
    return ["pyproject.toml"]

declare_test_requirement

declare_test_requirement(package: Package, dependency: Package, floor: str) -> list[str] | None

Write <dependency>>=<floor> into the test extra; the files changed.

The python extension's writer of a test requirement, its answer to the test-requirement-writers query. It takes a sibling whose set holds python, and returns None for any other sibling. The line carries the edge's floor: one that names the sibling at another constraint is replaced, and one that carries the floor already means nothing to write. An empty floor writes the name alone. A text edit that keeps the manifest's formatting and comments: the line joins the extra, kept on one line while it fits in 88 columns and one requirement to a line beyond; the extra opens, after a comment saying what it holds, at the end of [project.optional-dependencies]; and that table opens after the [project] table when the project declares none.

Raises:

Type Description
Failed

when the manifest has no [project] table, and when its test extra is spelled in a form the edit does not take, naming the manifest.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def declare_test_requirement(
    package: Package, dependency: Package, floor: str
) -> list[str] | None:
    """Write ``<dependency>>=<floor>`` into the ``test`` extra; the files changed.

    The python extension's writer of a test requirement, its answer to
    the ``test-requirement-writers`` query. It takes a sibling whose set
    holds python, and returns None for any other sibling. The line
    carries the edge's floor: one that names the sibling at another
    constraint is replaced, and one that carries the floor already
    means nothing to write. An empty *floor* writes the name alone. A
    text edit that keeps the manifest's formatting and comments: the
    line joins the extra, kept on one line while it fits in 88 columns
    and one requirement to a line beyond; the extra opens, after a
    comment saying what it holds, at the end of
    ``[project.optional-dependencies]``; and that table opens after the
    ``[project]`` table when the project declares none.

    Raises:
        Failed: when the manifest has no ``[project]`` table, and when
            its test extra is spelled in a form the edit does not take,
            naming the manifest.
    """
    from livery.workshop import extension_set

    if EXTENSION not in extension_set(dependency):
        return None
    held = declared_test_requirements(package).get(dependency.name)
    if held is not None and (not floor or f">={floor}" in held):
        return []
    pyproject = package.directory / "pyproject.toml"
    line = f"{dependency.name}>={floor}" if floor else dependency.name
    text = _with_test_line(pyproject, dependency.name, line)
    pyproject.write_text(text, encoding="utf-8")
    return ["pyproject.toml"]

module_docs_dir

module_docs_dir(package: Package) -> Path | None

Where package's wheel-embedded _docs lives; None without a module.

In the shallowest of the package's module roots (module_roots) whose directory exists under src, the importable package the wheel ships. Of two roots with as many parts, the one answered first.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def module_docs_dir(package: Package) -> Path | None:
    """Where *package*'s wheel-embedded ``_docs`` lives; None without a module.

    In the shallowest of the package's module roots (`module_roots`)
    whose directory exists under ``src``, the importable package the
    wheel ships. Of two roots with as many parts, the one answered
    first.
    """
    src = package.directory / "src"
    directories = [src.joinpath(*root.split(".")) for root in module_roots(package)]
    present = [directory for directory in directories if directory.is_dir()]
    if not present:
        return None
    return min(present, key=lambda directory: len(directory.parts)) / "_docs"

materialise_module_docs

materialise_module_docs(package: Package) -> Path | None

Copy the package's docs/ into its wheel-embedded _docs, whole.

The copy is rebuilt from scratch, so the wheel never carries docs older than the tree it is built from, and a package without docs/ loses its old copy instead of shipping it.

Returns:

Type Description
Path | None

The copy's path; None when the package has no module to carry

Path | None

it, or no docs/ to copy.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def materialise_module_docs(package: Package) -> Path | None:
    """Copy the package's ``docs/`` into its wheel-embedded ``_docs``, whole.

    The copy is rebuilt from scratch, so the wheel never carries docs
    older than the tree it is built from, and a package without
    ``docs/`` loses its old copy instead of shipping it.

    Returns:
        The copy's path; None when the package has no module to carry
        it, or no ``docs/`` to copy.
    """
    target = module_docs_dir(package)
    if target is None:
        return None
    shutil.rmtree(target, ignore_errors=True)
    docs = package.directory / "docs"
    if not docs.is_dir():
        return None
    shutil.copytree(docs, target)
    return target

module_docs

module_docs(package: Package) -> Generator[Path | None]

The wheel-embedded _docs, in the source tree for one build alone.

On entry the package's docs/ is copied whole to _docs in the shallowest of its module roots, the importable package its wheel ships, replacing any older copy. On exit the copy is removed, after a failed build too. A copy left behind puts the docs' example files under the package's source, where every checker that walks the tree judges them as the package's own code.

Yields:

Type Description
Generator[Path | None]

The copy's path; None when the package has no module to carry

Generator[Path | None]

it, or no docs/ to copy.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
@contextmanager
def module_docs(package: Package) -> Generator[Path | None]:
    """The wheel-embedded ``_docs``, in the source tree for one build alone.

    On entry the package's ``docs/`` is copied whole to ``_docs`` in
    the shallowest of its module roots, the importable package its
    wheel ships, replacing any older copy. On exit the copy is
    removed, after a failed build too. A copy left behind puts the
    docs' example files under the package's source, where every
    checker that walks the tree judges them as the package's own code.

    Yields:
        The copy's path; None when the package has no module to carry
        it, or no ``docs/`` to copy.
    """
    target = materialise_module_docs(package)
    try:
        yield target
    finally:
        if target is not None:
            shutil.rmtree(target, ignore_errors=True)

build

build(package: Package, root: Path, *, epoch: int = 0) -> Path

Build package's wheel and sdist into its dist/; the dist dir.

Always from a clean dist/: reusing an artifact from an earlier build installs stale code under current tests, a silent footgun bought off for seconds of build. epoch (a commit's timestamp) rides SOURCE_DATE_EPOCH so a pure-Python rebuild at the same ref is byte-identical.

Raises:

Type Description
Failed

when uv build exits non-zero, when it writes no wheel, and when it writes a wheel tagged for a platform. Python's build ships a pure wheel, tagged none-any; a platform tag means compiled code built for this machine alone, and a package with compiled code lists the extension that builds a wheel for each platform.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def build(package: Package, root: Path, *, epoch: int = 0) -> Path:
    """Build *package*'s wheel and sdist into its ``dist/``; the dist dir.

    Always from a clean ``dist/``: reusing an artifact from an
    earlier build installs stale code under current tests, a silent
    footgun bought off for seconds of build. *epoch* (a commit's
    timestamp) rides ``SOURCE_DATE_EPOCH`` so a pure-Python rebuild
    at the same ref is byte-identical.

    Raises:
        Failed: when ``uv build`` exits non-zero, when it writes no
            wheel, and when it writes a wheel tagged for a platform.
            Python's build ships a pure wheel, tagged ``none-any``; a
            platform tag means compiled code built for this machine
            alone, and a package with compiled code lists the extension
            that builds a wheel for each platform.
    """
    dist = package.directory / "dist"
    shutil.rmtree(dist, ignore_errors=True)
    env = dict(os.environ)
    if epoch:
        env["SOURCE_DATE_EPOCH"] = str(epoch)
    # The wheel embeds the docs copied whole from packages/<name>/docs
    # for this build, so it never carries docs older than its tree.
    with module_docs(package):
        result = tools.uv.opts(
            cwd=package.directory, nofail=True, recorded=False, env=env
        )("build", "--out-dir", str(dist))
    if result.code != 0:
        fail(
            f"uv build ({package.name}) exited {result.code}:\n"
            f"{result.stdout}{result.stderr}"
        )
    wheels = sorted(dist.glob("*.whl"))
    if not wheels:
        fail(f"{package.name}: the build produced no wheel in {dist}")
    tagged = [wheel.name for wheel in wheels if not wheel.name.endswith(PURE_TAG)]
    if tagged:
        fail(
            f"{package.name}: the build produced a wheel tagged for a platform,"
            f" {', '.join(tagged)}; python's build ships a pure wheel, tagged"
            " none-any, so a package with compiled code lists the extension that"
            " builds its platform wheels"
        )
    return dist

publish_artifact

publish_artifact(package: Package, root: Path, *, version: str, target: RegistryTarget) -> bool

Upload dist/* to the python index: python's publish step calls it.

uv publish, to the target's upload endpoint with its credential. version and root are what another ecosystem's publisher reads: the wheels in dist/ already carry their versions, and the index needs nothing from the workspace.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def publish_artifact(
    package: Package, root: Path, *, version: str, target: RegistryTarget
) -> bool:
    """Upload ``dist/*`` to the python index: python's publish step calls it.

    ``uv publish``, to the target's upload endpoint with its
    credential. *version* and *root* are what another ecosystem's
    publisher reads: the wheels in ``dist/`` already carry their
    versions, and the index needs nothing from the workspace.
    """
    del root, version
    return publish_wheels(package, index_url=target.publish_url, token=target.token)

publish_wheels

publish_wheels(package: Package, *, index_url: str = '', token: str = '') -> bool

Upload dist/*; False when everything was already published.

uv publish, with the already-published duplicate the one tolerated failure: a re-run must walk past what an earlier attempt landed. Anything else, a rejected credential, an unreachable index, surfaces verbatim.

The upload address is required: without --publish-url uv silently defaults to PyPI, and an undeclared endpoint must refuse rather than surprise. A deliberate PyPI publish arrives here as the ecosystem rung's explicit URL.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def publish_wheels(package: Package, *, index_url: str = "", token: str = "") -> bool:
    """Upload ``dist/*``; False when everything was already published.

    ``uv publish``, with the already-published duplicate the one
    tolerated failure: a re-run must walk past what an earlier
    attempt landed. Anything else, a rejected credential, an
    unreachable index, surfaces verbatim.

    The upload address is required: without ``--publish-url`` uv
    silently defaults to PyPI, and an undeclared endpoint must
    refuse rather than surprise. A deliberate PyPI publish arrives
    here as the ecosystem rung's explicit URL.
    """
    if not index_url:
        fail(
            f"{package.name}: no publish address given, and an upload"
            " endpoint is never defaulted (uv's silent default is"
            " PyPI). Declare [registries.python] publish in"
            " workshop.toml, or set PYTHON_PUBLISH_INDEX."
        )
    command = ["publish", "--publish-url", index_url]
    if token:
        # A Secret, so a profile trace and every other place the
        # command line is shown carry *** in its place and uv alone
        # receives the value; recorded=False keeps the call out of
        # receipts, --json, and recordings as well.
        command += ["--token", footman.Secret(token)]
    command += [str(path) for path in sorted((package.directory / "dist").glob("*"))]
    # CI renders UV_PUBLISH_TOKEN from a secret that may be absent, and
    # an absent secret arrives as an empty string. uv treats a set but
    # empty token as a credential rather than as none: trusted
    # publishing is skipped and the index refuses the empty token. The
    # child sees the variable only when it carries a value.
    env = {k: v for k, v in os.environ.items() if k != "UV_PUBLISH_TOKEN" or v}
    result = tools.uv.opts(cwd=package.directory, nofail=True, recorded=False, env=env)(
        *command
    )
    if result.code == 0:
        return True
    output = f"{result.stdout}{result.stderr}"
    if _is_duplicate(output):
        print(f"  {package.name}: already published; walking past")
        return False
    fail(f"uv publish ({package.name}) exited {result.code}:\n{output}")

isolated_test

isolated_test(package: Package, root: Path, *, release_dirs: tuple[Path, ...], resolution: str) -> dict[str, str]

Test package's built wheel in a fresh venv at resolution; what it got.

livery.extensions.python.run_isolated_test runs it.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def isolated_test(
    package: Package, root: Path, *, release_dirs: tuple[Path, ...], resolution: str
) -> dict[str, str]:
    """Test *package*'s built wheel in a fresh venv at *resolution*; what it got.

    [livery.extensions.python.run_isolated_test][] runs it.
    """
    return run_isolated_test(
        package, root, release_dirs=release_dirs, resolution=resolution
    )

verify

verify(package: Package, *, tree: Path, version: str, python: str, index: str, extras: str) -> int

Install package's released version alone and run its tests at tree.

The exit code; livery.extensions.python._verify.verify runs it.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def verify(
    package: Package, *, tree: Path, version: str, python: str, index: str, extras: str
) -> int:
    """Install *package*'s released *version* alone and run its tests at *tree*.

    The exit code; [livery.extensions.python._verify.verify][] runs it.
    """
    from livery.extensions.python import _verify

    return _verify.verify(
        package, tree=tree, version=version, python=python, index=index, extras=extras
    )

run_isolated_test

run_isolated_test(package: Package, root: Path, *, release_dirs: tuple[Path, ...] = (), resolution: str = 'latest', wheels_dir: Path | None = None) -> dict[str, str]

Install the built wheel into a fresh venv and test the installed copy.

One leg of the release's isolated test, at resolution: floor puts every direct dependency at its declared floor, so a floor lying about compatibility fails here; latest resolves the newest, the world a fresh consumer gets; head installs at the versions the workspace lock pins, read as it stands, and refuses in a workspace without a lock.

--find-links is limited to release_dirs, the co-released set's dist/ directories: a leftover wheel from a non-released package must never mask that the release needs an unpublished dependency version. Everything else resolves from the repo's configured indexes, like a real consumer. Each distribution those directories carry is refreshed in uv's cache, so a member rebuilt at the same version installs the wheel just built and never an earlier build of the same filename.

The toolchain installs after the wheel, at the lock's dev-group pins where a lock exists (bare pytest otherwise), and a probe then re-reads the package's own direct dependencies: the second install is pip-shaped and moves versions without erroring, so a toolchain pin that overlaps a floored dependency would silently undo the starvation. Movement is a taught refusal.

Parameters:

Name Type Description Default
package Package

The member whose wheel is installed and tested.

required
root Path

The workspace root, whose lock and indexes the install reads.

required
release_dirs tuple[Path, ...]

The co-released set's dist/ directories, the only places a wheel resolves from beside the indexes.

()
resolution str

floor, latest or head.

'latest'
wheels_dir Path | None

Where the wheel to install is, for a leg that built one outside the collected dist/; None takes the package's own dist/.

None

Returns:

Type Description
dict[str, str]

The resolved version per distribution, the report's raw

dict[str, str]

material ("floor leg: livery-forge 0.1.0").

Raises:

Type Description
Failed

when resolution is none of the three, when no wheel is there to install, when the head leg finds no lock, when an install fails, when the toolchain install moves a direct dependency the leg resolved, and when the tests fail.

Source code in packages/extensions/python/src/livery/extensions/python/_backend.py
def run_isolated_test(
    package: Package,
    root: Path,
    *,
    release_dirs: tuple[Path, ...] = (),
    resolution: str = "latest",
    wheels_dir: Path | None = None,
) -> dict[str, str]:
    """Install the built wheel into a fresh venv and test the installed copy.

    One leg of the release's isolated test, at *resolution*: ``floor``
    puts every direct dependency at its declared floor, so a floor
    lying about compatibility fails here; ``latest`` resolves the
    newest, the world a fresh consumer gets; ``head`` installs at the
    versions the workspace lock pins, read as it stands, and refuses
    in a workspace without a lock.

    ``--find-links`` is limited to *release_dirs*, the co-released
    set's ``dist/`` directories: a leftover wheel from a non-released
    package must never mask that the release needs an unpublished
    dependency version. Everything else resolves from the repo's
    configured indexes, like a real consumer.
    Each distribution those directories carry is refreshed in uv's
    cache, so a member rebuilt at the same version installs the wheel
    just built and never an earlier build of the same filename.

    The toolchain installs after the wheel, at the lock's dev-group
    pins where a lock exists (bare pytest otherwise), and a probe
    then re-reads the package's own direct dependencies: the second
    install is pip-shaped and moves versions without erroring, so a
    toolchain pin that overlaps a floored dependency would silently
    undo the starvation. Movement is a taught refusal.

    Args:
        package: The member whose wheel is installed and tested.
        root: The workspace root, whose lock and indexes the install
            reads.
        release_dirs: The co-released set's ``dist/`` directories, the
            only places a wheel resolves from beside the indexes.
        resolution: ``floor``, ``latest`` or ``head``.
        wheels_dir: Where the wheel to install is, for a leg that built
            one outside the collected ``dist/``; None takes the
            package's own ``dist/``.

    Returns:
        The resolved version per distribution, the report's raw
        material ("floor leg: livery-forge 0.1.0").

    Raises:
        Failed: when *resolution* is none of the three, when no wheel
            is there to install, when the head leg finds no lock, when
            an install fails, when the toolchain install moves a direct
            dependency the leg resolved, and when the tests fail.
    """
    import json
    import tempfile

    if resolution not in RESOLUTIONS:
        fail(
            f"{package.name}: the isolated test resolves at"
            f" {', '.join(RESOLUTIONS)}, not {resolution!r}"
        )
    strategy, locked = RESOLUTIONS[resolution]

    # Sorted for determinism: with several wheels in dist a glob's
    # filesystem order once handed the leg a musllinux wheel the
    # venv could not install.
    built = wheels_dir if wheels_dir is not None else package.directory / "dist"
    wheels = sorted(built.glob("*.whl"))
    if not wheels:
        fail(f"{package.name}: no wheel in {built} to validate; build first")
    with tempfile.TemporaryDirectory() as scratch:
        from livery.workshop import venv_python

        venv = Path(scratch) / "venv"
        python = venv_python(venv)

        def _run_install(*args: str) -> None:
            result = tools.uv.opts(cwd=scratch, nofail=True, recorded=False)(*args)
            if result.code != 0:
                fail(
                    f"{package.name} isolated install ({resolution}) exited"
                    f" {result.code}:\n{result.stdout}{result.stderr}"
                )

        def _listing() -> dict[str, str]:
            listing = tools.uv.opts(cwd=scratch, nofail=True, recorded=False)(
                "pip", "list", "--python", str(python), "--format", "json"
            )
            versions: dict[str, str] = {}
            if listing.code == 0:
                for row in json.loads(listing.stdout or "[]"):
                    versions[str(row.get("name", ""))] = str(row.get("version", ""))
            return versions

        constraints: tuple[str, ...] = ()
        if locked:
            pins = _lock_pins(root, Path(scratch))
            if pins is None:
                fail(
                    f"{package.name}: the head leg installs at the versions the"
                    f" workspace lock pins, and uv export read no lock in {root};"
                    " lock the workspace, or list floor or latest in"
                    " [release] prove"
                )
            constraints = ("--constraint", str(pins))
        # The leg's own interpreter version, explicitly: bare `uv
        # venv` takes uv's default python, and a platform wheel
        # built for the running interpreter (cp311) cannot install
        # into a venv of another (cp314). Pure wheels never noticed.
        _run_install(
            "venv",
            "--python",
            f"{sys.version_info.major}.{sys.version_info.minor}",
            str(venv),
        )
        _run_install(
            "pip",
            "install",
            "--python",
            str(python),
            f"--resolution={strategy}",
            *[f"--find-links={d}" for d in release_dirs],
            *_refresh_args(release_dirs),
            *_index_args(root),
            *constraints,
            _install_target(package, wheels[0]),
            # The declared dependencies ride the command line so
            # the resolution strategy treats them as direct; see
            # _direct_requirements.
            *_direct_requirements(package),
        )
        resolved = _listing()
        before = _direct_versions(package, resolved)
        # The toolchain never rides the starved install: lowest-direct
        # aimed at it once dragged pytest back a decade. Locked pins
        # where the workspace has them, minus what the leg resolved,
        # so the leg keeps its floor or its latest; pytest is a no-op
        # re-request when the pins already hold it.
        # The toolchain resolves from the same indexes as the wheel:
        # the lock's pins name whatever versions the workspace's own
        # index serves, and a bare-PyPI install cannot see those.
        pins = _dev_pins(root, Path(scratch))
        if pins is not None:
            pins = _pins_without(pins, resolved)
            _run_install(
                "pip",
                "install",
                "--python",
                str(python),
                *_index_args(root),
                "-r",
                str(pins),
            )
        _run_install(
            "pip", "install", "--python", str(python), *_index_args(root), "pytest"
        )
        after = _direct_versions(package, _listing())
        moved = {
            name: (before[name], version)
            for name, version in after.items()
            if name in before and before[name] != version
        }
        if moved:
            listed = ", ".join(
                f"{name} {was} -> {now}" for name, (was, now) in sorted(moved.items())
            )
            fail(
                f"{package.name}: the toolchain install moved direct"
                f" dependencies the {resolution} leg had resolved: {listed}."
                " The starvation must stay honest: a toolchain tool needs"
                " another version of a dependency the member declares, so"
                " pin that tool where the two agree, or widen the member's"
                " floor."
            )
        tests = package.directory / "tests"
        if tests.is_dir():
            result = footman.run(
                [
                    str(python),
                    "-m",
                    "pytest",
                    str(tests),
                    "-q",
                    "-p",
                    "no:cacheprovider",
                    # pytest derives its rootdir from the test paths and
                    # finds the workspace's configuration, whose addopts
                    # would hand the leg xdist workers and coverage flags;
                    # the leg is serial and unmetered by design.
                    "-o",
                    "addopts=",
                ],
                cwd=scratch,
                env=_leg_env(root, venv),
                nofail=True,
                recorded=False,
            )
            if result.code != 0:
                fail(
                    f"{package.name} isolated tests ({resolution}) failed:\n"
                    f"{result.stdout[-4000:]}{result.stderr[-2000:]}"
                )
        return _listing()