Skip to content

livery.workshop._legs

livery.workshop._legs

Plan a CI run's check legs and shard counts from the selected test items.

A check leg whose configured shard count is above one does not need all of its configured shards when only a handful of test items are selected. plan_legs runs in the workflow's opening legs job (via fm ci.legs): for each platform leg it asks the proved record which suites and test items are selected, reads the leg's item durations and balance measures, and calls livery.workshop._shard.shards_for_selection to choose 1 .. max_shards shards. It writes the planned shard counts to plan/<run_id> (livery.workshop._shard.write_shard_plan) so the gate job's fold validates the exact shards started for the run, and emits the matrix JSON for fromJSON(needs.legs.outputs.matrix).

Functions:

Name Description
plan_legs

Compute the check matrix and planned shard counts per platform leg.

plan_legs

plan_legs(root: Path, *, point: str = 'gate', run: RunContext | None = None, output: Path | None = None, store: StateStore | None = None, record: bool = True) -> tuple[dict[str, Any], dict[str, int]]

Compute the check matrix and planned shard counts per platform leg.

Sizes each sharded platform leg to the shards its selected test items need, writes the planned counts to plan/<run_id> when inside CI (and record is true), prints one summary line per leg, and appends matrix=<json> and skip_check=<bool> to output when given.

On a push to main, checks the hybrid proved-tree record first: when HEAD's exact git tree was already proved green across every required leg (for example on an up-to-date pull request that just merged), promotes the branch's proved rows and extension parts to main, records the verified tree on plan/<run_id>, and emits skip_check=true.

Returns:

Type Description
dict[str, Any]

(matrix_dict, planned_counts) where planned_counts maps each

dict[str, int]

platform leg label (check-<os>-<version>) to its shard count.

Source code in packages/workshop/src/livery/workshop/_legs.py
def plan_legs(
    root: Path,
    *,
    point: str = "gate",
    run: RunContext | None = None,
    output: Path | None = None,
    store: StateStore | None = None,
    record: bool = True,
) -> tuple[dict[str, Any], dict[str, int]]:
    """Compute the check matrix and planned shard counts per platform leg.

    Sizes each sharded platform leg to the shards its selected test items
    need, writes the planned counts to ``plan/<run_id>`` when inside CI
    (and *record* is true), prints one summary line per leg, and appends
    ``matrix=<json>`` and ``skip_check=<bool>`` to *output* when given.

    On a ``push`` to ``main``, checks the hybrid proved-tree record first:
    when HEAD's exact git tree was already proved green across every required
    leg (for example on an up-to-date pull request that just merged), promotes
    the branch's proved rows and extension parts to ``main``, records the
    verified tree on ``plan/<run_id>``, and emits ``skip_check=true``.

    Returns:
        ``(matrix_dict, planned_counts)`` where *planned_counts* maps each
        platform leg label (``check-<os>-<version>``) to its shard count.
    """
    from livery.workshop._ci_generate import matrix_for_leg_counts

    active_run = run_context() if run is None else run
    runners, configured = _configured_runners_and_shards(root, active_run)
    versions = gate_pythons(root)
    expected_legs = tuple(
        f"check-{runner}-{version}" for runner in runners for version in versions
    )
    has_split = any(configured.get(runner, 1) > 1 for runner in runners)
    placeholder_matrix = matrix_for_leg_counts(
        runners[:1], versions[:1], {}, sharded=has_split
    )
    early_out = _try_verified_main_early_out(
        root,
        active_run=active_run,
        expected_legs=expected_legs,
        placeholder_matrix=placeholder_matrix,
        output=output,
        store=store,
        record=record,
    )
    if early_out is not None:
        return early_out

    packages = discover_packages(root)
    ws_suite = workspace_suite(root)
    suites = (*packages, ws_suite) if ws_suite is not None else packages

    items_by_step: dict[str, dict[str, tuple[str, ...]]] = {}
    all_items_set: set[str] = set()
    if has_split:
        listers = answer(root, TEST_ITEMS)
        for step_name, lister in sorted(listers.items()):
            by_suite: dict[str, tuple[str, ...]] = {}
            for suite in suites:
                found_items = tuple(sorted(lister(suite)))
                if found_items:
                    by_suite[suite.path] = found_items
                    all_items_set.update(found_items)
            if by_suite:
                items_by_step[step_name] = by_suite
    all_items = tuple(sorted(all_items_set))

    snapshot_ctx = (
        git.remote_snapshot(
            state_store(root) if store is None else store,
            fetch=_prefetch_prefixes(runners, versions, active_run),
        )
        if has_split and items_by_step
        else nullcontext()
    )

    planned: dict[str, int] = {}
    leg_counts: dict[tuple[str, str], int] = {}
    with snapshot_ctx:
        escaped: frozenset[str] = frozenset()
        if has_split and items_by_step:
            escaped, _escaped_why = active_escaped_packages(root, store=store)
        measured = (
            _balance_readings(root, store=store) if has_split and items_by_step else {}
        )
        before = checkout_time(root) if has_split and items_by_step else None
        installed_dists = (
            _installed_distributions() if has_split and items_by_step else None
        )

        split_specs: list[tuple[str, str, int, str]] = []
        is_fork = active_run is not None and active_run.is_fork_pr
        for runner in runners:
            max_shards = configured.get(runner, 1)
            for version in versions:
                leg = f"check-{runner}-{version}"
                if max_shards <= 1 or not items_by_step or is_fork:
                    planned[leg] = max_shards
                    leg_counts[(runner, version)] = max_shards
                else:
                    split_specs.append((runner, version, max_shards, leg))

        def _evaluate(
            spec: tuple[str, str, int, str],
        ) -> tuple[str, str, int, str, int, str, int]:
            runner, version, max_shards, leg = spec
            selected, note = _selected_items_for_leg(
                root,
                leg=leg,
                os_label=runner,
                version=version,
                suites=suites,
                items_by_step=items_by_step,
                all_items=all_items,
                escaped=escaped,
                run=active_run,
                point=point,
                store=store,
                installed_dists=installed_dists,
            )
            durations: dict[str, float] = {}
            if before is not None:
                durations, _head, _rows, _why = read_durations(root, leg, before=before)
            reading = measured.get((runner, version))
            count = shards_for_selection(
                selected,
                all_items,
                durations,
                max_shards=max_shards,
                fixed=reading.fixed if reading is not None and reading.enough else 0.0,
                other=reading.other if reading is not None and reading.enough else 0.0,
                speed=reading.speed if reading is not None and reading.enough else 0.0,
            )
            return (runner, version, max_shards, leg, count, note, len(selected))

        if len(split_specs) > 1:
            with ThreadPoolExecutor(max_workers=len(split_specs)) as pool:
                futures = [
                    pool.submit(copy_context().run, _evaluate, spec)
                    for spec in split_specs
                ]
                results = [future.result() for future in futures]
        else:
            results = [_evaluate(spec) for spec in split_specs]

        for runner, version, max_shards, leg, count, note, sel_count in results:
            planned[leg] = count
            leg_counts[(runner, version)] = count
            suffix = f" ({note})" if note else ""
            print(
                f"  legs: {leg}: {sel_count} of {len(all_items)} item(s)"
                f" selected -> {count} of {max_shards} shard(s){suffix}"
            )

    matrix = matrix_for_leg_counts(runners, versions, leg_counts, sharded=has_split)
    if active_run is not None and active_run.is_fork_pr:
        print("  fork PR: read-only mode, skipping state-store writes")
    elif record and active_run is not None and active_run.run_id:
        why = write_shard_plan(root, active_run.run_id, planned, store=store)
        if why:
            print(f"  legs: plan/{active_run.run_id} not written ({why})")
    _write_legs_output(output, matrix, skip_check=False)
    return matrix, planned