Files
computer-playbook/cli/meta/ci/matrix.py
T
kevinveenbirkenbachandClaude Opus 5 c7fb6e60c5 fix(ci): narrow a row's architectures by what its variant deploys
row_architectures intersected the run's pool with the declarations of
every role in the complexity closure. That closure follows every
conditional provider flag through the base graph, so tor -> web-svc-mirror
-> prometheus -> openwebui -> litellm -> lmstudio put the amd64-only
lmstudio into the closure of 93 of 128 roles, including the minimal
variants that never deploy it. A single amd64 pin would have withdrawn
arm64 from nearly the whole matrix.

The matrix now replaces a row's services with the include set that
plan_dev_inventory_matrix, the planner the deploy step itself uses,
resolves for that variant. Against CI run 35674334334 it matches every
data point: lmstudio for zammad#2, moodle#2 and xwiki#2, which pulled it
on arm64, and not for docs#0 or legal#0, which did not. With the pins of
the next commit, 126 of 128 roles keep arm64 rows instead of 34.

Without any architecture declaration the emitted matrix is byte-identical
to before under a fixed discovery seed. The planner adds about 37 s per
matrix build, and a role whose plan errors now stops the matrix instead of
only its own deploy job.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-22 16:01:09 +02:00

278 lines
9.6 KiB
Python

"""Build the CI deploy matrix of one sweep, chunk by chunk.
Usage:
python -m cli.meta.ci.matrix --index N [--sweep S] [--modes auto]
[--whitelist "..."] [--priority "..."] [--lifecycles "..."] [--tor auto]
[--distros "..."] [--filesystem "..."] [--architectures "..."]
This is the pipeline the deploy jobs discover through, and the single place
the run's shape is decided:
1. Two discovery queries, keeping today's filter semantics: the priority line
is queried on its own whitelist so priority roles run even when the
diff-derived whitelist would not have selected them, and the regular line
is queried on the effective whitelist with the priority rows withdrawn.
Concatenated, they are the sweep's ordered candidate list. Both lists are
selection tokens (:mod:`utils.github.variant.selection`): what a token pins
narrows the row, what it leaves open the line decides as it always did.
2. Every row is assigned its deploy mode, tor state, distro, filesystem and
CPU architecture by its position in that list (:mod:`utils.github.variant.axes`).
3. The list is cut into serial chunks with a hard boundary at the
priority/regular seam (:mod:`cli.meta.ci.chunks`), sized by the run's job
and queue budget (:mod:`cli.meta.ci.slots`).
``--index`` then prints one chunk as the matrix JSON. Every chunk block runs
the same computation and takes its own slice, so the blocks agree without
passing state between them.
"""
from __future__ import annotations
import argparse
import functools
import json
import os
import sys
from cli.administration.deploy.development.inventory.planner import (
plan_dev_inventory_matrix,
)
from cli.meta.ci import chunks, query, slots
from utils.cache.applications import get_variants
from utils.cache.files import PROJECT_ROOT
from utils.github.variant import axes, instructions, pools, selection, tor
from utils.roles.display import display_names
DROPPED = ("priority", "id", "covered", "clone")
"""Entry keys the plan table reads but the matrix JSON withholds, so a deploy
job cannot reference one: they describe the row's rank, not its deployment."""
def candidates(
*,
modes: tuple[str, ...],
whitelist: str,
priority: str,
lifecycles: str,
) -> list[dict]:
"""The sweep's ordered candidate rows: priority line first, then the
regular line, each annotated with the modes it offers and whether it is
priority."""
leading = selection.parse_list(priority)
keep = selection.parse_list(whitelist)
rows: list[dict] = []
if leading:
rows += [
{**row, "priority": True}
for row in selection.apply(
query.discover_rows(
modes, whitelist=selection.names(leading), lifecycles=lifecycles
),
leading,
)
]
pinned = {(pin.app, variant) for pin in leading for variant in pin.variants}
regular = [
row
for row in query.discover_rows(
modes,
whitelist=selection.names(keep),
blacklist=selection.names(pin for pin in leading if not pin.variants),
lifecycles=lifecycles,
)
if (row["name"], row.get("variant")) not in pinned
]
rows += [{**row, "priority": False} for row in selection.apply(regular, keep)]
return [{**row, "modes": query.row_modes(row, modes)} for row in rows]
@functools.cache
def deployed_rounds(app: str) -> tuple[tuple[str, ...], ...]:
"""The apps each variant round of *app* deploys."""
return tuple(
include
for _index, _dir, _variants, include, _purge in plan_dev_inventory_matrix(
roles_dir=str(PROJECT_ROOT / "roles"),
primary_apps=[app],
base_inventory_dir="plan",
)
)
def with_deployed_services(row: dict) -> dict:
"""*row* with ``services`` narrowed to what its variant deploys."""
return {**row, "services": deployed_rounds(row["name"])[row.get("variant") or 0]}
def entries_of(
*,
modes: tuple[str, ...],
whitelist: str,
priority: str,
lifecycles: str,
sweep: int,
tor_mode: str,
distros: tuple[str, ...],
filesystems: tuple[str, ...],
architectures: tuple[str, ...] = pools.ARCHITECTURES,
) -> list[dict[str, str]]:
"""Every candidate row of the sweep, axes assigned, in global order."""
return axes.assign(
[
with_deployed_services(row)
for row in candidates(
modes=modes,
whitelist=whitelist,
priority=priority,
lifecycles=lifecycles,
)
],
sweep=sweep,
tor_mode=tor_mode,
distros=distros,
filesystems=filesystems,
architectures=architectures,
variants_per_app=get_variants(),
)
def resolve_offset(raw: int | str | None = None) -> str:
"""The offset a run was given, as written. ``None`` reads
``INFINITO_CI_OFFSET``; :func:`offset_index` decides what it means."""
if raw is None:
raw = os.environ.get("INFINITO_CI_OFFSET")
return "" if raw is None else str(raw).strip()
def offset_index(raw: int | str | None, regular: list[dict[str, str]]) -> int:
"""Where the regular chunks start reading.
A number is that many rows; anything else is a selection token
(:mod:`utils.github.variant.selection`) and the start is the first regular
row it names. Resuming at a role beats counting rows by hand: the ranking
shifts whenever a variant is added, so the index that meant 'carry on
behind nextcloud' yesterday means something else today, while the token
still says it.
Args:
raw: the ``offset`` input, a count or a token.
regular: the regular line in ranking order.
Raises:
SystemExit: a token that names no regular row. Starting at 0 instead
would silently redeploy the head an operator meant to skip.
"""
text = "" if raw is None else str(raw).strip()
if not text:
return 0
if text.lstrip("+-").isdigit():
return max(int(text), 0)
pin = selection.parse(text)
for index, entry in enumerate(regular):
if selection.covers(pin, entry):
return index
raise SystemExit(
f"offset {selection.describe(pin)!r} names no row of the regular line; "
f"it is on the priority line, outside the run's filters, or gone"
)
def chunks_of(
entries: list[dict[str, str]], offset: int | str | None = 0
) -> list[list[dict[str, str]]]:
"""Cut the sweep's entries into its chunks, priority blocks first.
Chunk 0 holds the head of the ranking unless *offset* moves it; the order
*inside* a chunk is then sorted
(:func:`utils.github.variant.axes.sort_key`), so the job list reads by role
rather than by rank."""
regular = [
entry
for entry in entries
if entry["priority"] != "true" and not instructions.redundant(entry)
]
return [
sorted(chunk, key=axes.sort_key)
for chunk in chunks.plan(
[entry for entry in entries if entry["priority"] == "true"],
regular,
size=slots.chunk_size(),
blocks=slots.chunk_blocks(),
budget=slots.available(),
offset=offset_index(offset, regular),
)
]
def build_sweep(
*,
modes: tuple[str, ...],
whitelist: str,
priority: str,
lifecycles: str,
sweep: int,
tor_mode: str,
distros: tuple[str, ...],
filesystems: tuple[str, ...],
architectures: tuple[str, ...] = pools.ARCHITECTURES,
offset: int = 0,
) -> list[list[dict[str, str]]]:
"""Every chunk of the sweep, priority blocks first."""
return chunks_of(
entries_of(
modes=modes,
whitelist=whitelist,
priority=priority,
lifecycles=lifecycles,
sweep=sweep,
tor_mode=tor_mode,
distros=distros,
filesystems=filesystems,
architectures=architectures,
),
offset,
)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
description="Build the CI deploy matrix of one sweep chunk."
)
parser.add_argument("--index", type=int, required=True)
parser.add_argument("--sweep", type=int, default=None)
parser.add_argument("--modes", default=query.ALL_MODES)
parser.add_argument("--whitelist", default="")
parser.add_argument("--priority", default="")
parser.add_argument("--lifecycles", default="")
parser.add_argument("--tor", default=None)
parser.add_argument("--distros", default="")
parser.add_argument("--filesystem", default="")
parser.add_argument("--architectures", default="")
parser.add_argument("--offset", default=None)
args = parser.parse_args(argv)
codec = display_names()
if args.lifecycles.strip():
os.environ["INFINITO_LIFECYCLES"] = args.lifecycles
sweep = axes.resolve_sweep() if args.sweep is None else args.sweep
plan = build_sweep(
modes=query.resolve_modes(args.modes),
whitelist=codec.decode_list(args.whitelist),
priority=codec.decode_list(args.priority),
lifecycles=args.lifecycles,
sweep=sweep,
tor_mode=tor.resolve_tor_mode(args.tor),
distros=pools.resolve_distros(args.distros),
filesystems=pools.resolve_filesystems(args.filesystem),
architectures=pools.resolve_architectures(args.architectures),
offset=resolve_offset(args.offset),
)
chunk = plan[args.index] if 0 <= args.index < len(plan) else []
print(json.dumps([{k: v for k, v in e.items() if k not in DROPPED} for e in chunk]))
return 0
if __name__ == "__main__":
sys.exit(main())