Skip to content

livery.extensions.pytest._runner

livery.extensions.pytest._runner

Per-item pytest process runner with read-set recording (Phase C2).

Runs each test file in its own pytest process, starting files with no recorded duration first and then the longest files first so the tail stays short. Each process runs under the .pth observer hook (livery.extensions.pytest._observer), and collected items write their verdicts and recorded read-sets to the workshop's proved record. An item that collects no tests (pytest exit code 5) writes no row and is not a failure.

Classes:

Name Description
ItemOutcome

Result of executing one test item in its own pytest process.

Functions:

Name Description
order_items

Order items for scheduling: unmeasured first, then longest first.

runner_config_reads

Runner configuration files that govern item: existing hashes and absent paths.

declared_test_reads

Expand a package's [tests] reads patterns into files, absent, and dirs.

run_items

Run every test file in items in its own observed pytest process.

item_runner

Answer python.test.item-runner with ci_item_runner.

ci_item_runner

Answer python.test.item-runner: run CI test items one process per file.

Attributes:

Name Type Description
EXIT_NO_TESTS
CHANGED_ITEM_REPEATS
PROFILE_DIR_VARIABLE
RUNNER_CONFIG_FILES tuple[str, ...]

EXIT_NO_TESTS module-attribute

EXIT_NO_TESTS = 5

CHANGED_ITEM_REPEATS module-attribute

CHANGED_ITEM_REPEATS = 5

PROFILE_DIR_VARIABLE module-attribute

PROFILE_DIR_VARIABLE = 'FM_PROFILE_DIR'

RUNNER_CONFIG_FILES module-attribute

RUNNER_CONFIG_FILES: tuple[str, ...] = ('pytest.toml', '.coveragerc')

ItemOutcome dataclass

ItemOutcome(item: str, code: int, collected: bool, verdict: str, stdout: str, stderr: str, read_set: ItemReadSet | None, duration: float, repeats: int = 1, repeat_verdicts: tuple[str, ...] = (), escaped: bool = False, escape_changed: tuple[str, ...] = ())

Result of executing one test item in its own pytest process.

Attributes:

Name Type Description
item str

Repository-relative POSIX path of the test file.

code int

Raw pytest exit code.

collected bool

False when pytest exited with code 5 (0 tests collected).

verdict str

"green", "red", or "skipped" (when not collected).

stdout str

Captured standard output.

stderr str

Captured standard error.

read_set ItemReadSet | None

Recorded ItemReadSet, or None when no tests collected.

duration float

Wall-clock duration in seconds for this item's process.

repeats int

How many repeat processes ran for this item.

repeat_verdicts tuple[str, ...]

Verdict of each repeat process in execution order.

escaped bool

True when this item was proved green by its row yet failed on a scheduled audit run.

escape_changed tuple[str, ...]

Files changed since the proving row when escaped.

item instance-attribute

item: str

code instance-attribute

code: int

collected instance-attribute

collected: bool

verdict instance-attribute

verdict: str

stdout instance-attribute

stdout: str

stderr instance-attribute

stderr: str

read_set instance-attribute

read_set: ItemReadSet | None

duration instance-attribute

duration: float

repeats class-attribute instance-attribute

repeats: int = 1

repeat_verdicts class-attribute instance-attribute

repeat_verdicts: tuple[str, ...] = ()

escaped class-attribute instance-attribute

escaped: bool = False

escape_changed class-attribute instance-attribute

escape_changed: tuple[str, ...] = ()

flaky property

flaky: bool

Whether repeats produced both green and red verdicts for this item.

order_items

order_items(items: Sequence[str], durations: Mapping[str, float]) -> tuple[str, ...]

Order items for scheduling: unmeasured first, then longest first.

A test file with no entry in durations starts before every measured file (sorted alphabetically among unmeasured files). Measured files follow in descending duration order, tie-broken alphabetically.

Source code in packages/extensions/pytest/src/livery/extensions/pytest/_runner.py
def order_items(
    items: Sequence[str], durations: Mapping[str, float]
) -> tuple[str, ...]:
    """Order *items* for scheduling: unmeasured first, then longest first.

    A test file with no entry in *durations* starts before every measured
    file (sorted alphabetically among unmeasured files). Measured files
    follow in descending duration order, tie-broken alphabetically.
    """
    normalized = tuple(
        dict.fromkeys(item.replace("\\", "/").lstrip("./") for item in items)
    )
    unknown = sorted(item for item in normalized if item not in durations)
    known = sorted(
        (item for item in normalized if item in durations),
        key=lambda item: (-float(durations[item]), item),
    )
    return (*unknown, *known)

runner_config_reads

runner_config_reads(root: Path, item: str, *, package: Package | None = None) -> tuple[dict[str, str], tuple[str, ...]]

Runner configuration files that govern item: existing hashes and absent paths.

Includes root pytest.toml and .coveragerc, every ancestor conftest.py from item's directory up to root, and the owning package's workshop.toml and pyproject.toml. Missing paths land in absent so creating one invalidates the item.

Source code in packages/extensions/pytest/src/livery/extensions/pytest/_runner.py
def runner_config_reads(
    root: Path, item: str, *, package: Package | None = None
) -> tuple[dict[str, str], tuple[str, ...]]:
    """Runner configuration files that govern *item*: existing hashes and absent paths.

    Includes root ``pytest.toml`` and ``.coveragerc``, every ancestor
    ``conftest.py`` from *item*'s directory up to *root*, and the owning
    package's ``workshop.toml`` and ``pyproject.toml``. Missing paths land
    in ``absent`` so creating one invalidates the item.
    """
    norm_item = item.replace("\\", "/").lstrip("./")
    candidates: list[str] = list(RUNNER_CONFIG_FILES)
    parent = PurePosixPath(norm_item).parent
    while True:
        conftest = (
            "conftest.py" if str(parent) in ("", ".") else f"{parent}/conftest.py"
        )
        candidates.append(conftest)
        if str(parent) in ("", "."):
            break
        parent = parent.parent
    if package is not None:
        candidates.append(f"{package.path}/workshop.toml")
        candidates.append(f"{package.path}/pyproject.toml")

    present: dict[str, str] = {}
    absent: list[str] = []
    for rel in dict.fromkeys(candidates):
        target = root / rel
        if target.is_file():
            present[rel] = _file_sha256(target)
        else:
            absent.append(rel)
    return present, tuple(sorted(absent))

declared_test_reads

declared_test_reads(root: Path, package_path: str, patterns: Sequence[str]) -> tuple[dict[str, str], tuple[str, ...], dict[str, str]]

Expand a package's [tests] reads patterns into files, absent, and dirs.

Source code in packages/extensions/pytest/src/livery/extensions/pytest/_runner.py
def declared_test_reads(
    root: Path, package_path: str, patterns: Sequence[str]
) -> tuple[dict[str, str], tuple[str, ...], dict[str, str]]:
    """Expand a package's ``[tests] reads`` *patterns* into files, absent, and dirs."""
    present: dict[str, str] = {}
    absent: set[str] = set()
    dirs: dict[str, str] = {}
    pkg_dir = root if package_path in ("", ".") else root / package_path

    for raw in patterns:
        if raw.startswith("//"):
            base_dir = root
            sub = raw[2:]
        else:
            base_dir = pkg_dir
            sub = raw
        if any(ch in sub for ch in "*?["):
            parts = PurePosixPath(sub).parts
            first_glob = next(
                i for i, part in enumerate(parts) if any(ch in part for ch in "*?[")
            )
            static_parts = parts[:first_glob]
            parent_dir = base_dir.joinpath(*static_parts) if static_parts else base_dir
            parent_rel = (
                "." if parent_dir == root else parent_dir.relative_to(root).as_posix()
            )
            if not parent_dir.is_dir():
                absent.add(parent_rel)
                continue
            dirs[parent_rel] = _dir_digest(root, parent_rel)
            for matched in sorted(base_dir.glob(sub)):
                m_rel = matched.relative_to(root).as_posix()
                if _is_ignored_relative(m_rel):
                    continue
                if matched.is_file():
                    present[m_rel] = _file_sha256(matched)
                else:
                    dirs[m_rel] = _dir_digest(root, m_rel)
            continue

        target = base_dir / sub
        rel = target.relative_to(root).as_posix()
        if target.is_file():
            present[rel] = _file_sha256(target)
        elif target.is_dir():
            dirs[rel] = _dir_digest(root, rel)
            for child in sorted(target.rglob("*")):
                if child.is_file():
                    c_rel = child.relative_to(root).as_posix()
                    if not _is_ignored_relative(c_rel):
                        present[c_rel] = _file_sha256(child)
        else:
            absent.add(rel)

    return present, tuple(sorted(absent - set(present))), dirs

run_items

run_items(root: Path, items: Sequence[str], *, pytest_args: Sequence[str] = (), env: Mapping[str, str] | None = None, durations: Mapping[str, float] | None = None, max_workers: int | None = None, record: bool = False, shadow: bool = False, select: bool = False, audit: bool = False, local: bool = False, sums_file: Path | None = None, step: str = 'test.pytest', store: StateStore | None = None, python_exe: str = '', on_start: Callable[[str], None] | None = None, repeat_items: frozenset[str] = frozenset(), repeat_count: int = CHANGED_ITEM_REPEATS) -> tuple[ItemOutcome, ...]

Run every test file in items in its own observed pytest process.

Starts unmeasured files first, then longest files first. Items in repeat_items run repeat_count times concurrently with distinct PYTHONHASHSEED values so flaky tests are caught immediately. When select is true (and audit is false), packages with [tests] selection = "on" skip proved items unless an active escape put the package back to whole runs. When audit is true (scheduled runs), every item executes and any red item that its row had proved green is recorded as an escape. Records collected items' verdicts and read-sets when record is true; an item that collected no tests (exit code 5) writes no row.

Source code in packages/extensions/pytest/src/livery/extensions/pytest/_runner.py
def run_items(
    root: Path,
    items: Sequence[str],
    *,
    pytest_args: Sequence[str] = (),
    env: Mapping[str, str] | None = None,
    durations: Mapping[str, float] | None = None,
    max_workers: int | None = None,
    record: bool = False,
    shadow: bool = False,
    select: bool = False,
    audit: bool = False,
    local: bool = False,
    sums_file: Path | None = None,
    step: str = "test.pytest",
    store: git.StateStore | None = None,
    python_exe: str = "",
    on_start: Callable[[str], None] | None = None,
    repeat_items: frozenset[str] = frozenset(),
    repeat_count: int = CHANGED_ITEM_REPEATS,
) -> tuple[ItemOutcome, ...]:
    """Run every test file in *items* in its own observed pytest process.

    Starts unmeasured files first, then longest files first. Items in
    *repeat_items* run *repeat_count* times concurrently with distinct
    ``PYTHONHASHSEED`` values so flaky tests are caught immediately.
    When *select* is true (and *audit* is false), packages with
    ``[tests] selection = "on"`` skip proved items unless an active escape
    put the package back to whole runs. When *audit* is true (scheduled
    runs), every item executes and any red item that its row had proved
    green is recorded as an escape. Records collected items' verdicts and
    read-sets when *record* is true; an item that collected no tests
    (exit code 5) writes no row.
    """
    ordered = order_items(items, durations or {})
    if not ordered:
        return ()
    packages: tuple[Package, ...] = ()
    if (root / "packages").is_dir():
        try:
            packages = discover_packages(root)
        except (ValueError, OSError):
            packages = ()

    selection: ItemSelection | None = None
    if shadow or select or audit:
        selection, shadow_why = shadow_select_items(
            root, ordered, step=step, store=store
        )
        if shadow_why:
            print(f"  proved (shadow items): {shadow_why}")
            selection = None
        elif shadow:
            print(
                f"  proved (shadow items): would run"
                f" {len(selection.selected)}/{len(ordered)} item(s),"
                f" skipping {len(selection.skipped)}"
            )

    to_run: tuple[str, ...] = ordered
    skipped_live: tuple[str, ...] = ()
    skipped_fps: dict[str, str] = {}
    if select and not audit and selection is not None:
        escaped_pkgs, _esc_why = active_escaped_packages(root, store=store)
        to_run, skipped_live = _filter_selected_items(
            ordered,
            packages=packages,
            selection=selection,
            escaped_pkgs=escaped_pkgs,
        )
        skipped_fps = {
            item: selection.fingerprints[item]
            for item in skipped_live
            if item in selection.fingerprints
        }
        if not to_run:
            record_ran_items(root, skipped=skipped_fps, narrowed=bool(skipped_live))
            if shadow and (active_run := ci_run()) is not None:
                measure_why = record_selection_measure(
                    root,
                    run=active_run,
                    selection=selection,
                    durations={},
                    step=step,
                    store=store,
                )
                if measure_why:
                    print(f"  measures: {measure_why}")
            return ()

    ensure_pth()
    cleaned_args = _strip_xdist_args(pytest_args)
    if GUARD_FLAG not in cleaned_args:
        cleaned_args = (GUARD_FLAG, *cleaned_args)
    base_env = dict(os.environ if env is None else env)
    exe = python_exe or sys.executable

    item_cov_files: dict[str, Path] = {}
    if base_env.get(METER):
        for item in to_run:
            cov_dir = item_coverage_dir(root, item)
            cov_dir.mkdir(parents=True, exist_ok=True)
            for stale in cov_dir.glob(f"{DATA_FILE}*"):
                stale.unlink(missing_ok=True)
            item_cov_files[item] = cov_dir / DATA_FILE

    norm_repeats = frozenset(
        item.replace("\\", "/").lstrip("./") for item in repeat_items
    )
    jobs: list[tuple[int, str, int, str | None]] = []
    for idx, item in enumerate(to_run):
        count = repeat_count if (item in norm_repeats and repeat_count > 1) else 1
        if count == 1:
            jobs.append((idx, item, 0, None))
        else:
            for rep in range(count):
                jobs.append((idx, item, rep, _hash_seed(rep)))

    workers = (
        max(1, max_workers)
        if max_workers is not None
        else max(1, min(len(jobs), os.cpu_count() or 4))
    )

    runs_by_index: dict[int, list[tuple[int, ItemOutcome]]] = {}
    speed_files: list[Path] = []
    outer_profile = base_env.get(PROFILE_DIR_VARIABLE, "").strip()
    profile_fragments: list[tuple[int, Path]] = []
    tmp_root = Path(tempfile.mkdtemp(prefix="livery-items-"))
    try:
        if workers == 1:
            for idx, item, rep, seed in jobs:
                item_scratch = tmp_root / f"item-{idx}-r{rep}"
                item_profile = (item_scratch / "profile") if outer_profile else None
                outcome, speed_file = _run_one_item(
                    root,
                    item,
                    item_scratch,
                    base_args=cleaned_args,
                    base_env=base_env,
                    python_exe=exe,
                    on_start=on_start,
                    profile_dir=item_profile,
                    package=_package_for_item(item, packages),
                    hash_seed=seed,
                    coverage_file=item_cov_files.get(item),
                )
                runs_by_index.setdefault(idx, []).append((rep, outcome))
                if rep == 0:
                    speed_files.append(speed_file)
                if item_profile is not None:
                    profile_fragments.append((0, item_profile))
        else:
            slots: queue.SimpleQueue[int] = queue.SimpleQueue()
            for slot in range(workers):
                slots.put(slot)

            def _run_slotted(
                idx: int, item: str, rep: int, seed: str | None
            ) -> tuple[int, int, ItemOutcome, Path, Path | None]:
                slot = slots.get()
                try:
                    item_scratch = tmp_root / f"item-{idx}-r{rep}"
                    item_profile = (item_scratch / "profile") if outer_profile else None
                    outcome, speed_file = _run_one_item(
                        root,
                        item,
                        item_scratch,
                        base_args=cleaned_args,
                        base_env=base_env,
                        python_exe=exe,
                        on_start=on_start,
                        profile_dir=item_profile,
                        package=_package_for_item(item, packages),
                        hash_seed=seed,
                        coverage_file=item_cov_files.get(item),
                    )
                    return slot, rep, outcome, speed_file, item_profile
                finally:
                    slots.put(slot)

            with ThreadPoolExecutor(max_workers=workers) as pool:
                futures = [
                    (idx, pool.submit(_run_slotted, idx, item, rep, seed))
                    for idx, item, rep, seed in jobs
                ]
                for idx, future in futures:
                    slot, rep, outcome, speed_file, item_profile = future.result()
                    runs_by_index.setdefault(idx, []).append((rep, outcome))
                    if rep == 0:
                        speed_files.append(speed_file)
                    if item_profile is not None:
                        profile_fragments.append((slot, item_profile))
        if sums_file is not None:
            _merge_speed_files(speed_files, sums_file)
        if outer_profile and profile_fragments:
            _merge_profile_fragments(profile_fragments, Path(outer_profile))
    finally:
        # Avoid `TemporaryDirectory(ignore_cleanup_errors=True)` which on
        # Python 3.14 still raises `PermissionError` in `_resetperms` when
        # Docker leaves root-owned files inside `basetemp`.
        shutil.rmtree(tmp_root, ignore_errors=True)

    per_item_runs = [
        [out for _, out in sorted(runs_by_index[i], key=lambda pair: pair[0])]
        for i in range(len(to_run))
    ]
    outcomes = tuple(_aggregate_repeats(runs) for runs in per_item_runs)
    if audit and selection is not None:
        red_items = [o.item for o in outcomes if o.verdict == "red"]
        escapes = detect_item_escapes(
            root,
            step=step,
            selection=selection,
            red_items=red_items,
            packages=packages,
            store=store,
        )
        if escapes:
            esc_by_item = {esc.item: esc for esc in escapes}
            esc_why = record_escapes(root, escapes, local=local, store=store)
            for esc in escapes:
                changed = ", ".join(esc.changed_files) or "(unknown)"
                print(
                    f"  ESCAPE: {esc.unit} proved green but failed on scheduled"
                    f" audit (changed: {changed}); putting {esc.package} back to"
                    " whole runs"
                )
            if esc_why:
                print(f"  proved (escapes): {esc_why}")
            outcomes = tuple(
                ItemOutcome(
                    item=o.item,
                    code=o.code,
                    collected=o.collected,
                    verdict=o.verdict,
                    stdout=o.stdout,
                    stderr=o.stderr,
                    read_set=o.read_set,
                    duration=o.duration,
                    repeats=o.repeats,
                    repeat_verdicts=o.repeat_verdicts,
                    escaped=True,
                    escape_changed=esc_by_item[o.item].changed_files,
                )
                if o.item in esc_by_item
                else o
                for o in outcomes
            )
    ran_fps: dict[str, str] = {}
    to_record: list[tuple[str, str, ItemReadSet]] = []
    for runs in per_item_runs:
        collected_runs = [o for o in runs if o.collected and o.read_set is not None]
        if not collected_runs:
            ran_fps[runs[0].item] = ""
            continue
        shared_rs = (
            _union_read_sets(
                [o.read_set for o in collected_runs if o.read_set is not None]
            )
            if len(collected_runs) > 1
            else collected_runs[0].read_set
        )
        assert shared_rs is not None
        ran_fps[runs[0].item] = "" if shared_rs.unrecorded else shared_rs.fingerprint()
        if record:
            for o in collected_runs:
                to_record.append((o.item, o.verdict, shared_rs))
    if to_record:
        why = record_item_observations(root, step, to_record, local=local, store=store)
        if why:
            print(f"  proved (items): {why}")
        else:
            unrec = sum(1 for _, _, rs in to_record if rs.unrecorded)
            suffix = f" ({unrec} unrecorded)" if unrec else ""
            print(f"  proved (items): recorded {len(to_record)} item(s){suffix}")
    record_ran_items(
        root,
        ran=ran_fps,
        skipped=skipped_fps,
        narrowed=bool(skipped_live),
    )
    if shadow and selection is not None and (active_run := ci_run()) is not None:
        item_durations = {o.item: o.duration for o in outcomes}
        measure_why = record_selection_measure(
            root,
            run=active_run,
            selection=selection,
            durations=item_durations,
            step=step,
            store=store,
        )
        if measure_why:
            print(f"  measures: {measure_why}")
    return outcomes

item_runner

item_runner(root: Path) -> Callable[..., list[str]]

Answer python.test.item-runner with ci_item_runner.

Source code in packages/extensions/pytest/src/livery/extensions/pytest/_runner.py
def item_runner(root: Path) -> Callable[..., list[str]]:
    """Answer ``python.test.item-runner`` with `ci_item_runner`."""
    del root
    return ci_item_runner

ci_item_runner

ci_item_runner(*pytest_args: str, dirs: tuple[str, ...], root: Path, env: Mapping[str, str], serial: bool = False, sums_file: Path | None = None) -> list[str]

Answer python.test.item-runner: run CI test items one process per file.

Returns a list of failure descriptions (empty when every item passed or collected no tests). Prints captured output for every red item so CI logs carry the full failure trace.

Source code in packages/extensions/pytest/src/livery/extensions/pytest/_runner.py
def ci_item_runner(
    *pytest_args: str,
    dirs: tuple[str, ...],
    root: Path,
    env: Mapping[str, str],
    serial: bool = False,
    sums_file: Path | None = None,
) -> list[str]:
    """Answer ``python.test.item-runner``: run CI test items one process per file.

    Returns a list of failure descriptions (empty when every item passed or
    collected no tests). Prints captured output for every red item so CI
    logs carry the full failure trace.
    """
    items = _expand_targets(root, dirs)
    if not items:
        return []
    run = ci_run()
    durations: dict[str, float] = {}
    if run is not None and run.leg:
        loaded, _head, _rows, _why = read_durations(
            root, run.leg, before=checkout_time(root)
        )
        durations = dict(loaded)
    is_nightly = (
        env.get(POINT_VARIABLE, os.environ.get(POINT_VARIABLE, "")) == "nightly"
        or "--workshop-point=nightly" in pytest_args
    )
    no_select = item_selection_disabled(env)
    changed_items = _changed_test_items(root, items, run)
    if changed_items:
        print(
            f"  proved (repeats): repeating {len(changed_items)} changed item(s)"
            f" {CHANGED_ITEM_REPEATS}x with distinct PYTHONHASHSEED"
        )
    outcomes = run_items(
        root,
        items,
        pytest_args=pytest_args,
        env=env,
        durations=durations,
        max_workers=1 if serial else None,
        record=True,
        local=run is None,
        shadow=run is not None,
        select=not is_nightly and not no_select,
        audit=is_nightly,
        sums_file=sums_file,
        repeat_items=changed_items,
    )
    failures: list[str] = []
    for outcome in outcomes:
        if outcome.verdict == "red":
            if outcome.flaky:
                passed = sum(1 for v in outcome.repeat_verdicts if v == "green")
                failed = sum(1 for v in outcome.repeat_verdicts if v == "red")
                print(
                    f"  flaky: {outcome.item} passed {passed}/{outcome.repeats}"
                    f" repeats, failed {failed}/{outcome.repeats}"
                )
            if outcome.stdout:
                print(outcome.stdout, end="")
            if outcome.stderr:
                print(outcome.stderr, end="")
            if outcome.escaped:
                changed_desc = ", ".join(outcome.escape_changed) or "unknown"
                failures.append(f"{outcome.item} (ESCAPE: changed {changed_desc})")
            elif outcome.flaky:
                passed = sum(1 for v in outcome.repeat_verdicts if v == "green")
                failures.append(
                    f"{outcome.item} (flaky: {passed}/{outcome.repeats} green)"
                )
            else:
                failures.append(f"{outcome.item} (exit {outcome.code})")
    return failures