diff --git a/cli/meta/ci/variant_split/__init__.py b/cli/meta/ci/variant_split/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/cli/meta/ci/variant_split/__main__.py b/cli/meta/ci/variant_split/__main__.py new file mode 100644 index 0000000000..43623f3b98 --- /dev/null +++ b/cli/meta/ci/variant_split/__main__.py @@ -0,0 +1,191 @@ +"""Verify that a variant split keeps the coverage of the row it shortens.""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + +from utils.cache.files import read_text + +from . import compare, cost, segments, snapshot + +DEFAULT_SWEEPS = "0,1,2,3,4,5" + + +def _load(path: str) -> dict: + return json.loads(read_text(path)) + + +def _tokens(raw: str) -> list[str]: + return [part.strip() for part in raw.split(",") if part.strip()] + + +def build_parser() -> argparse.ArgumentParser: + p = argparse.ArgumentParser( + prog="infinito meta ci variant_split", + description=( + "Check a variant split against the CI matrix the repository really " + "plans: 'snapshot' records the rows, rounds, edges, axes and budget " + "of the current tree under one CI run's discovery seed; 'compare' " + "diffs a snapshot taken before the split with one taken after it, " + "edge by edge, pin-aware coverage credit by credit and axis pair by " + "axis pair over the sweeps; 'segments' measures one row's per-app " + "time on one runner and 'merge' joins measurements of one runner; " + "'cost' turns them into the per-row saving and the net runner-time " + "delta. Nothing is deployed or written outside --out." + ), + ) + sub = p.add_subparsers(dest="command", required=True) + snap = sub.add_parser("snapshot", help="Record the current tree's matrix.") + snap.add_argument("--out", required=True, help="JSON file to write.") + snap.add_argument( + "--seed", + required=True, + help="Discovery seed: the CI run id, as CI sets INFINITO_DISCOVERY_SEED.", + ) + snap.add_argument( + "--sweeps", default=DEFAULT_SWEEPS, help="Comma-separated sweep numbers." + ) + cmp_ = sub.add_parser("compare", help="Diff a before and an after snapshot.") + cmp_.add_argument("before", help="Snapshot of the tree without the split.") + cmp_.add_argument("after", help="Snapshot of the tree with the split.") + cmp_.add_argument( + "--old", required=True, help="Comma-separated tokens the split replaces." + ) + cmp_.add_argument( + "--split", required=True, help="Comma-separated tokens that carry them now." + ) + cmp_.add_argument("--out", default=None, help="Write the verdict JSON here too.") + cst = sub.add_parser("cost", help="Per-row saving and net runner-time delta.") + cst.add_argument("before", help="Snapshot of the tree without the split.") + cst.add_argument("after", help="Snapshot of the tree with the split.") + cst.add_argument("--segments", required=True, help="Measured per-app segment JSON.") + cst.add_argument("--old", required=True, help="Comma-separated replaced tokens.") + cst.add_argument("--split", required=True, help="Comma-separated carrying tokens.") + seg = sub.add_parser("segments", help="Per-app segments of one measured row.") + seg.add_argument("snapshot", help="Snapshot whose round of --row is measured.") + seg.add_argument("--row", required=True, help="The measured row's token.") + seg.add_argument( + "--runner", + required=True, + help="The runner the measured job ran on; merge joins one runner only.", + ) + seg.add_argument( + "--pass", + dest="passes", + action="append", + required=True, + metavar="N=TSV|N=FIRST:LAST", + help=( + "Pass number and its per-task wall TSV, or with --log its line " + "range from the PASS marker (LAST empty: end of log); repeat per pass." + ), + ) + seg.add_argument( + "--log", + default=None, + help="Raw deploy log to segment by first task per app; prints aggregates only.", + ) + seg.add_argument("--cut", default="", help="Comma-separated passes that were cut.") + seg.add_argument("--out", required=True, help="Segments JSON to write.") + mrg = sub.add_parser("merge", help="Join segments files of one runner.") + mrg.add_argument( + "files", nargs="+", help="Segments files, the primary first; one runner." + ) + mrg.add_argument("--out", required=True, help="Merged segments JSON to write.") + return p + + +def _span(span: str) -> tuple[int, int | None]: + first, _, last = span.partition(":") + return int(first), int(last) if last else None + + +def _segments(args: argparse.Namespace) -> int: + from utils.roles.entity.name import entity_name + + record = _load(args.snapshot)["rounds"][args.row] + passes = dict(item.split("=", 1) for item in args.passes) + source = f"{args.row}: " + ", ".join( + f"pass {n} {p}" for n, p in sorted(passes.items()) + ) + if args.log: + data = segments.build_from_log( + read_text(args.log).splitlines(), + {number: _span(span) for number, span in passes.items()}, + list(record["include"]), + runner=args.runner, + cut=_tokens(args.cut), + source=f"{Path(args.log).name} {source}", + ) + else: + data = segments.build( + {number: read_text(path) for number, path in passes.items()}, + list(record["include"]), + entity_of=entity_name, + runner=args.runner, + cut=_tokens(args.cut), + source=source, + ) + Path(args.out).write_text(json.dumps(data, sort_keys=True)) + for number in sorted(data["passes"]): + top = sorted(data["passes"][number].items(), key=lambda kv: -kv[1])[:8] + print( + f"pass {number}: total {data['measured_total'][number]}s, fixed " + f"{data['measured_fixed'][number]}s, top apps {top}" + ) + return 0 + + +def _merge(args: argparse.Namespace) -> int: + data = segments.merge([_load(path) for path in args.files]) + Path(args.out).write_text(json.dumps(data, sort_keys=True)) + priced = {number: len(apps) for number, apps in sorted(data["passes"].items())} + print( + f"runner {data['runner']}: apps priced per pass {priced}, lower bound " + f"{data['lower_bound']} -> {args.out}" + ) + return 0 + + +def _run(args: argparse.Namespace) -> int: + if args.command == "snapshot": + data = snapshot.take([int(s) for s in _tokens(args.sweeps)], seed=args.seed) + Path(args.out).write_text(json.dumps(data, sort_keys=True)) + print( + f"{len(data['rows'])} rows, {len(data['rounds'])} rounds, sweeps " + f"{sorted(data['sweeps'])}, budget {data['budget']['available']}, " + f"seed {data['seed']} -> {args.out}" + ) + return 0 + if args.command == "segments": + return _segments(args) + if args.command == "merge": + return _merge(args) + before, after = _load(args.before), _load(args.after) + snapshot.check_seeds(before, after) + old, split = _tokens(args.old), _tokens(args.split) + if args.command == "compare": + verdict = compare.verdict(before, after, old=old, split=split) + print(compare.render(verdict)) + if args.out: + Path(args.out).write_text(json.dumps(verdict, sort_keys=True, default=list)) + return 0 if verdict["kept"] else 1 + result = cost.delta(before, after, _load(args.segments), old=old, split=split) + print(cost.render(result)) + return 0 + + +def main(argv: list[str] | None = None) -> int: + args = build_parser().parse_args(argv) + try: + return _run(args) + except ValueError as exc: + print(f"error: {exc}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/cli/meta/ci/variant_split/compare.py b/cli/meta/ci/variant_split/compare.py new file mode 100644 index 0000000000..50f16140ae --- /dev/null +++ b/cli/meta/ci/variant_split/compare.py @@ -0,0 +1,361 @@ +"""Diff a before and an after snapshot into the verdict on a variant split.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from .coverage import children, credit_findings, declared +from .edges import LEVELS, Edge, missing, union +from .rounds import edges_of + +if TYPE_CHECKING: + from collections.abc import Iterable, Mapping + +LEVEL = "keys" + + +def _tok(entry: Mapping[str, str]) -> str: + return f"{entry['apps']}#{entry['variant'] or 0}" + + +def regular_tokens(snap: Mapping[str, Any], sweep: str) -> list[str]: + """Tokens of the job list of one sweep, in ranking order. + + Args: + snap: a snapshot. + sweep: the sweep key. + """ + return list(snap["sweeps"][sweep]["jobs"]) + + +def head_tokens(snap: Mapping[str, Any], sweep: str) -> set[str]: + """Tokens the sweep's budget head deploys. + + Args: + snap: a snapshot. + sweep: the sweep key. + """ + return {_tok(e) for e in snap["sweeps"][sweep]["head"]} + + +def _edges(snap: Mapping[str, Any], tokens: Iterable[str]) -> list[set[Edge]]: + return [edges_of(snap["rounds"][t]) for t in tokens if t in snap["rounds"]] + + +def edge_check( + before: Mapping[str, Any], + after: Mapping[str, Any], + *, + old: list[str], + split: list[str], +) -> dict[str, Any]: + """Whether the edges of the replaced rows still run after the split. + + Each old row's round is collapsed on its own (:func:`.edges.union`), so + the check never asks for a key set that no single old round deployed. + + Args: + before: the snapshot without the split. + after: the snapshot with it. + old: the tokens the split replaces. + split: the tokens that carry them now. + """ + old_rounds = _edges(before, old) + sweeps = sorted(after["sweeps"]) + head = set().union(*(head_tokens(after, s) for s in sweeps)) + jobs = set().union(*(regular_tokens(after, s) for s in sweeps)) + before_head = set().union(*(head_tokens(before, s) for s in sweeps)) + out: dict[str, Any] = {"total": {}, "local": {}, "head": {}, "jobs": {}} + for level in LEVELS: + out["total"][level] = len(union(old_rounds, level)) + out["local"][level] = sorted(missing(old_rounds, _edges(after, split), level)) + out["head"][level] = sorted(missing(old_rounds, _edges(after, head), level)) + out["jobs"][level] = sorted(missing(old_rounds, _edges(after, jobs), level)) + out["regression"] = sorted( + missing(_edges(before, before_head), _edges(after, head), LEVEL) + ) + return out + + +def _include_pairs( + snap: Mapping[str, Any], entries: Iterable[Mapping[str, str]], axis: str +) -> set[tuple[str, str]]: + out = set() + for entry in entries: + record = snap["rounds"].get(_tok(entry)) + if not record: + continue + for role in record["include"]: + out.add((f"{role}#{record['active'].get(role, 0)}", entry[axis])) + return out + + +def axes_check(before: Mapping[str, Any], after: Mapping[str, Any]) -> dict[str, Any]: + """What the shifted rotation and budget cost per sweep and over all sweeps. + + Args: + before: the snapshot without the split. + after: the snapshot with it. + """ + per_sweep = {} + union_lost: dict[str, list[set]] = {} + for sweep in sorted(set(before["sweeps"]) & set(after["sweeps"])): + b_head = before["sweeps"][sweep]["head"] + a_head = after["sweeps"][sweep]["head"] + facts: dict[str, Any] = { + "head_lost": sorted(head_tokens(before, sweep) - head_tokens(after, sweep)), + "head_gained": sorted( + head_tokens(after, sweep) - head_tokens(before, sweep) + ), + "spill_before": len(before["sweeps"][sweep]["jobs"]) + - before["budget"]["available"], + "spill_after": len(after["sweeps"][sweep]["jobs"]) + - after["budget"]["available"], + } + pairs = { + "row_mode": ( + {(_tok(e), e["mode"]) for e in b_head}, + {(_tok(e), e["mode"]) for e in a_head}, + ), + "include_mode": ( + _include_pairs(before, b_head, "mode"), + _include_pairs(after, a_head, "mode"), + ), + "include_network": ( + _include_pairs(before, b_head, "network"), + _include_pairs(after, a_head, "network"), + ), + "include_distro": ( + _include_pairs(before, b_head, "distro"), + _include_pairs(after, a_head, "distro"), + ), + } + for name, (b, a) in pairs.items(): + facts[name] = sorted(b - a) + union_lost.setdefault(name, [set(), set()]) + union_lost[name][0] |= b + union_lost[name][1] |= a + per_sweep[sweep] = facts + return { + "per_sweep": per_sweep, + "union": {name: sorted(b - a) for name, (b, a) in union_lost.items()}, + } + + +def pin_check(before: Mapping[str, Any], after: Mapping[str, Any]) -> dict[str, Any]: + """New pins and whether they reciprocate, new dark pins, new round errors. + + Args: + before: the snapshot without the split. + after: the snapshot with it. + """ + seen = {(p["carrier"], p["partner"], p["target"]) for p in before["pins"]} + new_pins = [ + p + for p in after["pins"] + if (p["carrier"], p["partner"], p["target"]) not in seen + ] + unreciprocated = [ + p + for p in new_pins + if not isinstance(p["reciprocal"], int) + or (p["target"] != "reciprocal" and int(p["target"]) != p["reciprocal"]) + ] + + def faults(snap: Mapping[str, Any], field: str) -> set[str]: + out = set() + for tok, record in snap["rounds"].items(): + value = record.get(field) + for item in value if isinstance(value, list) else [value] if value else []: + out.add(f"{tok}: {item}") + return out + + grown = { + role: (before["variant_counts"].get(role, 1), count) + for role, count in after["variant_counts"].items() + if count > before["variant_counts"].get(role, 1) + } + return { + "new_pins": new_pins, + "unreciprocated": unreciprocated, + "new_dark_pins": sorted( + faults(after, "dark_pins") - faults(before, "dark_pins") + ), + "new_errors": sorted(faults(after, "error") - faults(before, "error")), + "variants_grown": grown, + } + + +def _false_credits(found: Mapping[str, Any]) -> set[tuple[str, str | None, str]]: + return { + (tok, coverer, fault) + for tok, (coverer, fault) in found["false_credits"].items() + } + + +def invariant_check( + before: Mapping[str, Any], after: Mapping[str, Any] +) -> dict[str, Any]: + """The coverage invariant over the full job list, before and after. + + A row past the budget still counts: what must hold is that every child is + deployed by some row of the job list, every edge is carried by one, and no + credit is false. A false credit is the row, its coverer and the reason; + moving a credit from one wrong coverer to another introduces a new one. An + edge at variant level counts as lost only while the after tree still + declares it (:func:`.coverage.declared`); one the split retires from a + variant's own config is no loss. + + Args: + before: the snapshot without the split. + after: the snapshot with it. + """ + b, a = children(before), children(after) + + def counts(found: Mapping[str, Any]) -> dict[str, Any]: + return { + "jobs": len(found["jobs"]), + "uncovered": sorted(found["uncovered"]), + "false_credits": sorted( + f"{tok}: {fault}" for tok, _coverer, fault in _false_credits(found) + ), + "edges": len(found["edges"]), + "variant_edges": len(found["variant_edges"]), + } + + lost_variant_edges = b["variant_edges"] - a["variant_edges"] + return { + "before": counts(b), + "after": counts(a), + "newly_uncovered": sorted(set(a["uncovered"]) - set(b["uncovered"])), + "introduced_false_credits": sorted( + f"{tok}: {fault}" + for tok, _coverer, fault in _false_credits(a) - _false_credits(b) + ), + "edges_lost": sorted(b["edges"] - a["edges"]), + "variant_edges_lost": sorted( + list(edge) for edge in lost_variant_edges if declared(after, edge) + ), + "variant_edges_retired": len( + [edge for edge in lost_variant_edges if not declared(after, edge)] + ), + } + + +def verdict( + before: Mapping[str, Any], + after: Mapping[str, Any], + *, + old: list[str], + split: list[str], +) -> dict[str, Any]: + """Every check of a split and whether it keeps all coverage. + + Coverage is judged over the full job list (:func:`invariant_check`); the + budget head and the axes per sweep are reported, not judged. + + Args: + before: the snapshot without the split. + after: the snapshot with it. + old: the tokens the split replaces. + split: the tokens that carry them now. + """ + edges = edge_check(before, after, old=old, split=split) + credit = credit_findings(before, after) + axes = axes_check(before, after) + pins = pin_check(before, after) + invariant = invariant_check(before, after) + kept = not ( + invariant["newly_uncovered"] + or invariant["introduced_false_credits"] + or invariant["edges_lost"] + or invariant["variant_edges_lost"] + or credit["introduced"] + or pins["unreciprocated"] + or pins["new_dark_pins"] + or pins["new_errors"] + ) + return { + "kept": kept, + "invariant": invariant, + "edges": edges, + "coverage": credit, + "axes": axes, + "pins": pins, + } + + +def render(result: Mapping[str, Any]) -> str: + """A plain-text summary of :func:`verdict`. + + Args: + result: the verdict. + """ + e, c, a, p = result["edges"], result["coverage"], result["axes"], result["pins"] + inv = result["invariant"] + total = e["total"][LEVEL] + lines = [ + f"coverage kept: {'yes' if result['kept'] else 'NO'}", + ( + f"job list before/after: rows {inv['before']['jobs']}/" + f"{inv['after']['jobs']}, uncovered children " + f"{len(inv['before']['uncovered'])}/{len(inv['after']['uncovered'])}, " + f"false credits {len(inv['before']['false_credits'])}/" + f"{len(inv['after']['false_credits'])}, edges " + f"{inv['before']['edges']}/{inv['after']['edges']}, variant edges " + f"{inv['before']['variant_edges']}/{inv['after']['variant_edges']}" + ), + f" newly uncovered {inv['newly_uncovered']}", + f" introduced false credits {inv['introduced_false_credits']}", + ( + f" edges lost over the job list {len(inv['edges_lost'])} " + f"{inv['edges_lost'][:12]}" + ), + ( + f" variant edges lost over the job list " + f"{len(inv['variant_edges_lost'])} {inv['variant_edges_lost'][:12]}, " + f"retired by the split {inv['variant_edges_retired']}" + ), + ( + f"edges ({LEVEL}): local {total - len(e['local'][LEVEL])}/{total}, " + f"head {total - len(e['head'][LEVEL])}/{total}, " + f"jobs {total - len(e['jobs'][LEVEL])}/{total}; strict local " + f"{e['total']['strict'] - len(e['local']['strict'])}/{e['total']['strict']}" + ), + ( + f"budget-head regression ({LEVEL}, reported only): " + f"{len(e['regression'])} {e['regression'][:12]}" + ), + ( + f"coverage credits: introduced false {len(c['introduced'])}, pre-existing " + f"false {len(c['preexisting'])}, thinner {len(c['thinner'])}, newly " + f"uncovered {c['newly_uncovered']}, newly covered {c['newly_covered']}" + ), + ] + lines.extend(f" {item}" for item in (c["introduced"] + c["thinner"])[:12]) + for sweep, facts in sorted(a["per_sweep"].items()): + lines.append( + f"sweep {sweep}: spill {facts['spill_before']} -> {facts['spill_after']}, " + f"head lost {facts['head_lost']}, gained {facts['head_gained']}, lost " + f"row x mode {len(facts['row_mode'])}, include x mode " + f"{len(facts['include_mode'])}, x network {len(facts['include_network'])}, " + f"x distro {len(facts['include_distro'])}" + ) + lines.append( + "sweeps union lost: " + + ", ".join( + f"{name} {len(items)}" for name, items in sorted(a["union"].items()) + ) + ) + lines.append(f" row x mode: {a['union']['row_mode'][:16]}") + lines.append(f" include x mode: {a['union']['include_mode'][:16]}") + lines.append( + f"pins: new {len(p['new_pins'])}, unreciprocated {len(p['unreciprocated'])}, " + f"new dark {p['new_dark_pins']}, new errors {p['new_errors']}, " + f"variants grown {p['variants_grown']}" + ) + lines.extend( + f" {pin['carrier']} -> {pin['partner']}#{pin['target']}: {pin['reciprocal']}" + for pin in p["unreciprocated"] + ) + return "\n".join(lines) diff --git a/cli/meta/ci/variant_split/cost.py b/cli/meta/ci/variant_split/cost.py new file mode 100644 index 0000000000..8a6ce6c504 --- /dev/null +++ b/cli/meta/ci/variant_split/cost.py @@ -0,0 +1,181 @@ +"""Per-row saving and net runner-time delta of a split, from measured segments. + +A row's time is its fixed cost plus the measured segment of every app its +round deploys, per pass. An app with no measured segment adds nothing and is +listed, so every figure is a lower bound until the list is empty. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from collections.abc import Iterable, Mapping + +FIXED = { + "prep": 273.0, + "container": 204.0, + "infra_per_pass": 540.0, + "backup": 340.0, + "dr_drill_variant0": 152.0, + "reset_post": 170.0, +} + + +def row_cost( + include: Iterable[str], variant: int, segments: Mapping[str, Any] +) -> tuple[float, list[str]]: + """The modelled seconds of one row and the apps it could not price. + + Args: + include: the apps the row's round deploys. + variant: the row's variant index; only ``#0`` runs the DR drill. + segments: ``passes`` (pass -> {app: seconds}), optional ``e2e`` + ({app: seconds}), optional ``fixed`` overrides of :data:`FIXED`, + and optional ``measured_e2e`` (pass -> the measured row's E2E + tail) with ``measured_apps`` (its include size); the tail is then + scaled by the share of priced apps, a linear stand-in for a + parallel Playwright drain. + """ + fixed = {**FIXED, **(segments.get("fixed") or {})} + passes: Mapping[str, Mapping[str, float]] = segments["passes"] + seconds = ( + fixed["prep"] + + fixed["container"] + + fixed["backup"] + + fixed["reset_post"] + + fixed["infra_per_pass"] * len(passes) + + (fixed["dr_drill_variant0"] if variant == 0 else 0.0) + ) + unpriced: set[str] = set() + apps = list(include) + for per_app in passes.values(): + for app in apps: + if app in per_app: + seconds += float(per_app[app]) + else: + unpriced.add(app) + e2e = segments.get("e2e") or {} + seconds += sum(float(e2e.get(app, 0.0)) for app in apps) + measured_apps = segments.get("measured_apps") or 0 + if measured_apps: + priced = len([app for app in apps if app not in unpriced]) + seconds += ( + sum(segments.get("measured_e2e", {}).values()) * priced / measured_apps + ) + return seconds, sorted(unpriced) + + +def _variant(tok: str) -> int: + return int(tok.rsplit("#", 1)[1]) + + +def _priced( + snap: Mapping[str, Any], tok: str, segments: Mapping[str, Any] +) -> tuple[float, list[str]]: + record = snap["rounds"].get(tok) + if not record: + return 0.0, [] + return row_cost(record["include"], _variant(tok), segments) + + +def _changed( + before: Mapping[str, Any], + after: Mapping[str, Any], + b_set: set[str], + a_set: set[str], +) -> tuple[set[str], set[str]]: + same = { + tok + for tok in b_set & a_set + if before["rounds"][tok]["include"] == after["rounds"][tok]["include"] + } + return b_set - same, a_set - same + + +def delta( + before: Mapping[str, Any], + after: Mapping[str, Any], + segments: Mapping[str, Any], + *, + old: list[str], + split: list[str], +) -> dict[str, Any]: + """The saving per replaced row and the runner-time delta of the whole list. + + Args: + before: the snapshot without the split. + after: the snapshot with it. + segments: the measured per-app segments (:func:`row_cost`). + old: the tokens the split replaces. + split: the tokens that carry them now. + """ + rows = {} + for tok in sorted(set(old) | set(split)): + b, b_unpriced = ( + _priced(before, tok, segments) if tok in before["rounds"] else (0.0, []) + ) + a, a_unpriced = ( + _priced(after, tok, segments) if tok in after["rounds"] else (0.0, []) + ) + rows[tok] = { + "before": round(b), + "after": round(a), + "saving": round(b - a), + "unpriced": sorted(set(b_unpriced) | set(a_unpriced)), + } + scopes = {} + for scope, pick in (("jobs", "jobs"), ("head", "head")): + if pick == "jobs": + b_set = set().union( + *(before["sweeps"][s]["jobs"] for s in before["sweeps"]) + ) + a_set = set().union(*(after["sweeps"][s]["jobs"] for s in after["sweeps"])) + else: + b_set = { + f"{e['apps']}#{e['variant'] or 0}" + for e in before["sweeps"]["0"]["head"] + } + a_set = { + f"{e['apps']}#{e['variant'] or 0}" for e in after["sweeps"]["0"]["head"] + } + gone, came = _changed(before, after, b_set, a_set) + b_total = sum(_priced(before, t, segments)[0] for t in gone) + a_total = sum(_priced(after, t, segments)[0] for t in came) + unpriced = sorted( + {app for t in gone for app in _priced(before, t, segments)[1]} + | {app for t in came for app in _priced(after, t, segments)[1]} + ) + scopes[scope] = { + "removed_or_changed": sorted(gone), + "added_or_changed": sorted(came), + "delta": round(a_total - b_total), + "unpriced": unpriced, + } + return { + "rows": rows, + "net": scopes, + "source": segments.get("source", ""), + "runner": segments["runner"], + } + + +def render(result: Mapping[str, Any]) -> str: + """A plain-text summary of :func:`delta`. + + Args: + result: the cost result. + """ + lines = [f"segments: {result['source']} on runner {result['runner']}"] + for tok, facts in result["rows"].items(): + lines.append( + f"{tok}: {facts['before']}s -> {facts['after']}s, saving {facts['saving']}s; " + f"unpriced {facts['unpriced']}" + ) + for scope, facts in result["net"].items(): + lines.append( + f"net runner time over the {scope}: {facts['delta']:+d}s " + f"(out {facts['removed_or_changed']}, in {facts['added_or_changed']}); " + f"unpriced {facts['unpriced']}" + ) + return "\n".join(lines) diff --git a/cli/meta/ci/variant_split/coverage.py b/cli/meta/ci/variant_split/coverage.py new file mode 100644 index 0000000000..94aaf500f0 --- /dev/null +++ b/cli/meta/ci/variant_split/coverage.py @@ -0,0 +1,247 @@ +"""Pin-aware check of the coverage credits the sweep drops rows on. + +``_mark_covered`` in :mod:`cli.meta.roles.applications.complexity.cli` +credits a row to an earlier row whose role-level closure names it, and never +looks at the pins that settle the coverer's round. This module re-checks every +credit against the round the coverer really deploys. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from .edges import MCP_KEY, Edge, identities +from .rounds import edges_of + +if TYPE_CHECKING: + from collections.abc import Mapping + +LEVEL = "keys" + + +def _by_id(snap: Mapping[str, Any]) -> dict[int, Mapping[str, Any]]: + return {row["id"]: row for row in snap["rows"]} + + +def credit_state( + snap: Mapping[str, Any], row: Mapping[str, Any] +) -> tuple[str | None, set[tuple] | None, str | None]: + """How the round that covers *row* really deploys it. + + Args: + snap: a snapshot. + row: a covered row of it. + + Returns: + ``(coverer token, keys-level identities of the row's role as a + consumer in that round, fault)``; the fault names a credit the round + does not honour, else it is ``None``. + """ + coverer = _by_id(snap).get(row["covered_by"]) + if coverer is None: + return None, None, f"coverer id {row['covered_by']} is not a row" + record = snap["rounds"].get(coverer["token"]) or {} + name = row["name"] + if name not in record.get("include", ()): + return coverer["token"], None, f"{coverer['token']} does not deploy {name}" + dictator = record.get("dictated", {}).get(name) + if dictator: + return ( + coverer["token"], + None, + f"{dictator} dictates the config of {name} in {coverer['token']}", + ) + index = record["active"].get(name, 0) + own = {edge for edge in edges_of(record) if edge.consumer == name} + fault = ( + None + if index == 0 + else f"{coverer['token']} runs {name}#{index}, not the credited #0" + ) + return coverer["token"], identities(own, LEVEL), fault + + +def own_round(snap: Mapping[str, Any], row: Mapping[str, Any]) -> set[tuple]: + """The row's role as a consumer in its own round. + + Args: + snap: a snapshot. + row: a row of it. + """ + record = snap["rounds"].get(row["token"]) or {} + return identities( + {edge for edge in edges_of(record) if edge.consumer == row["name"]}, LEVEL + ) + + +def credit_findings( + before: Mapping[str, Any], after: Mapping[str, Any] +) -> dict[str, Any]: + """Credits the split breaks or thins, and rows it moves in or out of the list. + + Args: + before: the snapshot without the split. + after: the snapshot with it. + + Returns: + ``introduced`` (a credit the coverer's round does not honour, unless + the row's credit was already broken by the same coverer in the same + way), ``preexisting`` (those unchanged broken credits), ``thinner`` + (the row's role reaches fewer providers under its coverer than it did + before), ``newly_uncovered`` and ``newly_covered`` tokens. + """ + old_rows = {row["token"]: row for row in before["rows"]} + introduced, preexisting, thinner = [], [], [] + newly_uncovered, newly_covered = [], [] + for row in after["rows"]: + old = old_rows.get(row["token"]) + old_covered = bool(old and old["covered_by"] and not old["clone"]) + if row["clone"]: + continue + if not row["covered_by"]: + if old_covered: + newly_uncovered.append(row["token"]) + continue + coverer, held, fault = credit_state(after, row) + if old_covered: + old_coverer, old_held, old_fault = credit_state(before, old) + else: + newly_covered.append(row["token"]) + old_coverer, old_held, old_fault = ( + row["token"], + own_round(before, old or row), + None, + ) + if fault: + unchanged = old_fault is not None and (old_coverer, old_fault) == ( + coverer, + fault, + ) + (preexisting if unchanged else introduced).append( + f"{row['token']}: {fault}" + ) + continue + lost = (old_held or set()) - (held or set()) + if lost: + thinner.append( + f"{row['token']}: under {coverer} it no longer reaches " + f"{sorted(item[1] for item in lost)} the way {old_coverer} did" + ) + return { + "introduced": sorted(introduced), + "preexisting": sorted(preexisting), + "thinner": sorted(thinner), + "newly_uncovered": sorted(newly_uncovered), + "newly_covered": sorted(newly_covered), + } + + +def job_tokens(snap: Mapping[str, Any]) -> set[str]: + """Every row of the job list, over all sweeps, inside the budget or past it. + + Args: + snap: a snapshot. + """ + return set().union(*(snap["sweeps"][s]["jobs"] for s in snap["sweeps"])) + + +def children(snap: Mapping[str, Any]) -> dict[str, Any]: + """The coverage invariant over the full job list of one snapshot. + + A child is every candidate ``role#variant``. It is covered when some row of + the job list, run or not, deploys that role at that variant in its settled + round with the config the role declares. A credit is false when its + coverer is not in the job list or its round does not deploy the credited + role at variant 0 with its own config. + + Args: + snap: a snapshot. + + Returns: + ``jobs`` (tokens), ``uncovered`` (token -> reason), ``false_credits`` + (token -> ``(coverer token, reason)``), ``edges`` (keys-level + identities the job list carries) and ``variant_edges`` (every + :class:`Edge` the job list carries, variants included). + """ + jobs = job_tokens(snap) + deployed: set[str] = set() + edges: set[tuple] = set() + variant_edges: set[Edge] = set() + for tok in jobs: + record = snap["rounds"].get(tok) + if not record: + continue + own_config = set(record["include"]) - set(record.get("dictated", {})) + deployed |= {f"{role}#{record['active'].get(role, 0)}" for role in own_config} + round_edges = edges_of(record) + edges |= identities(round_edges, LEVEL) + variant_edges |= round_edges + by_id = _by_id(snap) + uncovered, false_credits = {}, {} + for row in snap["rows"]: + child = f"{row['name']}#{row['variant'] or 0}" + if child not in deployed: + uncovered[row["token"]] = ( + "no row of the job list deploys it at this variant" + ) + if row["clone"] or not row["covered_by"]: + continue + coverer = by_id.get(row["covered_by"]) + token, _held, fault = credit_state(snap, row) + if coverer is not None and coverer["token"] not in jobs: + fault = f"{coverer['token']} is not in the job list" + if fault: + false_credits[row["token"]] = (token, fault) + return { + "jobs": jobs, + "uncovered": uncovered, + "false_credits": false_credits, + "edges": edges, + "variant_edges": variant_edges, + } + + +def declared(snap: Mapping[str, Any], edge: Edge) -> bool: + """Whether the tree of *snap* still declares *edge* at its variants. + + A service key lives in the consumer's map, so the consumer's own row + decides; an MCP pair is admitted by the provider's map, so the provider's + own row decides. Without that row the edge counts as declared while its + variant still exists, so a loss is never explained away by a missing row. + + Args: + snap: a snapshot. + edge: an edge some earlier job list carried. + """ + if edge.key == MCP_KEY: + role, variant = edge.provider, edge.provider_variant + else: + role, variant = edge.consumer, edge.consumer_variant + record = snap["rounds"].get(f"{role}#{variant}") + if record is None: + return variant < snap["variant_counts"].get(role, 1) + for held in edges_of(record): + if edge.key == MCP_KEY: + same = (held.consumer, held.key, held.provider, held.provider_variant) == ( + edge.consumer, + edge.key, + edge.provider, + edge.provider_variant, + ) + else: + same = ( + held.consumer, + held.consumer_variant, + held.key, + held.provider, + held.shared, + ) == ( + edge.consumer, + edge.consumer_variant, + edge.key, + edge.provider, + edge.shared, + ) + if same: + return True + return False diff --git a/cli/meta/ci/variant_split/edges.py b/cli/meta/ci/variant_split/edges.py new file mode 100644 index 0000000000..1f749f0c7d --- /dev/null +++ b/cli/meta/ci/variant_split/edges.py @@ -0,0 +1,171 @@ +"""The consumer-to-provider edges one resolved round deploys, and the check +that a variant split keeps every edge of the row it replaces.""" + +from __future__ import annotations + +from collections.abc import Callable, Iterable, Mapping +from typing import Any, NamedTuple + +MCP_KEY = "mcp" +LEVELS = ("pair", "keys", "strict") + + +class Edge(NamedTuple): + """One service edge of a round. + + Attributes: + consumer: the role whose services map carries the key. + consumer_variant: the variant the round runs the consumer in. + key: the service key, or ``mcp`` for an MCP client/provider pair. + provider: the role the key resolves to. + provider_variant: the variant the round runs the provider in. + shared: ``shared``, ``dedicated`` or ``unset``. + """ + + consumer: str + consumer_variant: int + key: str + provider: str + provider_variant: int + shared: str + + +def is_active(entry: Any) -> bool: + """Whether a service entry switches its key on. + + Args: + entry: one value of a services map. + """ + if not isinstance(entry, Mapping): + return False + enabled = entry.get("enabled") + return enabled is not False and str(enabled).strip().lower() not in ("false", "") + + +def sharing(entry: Mapping[str, Any]) -> str: + """The ``shared`` flag of an entry, normalised. + + Args: + entry: one active value of a services map. + """ + if "shared" not in entry: + return "unset" + value = entry["shared"] + if value is False or str(value).strip().lower() in ("false", ""): + return "dedicated" + return "shared" + + +def round_edges( + *, + include: Iterable[str], + maps: Mapping[str, Any], + active_index: Mapping[str, int], + provider_of: Callable[[str], str | None], + mcp_pairs: Iterable[tuple[str, str]] = (), +) -> set[Edge]: + """Every edge of one round whose provider the round deploys. + + Args: + include: the round's include set. + maps: role -> the services map the round runs it with. + active_index: role -> the variant the round runs it in; a role without + variants counts as 0. + provider_of: service key -> providing role, or ``None``. + mcp_pairs: ``(client, provider)`` pairs the round's MCP wiring admits. + """ + members = set(include) + out: set[Edge] = set() + for consumer in members: + services = maps.get(consumer) + if not isinstance(services, Mapping): + continue + for key, entry in services.items(): + provider = provider_of(str(key)) + if not provider or provider == consumer or provider not in members: + continue + if not is_active(entry): + continue + out.add( + Edge( + consumer, + active_index.get(consumer, 0), + str(key), + provider, + active_index.get(provider, 0), + sharing(entry), + ) + ) + for client, provider in mcp_pairs: + if client in members and provider in members and client != provider: + out.add( + Edge( + client, + active_index.get(client, 0), + MCP_KEY, + provider, + active_index.get(provider, 0), + "shared", + ) + ) + return out + + +def identities(edges: Iterable[Edge], level: str) -> set[tuple]: + """Collapse a round's edges to the identity one comparison level checks. + + Args: + edges: the edges of one round. + level: ``pair`` (consumer, provider), ``keys`` (plus the set of active + keys and their sharing between the two) or ``strict`` (plus both + variant indices). + + Raises: + ValueError: an unknown level. + """ + if level not in LEVELS: + raise ValueError(f"unknown edge level {level!r}; expected one of {LEVELS}") + grouped: dict[tuple, set[tuple[str, str]]] = {} + for edge in edges: + if level == "strict": + head: tuple = ( + edge.consumer, + edge.consumer_variant, + edge.provider, + edge.provider_variant, + ) + else: + head = (edge.consumer, edge.provider) + grouped.setdefault(head, set()).add((edge.key, edge.shared)) + if level == "pair": + return set(grouped) + return {(*head, frozenset(keys)) for head, keys in grouped.items()} + + +def union(rounds: Iterable[Iterable[Edge]], level: str) -> set[tuple]: + """The identities of several rounds, each round collapsed on its own. + + Collapsing the rounds one by one keeps the keys two rounds give the same + pair apart, so no identity names a key set that no single round deploys. + + Args: + rounds: the edges of each round. + level: the comparison level (:func:`identities`). + """ + out: set[tuple] = set() + for edges in rounds: + out |= identities(edges, level) + return out + + +def missing( + old: Iterable[Iterable[Edge]], carriers: Iterable[Iterable[Edge]], level: str +) -> set[tuple]: + """The identities of the old rounds no carrier round holds. + + Args: + old: the edges of each round being replaced. + carriers: the edges of each round that may carry them. + level: the comparison level (:func:`identities`). + """ + return union(old, level) - union(carriers, level) diff --git a/cli/meta/ci/variant_split/rounds.py b/cli/meta/ci/variant_split/rounds.py new file mode 100644 index 0000000000..21880448e0 --- /dev/null +++ b/cli/meta/ci/variant_split/rounds.py @@ -0,0 +1,294 @@ +"""Resolve one CI row the way the deploy does and record what it carries.""" + +from __future__ import annotations + +import functools +from collections.abc import Mapping +from pathlib import Path +from typing import Any + +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.applications import variant_pins +from utils.roles.applications import variants as round_variants +from utils.roles.applications.mcp import derive_allowed_consumers +from utils.roles.applications.services.registry import ( + build_service_registry_from_roles_dir, +) +from utils.roles.applications.topics import overridden_providers, provider_of +from utils.roles.applications.variant_pins import ( + PIN, + VariantPinError, + _reciprocal_index, + _service_key_lines, +) +from utils.roles.mapping import ( + ROLE_FILE_META_MCP, + ROLE_FILE_META_SERVICES, + ROLE_FILE_META_VARIANTS, +) + +from .edges import Edge, round_edges + + +def token(name: str, variant: int | None) -> str: + """The ``role#variant`` token of a row; a whole-role row is ``#0``. + + Args: + name: the row's role. + variant: the row's variant index, or ``None``. + """ + return f"{name}#{variant or 0}" + + +@functools.cache +def service_registry(roles_dir: str) -> Any: + """The service registry of a roles tree, built once per tree. + + Args: + roles_dir: the roles tree. + """ + return build_service_registry_from_roles_dir(Path(roles_dir)) + + +@functools.cache +def _mcp_providers(roles_dir: str) -> frozenset[str]: + return frozenset( + p.parent.parent.name for p in Path(roles_dir).glob(f"*/{ROLE_FILE_META_MCP}") + ) + + +@functools.cache +def _dictating(roles_dir: str) -> dict[tuple[str, int], frozenset[str]]: + return { + pair: frozenset(found) + for pair, found in overridden_providers(roles_dir).items() + } + + +def dictated( + include: list[str], active: Mapping[str, int], *, roles_dir: str +) -> dict[str, str]: + """Map every member whose config a member's variant dictates -> that ``role#index``. + + Such a member runs a configuration it does not declare, so its round is no + evidence about it; ``_mark_covered`` never credits it either. + + Args: + include: the round's include set. + active: role -> the variant the round runs it in. + roles_dir: the roles tree. + """ + members = set(include) + found: dict[str, str] = {} + for role in include: + index = active.get(role, 0) + for provider in sorted(_dictating(roles_dir).get((role, index), ())): + if provider in members: + found.setdefault(provider, f"{role}#{index}") + return found + + +def base_services(role: str, roles_dir: str) -> Mapping[str, Any]: + """A role's ``meta/services.yml`` mapping, empty when it has none. + + Args: + role: the role. + roles_dir: the roles tree. + """ + path = Path(roles_dir) / role / ROLE_FILE_META_SERVICES + if not path.is_file(): + return {} + data = load_yaml_any(str(path)) or {} + return data if isinstance(data, Mapping) else {} + + +@functools.cache +def pinned_keys(role: str, roles_dir: str) -> dict[int, dict[str, tuple[str, str]]]: + """Map variant index -> {partner: (target, service key the pin stands above)}. + + Args: + role: the carrier role. + roles_dir: the roles tree. + """ + path = Path(roles_dir) / role / ROLE_FILE_META_VARIANTS + if not path.is_file(): + return {} + text = read_text(str(path)) + lines = text.splitlines() + found: dict[int, dict[str, tuple[str, str]]] = {} + for index, keys in _service_key_lines(text).items(): + for key, line_no in keys.items(): + match = PIN.search(lines[line_no - 1]) if line_no else None + if match: + found.setdefault(index, {})[match.group(1)] = ( + match.group(2).lower(), + key, + ) + return found + + +def pin_findings( + role: str, *, roles_dir: str, variants_per_app: Mapping[str, list] +) -> list[dict[str, Any]]: + """Every pin *role* declares, with the variant that reciprocates it. + + Args: + role: the carrier role. + roles_dir: the roles tree. + variants_per_app: parsed variants per role. + """ + out = [] + for index, pins in sorted(pinned_keys(role, roles_dir).items()): + for partner, (target, key) in sorted(pins.items()): + try: + reciprocal: int | str = _reciprocal_index( + partner, + role, + roles_dir=roles_dir, + variants_per_app=variants_per_app, + ) + except VariantPinError as exc: + reciprocal = f"error: {exc}" + out.append( + { + "carrier": f"{role}#{index}", + "partner": partner, + "target": target, + "key": key, + "reciprocal": reciprocal, + } + ) + return out + + +def settle( + name: str, + variant: int | None, + *, + roles_dir: str, + variants_per_app: Mapping[str, list], +) -> tuple[list[str], dict[str, Any], dict[str, int]]: + """The include, services maps and variants one row's round settles on. + + This is the single resolver both the split check and the variant tree + read, so the two can never disagree about what a row deploys. + + Args: + name: the primary role. + variant: the row's variant index, or ``None`` for a whole-role row. + roles_dir: the roles tree. + variants_per_app: parsed variants per role. + + Raises: + VariantPinError: the round's pins do not settle. + """ + index = variant or 0 + resolved = round_variants.resolve_round( + roles_dir=roles_dir, + round_index=index, + primary_app_variants={name: index}, + variants_per_app=variants_per_app, + ) + include = list(resolved.include) + maps = { + role: resolved.services_overrides.get(role, base_services(role, roles_dir)) + for role in include + } + active = {role: resolved.active_index.get(role, 0) for role in include} + return include, maps, active + + +def pins_in_force( + include: list[str], active: Mapping[str, int], *, roles_dir: str +) -> dict[str, str]: + """Map every role a pin in force moves -> the ``carrier#index`` pinning it. + + Args: + include: the round's include set. + active: role -> the variant the round runs it in. + roles_dir: the roles tree. + """ + found: dict[str, str] = {} + for carrier in include: + for partner in variant_pins.pins_of(carrier, roles_dir=roles_dir).get( + active.get(carrier, 0), {} + ): + if partner in active: + found.setdefault(partner, f"{carrier}#{active.get(carrier, 0)}") + return found + + +def resolve_row( + name: str, + variant: int | None, + *, + roles_dir: str, + variants_per_app: Mapping[str, list], +) -> dict[str, Any]: + """What one row deploys once its pins settle. + + Args: + name: the primary role. + variant: the row's variant index, or ``None`` for a whole-role row. + roles_dir: the roles tree. + variants_per_app: parsed variants per role. + + Returns: + ``include``, ``active`` (role -> variant), ``edges`` (lists in + :class:`Edge` order), ``dark_pins`` (pins in force above a key the + carrier runs switched off), ``dictated`` (:func:`dictated`) and + ``error`` (a ``VariantPinError`` text, else ``None``). + """ + try: + include, maps, active = settle( + name, variant, roles_dir=roles_dir, variants_per_app=variants_per_app + ) + except VariantPinError as exc: + return { + "include": [], + "active": {}, + "edges": [], + "dark_pins": [], + "dictated": {}, + "error": str(exc), + } + registry = service_registry(roles_dir) + mcp_pairs = [ + (client, provider) + for provider in sorted(_mcp_providers(roles_dir) & set(include)) + for client in derive_allowed_consumers(provider, dict(maps)) + ] + edges = round_edges( + include=include, + maps=maps, + active_index=active, + provider_of=lambda key: provider_of(key, registry), + mcp_pairs=mcp_pairs, + ) + dark = [] + for carrier in include: + services = maps.get(carrier) + for partner, (_target, key) in ( + pinned_keys(carrier, roles_dir).get(active[carrier], {}).items() + ): + entry = services.get(key) if isinstance(services, Mapping) else None + if isinstance(entry, Mapping) and entry.get("enabled") is False: + dark.append(f"{carrier}#{active[carrier]} pins {partner} above {key}") + return { + "include": include, + "active": active, + "edges": sorted(list(edge) for edge in edges), + "dark_pins": sorted(dark), + "dictated": dictated(include, active, roles_dir=roles_dir), + "error": None, + } + + +def edges_of(record: Mapping[str, Any]) -> set[Edge]: + """The edges of a recorded row as :class:`Edge` tuples. + + Args: + record: one ``rounds`` entry of a snapshot. + """ + return {Edge(*edge) for edge in record.get("edges", ())} diff --git a/cli/meta/ci/variant_split/segments.py b/cli/meta/ci/variant_split/segments.py new file mode 100644 index 0000000000..6ea9f9faaf --- /dev/null +++ b/cli/meta/ci/variant_split/segments.py @@ -0,0 +1,284 @@ +"""Per-app wall segments of one measured row, from its per-task wall TSVs. + +Each TSV line is ``secondscounttask header``, the aggregate the +deploy log's task gaps produce for one pass. A task belongs to an app when its +role prefix is that app, or when its header names exactly that app; a helper +task that names several apps is split between them. A helper repeated for at +least half of the row's apps is a per-stack cost and is spread over every app +of the row; everything else is the pass's fixed cost. + +An app the pass never reached is left out of that pass, so :mod:`.cost` lists +it as unpriced instead of pricing it at zero. Every file names the runner it +was measured on: runners differ in speed, so one row's figures never price +another runner's gaps. +""" + +from __future__ import annotations + +import re +from datetime import datetime +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Mapping + +TOTAL = "TOTAL" + + +def parse_tsv(text: str) -> list[tuple[float, int, str]]: + """The task rows of one TSV, without its ``TOTAL`` line. + + Args: + text: the TSV content. + """ + rows = [] + for line in text.splitlines(): + parts = line.split("\t", 2) + if len(parts) != 3 or parts[2] == TOTAL: + continue + rows.append((float(parts[0]), int(parts[1]), parts[2])) + return rows + + +def _mentions( + header: str, apps: Iterable[str], entity_of: Callable[[str], str] +) -> list[str]: + hits = [] + for app in apps: + entity = re.escape(entity_of(app)) + if app in header or re.search(rf"['/]{entity}['/]", header): + hits.append(app) + return hits + + +def attribute( + tasks: Iterable[tuple[float, int, str]], + apps: list[str], + *, + entity_of: Callable[[str], str], +) -> dict[str, Any]: + """Split one pass's task time between the row's apps and its fixed cost. + + Args: + tasks: ``(seconds, count, header)`` rows of one pass. + apps: the include of the measured row. + entity_of: role -> entity name, as it appears in paths and quotes. + + Returns: + ``apps`` (app -> seconds, only apps some task was attributed to), + ``fixed`` (seconds no app owns) and ``total``. + """ + per_app: dict[str, float] = {} + fixed = 0.0 + total = 0.0 + repeated = max(2, len(apps) // 2) + for seconds, count, header in tasks: + total += seconds + prefix = header.split(" : ", 1)[0] if " : " in header else "" + if prefix in apps: + per_app[prefix] = per_app.get(prefix, 0.0) + seconds + continue + named = _mentions(header, apps, entity_of) + if named: + for app in named: + per_app[app] = per_app.get(app, 0.0) + seconds / len(named) + elif prefix and count >= repeated: + for app in apps: + per_app[app] = per_app.get(app, 0.0) + seconds / len(apps) + else: + fixed += seconds + return { + "apps": {app: round(value, 1) for app, value in per_app.items()}, + "fixed": round(fixed, 1), + "total": round(total, 1), + } + + +HEADER = re.compile( + r"^(?P\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?)Z?\s.*?" + r"(?:TASK|RUNNING HANDLER) \[(?P[^\]]*)\]" +) +E2E_PREFIX = "test-e2e-" + + +def _epoch(stamp: str) -> float: + head, _, frac = stamp.partition(".") + return datetime.fromisoformat(head).timestamp() + ( + float(f"0.{frac}") if frac else 0.0 + ) + + +def first_task_segments(lines: Iterable[str], apps: list[str]) -> dict[str, Any]: + """Per-app wall time of one pass, from an app's first task to the next's. + + Only aggregated seconds leave this function, never log text: deploy logs + carry credentials. + + Args: + lines: the log lines of one pass, in order. + apps: the include of the measured row. + + Returns: + ``apps`` (app -> seconds, only apps the pass reached), ``fixed`` (pass + start to the first app), ``e2e`` (the first ``test-e2e-*`` task to the + pass end), ``unseen`` (apps with no task in the pass) and ``total``. + """ + members = set(apps) + firsts: list[tuple[float, str]] = [] + seen: set[str] = set() + start = end = e2e_start = None + for line in lines: + match = HEADER.match(line) + if not match: + continue + stamp = _epoch(match.group("ts")) + start = stamp if start is None else start + end = stamp + name = match.group("name") + role = name.split(" : ", 1)[0] if " : " in name else "" + if role.startswith(E2E_PREFIX) and e2e_start is None: + e2e_start = stamp + if role in members and role not in seen and e2e_start is None: + seen.add(role) + firsts.append((stamp, role)) + if start is None: + return { + "apps": {}, + "fixed": 0.0, + "e2e": 0.0, + "unseen": sorted(apps), + "total": 0.0, + } + stop = e2e_start if e2e_start is not None else end + bounds = [stamp for stamp, _ in firsts[1:]] + [stop] + per_app = { + role: round(until - stamp, 1) + for (stamp, role), until in zip(firsts, bounds, strict=True) + } + return { + "apps": per_app, + "fixed": round((firsts[0][0] if firsts else stop) - start, 1), + "e2e": round(end - stop, 1), + "unseen": sorted(members - seen), + "total": round(end - start, 1), + } + + +def _source(source: str, cut_passes: list[str]) -> str: + if not cut_passes: + return source + return f"{source} (lower bound: pass {', '.join(cut_passes)} cut)" + + +def build_from_log( + lines: list[str], + ranges: Mapping[str, tuple[int, int | None]], + apps: list[str], + *, + runner: str, + cut: Iterable[str] = (), + source: str = "", +) -> dict[str, Any]: + """The segments file :mod:`.cost` reads, measured from a raw deploy log. + + Args: + lines: the log's lines. + ranges: pass number -> (first line, last line or ``None`` for the end), + 1-based, as the PASS markers give them. + apps: the include of the measured row. + runner: the runner the log ran on. + cut: the passes whose log was cut, so their figures are lower bounds. + source: where the log came from. + """ + measured = { + number: first_task_segments(lines[first - 1 : last], apps) + for number, (first, last) in ranges.items() + } + cut_passes = sorted(set(cut)) + return { + "source": _source(source, cut_passes), + "runner": runner, + "lower_bound": bool(cut_passes), + "passes": {number: facts["apps"] for number, facts in measured.items()}, + "measured_fixed": { + number: facts["fixed"] for number, facts in measured.items() + }, + "measured_e2e": {number: facts["e2e"] for number, facts in measured.items()}, + "measured_apps": len(apps), + "measured_total": { + number: facts["total"] for number, facts in measured.items() + }, + "unseen": {number: facts["unseen"] for number, facts in measured.items()}, + } + + +def build( + passes: Mapping[str, str], + apps: list[str], + *, + entity_of: Callable[[str], str], + runner: str, + cut: Iterable[str] = (), + source: str = "", +) -> dict[str, Any]: + """The segments file :mod:`.cost` reads. + + Args: + passes: pass number -> TSV content. + apps: the include of the measured row. + entity_of: role -> entity name. + runner: the runner the TSVs were measured on. + cut: the passes whose log was cut, so their figures are lower bounds. + source: where the TSVs came from. + """ + attributed = { + number: attribute(parse_tsv(text), apps, entity_of=entity_of) + for number, text in passes.items() + } + cut_passes = sorted(set(cut)) + return { + "source": _source(source, cut_passes), + "runner": runner, + "lower_bound": bool(cut_passes), + "passes": {number: facts["apps"] for number, facts in attributed.items()}, + "measured_fixed": { + number: facts["fixed"] for number, facts in attributed.items() + }, + "measured_total": { + number: facts["total"] for number, facts in attributed.items() + }, + } + + +def merge(files: list[Mapping[str, Any]]) -> dict[str, Any]: + """One segments file from several measured rows of the same runner. + + The first file prices an app; a later file only prices the apps the + earlier ones did not reach in that pass. + + Args: + files: segments files, the primary first. + + Raises: + ValueError: no file, or the files name different runners. + """ + if not files: + raise ValueError("merge needs at least one segments file") + runners = sorted({str(data["runner"]) for data in files}) + if len(runners) != 1: + raise ValueError( + f"segments of runners {runners} cannot be merged: a slower runner's " + f"figures would price a faster runner's gaps" + ) + primary = files[0] + passes = {number: dict(apps) for number, apps in primary["passes"].items()} + for data in files[1:]: + for number, apps in passes.items(): + for app, seconds in (data["passes"].get(number) or {}).items(): + apps.setdefault(app, seconds) + return { + **primary, + "source": " + ".join(str(data["source"]) for data in files), + "lower_bound": any(data["lower_bound"] for data in files), + "passes": passes, + } diff --git a/cli/meta/ci/variant_split/snapshot.py b/cli/meta/ci/variant_split/snapshot.py new file mode 100644 index 0000000000..3b63a78bff --- /dev/null +++ b/cli/meta/ci/variant_split/snapshot.py @@ -0,0 +1,288 @@ +"""Record the CI matrix the current tree plans, through the real pipeline. + +A snapshot holds what a variant split can change: the candidate rows and +their coverage credits, every row's settled round and edges, the axes and the +budget head of each sweep, and every variant pin. Two snapshots, one taken +before the split and one after, are what :mod:`.compare` diffs. +""" + +from __future__ import annotations + +import hashlib +import os +from pathlib import Path +from typing import TYPE_CHECKING, Any + +from utils.roles.mapping import ROLE_FILE_META_VARIANTS + +from .rounds import pin_findings, resolve_row, token + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Mapping + +SEED_ENV = "INFINITO_DISCOVERY_SEED" + +ENTRY_KEYS = ( + "apps", + "variant", + "mode", + "network", + "vpn", + "distro", + "filesystem", + "architecture", + "priority", + "covered", + "clone", + "id", +) + + +def variants_digest(roles_dir: str) -> str: + """A digest over the path, mtime and size of every ``meta/variants.yml``. + + ``read_text`` caches per process, so a digest over content would miss an + edit made after the first read; the file stat cannot. + + Args: + roles_dir: the roles tree. + """ + digest = hashlib.sha256() + for path in sorted(Path(roles_dir).glob(f"*/{ROLE_FILE_META_VARIANTS}")): + stat = path.stat() + digest.update( + f"{path.relative_to(roles_dir)}:{stat.st_mtime_ns}:{stat.st_size};".encode() + ) + return digest.hexdigest() + + +def check_seeds(before: Mapping[str, Any], after: Mapping[str, Any]) -> str: + """The discovery seed both snapshots share. + + Rows that tie in the ranking are ordered by a draw the seed fixes, so two + snapshots with different or missing seeds differ by noise the split never + caused, such as a credit that moves to another coverer. + + Args: + before: the snapshot without the split. + after: the snapshot with it. + + Raises: + ValueError: a snapshot carries no seed, or the two differ. + """ + seeds = (before.get("seed"), after.get("seed")) + if not all(seeds) or seeds[0] != seeds[1]: + raise ValueError( + f"snapshot seeds {seeds[0]!r} and {seeds[1]!r} must be one run id: " + f"take both with the same --seed, as CI sets {SEED_ENV}" + ) + return str(seeds[0]) + + +def compact(entry: Mapping[str, Any]) -> dict[str, str]: + """The axis fields of one matrix entry. + + Args: + entry: an entry :func:`utils.github.variant.axes.assign` produced. + """ + return {key: str(entry.get(key, "")) for key in ENTRY_KEYS} + + +def row_of(candidate: Mapping[str, Any]) -> dict[str, Any]: + """The ranking fields of one candidate row. + + Args: + candidate: a row :func:`cli.meta.ci.matrix.candidates` produced. + """ + return { + "token": token(candidate["name"], candidate.get("variant")), + "name": candidate["name"], + "variant": candidate.get("variant"), + "id": int(candidate.get("id", 0)), + "covered_by": int(candidate.get("covered_by", 0)), + "clone": bool(candidate.get("clone")), + "priority": bool(candidate.get("priority")), + } + + +def assemble( + *, + candidates: list[Mapping[str, Any]], + sweeps: Iterable[int], + assign: Callable[[list, int], list[dict]], + head_of: Callable[[list[dict]], list[dict]], + is_regular: Callable[[Mapping[str, str]], bool], + resolve: Callable[[str, int | None], dict[str, Any]], + budget: Mapping[str, int], + variant_counts: Mapping[str, int], + pins: list[dict[str, Any]], + digest: str, + seed: str, +) -> dict[str, Any]: + """Build a snapshot from the pipeline's pieces. + + Args: + candidates: the sweep's ordered candidate rows. + sweeps: the sweep numbers to assign axes for. + assign: ``(candidates, sweep) -> entries``, the real axis assignment. + head_of: ``entries -> the entries the sweep deploys``, the real chunker. + is_regular: whether an entry stays in the job list. + resolve: ``(role, variant) -> round record`` (:func:`.rounds.resolve_row`). + budget: :func:`cli.meta.ci.slots.budget`. + variant_counts: role -> how many variants it declares. + pins: every pin of the tree (:func:`.rounds.pin_findings`). + digest: :func:`variants_digest` of the tree. + seed: the discovery seed the ranking ran under. + """ + rows = [row_of(candidate) for candidate in candidates] + rounds = {row["token"]: resolve(row["name"], row["variant"]) for row in rows} + per_sweep = {} + for sweep in sweeps: + entries = assign(list(candidates), sweep) + per_sweep[str(sweep)] = { + "entries": [compact(entry) for entry in entries], + "jobs": [ + token(entry["apps"], int(entry["variant"] or 0)) + for entry in entries + if is_regular(entry) + ], + "head": [compact(entry) for entry in head_of(entries)], + } + return { + "digest": digest, + "seed": seed, + "budget": dict(budget), + "rows": rows, + "rounds": rounds, + "sweeps": per_sweep, + "variant_counts": dict(variant_counts), + "pins": pins, + } + + +def pipeline() -> dict[str, Any]: + """The repository's own matrix pipeline for the current tree. + + Returns: + ``roles_dir``, ``variants_per_app``, ``candidates`` and the + ``assign``, ``head_of`` and ``is_regular`` callables of + :func:`assemble`. + """ + from cli.meta.ci import matrix, query + from utils.cache.applications import get_variants + from utils.cache.files import PROJECT_ROOT + from utils.github.variant import instructions, network, pools, vpn + + roles_dir = str(PROJECT_ROOT / "roles") + axes_args = { + "network_input": network.resolve_network_input(None), + "vpn_mode": vpn.resolve_vpn_mode(None), + "distros": pools.resolve_distros(""), + "filesystems": pools.resolve_filesystems(""), + "architectures": pools.resolve_architectures(""), + } + return { + "roles_dir": roles_dir, + "variants_per_app": get_variants(roles_dir=roles_dir, readonly=True), + "candidates": matrix.candidates( + modes=query.resolve_modes(query.ALL_MODES), + whitelist="", + priority="", + lifecycles="", + ), + "assign": lambda rows, sweep: matrix.assigned(rows, sweep=sweep, **axes_args), + "head_of": lambda entries: [ + e for chunk in matrix.chunks_of(entries, 0) for e in chunk + ], + "is_regular": lambda e: ( + e["priority"] != "true" and not instructions.redundant(e) + ), + } + + +def row_axes(tok: str, sweeps: Iterable[int]) -> dict[str, Any]: + """The axes, job-list position and budget fate one row gets per sweep. + + Args: + tok: the row's ``role#variant`` token. + sweeps: the sweep numbers to assign axes for. + """ + pipe = pipeline() + out: dict[str, Any] = {} + for sweep in sweeps: + entries = pipe["assign"](list(pipe["candidates"]), sweep) + jobs = [ + token(e["apps"], int(e["variant"] or 0)) + for e in entries + if pipe["is_regular"](e) + ] + head = { + token(e["apps"], int(e["variant"] or 0)) for e in pipe["head_of"](entries) + } + mine = [ + { + key: e[key] + for key in ("mode", "network", "distro", "filesystem", "architecture") + } + for e in entries + if token(e["apps"], int(e["variant"] or 0)) == tok + ] + out[str(sweep)] = { + "entries": mine, + "job_position": jobs.index(tok) if tok in jobs else None, + "in_budget_head": tok in head, + "covered": next( + ( + e["covered"] + for e in entries + if token(e["apps"], int(e["variant"] or 0)) == tok + ), + None, + ), + } + return out + + +def take(sweeps: Iterable[int], *, seed: str) -> dict[str, Any]: + """Snapshot the current tree with the repository's own pipeline. + + Args: + sweeps: the sweep numbers to assign axes for. + seed: the discovery seed, the CI run id; it is exported as + :data:`SEED_ENV` for this process, as CI exports it for a run. + + Raises: + ValueError: the seed is empty. + """ + from cli.meta.ci import slots + + if not seed.strip(): + raise ValueError(f"a snapshot needs the CI run id as its seed ({SEED_ENV})") + os.environ[SEED_ENV] = seed + pipe = pipeline() + roles_dir, variants_per_app = pipe["roles_dir"], pipe["variants_per_app"] + pins = [ + finding + for role in sorted(variants_per_app) + for finding in pin_findings( + role, roles_dir=roles_dir, variants_per_app=variants_per_app + ) + ] + return assemble( + candidates=pipe["candidates"], + sweeps=sweeps, + assign=pipe["assign"], + head_of=pipe["head_of"], + is_regular=pipe["is_regular"], + resolve=lambda name, variant: resolve_row( + name, variant, roles_dir=roles_dir, variants_per_app=variants_per_app + ), + budget=slots.budget(), + variant_counts={ + role: max(1, len(entries or [{}])) + for role, entries in variants_per_app.items() + }, + pins=pins, + digest=variants_digest(roles_dir), + seed=seed, + ) diff --git a/cli/meta/ci/variant_tree/__init__.py b/cli/meta/ci/variant_tree/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/cli/meta/ci/variant_tree/__main__.py b/cli/meta/ci/variant_tree/__main__.py new file mode 100644 index 0000000000..1212d4238f --- /dev/null +++ b/cli/meta/ci/variant_tree/__main__.py @@ -0,0 +1,70 @@ +"""Print the variant tree of one CI row as text, JSON or YAML.""" + +from __future__ import annotations + +import argparse +import json +import sys + +from utils.cache.yaml import dump_yaml_str + +from . import tree + + +def build_parser() -> argparse.ArgumentParser: + p = argparse.ArgumentParser( + prog="infinito meta ci variant_tree", + description=( + "Print the variant tree one CI row really deploys: the primary " + "role#variant, every dependency with the variant its round settles " + "on and why (round index, a variant pin in force, or default 0), " + "each node's services and their state (required, presence-gated, " + "forced by override, implicit, off), the closure size as the " + "resolve_round include count, and the axes the job list assigns " + "the row per sweep. Reads the tree, deploys nothing." + ), + ) + p.add_argument( + "row", metavar="ROLE#VARIANT", help="The row, e.g. web-app-wordpress#0." + ) + fmt = p.add_mutually_exclusive_group() + fmt.add_argument("--json", action="store_true", help="Print JSON.") + fmt.add_argument("--yaml", action="store_true", help="Print YAML.") + p.add_argument( + "--sweeps", + default="0", + help="Comma-separated sweeps to assign axes for; empty skips the axes.", + ) + return p + + +def main(argv: list[str] | None = None) -> int: + args = build_parser().parse_args(argv) + from cli.meta.ci.variant_split.snapshot import row_axes + from utils.cache.applications import get_variants + from utils.cache.files import PROJECT_ROOT + + roles_dir = str(PROJECT_ROOT / "roles") + try: + data = tree.build( + args.row, + roles_dir=roles_dir, + variants_per_app=get_variants(roles_dir=roles_dir, readonly=True), + ) + except ValueError as exc: + print(f"error: {exc}", file=sys.stderr) + return 2 + sweeps = [int(s) for s in args.sweeps.split(",") if s.strip()] + if sweeps and not data.get("error"): + data["axes"] = row_axes(data["primary"], sweeps) + if args.json: + print(json.dumps(data, indent=2)) + elif args.yaml: + print(dump_yaml_str(data), end="") + else: + print(tree.render_text(data)) + return 1 if data.get("error") else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/cli/meta/ci/variant_tree/tree.py b/cli/meta/ci/variant_tree/tree.py new file mode 100644 index 0000000000..9503e21fc2 --- /dev/null +++ b/cli/meta/ci/variant_tree/tree.py @@ -0,0 +1,192 @@ +"""Build and render the variant tree of one CI row.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from cli.meta.ci.variant_split.edges import is_active +from cli.meta.ci.variant_split.rounds import ( + base_services, + pins_in_force, + service_registry, + settle, +) +from utils.roles.applications.topics import provider_of +from utils.roles.applications.variant_pins import VariantPinError + + +def parse_token(tok: str) -> tuple[str, int]: + """Split ``role#variant``; a bare role means variant 0. + + Args: + tok: the row token. + + Raises: + ValueError: the variant part is not a number. + """ + name, _, variant = tok.partition("#") + if variant and not variant.isdigit(): + raise ValueError(f"{tok!r}: the variant after '#' must be a number") + return name, int(variant or 0) + + +def reason( + role: str, *, primary: str, index: int, count: int, pinned: Mapping[str, str] +) -> str: + """Why the round runs *role* in the variant it does. + + Args: + role: the node. + primary: the row's primary role. + index: the row's round index. + count: how many variants *role* declares. + pinned: role -> the ``carrier#index`` whose pin in force moves it. + """ + if role == primary: + return "primary" + if role in pinned: + return f"pin by {pinned[role]}" + if index < count: + return "round index" + return "default 0: round past its variants" + + +def state(entry: Any, base_entry: Any) -> str: + """How a service key of a node is switched in this round. + + Args: + entry: the key's entry in the round's services map. + base_entry: the key's entry in the role's ``meta/services.yml``. + """ + if not is_active(entry): + return "off" + enabled = entry.get("enabled") + if enabled is True: + base_on = isinstance(base_entry, Mapping) and base_entry.get("enabled") is True + return "required" if base_on else "forced by override" + if isinstance(enabled, str) and "group_names" in enabled: + return "presence-gated" + if enabled is None: + return "implicit" + return "templated" + + +def build( + tok: str, *, roles_dir: str, variants_per_app: Mapping[str, list] +) -> dict[str, Any]: + """The variant tree of one row, in plain JSON types. + + Args: + tok: the row's ``role#variant`` token. + roles_dir: the roles tree. + variants_per_app: parsed variants per role. + + Raises: + ValueError: the role is not in the tree, or it declares no variant at + that index. + """ + name, index = parse_token(tok) + if name not in variants_per_app: + raise ValueError(f"{tok!r}: no role {name!r} in the roles tree") + declared = max(1, len(variants_per_app[name] or [])) + if index >= declared: + raise ValueError( + f"{tok!r}: {name} declares {declared} variant(s), so the variant " + f"after '#' must be 0..{declared - 1}" + ) + head = {"primary": f"{name}#{index}", "round_index": index} + try: + include, maps, active = settle( + name, index, roles_dir=roles_dir, variants_per_app=variants_per_app + ) + except VariantPinError as exc: + return {**head, "include_count": 0, "error": str(exc), "nodes": []} + pinned = pins_in_force(include, active, roles_dir=roles_dir) + registry = service_registry(roles_dir) + nodes = [] + for role in include: + count = len(variants_per_app.get(role) or []) + base = base_services(role, roles_dir) + services_map = maps.get(role) + services = [] + for key, entry in ( + sorted((services_map or {}).items()) + if isinstance(services_map, Mapping) + else [] + ): + provider = provider_of(str(key), registry) + if not provider or provider == role: + continue + services.append( + { + "key": str(key), + "provider": provider, + "state": state(entry, base.get(key)), + "deployed": provider in include, + } + ) + nodes.append( + { + "role": role, + "variant": active[role], + "variants": max(count, 1), + "reason": reason( + role, primary=name, index=index, count=count, pinned=pinned + ), + "services": services, + "children": sorted( + { + s["provider"] + for s in services + if s["deployed"] and s["state"] != "off" + } + ), + } + ) + return {**head, "include_count": len(include), "error": None, "nodes": nodes} + + +def render_text(tree: Mapping[str, Any]) -> str: + """The tree as indented text, each node once, later visits referenced. + + Args: + tree: a tree :func:`build` produced, optionally with ``axes``. + """ + lines = [ + f"{tree['primary']}: include {tree['include_count']} (resolve_round), round index {tree['round_index']}" + ] + if tree.get("error"): + return "\n".join([*lines, f"error: {tree['error']}"]) + for sweep, facts in sorted((tree.get("axes") or {}).items()): + lines.append( + f"sweep {sweep}: {facts['entries']} job position {facts['job_position']}, " + f"in budget head {facts['in_budget_head']}, covered {facts['covered']}" + ) + nodes = {node["role"]: node for node in tree["nodes"]} + seen: set[str] = set() + + def walk(role: str, depth: int) -> None: + node = nodes[role] + pad = " " * depth + label = f"{pad}{role}#{node['variant']}/{node['variants']} [{node['reason']}]" + if role in seen: + lines.append(f"{label} (above)") + return + seen.add(role) + lines.append(label) + for svc in node["services"]: + mark = "" if svc["deployed"] else " (not deployed)" + lines.append( + f"{pad} . {svc['key']} -> {svc['provider']}: {svc['state']}{mark}" + ) + for child in node["children"]: + walk(child, depth + 1) + + primary = tree["primary"].split("#", 1)[0] + if primary in nodes: + walk(primary, 0) + for role in nodes: + if role not in seen: + walk(role, 0) + return "\n".join(lines) diff --git a/docs/contributing/tools/agents/cheatsheet.md b/docs/contributing/tools/agents/cheatsheet.md index abcebf530f..77355bf56a 100644 --- a/docs/contributing/tools/agents/cheatsheet.md +++ b/docs/contributing/tools/agents/cheatsheet.md @@ -29,6 +29,8 @@ from its procedure file. Run `make install-skills` to (re)install them. | Running the full gate (`make quality-high`: quality plus every lint) to green | `i8-quality-high` | | Cleaning up code, docs, or roles after a change | `i8-refactor` | | Making CI, a deploy or a gate faster without giving up coverage | `i8-tuner` | +| Splitting an over-budget CI row into variants that keep its coverage | `i8-variant-split` | +| Inspecting the variant tree one CI row really deploys | `i8-variant-tree` | | Checking a branch out into a parallel worktree | `i8-worktree-create` | | Releasing a parallel worktree and its slot | `i8-worktree-down` | | Freeing disk space and `/tmp` that agents filled | `i8-cleanup` | diff --git a/skills/i8-variant-split/SKILL.md b/skills/i8-variant-split/SKILL.md new file mode 100644 index 0000000000..1273d8eb96 --- /dev/null +++ b/skills/i8-variant-split/SKILL.md @@ -0,0 +1,131 @@ +--- +name: i8-variant-split +description: > + Shorten an over-budget CI matrix row without losing coverage: split its + primary role into new variants that together carry every edge, credit and + axis pair the old row carried, verified against the repository's real round + resolver, coverage credit, axes rotation and budget. Trigger when a row dies + on the deploy cap, on /i8-variant-split, or when the operator asks to split a + variant. Infinito.Nexus specific. +--- + +# Variant Split + +Follow the instructions from AGENTS.md. A split is a **coverage change**: it is +always handed to the operator as an uncommitted proposal with its verification +table, never committed or merged by the agent. + +## What must hold + +A split replaces one row (`role#N`) with rows that share its work. Coverage is +judged over the **full job list**, every row of every sweep whether the budget +runs it or not: a tail past the budget is fine. The split keeps coverage only +when all of these hold, and each one is checked by +`python -m cli.meta.ci.variant_split`, never by eye: + +| Check | Why a split can break it | Where it is checked | +| ----- | ------------------------ | ------------------- | +| Children | Every `role#variant` row must be deployed at that variant by some row of the job list, its own or the one that credits it | `compare`: job list `uncovered children`, `newly uncovered` | +| Edges | Every consumer-to-provider edge, including the dep-to-dep edges inside a closure and MCP pairs, must still run with the same active keys in some row of the job list, and at the same consumer and provider variants while the tree still declares them | `compare`: `edges lost over the job list` and `variant edges lost`; edges the split retires from a variant's own config are counted, not failed; `local`, `head` and `jobs` key counts are reported | +| No false credit | `_mark_covered` credits role-level closures and ignores pins, so a row can stay "covered" by a round that no longer deploys it at `#0`, that dictates its config, or by a coverer outside the job list | `compare`: `introduced false credits`, judged by row, coverer and reason; only one unchanged in all three is pre-existing | +| Pins | A `# variant-pin:` must reciprocate (`test_variant_pins`), settle (`test_variant_pin_fixed_point`) and never stand above a key its carrier switches off | `compare`: new pins, `unreciprocated`, new dark pins, new round errors | +| Limits | `MAX_VARIANTS` is 3 per role (`test_limit.py`) | `compare`: `variants grown` | +| Cost | A new row pays about 2.2 ks of fixed cost; per-app time is not linear | `cost` with measured per-app segments | + +Head rows pushed past the budget and the mode, network and distro pairs that +rotate by position are reported per sweep 0-5 but do not fail the verdict. A +lost child, edge or true credit stays lost even when a check is noisy. Never +call a loss covered. + +## Procedure + +Stream every command to `/tmp/variant-split--.log` and read the log +rather than re-running it. + +1. **Snapshot before.** On a tree whose `roles/` equals the merge target: + `python -m cli.meta.ci.variant_split snapshot --seed --out /tmp/vs/before.json`. + The seed is the id of the CI run the row failed in, as CI sets + `INFINITO_DISCOVERY_SEED`; without it equal rows rank at random and the + compare reports coverer moves that are noise. `compare` and `cost` refuse + two snapshots of different seeds. +2. **Measure.** Turn the row's per-task wall TSVs (seconds, count, task + header, one per pass) or its raw deploy log into per-app segments: + `python -m cli.meta.ci.variant_split segments /tmp/vs/before.json --row --runner --pass 1= --pass 2= [--cut 2] --out /tmp/vs/seg.json`. + A cut pass makes every figure a lower bound; say so in the table. An app a + pass never reached stays unpriced, never zero. To price apps the row does + not deploy, measure another row on the **same runner** and join them with + `python -m cli.meta.ci.variant_split merge /tmp/vs/seg.json /tmp/vs/seg-2.json --out /tmp/vs/seg-all.json`; + `merge` refuses segments of two runners. +3. **Find the heavy core.** `python -m cli.meta.ci.variant_tree ` + shows which dependency closure carries the weight and why each dependency + runs the variant it runs. +4. **Edit** only `roles//meta/variants.yml`: new variants of the primary, + each pinning only the sub-variants it needs, or turning keys off. Read the + role's `AGENTS.md` first when it has one. +5. **Snapshot after** with the same `--seed` into `/tmp/vs/after.json`, then + `python -m cli.meta.ci.variant_split compare /tmp/vs/before.json /tmp/vs/after.json --old --split ,` + and `python -m cli.meta.ci.variant_split cost ... --segments /tmp/vs/seg.json`. +6. **Run the guards** that the edit touches: + `tests/integration/roles/meta/variants`, `tests/lint/ansible/roles`, + `tests/lint/agents` when present, `tests/lint/repository` and + `tests/lint/filesystem`. +7. **Report** the verification table below, one line per replaced row. + +## Pitfalls that already cost a round + +- **Reciprocity blocks most pins.** A pin `partner#i` resolves only when the + partner's `meta/services.yml` has a key gated on + `'' in group_names`, and exactly one partner variant sets that key + literally true. A partner with no such back-reference cannot be pinned by + that carrier. Adding the key is a role change and an operator decision. +- **The round index is a pin too.** A primary variant at index `i` runs every + dependency with more than `i` variants at `#i`. A new variant therefore + changes its dependencies' variants even without a marker, and the strict + edge level shows it. +- **One closure can be the whole problem.** When the weight sits in one + dependency's own closure, splitting the primary's keys only moves that + closure into the new row. Report that instead of a split. +- **Edges against the job list, with the settled maps.** Compare against the + rows of the job list, with the services maps the settled round uses, not the + role's raw `meta/services.yml`. +- **A back-reference key joins the closures.** Coverage credits and the DNA + clone election read the role-level closure, where a key gated on + `group_names` always counts. A back-reference therefore puts carrier and + partner in one cycle: every role embedding the partner then embeds the + carrier, credits move to rows that never deploy it, and cycle members can + share one DNA and drop out as clones. Snapshot again after adding one. +- **The partner's own row runs at the same index.** The partner variant a + carrier pins also becomes a row of its own, whose round hands every other + dependency that index. Its include can carry partners the carrier never + pulls, and their pins can conflict with the one it needs. +- **A coverer's true credits fix its floor.** A row that truly covers + `x#0` must keep deploying `x#0`, or the credit turns false. When those + credits arrive through a shared dependency, that dependency's variant 0 must + keep `x` too, and the floor of every row pulling it rises with it. Read the + rows whose `covered_by` names the coverer in the snapshot before slimming the + dependency. + +## Operator decisions, never taken by the agent + +- `# nocheck: variant-limit` or any other new nocheck marker or suppression: + it needs the operator's approval for that role and variant, as the fourth + `web-app-wordpress` variant had, and the marker names why the variant is + needed. +- Back-reference keys in a dependency's `meta/services.yml`. +- A fix to `_mark_covered` for credits the pin-aware check proves false. +- Accepting any loss the verification table lists. + +## Verification table + +| Row | Job-list children uncovered (before/after) | Edges lost over the job list | Introduced false credits | Axes per sweep 0-5 (reported) | Pins and reciprocity | Saving per row | Net runner-time delta | +| --- | ------------------------------------------ | ---------------------------- | ------------------------ | ----------------------------- | -------------------- | -------------- | --------------------- | + +Fill the axes column with the union over sweeps 0-5 and the per-sweep +maximum, and both time columns with their segment source and whether it is a +lower bound. + +Begin by clarifying every open requirement with the `active-listening` skill +(escalating any design question you are not ~99% sure of to the `dialectic` +skill), then work under the `robot` skill. The task is finished when every row +the operator named has a filled table line, or a stated reason why no split +keeps its coverage together with the best candidate and exactly what it loses. diff --git a/skills/i8-variant-tree/SKILL.md b/skills/i8-variant-tree/SKILL.md new file mode 100644 index 0000000000..16328a8d83 --- /dev/null +++ b/skills/i8-variant-tree/SKILL.md @@ -0,0 +1,32 @@ +--- +name: i8-variant-tree +description: > + Print the variant tree one CI row really deploys, as text, JSON or YAML: the + primary role#variant, every dependency with the variant its round settles on + and why, each node's services and their state, the closure size and the + axes the job list gives the row. Trigger on /i8-variant-tree or when the + operator asks what a variant pulls in. Infinito.Nexus specific. +--- + +# Variant Tree + +Follow the instructions from AGENTS.md, then run: + +```bash +python -m cli.meta.ci.variant_tree [--json | --yaml] [--sweeps 0,1] +``` + +The tree reads the same resolver as `i8-variant-split` +(`cli.meta.ci.variant_split.rounds.settle`), so both always agree about what a +row deploys. It deploys and writes nothing. + +| Field | Meaning | +| ----- | ------- | +| `primary` | The row, `role#variant`; a bare role means `#0`. A variant the role does not declare, or an unknown role, exits 2 naming the valid range. | +| `include_count` | The closure size as the `resolve_round` include count. The role-level model in `infinito meta roles applications complexity` is a different, larger number. | +| `nodes[].variant`, `reason` | The variant the round runs the node in: `primary`, `pin by #` (a `# variant-pin:` in force), `round index`, or `default 0` when the role has fewer variants than the round. | +| `nodes[].services[].state` | `required` (literal true in `meta/services.yml`), `presence-gated` (`'' in group_names`), `forced by override` (a variant or a nested demand sets it true), `implicit` (no `enabled` flag), `templated`, or `off`; `deployed` says whether the provider is in the include. | +| `axes` | Per requested sweep: the mode, network, distro, filesystem and architecture `axes.assign` gives the row, its job-list position, whether it is inside the budget head, and its coverage credit. `--sweeps ''` skips this step, which runs the whole matrix pipeline. | + +Report the tree the operator asked for in the format they named. When a row +errors (`VariantPinError`), report the error text; do not guess the tree. diff --git a/tests/integration/roles/meta/variants/test_variant_tree.py b/tests/integration/roles/meta/variants/test_variant_tree.py new file mode 100644 index 0000000000..63c93a2a2a --- /dev/null +++ b/tests/integration/roles/meta/variants/test_variant_tree.py @@ -0,0 +1,151 @@ +"""Golden guard for ``python -m cli.meta.ci.variant_tree``. + +The tree is the operator's view of what one CI row deploys. It must read the +same resolver the deploy does, so its closure is the ``resolve_round`` include +and every pinned partner names the pin that moved it. +""" + +from __future__ import annotations + +import json +import unittest + +from cli.meta.ci.variant_tree import tree +from utils.cache.applications import get_variants +from utils.cache.yaml import dump_yaml_str, load_yaml_str +from utils.roles.applications import variants as round_variants + +from . import PROJECT_ROOT + +ROLES_DIR = str(PROJECT_ROOT / "roles") +UNPINNED_ROW = "web-app-nextcloud#1" + +SHARED = { + "svc-ai-libretranslate-engine", + "svc-bkp-secrets-2-local", + "svc-bkp-volume-2-local", + "svc-db-mariadb", + "svc-db-openldap", + "svc-db-postgres", + "svc-db-redis", + "svc-net-tor", + "svc-net-tor-smtp", + "web-app-dashboard", + "web-app-discourse", + "web-app-jitsi", + "web-app-keycloak", + "web-app-matomo", + "web-app-matrix", + "web-app-prometheus", + "web-app-stalwart", + "web-app-weblate", + "web-svc-asset", + "web-svc-cdn", + "web-svc-coturn", + "web-svc-design", + "web-svc-file", + "web-svc-logout", + "web-svc-mirror", + "web-svc-seaweedfs", + "web-svc-simpleicons", + "web-svc-translate", +} +PINNED = { + "web-app-keycloak": (0, "pin by web-app-dashboard#0"), + "web-app-matomo": (0, "pin by web-app-dashboard#0"), + "web-svc-logout": (0, "pin by web-app-matomo#0"), +} +GOLDEN = { + "web-app-wordpress#0": (29, SHARED | {"web-app-wordpress"}, "round index", PINNED), + "web-app-nextcloud#7": ( + 29, + SHARED | {"web-app-nextcloud"}, + "default 0: round past its variants", + PINNED, + ), +} + + +def _tree(tok: str) -> dict: + return tree.build( + tok, + roles_dir=ROLES_DIR, + variants_per_app=get_variants(roles_dir=ROLES_DIR, readonly=True), + ) + + +class TestVariantTreeGolden(unittest.TestCase): + def test_golden_rows(self) -> None: + for tok, (count, roles, default, pinned) in GOLDEN.items(): + with self.subTest(row=tok): + built = _tree(tok) + name, index = tree.parse_token(tok) + self.assertEqual(built["include_count"], count) + got = { + node["role"]: (node["variant"], node["reason"]) + for node in built["nodes"] + } + want = { + role: (index, "primary") + if role == name + else pinned.get(role, (0, default)) + for role in roles + } + self.assertEqual(got, want) + + def test_the_closure_is_the_resolve_round_include(self) -> None: + variants = get_variants(roles_dir=ROLES_DIR, readonly=True) + resolved = round_variants.resolve_round( + roles_dir=ROLES_DIR, + round_index=7, + primary_app_variants={"web-app-nextcloud": 7}, + variants_per_app=variants, + ) + self.assertEqual( + [node["role"] for node in _tree("web-app-nextcloud#7")["nodes"]], + list(resolved.include), + ) + + def test_negative_control_a_partner_whose_carrier_is_absent_is_not_pinned( + self, + ) -> None: + built = _tree(UNPINNED_ROW) + roles = {node["role"]: node for node in built["nodes"]} + self.assertNotIn("web-app-dashboard", roles) + self.assertFalse(roles["web-app-keycloak"]["reason"].startswith("pin by")) + + def test_the_pin_reason_names_a_carrier_the_resolver_runs(self) -> None: + variants = get_variants(roles_dir=ROLES_DIR, readonly=True) + resolved = round_variants.resolve_round( + roles_dir=ROLES_DIR, + round_index=0, + primary_app_variants={"web-app-wordpress": 0}, + variants_per_app=variants, + ) + for node in _tree("web-app-wordpress#0")["nodes"]: + if not node["reason"].startswith("pin by "): + continue + carrier, _, index = node["reason"].removeprefix("pin by ").partition("#") + with self.subTest(node=node["role"]): + self.assertIn(carrier, resolved.include) + self.assertEqual(resolved.active_index.get(carrier, 0), int(index)) + + def test_json_and_yaml_round_trip_to_the_same_structure(self) -> None: + built = _tree("web-app-wordpress#0") + self.assertEqual(json.loads(json.dumps(built)), built) + self.assertEqual(load_yaml_str(dump_yaml_str(built)), built) + + def test_a_malformed_token_is_rejected(self) -> None: + with self.assertRaises(ValueError): + tree.parse_token("web-app-wordpress#x") + + def test_negative_control_a_variant_the_role_lacks_is_rejected(self) -> None: + count = len( + get_variants(roles_dir=ROLES_DIR, readonly=True)["web-app-wordpress"] + ) + with self.assertRaisesRegex(ValueError, rf"must be 0\.\.{count - 1}"): + _tree(f"web-app-wordpress#{count}") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/meta/ci/variant_split/__init__.py b/tests/unit/python/cli/meta/ci/variant_split/__init__.py new file mode 100644 index 0000000000..ec645df9db --- /dev/null +++ b/tests/unit/python/cli/meta/ci/variant_split/__init__.py @@ -0,0 +1,94 @@ +"""Snapshot builders shared by the variant-split tests.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Iterable + +SEED = "42305502796" + + +def edge( + consumer: str, + key: str, + provider: str, + *, + cv: int = 0, + pv: int = 0, + shared: str = "shared", +) -> list: + return [consumer, cv, key, provider, pv, shared] + + +def record( + include: Iterable[str], + edges: Iterable[list] = (), + *, + active: dict[str, int] | None = None, + dark: Iterable[str] = (), + dictated: dict[str, str] | None = None, + error: str | None = None, +) -> dict: + members = list(include) + return { + "include": members, + "active": {role: (active or {}).get(role, 0) for role in members}, + "edges": sorted(edges), + "dark_pins": list(dark), + "dictated": dict(dictated or {}), + "error": error, + } + + +def entry(tok: str, mode: str = "compose", network: str = "clearnet") -> dict: + name, variant = tok.rsplit("#", 1) + return { + "apps": name, + "variant": variant, + "mode": mode, + "network": network, + "distro": "debian", + "priority": "false", + "covered": "0", + "clone": "false", + } + + +def row(tok: str, rid: int, covered_by: int = 0) -> dict: + name, variant = tok.rsplit("#", 1) + return { + "token": tok, + "name": name, + "variant": int(variant), + "id": rid, + "covered_by": covered_by, + "clone": False, + "priority": False, + } + + +def snapshot( + rows: list[dict], + rounds: dict[str, dict], + *, + head: Iterable[dict], + jobs: Iterable[str], + budget: int = 208, + pins: Iterable[dict] = (), + counts: dict[str, int] | None = None, +) -> dict: + head_entries = list(head) + return { + "digest": "x", + "seed": SEED, + "budget": {"available": budget}, + "rows": rows, + "rounds": rounds, + "sweeps": { + "0": {"entries": head_entries, "jobs": list(jobs), "head": head_entries} + }, + "variant_counts": counts or {}, + "pins": list(pins), + } diff --git a/tests/unit/python/cli/meta/ci/variant_split/test_compare.py b/tests/unit/python/cli/meta/ci/variant_split/test_compare.py new file mode 100644 index 0000000000..d230d72a51 --- /dev/null +++ b/tests/unit/python/cli/meta/ci/variant_split/test_compare.py @@ -0,0 +1,315 @@ +from __future__ import annotations + +import unittest + +from cli.meta.ci.variant_split import compare + +from . import edge, entry, record, row, snapshot + +HEAVY = [edge("app", "a", "pa"), edge("app", "b", "pb"), edge("pa", "c", "pc")] + + +def _before() -> dict: + rows = [row("app#0", 1), row("other#0", 2)] + rounds = { + "app#0": record(["pa", "pb", "pc", "app"], HEAVY), + "other#0": record(["other"], []), + } + return snapshot( + rows, + rounds, + head=[entry("app#0"), entry("other#0")], + jobs=["app#0", "other#0"], + budget=2, + ) + + +def _after(*, keep_c: bool = True, budget: int = 3, pin: dict | None = None) -> dict: + rows = [row("app#0", 1), row("app#3", 2), row("other#0", 3)] + split = [edge("app", "b", "pb")] + ([edge("pa", "c", "pc")] if keep_c else []) + rounds = { + "app#0": record(["pa", "app"], [edge("app", "a", "pa")]), + "app#3": record(["pa", "pb", "pc", "app"], split, active={"app": 3}), + "other#0": record(["other"], []), + } + tokens = ["app#0", "app#3", "other#0"][:budget] + return snapshot( + rows, + rounds, + head=[entry(t) for t in tokens], + jobs=["app#0", "app#3", "other#0"], + budget=budget, + pins=[pin] if pin else [], + ) + + +class TestVerdict(unittest.TestCase): + def test_a_snapshot_against_itself_keeps_everything(self) -> None: + self.assertTrue( + compare.verdict(_before(), _before(), old=["app#0"], split=["app#0"])[ + "kept" + ] + ) + + def test_a_split_that_carries_every_edge_inside_the_budget_is_kept(self) -> None: + result = compare.verdict( + _before(), _after(), old=["app#0"], split=["app#0", "app#3"] + ) + self.assertEqual(result["edges"]["local"]["keys"], []) + self.assertTrue(result["kept"], compare.render(result)) + + def test_negative_control_a_dep_edge_left_behind_is_reported(self) -> None: + result = compare.verdict( + _before(), _after(keep_c=False), old=["app#0"], split=["app#0", "app#3"] + ) + lost = [("pa", "pc", frozenset({("c", "shared")}))] + self.assertEqual(result["edges"]["head"]["keys"], lost) + self.assertEqual(result["invariant"]["edges_lost"], lost) + self.assertFalse(result["kept"]) + + def test_a_row_pushed_past_the_budget_stays_covered(self) -> None: + result = compare.verdict( + _before(), _after(budget=2), old=["app#0"], split=["app#0", "app#3"] + ) + self.assertEqual(result["axes"]["per_sweep"]["0"]["head_lost"], ["other#0"]) + self.assertEqual(result["invariant"]["newly_uncovered"], []) + self.assertTrue(result["kept"], compare.render(result)) + + def test_negative_control_one_false_credit_fails_the_invariant(self) -> None: + after = _after() + after["rows"].append(row("lone#0", 4, covered_by=1)) + result = compare.verdict( + _before(), after, old=["app#0"], split=["app#0", "app#3"] + ) + self.assertEqual( + result["invariant"]["introduced_false_credits"], + ["lone#0: app#0 does not deploy lone"], + ) + self.assertEqual(result["invariant"]["newly_uncovered"], ["lone#0"]) + self.assertFalse(result["kept"]) + + def test_negative_control_a_child_no_job_row_deploys_fails(self) -> None: + after = _after() + after["rows"].append({**row("app#5", 5), "clone": True}) + result = compare.verdict( + _before(), after, old=["app#0"], split=["app#0", "app#3"] + ) + self.assertEqual(result["invariant"]["newly_uncovered"], ["app#5"]) + self.assertFalse(result["kept"]) + + def test_a_credit_to_a_coverer_outside_the_job_list_is_false(self) -> None: + after = _after() + after["rows"].append(row("pb#0", 4, covered_by=2)) + after["sweeps"]["0"]["jobs"].remove("app#3") + result = compare.verdict( + _before(), after, old=["app#0"], split=["app#0", "app#3"] + ) + self.assertEqual( + result["invariant"]["introduced_false_credits"], + ["pb#0: app#3 is not in the job list"], + ) + self.assertFalse(result["kept"]) + + def test_negative_control_a_new_pin_without_reciprocity_fails(self) -> None: + pin = { + "carrier": "app#3", + "partner": "pa", + "target": "1", + "key": "a", + "reciprocal": "error: no gate", + } + result = compare.verdict( + _before(), _after(pin=pin), old=["app#0"], split=["app#0", "app#3"] + ) + self.assertEqual(result["pins"]["unreciprocated"], [pin]) + self.assertFalse(result["kept"]) + + def test_a_reciprocal_new_pin_passes(self) -> None: + pin = { + "carrier": "app#3", + "partner": "pa", + "target": "1", + "key": "a", + "reciprocal": 1, + } + result = compare.verdict( + _before(), _after(pin=pin), old=["app#0"], split=["app#0", "app#3"] + ) + self.assertEqual(result["pins"]["unreciprocated"], []) + + def test_the_render_names_the_verdict(self) -> None: + text = compare.render( + compare.verdict( + _before(), _after(keep_c=False), old=["app#0"], split=["app#0", "app#3"] + ) + ) + self.assertIn("coverage kept: NO", text) + + +def _gate( + *, + jobs: list[str], + big_include: list[str], + dark: tuple[str, ...] = (), + error: str | None = None, +) -> dict: + rows = [row("big#0", 1), row("dep#0", 2, covered_by=1), row("other#0", 3)] + rounds = { + "big#0": record(big_include), + "dep#0": record(["dep"]), + "other#0": record(["dep", "big", "other"], dark=dark, error=error), + } + return snapshot(rows, rounds, head=[entry(t) for t in jobs], jobs=jobs) + + +def _gate_verdict(before: dict, after: dict) -> dict: + return compare.verdict(before, after, old=["big#0"], split=["big#0"]) + + +class TestEachGateAlone(unittest.TestCase): + def test_a_coverer_leaving_the_job_list_fails_on_the_invariant_alone(self) -> None: + before = _gate(jobs=["big#0", "other#0"], big_include=["dep", "big"]) + after = _gate(jobs=["other#0"], big_include=["dep", "big"]) + result = _gate_verdict(before, after) + self.assertEqual( + result["invariant"]["introduced_false_credits"], + ["dep#0: big#0 is not in the job list"], + ) + self.assertEqual(result["coverage"]["introduced"], []) + self.assertFalse(result["kept"]) + + def test_a_coverer_dropping_the_role_fails_on_the_credit_check_alone(self) -> None: + before = _gate(jobs=["other#0"], big_include=["dep", "big"]) + after = _gate(jobs=["other#0"], big_include=["big"]) + result = _gate_verdict(before, after) + self.assertEqual(result["invariant"]["introduced_false_credits"], []) + self.assertEqual( + result["coverage"]["introduced"], ["dep#0: big#0 does not deploy dep"] + ) + self.assertFalse(result["kept"]) + + def test_a_new_dark_pin_fails_alone(self) -> None: + before = _gate(jobs=["big#0", "other#0"], big_include=["dep", "big"]) + after = _gate( + jobs=["big#0", "other#0"], + big_include=["dep", "big"], + dark=("other#0 pins dep above k",), + ) + result = _gate_verdict(before, after) + self.assertEqual( + result["pins"]["new_dark_pins"], ["other#0: other#0 pins dep above k"] + ) + self.assertFalse(result["kept"]) + + def test_a_new_round_error_fails_alone(self) -> None: + before = _gate(jobs=["big#0", "other#0"], big_include=["dep", "big"]) + after = _gate( + jobs=["big#0", "other#0"], big_include=["dep", "big"], error="pins cycle" + ) + result = _gate_verdict(before, after) + self.assertEqual(result["pins"]["new_errors"], ["other#0: pins cycle"]) + self.assertFalse(result["kept"]) + + def test_the_gate_fixture_alone_keeps_everything(self) -> None: + snap = _gate(jobs=["big#0", "other#0"], big_include=["dep", "big"]) + self.assertTrue(_gate_verdict(snap, snap)["kept"]) + + +def _moved(coverer: int) -> dict: + rows = [ + row("app-a#0", 1), + row("app-c#0", 3), + row("app-r#0", 4, covered_by=coverer), + ] + rounds = { + "app-a#0": record(["app-a", "app-r"], active={"app-r": 1}), + "app-c#0": record(["app-c"]), + "app-r#0": record(["app-r"]), + } + jobs = ["app-a#0", "app-c#0", "app-r#0"] + return snapshot(rows, rounds, head=[entry(t) for t in jobs], jobs=jobs) + + +class TestFalseCreditIdentity(unittest.TestCase): + def test_negative_control_a_false_credit_moved_to_another_coverer_is_new( + self, + ) -> None: + result = compare.verdict( + _moved(1), _moved(3), old=["app-a#0"], split=["app-a#0"] + ) + self.assertEqual( + result["invariant"]["introduced_false_credits"], + ["app-r#0: app-c#0 does not deploy app-r"], + ) + self.assertFalse(result["kept"]) + + def test_an_unchanged_false_credit_is_not_blamed_on_the_split(self) -> None: + result = compare.verdict( + _moved(1), _moved(1), old=["app-a#0"], split=["app-a#0"] + ) + self.assertEqual(result["invariant"]["introduced_false_credits"], []) + self.assertTrue(result["kept"]) + + +def _variant(other_edges: list, big_edges: list) -> dict: + rows = [row("big#0", 1), row("dep#0", 2), row("other#0", 3)] + rounds = { + "big#0": record(["dep", "big"], big_edges), + "dep#0": record(["dep"]), + "other#0": record( + ["dep", "big", "other"], + other_edges, + active={"dep": other_edges[0][4] if other_edges else 0}, + ), + } + jobs = ["other#0", "dep#0"] + return snapshot( + rows, + rounds, + head=[entry(t) for t in jobs], + jobs=jobs, + counts={"dep": 2}, + ) + + +class TestVariantEdges(unittest.TestCase): + OWN = (edge("big", "k", "dep"),) + + def test_negative_control_a_declared_edge_at_a_lost_variant_pair_fails( + self, + ) -> None: + before = _variant([edge("big", "k", "dep")], list(self.OWN)) + after = _variant([edge("big", "k", "dep", pv=1)], list(self.OWN)) + result = compare.verdict(before, after, old=["other#0"], split=["other#0"]) + self.assertEqual(result["invariant"]["edges_lost"], []) + self.assertEqual( + result["invariant"]["variant_edges_lost"], + [["big", 0, "k", "dep", 0, "shared"]], + ) + self.assertFalse(result["kept"]) + + def test_an_edge_the_consumer_no_longer_declares_is_retired(self) -> None: + before = _variant([edge("big", "k", "dep")], list(self.OWN)) + after = _variant([], []) + result = compare.verdict(before, after, old=["other#0"], split=["other#0"]) + self.assertEqual(result["invariant"]["variant_edges_lost"], []) + self.assertEqual(result["invariant"]["variant_edges_retired"], 1) + + +class TestEdgeCheckPerRound(unittest.TestCase): + def test_keys_of_two_old_rounds_are_never_merged_into_one_identity(self) -> None: + rows = [row("app#0", 1), row("app#1", 2)] + rounds = { + "app#0": record(["kc", "app"], [edge("app", "sso", "kc")]), + "app#1": record(["kc", "app"], [edge("app", "oidc", "kc", cv=1)]), + } + snap = snapshot(rows, rounds, head=[], jobs=["app#0", "app#1"]) + result = compare.edge_check( + snap, snap, old=["app#0", "app#1"], split=["app#0", "app#1"] + ) + self.assertEqual(result["total"]["keys"], 2) + self.assertEqual(result["local"]["keys"], []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/meta/ci/variant_split/test_cost.py b/tests/unit/python/cli/meta/ci/variant_split/test_cost.py new file mode 100644 index 0000000000..7db20eafd6 --- /dev/null +++ b/tests/unit/python/cli/meta/ci/variant_split/test_cost.py @@ -0,0 +1,72 @@ +from __future__ import annotations + +import unittest + +from cli.meta.ci.variant_split import cost + +from . import entry, record, row, snapshot + +SEGMENTS = { + "passes": {"1": {"app": 100.0, "heavy": 900.0}, "2": {"app": 10.0, "heavy": 20.0}}, + "fixed": { + "prep": 0, + "container": 0, + "backup": 0, + "reset_post": 0, + "infra_per_pass": 0, + "dr_drill_variant0": 50, + }, + "runner": "r1", +} + + +class TestRowCost(unittest.TestCase): + def test_a_row_sums_its_apps_per_pass_plus_its_fixed_cost(self) -> None: + seconds, unpriced = cost.row_cost(["app", "heavy"], 0, SEGMENTS) + self.assertEqual(seconds, 50 + 110 + 920) + self.assertEqual(unpriced, []) + + def test_only_variant_0_pays_the_dr_drill(self) -> None: + self.assertEqual(cost.row_cost(["app"], 3, SEGMENTS)[0], 110) + + def test_negative_control_an_unmeasured_app_is_listed_not_hidden(self) -> None: + seconds, unpriced = cost.row_cost(["app", "new"], 3, SEGMENTS) + self.assertEqual(seconds, 110) + self.assertEqual(unpriced, ["new"]) + + def test_the_default_fixed_cost_is_the_measured_per_row_overhead(self) -> None: + seconds, _ = cost.row_cost([], 0, {"passes": {"1": {}, "2": {}}}) + self.assertEqual(seconds, 273 + 204 + 340 + 170 + 2 * 540 + 152) + + +class TestDelta(unittest.TestCase): + def test_a_split_reports_the_saving_and_the_added_runner_time(self) -> None: + before = snapshot( + [row("app#0", 1)], + {"app#0": record(["heavy", "app"])}, + head=[entry("app#0")], + jobs=["app#0"], + ) + after = snapshot( + [row("app#0", 1), row("app#3", 2)], + {"app#0": record(["app"]), "app#3": record(["heavy", "app"])}, + head=[entry("app#0"), entry("app#3")], + jobs=["app#0", "app#3"], + ) + result = cost.delta( + before, after, SEGMENTS, old=["app#0"], split=["app#0", "app#3"] + ) + self.assertEqual(result["rows"]["app#0"]["saving"], 920) + self.assertEqual(result["net"]["jobs"]["delta"], (160 + 1030) - 1080) + self.assertIn("app#3", cost.render(result)) + + def test_the_render_names_the_runner_the_segments_came_from(self) -> None: + snap = snapshot( + [row("app#0", 1)], {"app#0": record(["app"])}, head=[], jobs=["app#0"] + ) + result = cost.delta(snap, snap, SEGMENTS, old=["app#0"], split=["app#0"]) + self.assertIn("on runner r1", cost.render(result)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/meta/ci/variant_split/test_coverage.py b/tests/unit/python/cli/meta/ci/variant_split/test_coverage.py new file mode 100644 index 0000000000..e7611868cc --- /dev/null +++ b/tests/unit/python/cli/meta/ci/variant_split/test_coverage.py @@ -0,0 +1,111 @@ +from __future__ import annotations + +import unittest + +from cli.meta.ci.variant_split.coverage import children, credit_findings, declared +from cli.meta.ci.variant_split.edges import Edge + +from . import edge, record, row, snapshot + + +def _snap(coverer_round: dict) -> dict: + rows = [row("big#0", 1), row("dep#0", 2, covered_by=1)] + rounds = { + "big#0": coverer_round, + "dep#0": record(["db", "dep"], [edge("dep", "db", "db")]), + } + return snapshot(rows, rounds, head=[], jobs=["big#0"]) + + +HONOURED = record( + ["db", "dep", "big"], [edge("dep", "db", "db"), edge("big", "dep", "dep")] +) + + +class TestCreditFindings(unittest.TestCase): + def test_an_unchanged_honoured_credit_has_no_finding(self) -> None: + found = credit_findings(_snap(HONOURED), _snap(HONOURED)) + self.assertEqual( + found["introduced"] + found["thinner"] + found["preexisting"], [] + ) + + def test_negative_control_a_coverer_that_drops_the_role_is_a_false_credit( + self, + ) -> None: + after = _snap(record(["big"], [])) + found = credit_findings(_snap(HONOURED), after) + self.assertEqual(found["introduced"], ["dep#0: big#0 does not deploy dep"]) + + def test_negative_control_a_pin_that_moves_the_role_off_variant_0_is_caught( + self, + ) -> None: + pinned = record( + ["db", "dep", "big"], [edge("dep", "db", "db", cv=2)], active={"dep": 2} + ) + found = credit_findings(_snap(HONOURED), _snap(pinned)) + self.assertEqual( + found["introduced"], ["dep#0: big#0 runs dep#2, not the credited #0"] + ) + + def test_negative_control_a_coverer_that_switches_a_key_off_thins_the_credit( + self, + ) -> None: + lean = record(["db", "dep", "big"], [edge("big", "dep", "dep")]) + found = credit_findings(_snap(HONOURED), _snap(lean)) + self.assertEqual(len(found["thinner"]), 1) + self.assertIn("db", found["thinner"][0]) + + def test_a_credit_that_was_already_false_stays_pre_existing(self) -> None: + broken = _snap(record(["big"], [])) + found = credit_findings(broken, broken) + self.assertEqual(found["introduced"], []) + self.assertEqual(len(found["preexisting"]), 1) + + def test_negative_control_a_credit_broken_another_way_is_introduced(self) -> None: + dropped = _snap(record(["big"], [])) + pinned = _snap(record(["db", "dep", "big"], [], active={"dep": 2})) + found = credit_findings(dropped, pinned) + self.assertEqual(found["preexisting"], []) + self.assertEqual( + found["introduced"], ["dep#0: big#0 runs dep#2, not the credited #0"] + ) + + def test_negative_control_a_coverer_that_dictates_the_roles_config_is_false( + self, + ) -> None: + dictated = record( + ["db", "dep", "big"], list(HONOURED["edges"]), dictated={"dep": "big#0"} + ) + found = credit_findings(_snap(HONOURED), _snap(dictated)) + self.assertEqual( + found["introduced"], ["dep#0: big#0 dictates the config of dep in big#0"] + ) + + def test_a_dictated_member_does_not_cover_its_child(self) -> None: + dictated = record(["db", "dep", "big"], dictated={"dep": "big#0"}) + self.assertIn("dep#0", children(_snap(dictated))["uncovered"]) + + def test_a_row_that_starts_running_itself_is_reported(self) -> None: + after = _snap(HONOURED) + after["rows"][1]["covered_by"] = 0 + self.assertEqual( + credit_findings(_snap(HONOURED), after)["newly_uncovered"], ["dep#0"] + ) + + +class TestDeclared(unittest.TestCase): + EDGE = Edge("ghost", 1, "db", "db", 0, "shared") + + def test_negative_control_an_edge_without_its_row_still_counts_as_declared( + self, + ) -> None: + snap = {"rounds": {}, "variant_counts": {"ghost": 2}} + self.assertTrue(declared(snap, self.EDGE)) + + def test_an_edge_of_a_variant_the_role_no_longer_has_is_retired(self) -> None: + snap = {"rounds": {}, "variant_counts": {"ghost": 1}} + self.assertFalse(declared(snap, self.EDGE)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/meta/ci/variant_split/test_edges.py b/tests/unit/python/cli/meta/ci/variant_split/test_edges.py new file mode 100644 index 0000000000..e3b4f5f528 --- /dev/null +++ b/tests/unit/python/cli/meta/ci/variant_split/test_edges.py @@ -0,0 +1,128 @@ +from __future__ import annotations + +import unittest + +from cli.meta.ci.variant_split.edges import ( + Edge, + identities, + is_active, + missing, + round_edges, + sharing, + union, +) + +PROVIDERS = {"sso": "keycloak", "db": "postgres", "matrix": "matrix"} + + +def _edges(maps, include, active=None, mcp=()): + return round_edges( + include=include, + maps=maps, + active_index=active or {}, + provider_of=PROVIDERS.get, + mcp_pairs=mcp, + ) + + +class TestActivity(unittest.TestCase): + def test_a_literal_false_or_empty_flag_is_off(self) -> None: + self.assertFalse(is_active({"enabled": False})) + self.assertFalse(is_active({"enabled": "false"})) + self.assertFalse(is_active({"enabled": ""})) + self.assertFalse(is_active("not a mapping")) + + def test_a_presence_gate_or_a_missing_flag_counts_as_on(self) -> None: + self.assertTrue(is_active({"enabled": "{{ 'x' in group_names }}"})) + self.assertTrue(is_active({"shared": True})) + + def test_sharing_is_normalised(self) -> None: + self.assertEqual(sharing({"shared": True}), "shared") + self.assertEqual(sharing({"shared": False}), "dedicated") + self.assertEqual(sharing({"enabled": True}), "unset") + + +class TestRoundEdges(unittest.TestCase): + def test_only_active_keys_to_deployed_providers_become_edges(self) -> None: + maps = { + "app": { + "sso": {"enabled": True, "shared": True}, + "db": {"enabled": False}, + "matrix": {"enabled": True, "shared": True}, + } + } + edges = _edges(maps, ["app", "keycloak", "postgres"]) + self.assertEqual(edges, {Edge("app", 0, "sso", "keycloak", 0, "shared")}) + + def test_mcp_pairs_count_only_when_both_ends_are_deployed(self) -> None: + edges = _edges( + {}, ["client", "server"], mcp=[("client", "server"), ("client", "gone")] + ) + self.assertEqual( + {(e.consumer, e.key, e.provider) for e in edges}, + {("client", "mcp", "server")}, + ) + + +OLD = frozenset( + { + Edge("app", 0, "sso", "keycloak", 0, "shared"), + Edge("app", 0, "db", "postgres", 0, "shared"), + } +) +OIDC = Edge("app", 0, "oidc", "keycloak", 0, "shared") + + +class TestMissing(unittest.TestCase): + def test_a_carrier_with_the_same_edges_leaves_nothing_missing(self) -> None: + self.assertEqual(missing([OLD], [OLD], "strict"), set()) + + def test_negative_control_an_extra_key_breaks_the_keys_level_only(self) -> None: + carrier = OLD | {OIDC} + self.assertEqual(missing([OLD], [carrier], "pair"), set()) + self.assertEqual( + missing([OLD], [carrier], "keys"), + {("app", "keycloak", frozenset({("sso", "shared")}))}, + ) + + def test_negative_control_a_moved_variant_breaks_the_strict_level_only( + self, + ) -> None: + carrier = { + Edge(c, cv, k, p, 2 if p == "postgres" else pv, s) + for c, cv, k, p, pv, s in OLD + } + self.assertEqual(missing([OLD], [carrier], "keys"), set()) + self.assertEqual(len(missing([OLD], [carrier], "strict")), 1) + + def test_edges_split_over_two_carriers_are_all_held(self) -> None: + first, second = sorted(OLD) + self.assertEqual(missing([OLD], [{first}, {second}], "keys"), set()) + + def test_negative_control_a_carrier_missing_one_edge_leaves_it_missing( + self, + ) -> None: + first, _second = sorted(OLD) + self.assertEqual(len(missing([OLD], [{first}], "keys")), 1) + + def test_two_old_rounds_keep_their_key_sets_apart(self) -> None: + sso = {e for e in OLD if e.key == "sso"} + self.assertEqual(missing([sso, {OIDC}], [sso, {OIDC}], "keys"), set()) + + def test_the_union_collapses_each_round_on_its_own(self) -> None: + sso = {e for e in OLD if e.key == "sso"} + self.assertEqual( + union([sso, {OIDC}], "keys"), + { + ("app", "keycloak", frozenset({("sso", "shared")})), + ("app", "keycloak", frozenset({("oidc", "shared")})), + }, + ) + + def test_an_unknown_level_is_rejected(self) -> None: + with self.assertRaises(ValueError): + identities(OLD, "loose") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/meta/ci/variant_split/test_main.py b/tests/unit/python/cli/meta/ci/variant_split/test_main.py new file mode 100644 index 0000000000..9739ea1398 --- /dev/null +++ b/tests/unit/python/cli/meta/ci/variant_split/test_main.py @@ -0,0 +1,171 @@ +from __future__ import annotations + +import io +import json +import tempfile +import unittest +from contextlib import redirect_stderr, redirect_stdout +from pathlib import Path +from unittest import mock + +from cli.meta.ci.variant_split import __main__ as cli +from cli.meta.ci.variant_split import snapshot as snapshot_module +from utils.cache.files import read_text + +from . import entry, record, row, snapshot + +LOG = ( + "2026-11-06T10:00:00.0Z TASK [prepare the host] ***\n" + "2026-11-06T10:00:10.0Z TASK [web-app-a : first] ***\n" + "2026-11-06T10:01:00.0Z TASK [web-app-b : first] ***\n" + "2026-11-06T10:02:00.0Z TASK [test-e2e-playwright : run] ***\n" +) + + +def _snap(*, with_b: bool = True, seed: str | None = None) -> dict: + include = ["web-app-b", "web-app-a"] if with_b else ["web-app-a"] + snap = snapshot( + [row("web-app-a#0", 1), row("web-app-b#0", 2)], + {"web-app-a#0": record(include), "web-app-b#0": record(["web-app-b"])}, + head=[entry("web-app-a#0")], + jobs=["web-app-a#0"], + ) + if seed is not None: + snap["seed"] = seed + return snap + + +def _json(path: str | Path) -> dict: + return json.loads(read_text(str(path))) + + +class TestMain(unittest.TestCase): + def setUp(self) -> None: + self.tmp = Path(self.enterContext(tempfile.TemporaryDirectory())) + + def _write(self, name: str, data: dict) -> str: + path = self.tmp / name + path.write_text(json.dumps(data)) + return str(path) + + def _run(self, *argv: str) -> tuple[int, str, str]: + out, err = io.StringIO(), io.StringIO() + with redirect_stdout(out), redirect_stderr(err): + rc = cli.main(list(argv)) + return rc, out.getvalue(), err.getvalue() + + def _compare(self, before: dict, after: dict) -> tuple[int, str, str]: + return self._run( + "compare", + self._write("before.json", before), + self._write("after.json", after), + "--old", + "web-app-a#0", + "--split", + "web-app-a#0", + ) + + def test_compare_of_a_snapshot_with_itself_exits_0(self) -> None: + rc, out, _ = self._compare(_snap(), _snap()) + self.assertEqual((rc, out.splitlines()[0]), (0, "coverage kept: yes")) + + def test_negative_control_compare_exits_1_when_coverage_is_lost(self) -> None: + rc, out, _ = self._compare(_snap(), _snap(with_b=False)) + self.assertEqual((rc, out.splitlines()[0]), (1, "coverage kept: NO")) + + def test_negative_control_compare_refuses_snapshots_of_two_seeds(self) -> None: + rc, _, err = self._compare(_snap(), _snap(seed="7")) + self.assertEqual(rc, 2) + self.assertIn("must be one run id", err) + + def test_compare_writes_the_verdict_when_asked(self) -> None: + out_path = self.tmp / "verdict.json" + self._run( + "compare", + self._write("before.json", _snap()), + self._write("after.json", _snap()), + "--old", + "web-app-a#0", + "--split", + "web-app-a#0", + "--out", + str(out_path), + ) + self.assertTrue(_json(out_path)["kept"]) + + def test_snapshot_passes_the_seed_and_records_it(self) -> None: + out_path = self.tmp / "snap.json" + with mock.patch.object( + snapshot_module, "take", return_value=_snap(seed="42") + ) as take: + rc, _, _ = self._run( + "snapshot", "--out", str(out_path), "--seed", "42", "--sweeps", "0,1" + ) + take.assert_called_once_with([0, 1], seed="42") + self.assertEqual((rc, _json(out_path)["seed"]), (0, "42")) + + def test_negative_control_snapshot_without_a_seed_is_a_usage_error(self) -> None: + with self.assertRaises(SystemExit), redirect_stderr(io.StringIO()): + cli.main(["snapshot", "--out", str(self.tmp / "snap.json")]) + + def _segments(self, runner: str, name: str) -> str: + out_path = self.tmp / name + self._run( + "segments", + self._write("snap.json", _snap()), + "--row", + "web-app-a#0", + "--runner", + runner, + "--pass", + "1=1:", + "--log", + str(self._log()), + "--out", + str(out_path), + ) + return str(out_path) + + def _log(self) -> Path: + path = self.tmp / "deploy.log" + path.write_text(LOG) + return path + + def test_segments_from_a_log_record_the_runner_and_the_seen_apps(self) -> None: + data = _json(self._segments("fast", "seg.json")) + self.assertEqual(data["runner"], "fast") + self.assertEqual(data["passes"]["1"], {"web-app-a": 50.0, "web-app-b": 60.0}) + + def test_negative_control_merge_of_two_runners_fails(self) -> None: + fast = self._segments("fast", "fast.json") + slow = self._segments("slow", "slow.json") + rc, _, err = self._run("merge", fast, slow, "--out", str(self.tmp / "m.json")) + self.assertEqual(rc, 2) + self.assertIn("cannot be merged", err) + + def test_merge_of_one_runner_writes_the_joined_file(self) -> None: + first = self._segments("fast", "a.json") + second = self._segments("fast", "b.json") + merged = self.tmp / "m.json" + rc, _, _ = self._run("merge", first, second, "--out", str(merged)) + self.assertEqual((rc, _json(merged)["runner"]), (0, "fast")) + + def test_cost_prints_the_saving_per_row(self) -> None: + seg = self._segments("fast", "seg.json") + rc, out, _ = self._run( + "cost", + self._write("before.json", _snap()), + self._write("after.json", _snap(with_b=False)), + "--segments", + seg, + "--old", + "web-app-a#0", + "--split", + "web-app-a#0", + ) + self.assertEqual(rc, 0) + self.assertIn("web-app-a#0: ", out) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/meta/ci/variant_split/test_rounds.py b/tests/unit/python/cli/meta/ci/variant_split/test_rounds.py new file mode 100644 index 0000000000..51502f89e6 --- /dev/null +++ b/tests/unit/python/cli/meta/ci/variant_split/test_rounds.py @@ -0,0 +1,113 @@ +from __future__ import annotations + +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from cli.meta.ci.variant_split import rounds +from utils.roles.mapping import ROLE_FILE_META_SERVICES, ROLE_FILE_META_VARIANTS + +CARRIER = """\ +- services: + # variant-pin: web-app-b#TARGET + b: + enabled: true + shared: true +""" +PARTNER = """\ +a: + enabled: "{{ 'web-app-a' in group_names }}" + shared: "{{ 'web-app-a' in group_names }}" +""" + + +def _tree(tmp: str, target: str, gate: bool = True) -> str: + root = Path(tmp) + (root / "web-app-a" / "meta").mkdir(parents=True) + (root / "web-app-b" / "meta").mkdir(parents=True) + (root / "web-app-a" / ROLE_FILE_META_VARIANTS).write_text( + CARRIER.replace("TARGET", target) + ) + (root / "web-app-b" / ROLE_FILE_META_SERVICES).write_text( + PARTNER if gate else "c: {}\n" + ) + return tmp + + +VARIANTS = { + "web-app-b": [ + {"services": {"a": {"enabled": False}}}, + {"services": {"a": {"enabled": True}}}, + ] +} + + +class TestPins(unittest.TestCase): + def test_a_pin_is_read_with_the_key_it_stands_above(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + self.assertEqual( + rounds.pinned_keys("web-app-a", _tree(tmp, "1")), + {0: {"web-app-b": ("1", "b")}}, + ) + + def test_a_reciprocating_pin_names_its_partner_variant(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + [finding] = rounds.pin_findings( + "web-app-a", roles_dir=_tree(tmp, "1"), variants_per_app=VARIANTS + ) + self.assertEqual((finding["target"], finding["reciprocal"]), ("1", 1)) + + def test_negative_control_a_pin_at_the_wrong_index_is_visible(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + [finding] = rounds.pin_findings( + "web-app-a", roles_dir=_tree(tmp, "0"), variants_per_app=VARIANTS + ) + self.assertEqual((finding["target"], finding["reciprocal"]), ("0", 1)) + + def test_negative_control_a_partner_without_a_back_gate_cannot_reciprocate( + self, + ) -> None: + with tempfile.TemporaryDirectory() as tmp: + [finding] = rounds.pin_findings( + "web-app-a", + roles_dir=_tree(tmp, "1", gate=False), + variants_per_app=VARIANTS, + ) + self.assertTrue(str(finding["reciprocal"]).startswith("error:")) + + +class TestToken(unittest.TestCase): + def test_a_whole_role_row_is_variant_0(self) -> None: + self.assertEqual(rounds.token("web-app-a", None), "web-app-a#0") + + def test_a_variant_row_keeps_its_index(self) -> None: + self.assertEqual(rounds.token("web-app-a", 3), "web-app-a#3") + + +class TestDictated(unittest.TestCase): + def setUp(self) -> None: + rounds._dictating.cache_clear() + self.addCleanup(rounds._dictating.cache_clear) + + def _dictated(self, include: list[str], active: dict[str, int]) -> dict: + found = {("web-app-a", 1): {"web-app-b", "web-app-gone"}} + with mock.patch.object(rounds, "overridden_providers", return_value=found): + return rounds.dictated(include, active, roles_dir="/roles") + + def test_a_member_whose_config_a_variant_dictates_names_that_variant( + self, + ) -> None: + found = self._dictated(["web-app-b", "web-app-a"], {"web-app-a": 1}) + self.assertEqual(found, {"web-app-b": "web-app-a#1"}) + + def test_negative_control_another_variant_of_the_carrier_dictates_nothing( + self, + ) -> None: + self.assertEqual( + self._dictated(["web-app-b", "web-app-a"], {"web-app-a": 0}), {} + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/meta/ci/variant_split/test_segments.py b/tests/unit/python/cli/meta/ci/variant_split/test_segments.py new file mode 100644 index 0000000000..8dbed12c00 --- /dev/null +++ b/tests/unit/python/cli/meta/ci/variant_split/test_segments.py @@ -0,0 +1,131 @@ +from __future__ import annotations + +import unittest + +from cli.meta.ci.variant_split import segments + +TSV = ( + "500\t0\tTOTAL\n" + "100\t1\tweb-app-a : own task\n" + "40\t1\tsys-svc-compose : Ensure instance dir for 'web-app-b' is up\n" + "30\t1\tsys-svc-compose : Render /opt/compose/b/compose.yml\n" + "60\t3\tsys-svc-compose : swarm: wait until stack tasks converge\n" + "20\t1\tsetup roles in run_after order\n" + "10\t1\tsys-x : touches 'web-app-a' and 'web-app-b'" +) +LOG = [ + "2026-11-06T10:00:00.0Z TASK [prepare the host] ***", + "2026-11-06T10:00:10.0Z TASK [web-app-a : first] ***", + "secret=hunter2 must never surface", + "2026-11-06T10:00:40.0Z TASK [sys-svc-compose : helper for b] ***", + "2026-11-06T10:01:00.0Z TASK [web-app-b : first] ***", + "2026-11-06T10:01:05.5Z RUNNING HANDLER [web-app-a : late handler] ***", + "2026-11-06T10:02:00.0Z TASK [test-e2e-playwright : run] ***", + "2026-11-06T10:05:00.0Z TASK [test-e2e-playwright : collect] ***", +] +APPS = ["web-app-a", "web-app-b", "web-app-c"] + + +def _entity(app: str) -> str: + return app.rsplit("-", 1)[1] + + +def _file(runner: str, passes: dict, source: str = "s", cut: bool = False) -> dict: + return {"source": source, "runner": runner, "lower_bound": cut, "passes": passes} + + +class TestSegments(unittest.TestCase): + def test_parse_skips_the_total_line(self) -> None: + self.assertEqual(len(segments.parse_tsv(TSV)), 6) + + def test_tasks_are_attributed_by_prefix_mention_spread_or_fixed(self) -> None: + result = segments.attribute(segments.parse_tsv(TSV), APPS, entity_of=_entity) + self.assertEqual( + result["apps"], {"web-app-a": 125.0, "web-app-b": 95.0, "web-app-c": 20.0} + ) + self.assertEqual(result["fixed"], 20.0) + self.assertEqual(result["total"], 260.0) + + def test_negative_control_another_apps_task_never_lands_on_this_app(self) -> None: + result = segments.attribute( + segments.parse_tsv(TSV), ["web-app-c"], entity_of=_entity + ) + self.assertEqual(result["apps"], {"web-app-c": 60.0}) + self.assertEqual(result["fixed"], 200.0) + + def test_an_app_no_task_reaches_stays_unpriced_in_a_tsv(self) -> None: + tasks = segments.parse_tsv("100\t1\tweb-app-a : own task") + result = segments.attribute( + tasks, ["web-app-a", "web-app-z"], entity_of=_entity + ) + self.assertEqual(result["apps"], {"web-app-a": 100.0}) + + def test_a_log_pass_is_cut_at_each_apps_first_task(self) -> None: + result = segments.first_task_segments(LOG, APPS) + self.assertEqual(result["apps"], {"web-app-a": 50.0, "web-app-b": 60.0}) + + def test_a_log_pass_splits_fixed_app_and_e2e_time(self) -> None: + result = segments.first_task_segments(LOG, APPS) + self.assertEqual( + (result["fixed"], result["e2e"], result["total"]), (10.0, 180.0, 300.0) + ) + + def test_negative_control_an_app_the_pass_never_reached_is_not_priced_at_zero( + self, + ) -> None: + result = segments.first_task_segments(LOG, APPS) + self.assertNotIn("web-app-c", result["apps"]) + self.assertEqual(result["unseen"], ["web-app-c"]) + + def test_no_log_text_leaves_the_segments(self) -> None: + self.assertNotIn("hunter2", repr(segments.first_task_segments(LOG, APPS))) + + def test_negative_control_a_log_without_headers_prices_nothing(self) -> None: + result = segments.first_task_segments(["no header here"], ["web-app-a"]) + self.assertEqual((result["apps"], result["total"]), ({}, 0.0)) + self.assertEqual(result["unseen"], ["web-app-a"]) + + def test_a_cut_pass_marks_the_file_a_lower_bound(self) -> None: + data = segments.build( + {"1": TSV, "2": TSV}, + ["web-app-a"], + entity_of=_entity, + runner="r1", + cut=["2"], + source="run 1", + ) + self.assertTrue(data["lower_bound"]) + self.assertIn("lower bound", data["source"]) + + def test_a_file_names_its_runner(self) -> None: + data = segments.build_from_log(LOG, {"1": (1, None)}, APPS, runner="r1") + self.assertEqual(data["runner"], "r1") + + +class TestMerge(unittest.TestCase): + def test_a_later_file_prices_only_the_gaps_of_its_runner(self) -> None: + merged = segments.merge( + [ + _file("r1", {"2": {"web-app-a": 10.0}}), + _file("r1", {"2": {"web-app-a": 99.0, "web-app-b": 20.0}}), + ] + ) + self.assertEqual( + merged["passes"], {"2": {"web-app-a": 10.0, "web-app-b": 20.0}} + ) + + def test_negative_control_files_of_two_runners_are_never_mixed(self) -> None: + with self.assertRaisesRegex(ValueError, "cannot be merged"): + segments.merge([_file("fast", {}), _file("slow", {})]) + + def test_a_lower_bound_file_makes_the_merge_a_lower_bound(self) -> None: + merged = segments.merge([_file("r1", {}), _file("r1", {}, cut=True)]) + self.assertTrue(merged["lower_bound"]) + + def test_nothing_to_merge_is_refused(self) -> None: + with self.assertRaises(ValueError): + segments.merge([]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/meta/ci/variant_split/test_snapshot.py b/tests/unit/python/cli/meta/ci/variant_split/test_snapshot.py new file mode 100644 index 0000000000..ea9b6f1399 --- /dev/null +++ b/tests/unit/python/cli/meta/ci/variant_split/test_snapshot.py @@ -0,0 +1,120 @@ +from __future__ import annotations + +import os +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from cli.meta.ci.variant_split import snapshot +from utils.roles.mapping import ROLE_FILE_META_VARIANTS + + +def _candidates() -> list[dict]: + return [ + {"name": "app", "variant": 0, "id": 1, "covered_by": 0, "clone": False}, + {"name": "dep", "variant": None, "id": 2, "covered_by": 1, "clone": False}, + ] + + +def _assign(rows: list, sweep: int) -> list[dict]: + return [ + { + "apps": r["name"], + "variant": "" if r["variant"] is None else str(r["variant"]), + "mode": "compose" if (i + sweep) % 2 == 0 else "swarm", + "priority": "false", + "covered": str(r["covered_by"]), + "clone": "false", + "id": str(r["id"]), + } + for i, r in enumerate(rows) + ] + + +class TestAssemble(unittest.TestCase): + def setUp(self) -> None: + self.resolved = [] + self.snap = snapshot.assemble( + candidates=_candidates(), + sweeps=[0, 1], + assign=_assign, + head_of=lambda entries: entries[:1], + is_regular=lambda e: e["covered"] == "0", + resolve=lambda name, variant: ( + self.resolved.append((name, variant)) or {"include": [name]} + ), + budget={"available": 1}, + variant_counts={"app": 1}, + pins=[], + digest="d", + seed="42", + ) + + def test_every_candidate_is_resolved_once(self) -> None: + self.assertEqual(self.resolved, [("app", 0), ("dep", None)]) + self.assertEqual(sorted(self.snap["rounds"]), ["app#0", "dep#0"]) + + def test_each_sweep_keeps_its_own_rotation_head(self) -> None: + self.assertEqual(self.snap["sweeps"]["0"]["head"][0]["mode"], "compose") + self.assertEqual(self.snap["sweeps"]["1"]["head"][0]["mode"], "swarm") + + def test_the_job_list_keeps_only_regular_entries(self) -> None: + self.assertEqual(self.snap["sweeps"]["0"]["jobs"], ["app#0"]) + + def test_rows_keep_their_coverage_credit(self) -> None: + self.assertEqual(self.snap["rows"][1]["covered_by"], 1) + + def test_the_snapshot_records_its_seed(self) -> None: + self.assertEqual(self.snap["seed"], "42") + + +class TestSeeds(unittest.TestCase): + def test_two_snapshots_of_one_run_id_share_it(self) -> None: + self.assertEqual(snapshot.check_seeds({"seed": "7"}, {"seed": "7"}), "7") + + def test_negative_control_different_seeds_are_refused(self) -> None: + with self.assertRaisesRegex(ValueError, "must be one run id"): + snapshot.check_seeds({"seed": "7"}, {"seed": "8"}) + + def test_negative_control_an_unseeded_snapshot_is_refused(self) -> None: + with self.assertRaises(ValueError): + snapshot.check_seeds({}, {}) + + def test_an_empty_seed_never_takes_a_snapshot(self) -> None: + with ( + mock.patch.object(snapshot, "pipeline") as pipeline, + self.assertRaises(ValueError), + ): + snapshot.take([0], seed=" ") + pipeline.assert_not_called() + + def test_the_seed_is_exported_before_the_pipeline_ranks(self) -> None: + seen = [] + + def pipeline() -> dict: + seen.append(os.environ[snapshot.SEED_ENV]) + raise RuntimeError + + with ( + mock.patch.dict(os.environ, {}), + mock.patch.object(snapshot, "pipeline", pipeline), + self.assertRaises(RuntimeError), + ): + snapshot.take([0], seed="42305502796") + self.assertEqual(seen, ["42305502796"]) + + +class TestDigest(unittest.TestCase): + def test_negative_control_an_edited_variants_file_changes_the_digest(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "role" / ROLE_FILE_META_VARIANTS + path.parent.mkdir(parents=True) + path.write_text("- {}\n") + first = snapshot.variants_digest(tmp) + path.write_text("- {}\n- {}\n") + self.assertNotEqual(first, snapshot.variants_digest(tmp)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/meta/ci/variant_tree/__init__.py b/tests/unit/python/cli/meta/ci/variant_tree/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/cli/meta/ci/variant_tree/test_main.py b/tests/unit/python/cli/meta/ci/variant_tree/test_main.py new file mode 100644 index 0000000000..da625b5722 --- /dev/null +++ b/tests/unit/python/cli/meta/ci/variant_tree/test_main.py @@ -0,0 +1,81 @@ +from __future__ import annotations + +import io +import json +import unittest +from contextlib import redirect_stderr, redirect_stdout +from unittest import mock + +from cli.meta.ci.variant_tree import __main__ as cli +from cli.meta.ci.variant_tree import tree + +FOUR = {"web-app-a": [{}, {}, {}, {}]} +BUILT = { + "primary": "web-app-a#1", + "round_index": 1, + "include_count": 1, + "error": None, + "nodes": [ + { + "role": "web-app-a", + "variant": 1, + "variants": 4, + "reason": "primary", + "services": [], + "children": [], + } + ], +} +AXES = {"0": {"entries": [], "job_position": 3, "in_budget_head": True, "covered": "0"}} + + +class TestMain(unittest.TestCase): + def _run( + self, *argv: str, built: dict | None = None + ) -> tuple[int, str, str, mock.Mock]: + out, err = io.StringIO(), io.StringIO() + with ( + mock.patch("utils.cache.applications.get_variants", return_value=FOUR), + mock.patch.object(tree, "build", wraps=tree.build) as build, + mock.patch( + "cli.meta.ci.variant_split.snapshot.row_axes", return_value=AXES + ) as axes, + redirect_stdout(out), + redirect_stderr(err), + ): + if built is not None: + build.side_effect = None + build.return_value = built + rc = cli.main(list(argv)) + return rc, out.getvalue(), err.getvalue(), axes + + def test_negative_control_a_variant_past_the_last_fails_naming_the_range( + self, + ) -> None: + rc, out, err, _ = self._run("web-app-a#9") + self.assertEqual((rc, out), (2, "")) + self.assertIn("must be 0..3", err) + + def test_the_json_form_carries_the_axes_of_each_sweep(self) -> None: + rc, out, _, _ = self._run("web-app-a#1", "--json", built=dict(BUILT)) + self.assertEqual((rc, json.loads(out)["axes"]), (0, AXES)) + + def test_an_empty_sweep_list_skips_the_axes(self) -> None: + _, _, _, axes = self._run("web-app-a#1", "--sweeps", "", built=dict(BUILT)) + axes.assert_not_called() + + def test_the_text_form_leads_with_the_row(self) -> None: + rc, out, _, _ = self._run("web-app-a#1", built=dict(BUILT)) + self.assertEqual(rc, 0) + self.assertTrue(out.startswith("web-app-a#1: include 1")) + + def test_negative_control_a_pin_error_exits_1(self) -> None: + failed = {**BUILT, "error": "pins cycle", "nodes": []} + rc, out, _, axes = self._run("web-app-a#1", built=failed) + self.assertEqual(rc, 1) + self.assertIn("error: pins cycle", out) + axes.assert_not_called() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/meta/ci/variant_tree/test_tree.py b/tests/unit/python/cli/meta/ci/variant_tree/test_tree.py new file mode 100644 index 0000000000..92a0a44536 --- /dev/null +++ b/tests/unit/python/cli/meta/ci/variant_tree/test_tree.py @@ -0,0 +1,117 @@ +from __future__ import annotations + +import unittest + +from cli.meta.ci.variant_tree import tree + +PINNED = {"b": "a#0"} +GATE = "{{ 'x' in group_names }}" +TREE = { + "primary": "a#0", + "round_index": 0, + "include_count": 2, + "error": None, + "nodes": [ + { + "role": "b", + "variant": 1, + "variants": 2, + "reason": "pin by a#0", + "services": [], + "children": [], + }, + { + "role": "a", + "variant": 0, + "variants": 1, + "reason": "primary", + "services": [ + {"key": "k", "provider": "b", "state": "required", "deployed": True} + ], + "children": ["b"], + }, + ], +} + + +def _reason(role: str, index: int, count: int) -> str: + return tree.reason(role, primary="a", index=index, count=count, pinned=PINNED) + + +class TestReason(unittest.TestCase): + def test_the_primary_is_named_first(self) -> None: + self.assertEqual(_reason("a", 0, 3), "primary") + + def test_a_pin_in_force_names_its_carrier(self) -> None: + self.assertEqual(_reason("b", 0, 3), "pin by a#0") + + def test_a_role_with_that_many_variants_follows_the_round_index(self) -> None: + self.assertEqual(_reason("c", 2, 3), "round index") + + def test_a_round_past_the_roles_variants_falls_back_to_0(self) -> None: + self.assertEqual(_reason("c", 5, 3), "default 0: round past its variants") + + def test_a_single_variant_role_past_round_0_falls_back_to_0(self) -> None: + self.assertEqual(_reason("d", 1, 1), "default 0: round past its variants") + + +class TestState(unittest.TestCase): + def test_a_literal_false_is_off(self) -> None: + self.assertEqual(tree.state({"enabled": False}, None), "off") + + def test_a_key_true_in_both_maps_is_required(self) -> None: + self.assertEqual(tree.state({"enabled": True}, {"enabled": True}), "required") + + def test_a_key_true_only_in_the_round_is_forced_by_override(self) -> None: + self.assertEqual( + tree.state({"enabled": True}, {"enabled": GATE}), "forced by override" + ) + + def test_a_group_names_gate_is_presence_gated(self) -> None: + self.assertEqual(tree.state({"enabled": GATE}, None), "presence-gated") + + def test_a_key_without_enabled_is_implicit(self) -> None: + self.assertEqual(tree.state({"shared": True}, None), "implicit") + + +class TestRender(unittest.TestCase): + def test_the_header_names_the_closure_size(self) -> None: + lines = tree.render_text(TREE).splitlines() + self.assertEqual(lines[0], "a#0: include 2 (resolve_round), round index 0") + + def test_the_primary_leads_and_its_providers_nest_below(self) -> None: + lines = tree.render_text(TREE).splitlines() + self.assertEqual( + (lines[1], lines[3]), ("a#0/1 [primary]", " b#1/2 [pin by a#0]") + ) + + def test_an_error_replaces_the_tree(self) -> None: + text = tree.render_text({**TREE, "error": "pins cycle", "nodes": []}) + self.assertIn("error: pins cycle", text) + + +class TestToken(unittest.TestCase): + def test_a_bare_role_is_variant_0(self) -> None: + self.assertEqual(tree.parse_token("web-app-a"), ("web-app-a", 0)) + + def test_a_token_keeps_its_variant(self) -> None: + self.assertEqual(tree.parse_token("web-app-a#7"), ("web-app-a", 7)) + + +FOUR = {"web-app-a": [{}, {}, {}, {}]} + + +class TestBuildRange(unittest.TestCase): + def test_negative_control_a_variant_past_the_last_names_the_valid_range( + self, + ) -> None: + with self.assertRaisesRegex(ValueError, r"4 variant\(s\).*must be 0\.\.3"): + tree.build("web-app-a#9", roles_dir="/roles", variants_per_app=FOUR) + + def test_negative_control_an_unknown_role_is_refused(self) -> None: + with self.assertRaisesRegex(ValueError, "no role 'web-app-z'"): + tree.build("web-app-z#0", roles_dir="/roles", variants_per_app=FOUR) + + +if __name__ == "__main__": + unittest.main()