diff --git a/.github/workflows/entry-manual-steer.yml b/.github/workflows/entry-manual-steer.yml index 914c84840a..d57f7bce72 100644 --- a/.github/workflows/entry-manual-steer.yml +++ b/.github/workflows/entry-manual-steer.yml @@ -14,12 +14,12 @@ on: default: "" type: string priority: - description: "⭐ Roles to deploy first, in every combination they can take (each variant × each offered mode × Tor and clearnet). They get chunks of their own; the regular rows wait until those are green." + description: "⭐ Roles to deploy first, in every combination left open (each variant × each offered mode × Tor and clearnet). Pin axes to narrow it: 'web-app-x#0,2@swarm+tor', or paste a job label back ('🚀🧅网络应用·Nextcloud#2'). They get chunks of their own; the regular rows wait until those are green." required: false default: "" type: string whitelist: - description: "🎯 Roles to deploy. Empty: diff vs origin/main. '__ALL__': every role." + description: "🎯 Roles to deploy, in their normal matrix position. Same token syntax as ⭐, but what a token leaves open stays on the sweep rotation instead of being covered in full. Empty: diff vs origin/main. '__ALL__': every role." required: false default: "" type: string diff --git a/cli/meta/ci/matrix.py b/cli/meta/ci/matrix.py index 8f6a27328b..74ce1414cf 100644 --- a/cli/meta/ci/matrix.py +++ b/cli/meta/ci/matrix.py @@ -11,7 +11,9 @@ the run's shape is decided: is queried on its own whitelist so priority roles run even when the diff-derived whitelist would not have selected them, and the regular line is queried on the effective whitelist with the priority roles blacklisted. - Concatenated, they are the sweep's ordered candidate list. + Concatenated, they are the sweep's ordered candidate list. Both lists are + selection tokens (:mod:`utils.github.variant.selection`): what a token pins + narrows the row, what it leaves open the line decides as it always did. 2. Every row is assigned its deploy mode and tor state by its position in that list (:mod:`utils.github.variant.axes`). 3. The list is cut into serial chunks with a hard boundary at the @@ -32,7 +34,7 @@ import sys from cli.meta.ci import chunks, query, slots from utils.cache.applications import get_variants -from utils.github.variant import axes +from utils.github.variant import axes, selection from utils.roles.display import display_names @@ -46,18 +48,29 @@ def candidates( """The sweep's ordered candidate rows: priority line first, then the regular line, each annotated with the modes it offers and whether it is priority.""" + leading = selection.parse_list(priority) + keep = selection.parse_list(whitelist) rows: list[dict] = [] - if priority.strip(): + if leading: rows += [ {**row, "priority": True} - for row in query.discover_rows( - modes, whitelist=priority, lifecycles=lifecycles + for row in selection.apply( + query.discover_rows( + modes, whitelist=selection.names(leading), lifecycles=lifecycles + ), + leading, ) ] rows += [ {**row, "priority": False} - for row in query.discover_rows( - modes, whitelist=whitelist, blacklist=priority, lifecycles=lifecycles + for row in selection.apply( + query.discover_rows( + modes, + whitelist=selection.names(keep), + blacklist=selection.names(leading), + lifecycles=lifecycles, + ), + keep, ) ] return [{**row, "modes": query.row_modes(row, modes)} for row in rows] @@ -87,15 +100,22 @@ def entries_of( def chunks_of(entries: list[dict[str, str]], sweep: int) -> list[list[dict[str, str]]]: - """Cut the sweep's entries into its chunks, priority blocks first.""" - return chunks.plan( - [entry for entry in entries if entry["priority"] == "true"], - [entry for entry in entries if entry["priority"] != "true"], - sweep=sweep, - size=slots.chunk_size(), - blocks=slots.chunk_count(), - budget=slots.available(), - ) + """Cut the sweep's entries into its chunks, priority blocks first. + + Which rows a chunk holds follows the discovery ranking; the order *inside* + a chunk is then sorted (:func:`utils.github.variant.axes.sort_key`), so the + job list of a chunk reads by role rather than by the sweep's rotation.""" + return [ + sorted(chunk, key=axes.sort_key) + for chunk in chunks.plan( + [entry for entry in entries if entry["priority"] == "true"], + [entry for entry in entries if entry["priority"] != "true"], + sweep=sweep, + size=slots.chunk_size(), + blocks=slots.chunk_count(), + budget=slots.available(), + ) + ] def build_sweep( diff --git a/scripts/github/resolve/effective_whitelist.sh b/scripts/github/resolve/effective_whitelist.sh index 200382092b..ec3250e037 100755 --- a/scripts/github/resolve/effective_whitelist.sh +++ b/scripts/github/resolve/effective_whitelist.sh @@ -5,7 +5,12 @@ # # Inputs via env: # INPUT_WHITELIST caller-provided whitelist (space-separated), as role ids -# or as the display names utils.roles.display renders. +# or as the display names utils.roles.display renders. A +# token may pin deploy axes onto the role +# (`#variant`, `@mode`, `+tor`, see +# utils.github.variant.selection); the pins are passed +# through untouched, and only the name in front of them is +# the directory this checks for. # Three cases, in this order of precedence: # * "__ALL__" (sentinel, case-insensitive): force # full deploy across the workflow's scope. Skips @@ -45,7 +50,7 @@ if [[ -n "${input_trimmed}" ]]; then input="$("${PYTHON}" -m utils.roles.display "${input}")" unknown=() for role in ${input}; do - [[ -d "roles/${role}" ]] || unknown+=("${role}") + [[ -d "roles/${role%%[#@+]*}" ]] || unknown+=("${role}") done if ((${#unknown[@]})); then echo "[ERROR] Unknown role id(s) in the caller-supplied whitelist: ${unknown[*]}" >&2 diff --git a/tests/unit/cli/meta/ci/test_matrix.py b/tests/unit/cli/meta/ci/test_matrix.py new file mode 100644 index 0000000000..d687b99031 --- /dev/null +++ b/tests/unit/cli/meta/ci/test_matrix.py @@ -0,0 +1,62 @@ +from __future__ import annotations + +import unittest +import unittest.mock as mock + +from cli.meta.ci import matrix + + +def _entry(app: str, variant: str, mode: str, *, priority: bool = False) -> dict: + return { + "apps": app, + "variant": variant, + "mode": mode, + "tor": "false", + "priority": "true" if priority else "false", + } + + +class TestChunksOf(unittest.TestCase): + def _chunks(self, entries: list[dict], *, size: int) -> list[list[dict]]: + with ( + mock.patch.object(matrix.slots, "chunk_size", return_value=size), + mock.patch.object(matrix.slots, "chunk_count", return_value=4), + mock.patch.object(matrix.slots, "available", return_value=99), + ): + return matrix.chunks_of(entries, 0) + + def test_a_chunk_is_sorted_by_name_then_variant(self) -> None: + entries = [ + _entry("web-app-b", "1", "compose"), + _entry("web-app-a", "1", "compose"), + _entry("web-app-a", "0", "compose"), + ] + chunk = self._chunks(entries, size=9)[0] + self.assertEqual( + [(e["apps"], e["variant"]) for e in chunk], + [("web-app-a", "0"), ("web-app-a", "1"), ("web-app-b", "1")], + ) + + def test_the_split_still_follows_the_discovery_ranking(self) -> None: + entries = [ + _entry("web-app-z", "0", "compose"), + _entry("web-app-a", "0", "compose"), + ] + chunks = self._chunks(entries, size=1) + self.assertEqual( + [chunk[0]["apps"] for chunk in chunks], ["web-app-z", "web-app-a"] + ) + + def test_priority_chunks_are_sorted_on_their_own(self) -> None: + entries = [ + _entry("web-app-z", "0", "compose", priority=True), + _entry("web-app-a", "0", "compose", priority=True), + _entry("web-app-b", "0", "compose"), + ] + chunks = self._chunks(entries, size=9) + self.assertEqual([e["apps"] for e in chunks[0]], ["web-app-a", "web-app-z"]) + self.assertEqual([e["apps"] for e in chunks[1]], ["web-app-b"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/utils/github/variant/test_axes.py b/tests/unit/utils/github/variant/test_axes.py index 26df6aaf70..71e70248f5 100644 --- a/tests/unit/utils/github/variant/test_axes.py +++ b/tests/unit/utils/github/variant/test_axes.py @@ -328,6 +328,115 @@ class TestAssign(unittest.TestCase): self.assertNotIn("false", [e["tor"] for e in entries]) +class TestPinnedAxes(unittest.TestCase): + def _entries(self, row: dict) -> list[dict[str, str]]: + return axes.assign([row], sweep=0, tor_mode="auto", variants_per_app=_VARIANTS) + + def test_a_pinned_mode_replaces_the_rotation(self) -> None: + row = _row("web-app-b", 0, ("compose", "swarm"), pin_mode="swarm") + self.assertEqual([e["mode"] for e in self._entries(row)], ["swarm"]) + + def test_a_pinned_onion_state_replaces_the_rotation(self) -> None: + row = _row("web-app-b", 0, ("compose",), pin_tor=True) + self.assertEqual([e["tor"] for e in self._entries(row)], ["true"]) + + def test_an_open_axis_still_rotates(self) -> None: + row = _row("web-app-b", 0, ("compose", "swarm"), pin_tor=False) + picks = { + axes.assign( + [row], sweep=sweep, tor_mode="auto", variants_per_app=_VARIANTS + )[0]["mode"] + for sweep in range(2) + } + self.assertEqual(picks, {"compose", "swarm"}) + + def test_pinning_the_onion_keeps_the_rotation_off_host(self) -> None: + row = _row("web-app-b", 0, ("compose", "host"), pin_tor=True) + for sweep in range(4): + with self.subTest(sweep=sweep): + entries = axes.assign( + [row], sweep=sweep, tor_mode="auto", variants_per_app=_VARIANTS + ) + self.assertEqual([e["mode"] for e in entries], ["compose"]) + + def test_a_pin_narrows_the_priority_cross_product(self) -> None: + row = _row( + "web-app-b", 0, ("compose", "swarm"), priority=True, pin_mode="compose" + ) + entries = self._entries(row) + self.assertEqual( + {(e["mode"], e["tor"]) for e in entries}, + {("compose", "true"), ("compose", "false")}, + ) + + def test_a_fully_pinned_priority_row_runs_exactly_once(self) -> None: + row = _row( + "web-app-b", + 0, + ("compose", "swarm"), + priority=True, + pin_mode="swarm", + pin_tor=False, + ) + self.assertEqual(len(self._entries(row)), 1) + + def test_an_unoffered_mode_aborts_the_matrix(self) -> None: + row = _row("web-app-b", 0, ("compose",), pin_mode="swarm") + with self.assertRaises(SystemExit): + self._entries(row) + + def test_an_impossible_onion_state_aborts_the_matrix(self) -> None: + row = _row("web-app-a", 1, ("compose",), pin_tor=True) + with self.assertRaises(SystemExit): + self._entries(row) + + def test_a_pin_fighting_the_runs_tor_axis_aborts(self) -> None: + row = _row("web-app-b", 0, ("compose",), pin_tor=True) + with self.assertRaises(SystemExit): + axes.assign([row], sweep=0, tor_mode="disabled", variants_per_app=_VARIANTS) + + +class TestSortKey(unittest.TestCase): + def _entries(self) -> list[dict[str, str]]: + rows = [ + _row("web-app-b", 0, ("swarm",)), + _row("web-app-a", 1, ("compose",)), + _row("web-app-a", 0, ("compose",)), + ] + return axes.assign(rows, sweep=0, tor_mode="auto", variants_per_app=_VARIANTS) + + def test_rows_sort_by_name_then_variant(self) -> None: + ordered = sorted(self._entries(), key=axes.sort_key) + self.assertEqual( + [(e["apps"], e["variant"]) for e in ordered], + [("web-app-a", "0"), ("web-app-a", "1"), ("web-app-b", "0")], + ) + + def test_the_mode_sorts_in_deploy_order_not_alphabetically(self) -> None: + entries = [ + {"apps": "web-app-a", "variant": "0", "mode": mode, "tor": "false"} + for mode in ("host", "swarm", "compose") + ] + ordered = sorted(entries, key=axes.sort_key) + self.assertEqual([e["mode"] for e in ordered], list(axes.MODES)) + + def test_clearnet_sorts_ahead_of_the_onion(self) -> None: + entries = [ + {"apps": "web-app-a", "variant": "0", "mode": "compose", "tor": tor} + for tor in ("true", "false") + ] + ordered = sorted(entries, key=axes.sort_key) + self.assertEqual([e["tor"] for e in ordered], ["false", "true"]) + + def test_a_variantless_row_sorts_ahead_of_variant_zero(self) -> None: + entries = [ + {"apps": "web-app-a", "variant": "0", "mode": "compose", "tor": "false"}, + {"apps": "web-app-a", "variant": "", "mode": "compose", "tor": "false"}, + ] + ordered = sorted(entries, key=axes.sort_key) + self.assertEqual([e["variant"] for e in ordered], ["", "0"]) + + class TestParseLabel(unittest.TestCase): def _title(self, mode: str, app: str, variant: str, **kw) -> str: rows = [_row(app, int(variant), (mode,), **kw)] diff --git a/tests/unit/utils/github/variant/test_selection.py b/tests/unit/utils/github/variant/test_selection.py new file mode 100644 index 0000000000..4124b27582 --- /dev/null +++ b/tests/unit/utils/github/variant/test_selection.py @@ -0,0 +1,121 @@ +from __future__ import annotations + +import unittest + +from utils.github.variant import selection +from utils.symbol_glossary import to_emoji + + +def _row(name: str, variant: int) -> dict: + return {"name": name, "variant": variant} + + +class TestParseAscii(unittest.TestCase): + def test_a_bare_role_pins_nothing(self) -> None: + pin = selection.parse("web-app-a") + self.assertEqual(pin, selection.Pin("web-app-a")) + self.assertFalse(pin.pinned) + + def test_every_axis_is_read(self) -> None: + self.assertEqual( + selection.parse("web-app-a#0,2@swarm+tor"), + selection.Pin("web-app-a", (0, 2), "swarm", True), + ) + + def test_clearnet_is_the_other_onion_state(self) -> None: + self.assertFalse(selection.parse("web-app-a@compose+clearnet").tor) + + def test_a_role_id_ending_in_tor_is_not_read_as_an_axis(self) -> None: + self.assertEqual(selection.parse("svc-net-tor"), selection.Pin("svc-net-tor")) + + def test_an_unknown_mode_aborts(self) -> None: + with self.assertRaises(SystemExit): + selection.parse("web-app-a@swrm") + + def test_an_unknown_onion_state_aborts(self) -> None: + with self.assertRaises(SystemExit): + selection.parse("web-app-a+onion") + + def test_an_unparsable_token_aborts(self) -> None: + with self.assertRaises(SystemExit): + selection.parse("web-app-a#zwei") + + +class TestParseLabel(unittest.TestCase): + def _label(self, mode: str, tor: str) -> str: + return f"{to_emoji(mode)}{to_emoji(tor)}web-app-a#2" + + def test_the_glyphs_carry_mode_and_onion(self) -> None: + self.assertEqual( + selection.parse(self._label("swarm", "tor")), + selection.Pin("web-app-a", (2,), "swarm", True), + ) + + def test_the_clearnet_glyph_pins_the_clearnet_state(self) -> None: + self.assertFalse(selection.parse(self._label("compose", "clearnet")).tor) + + def test_the_priority_star_is_not_part_of_the_name(self) -> None: + pasted = f"{self._label('compose', 'tor')} {to_emoji('priority')}" + self.assertEqual(selection.parse(pasted).app, "web-app-a") + + def test_a_host_label_pins_the_mode_only(self) -> None: + pasted = f"{to_emoji('host')}{to_emoji('test_host')}web-app-a" + self.assertEqual( + selection.parse(pasted), selection.Pin("web-app-a", (), "host") + ) + + def test_the_two_spellings_may_not_contradict_each_other(self) -> None: + with self.assertRaises(SystemExit): + selection.parse(f"{to_emoji('swarm')}web-app-a@compose") + + +class TestNames(unittest.TestCase): + def test_the_query_filters_on_role_ids_only(self) -> None: + pins = selection.parse_list("web-app-a#0@swarm web-app-b+tor") + self.assertEqual(selection.names(pins), "web-app-a web-app-b") + + def test_a_role_pinned_twice_is_named_once(self) -> None: + pins = selection.parse_list("web-app-a#0 web-app-a#1") + self.assertEqual(selection.names(pins), "web-app-a") + + +_ROWS = [_row("web-app-a", 0), _row("web-app-a", 1), _row("web-app-b", 0)] + + +class TestApply(unittest.TestCase): + def test_no_selection_keeps_every_row_untouched(self) -> None: + self.assertEqual(selection.apply(_ROWS, []), _ROWS) + + def test_a_pinned_variant_drops_the_other_variants(self) -> None: + kept = selection.apply(_ROWS, selection.parse_list("web-app-a#1")) + self.assertEqual([row["variant"] for row in kept], [1]) + + def test_the_pinned_axes_ride_along_on_the_row(self) -> None: + kept = selection.apply(_ROWS, selection.parse_list("web-app-a#0@swarm+tor")) + self.assertEqual(kept[0]["pin_mode"], "swarm") + self.assertTrue(kept[0]["pin_tor"]) + + def test_an_unpinned_row_carries_open_axes(self) -> None: + kept = selection.apply(_ROWS, selection.parse_list("web-app-b")) + self.assertEqual([kept[0]["pin_mode"], kept[0]["pin_tor"]], [None, None]) + + def test_two_pins_on_one_role_keep_their_own_axes(self) -> None: + kept = selection.apply( + _ROWS, selection.parse_list("web-app-a#0@swarm web-app-a#1@compose") + ) + self.assertEqual([row["pin_mode"] for row in kept], ["swarm", "compose"]) + + def test_the_query_order_survives_the_selection(self) -> None: + kept = selection.apply(_ROWS, selection.parse_list("web-app-b web-app-a")) + self.assertEqual([row["name"] for row in kept], [row["name"] for row in _ROWS]) + + def test_a_pin_that_matches_nothing_aborts_instead_of_running_empty(self) -> None: + with self.assertRaises(SystemExit): + selection.apply(_ROWS, selection.parse_list("web-app-b#7")) + + def test_a_bare_role_that_matches_nothing_is_tolerated(self) -> None: + self.assertEqual(selection.apply(_ROWS, selection.parse_list("web-app-c")), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/utils/roles/test_display.py b/tests/unit/utils/roles/test_display.py index f99c541714..048f11758d 100644 --- a/tests/unit/utils/roles/test_display.py +++ b/tests/unit/utils/roles/test_display.py @@ -1,6 +1,6 @@ import unittest -from utils.roles.display import display_names +from utils.roles.display import display_names, split_axes APP = "web-app-nextcloud" @@ -57,6 +57,14 @@ class TestRoleDisplayName(unittest.TestCase): ids = f"{APP} svc-db-postgres __ALL__" self.assertEqual(ids, self.codec.decode_list(self.codec.encode_list(ids))) + def test_an_axis_suffix_survives_the_decode(self): + encoded = f"{self.codec.encode(APP)}#0,2@swarm+tor" + self.assertEqual(f"{APP}#0,2@swarm+tor", self.codec.decode_list(encoded)) + + def test_a_role_id_holds_no_axis_seam(self): + self.assertEqual((APP, ""), split_axes(APP)) + self.assertEqual((APP, "@host"), split_axes(f"{APP}@host")) + def test_every_role_encodes_to_one_unique_space_free_token(self): seen: dict[str, str] = {} collisions = [] diff --git a/utils/github/variant/axes.py b/utils/github/variant/axes.py index d23ba57287..7a9dc6d3e9 100644 --- a/utils/github/variant/axes.py +++ b/utils/github/variant/axes.py @@ -265,6 +265,71 @@ def combinations( ] +def _reject(app: str, variant: str, reason: str) -> None: + """Abort on a selection the row cannot satisfy. + + Raises: + SystemExit: always. A pin the row cannot take is an operator mistake, + and dropping the row instead would report a green run for a + combination that never ran. + """ + shard = f"{VARIANT_SEPARATOR}{variant}" if variant else "" + raise SystemExit(f"selection {app}{shard}: {reason}") + + +def check_pins( + app: str, + variant: str, + offered: Sequence[str], + *, + pin_mode: str | None, + pin_tor: bool | None, + capable: bool, + tor_mode: str, +) -> None: + """Prove the row can take what the selection token pinned on it. + + The offered modes are already narrowed by the run's ``--modes`` input and + the onion states by its ``--tor`` input, so this catches a pin that fights + the role, the variant, or the run's own axes with one check each. + """ + if pin_mode is not None and pin_mode not in offered: + _reject( + app, + variant, + f"pinned mode {pin_mode!r} is not available here " + f"(offered: {', '.join(offered)})", + ) + if pin_tor is None: + return + for mode in (pin_mode,) if pin_mode else offered: + if pin_tor in tor_states(mode, capable=capable, tor_mode=tor_mode): + return + _reject( + app, + variant, + f"pinned onion state {'tor' if pin_tor else 'clearnet'} is impossible " + f"here (mode, variant or the run's tor axis rules it out)", + ) + + +def sort_key(entry: Mapping[str, str]) -> tuple[Any, ...]: + """Where one entry sorts inside its chunk: display name, then variant, + then deploy mode, then onion state. + + The chunk split itself is not sorted -- it follows the discovery ranking, + which is what decides who makes the budget cut. This only orders the jobs + a chunk already holds, so a chunk's job list reads like the plan table + instead of like the sweep's rotation. + """ + return ( + display_names().encode(entry["apps"]), + tuple(int(part) for part in entry["variant"].split(",") if part), + MODES.index(entry["mode"]) if entry["mode"] in MODES else len(MODES), + entry["tor"] == "true", + ) + + def assign( rows: Sequence[Mapping[str, Any]], *, @@ -277,6 +342,9 @@ def assign( Args: rows: discovery rows, each carrying ``name``, ``variant``, ``modes`` (the offered subset) and ``priority``, in global query order. + ``pin_mode``/``pin_tor``, when a selection token set them, pin that + axis: the priority line then covers only the combinations that + match, and the regular line takes the pin instead of its rotation. sweep: sweep number driving both rotations. tor_mode: ``enforced`` onions every capable row, ``disabled`` none, ``exclusive`` drops the rows that cannot take one, ``auto`` @@ -304,10 +372,32 @@ def assign( priority = bool(row.get("priority")) capable = tor_capable(app, variant, variants_per_app) offered = tuple(row["modes"]) + variant_csv = "" if variant is None else str(variant) + pin_mode = row.get("pin_mode") + pin_tor = row.get("pin_tor") + check_pins( + app, + variant_csv, + offered, + pin_mode=pin_mode, + pin_tor=pin_tor, + capable=capable, + tor_mode=tor_mode, + ) if priority: - picked = combinations(offered, capable=capable, tor_mode=tor_mode) + picked = [ + (mode, state) + for mode, state in combinations( + offered, capable=capable, tor_mode=tor_mode + ) + if pin_mode in (None, mode) and pin_tor in (None, state) + ] else: - mode = pick_mode(offered, position, sweep) + mode = pin_mode or pick_mode( + _offering(offered, pin_tor, capable=capable, tor_mode=tor_mode), + position, + sweep, + ) picked = [ (mode, state) for state in _rotated_tor( @@ -316,11 +406,11 @@ def assign( tor_mode=tor_mode, position=position, sweep=sweep, + pin=pin_tor, ) ] if app == provider: picked = [(mode, enabled) for mode, enabled in picked if enabled] - variant_csv = "" if variant is None else str(variant) label = codec.encode(app, variant_csv) for mode, enabled in picked: glyphs = to_emoji(mode) + ( @@ -345,12 +435,36 @@ def assign( return entries +def _offering( + offered: Sequence[str], pin: bool | None, *, capable: bool, tor_mode: str +) -> tuple[str, ...]: + """The modes the rotation may still draw from once an onion state is + pinned: pinning the onion on a row that also offers host must not rotate + the row onto host, where no onion exists.""" + if pin is None: + return tuple(offered) + return tuple( + mode + for mode in offered + if pin in tor_states(mode, capable=capable, tor_mode=tor_mode) + ) + + def _rotated_tor( - mode: str, *, capable: bool, tor_mode: str, position: int, sweep: int + mode: str, + *, + capable: bool, + tor_mode: str, + position: int, + sweep: int, + pin: bool | None = None, ) -> list[bool]: """The single onion state a regular row takes this sweep, or nothing when - ``exclusive`` drops it.""" + ``exclusive`` drops it. A pinned state replaces the rotation -- it was + proven possible by :func:`check_pins` before we get here.""" allowed = tor_states(mode, capable=capable, tor_mode=tor_mode) + if pin is not None: + return [pin] if len(allowed) < 2: return allowed return [capable and wants_tor(position, sweep)] diff --git a/utils/github/variant/selection.py b/utils/github/variant/selection.py new file mode 100644 index 0000000000..bad8e2b93a --- /dev/null +++ b/utils/github/variant/selection.py @@ -0,0 +1,214 @@ +"""Read the deploy axes an operator pins in ``whitelist`` and ``priority``. + +A selection token names a role and MAY narrow the axes that role's rows would +otherwise be assigned: which variants run, which deploy mode, and whether the +row goes behind the node onion. What a token leaves open stays open -- the +priority line then covers every combination of it, the whitelist line lets the +sweep rotation pick one, exactly as an unpinned run does. + +Two spellings are accepted, so an operator can either type the token or paste +back the job title of the run they want repeated: + +* the job label CI emits (``🚀🧅网络应用·Nextcloud#2``) -- the glyphs carry + mode and onion state, the ``#`` shard the variants; +* an ASCII form (``web-app-nextcloud#0,2@swarm+tor``). + +The onion state spells out as ``+tor``/``+clearnet`` rather than as a ``-tor`` +suffix: a role id may itself end in ``-tor`` (``svc-net-tor``), and a suffix +that eats the tail of a role name selects a different role in silence. + +Everything a token pins is checked against what the row can actually do +(:func:`utils.github.variant.axes.assign`) and against the run's own mode and +tor inputs. A contradiction aborts the matrix instead of quietly deploying +something else or nothing at all. +""" + +from __future__ import annotations + +import re +from typing import TYPE_CHECKING, NamedTuple + +from utils.github.variant.axes import MODES +from utils.roles.display import VARIANT_SEPARATOR, display_names +from utils.symbol_glossary import to_emoji + +if TYPE_CHECKING: + from collections.abc import Iterable, Mapping, Sequence + from typing import Any + +MODE_SEPARATOR = "@" + +TOR_SEPARATOR = "+" + +TOR_WORDS = {"tor": True, "clearnet": False} + +_STRIPPED_GLYPHS = ("priority", "test_host") + +_VARIATION = re.compile("[︎️]") + +_TOKEN = re.compile( + r"^(?P[^#@+\s]+)" + r"(?:" + re.escape(VARIANT_SEPARATOR) + r"(?P\d+(?:,\d+)*))?" + r"(?:" + re.escape(MODE_SEPARATOR) + r"(?P[a-z]+))?" + r"(?:" + re.escape(TOR_SEPARATOR) + r"(?P[a-z]+))?$" +) + +_SYNTAX = ( + f"[{VARIANT_SEPARATOR}]" + f"[{MODE_SEPARATOR}<{'|'.join(MODES)}>]" + f"[{TOR_SEPARATOR}<{'|'.join(TOR_WORDS)}>]" +) + + +class Pin(NamedTuple): + """One selection token, taken apart. + + ``variants`` empty, ``mode`` or ``tor`` ``None`` each mean "not pinned": + that axis keeps whatever the line it stands in would assign. + """ + + app: str + variants: tuple[int, ...] = () + mode: str | None = None + tor: bool | None = None + + @property + def pinned(self) -> bool: + """Whether the token narrows anything at all beyond the role name.""" + return bool(self.variants) or self.mode is not None or self.tor is not None + + +def describe(pin: Pin) -> str: + """The token as an operator would have written it, for error messages.""" + variants = ",".join(str(index) for index in pin.variants) + return ( + pin.app + + (f"{VARIANT_SEPARATOR}{variants}" if variants else "") + + (f"{MODE_SEPARATOR}{pin.mode}" if pin.mode else "") + + ( + f"{TOR_SEPARATOR}{'tor' if pin.tor else 'clearnet'}" + if pin.tor is not None + else "" + ) + ) + + +def _glyphs(text: str) -> tuple[str, str | None, bool | None]: + """Take the label glyphs off a pasted job title and read them as axes.""" + mode: str | None = None + tor: bool | None = None + for candidate in MODES: + glyph = to_emoji(candidate) + if glyph in text: + mode, text = candidate, text.replace(glyph, "") + for word, state in TOR_WORDS.items(): + glyph = to_emoji(word) + if glyph in text: + tor, text = state, text.replace(glyph, "") + for word in _STRIPPED_GLYPHS: + text = text.replace(to_emoji(word), "") + return text.strip(), mode, tor + + +def _agree(pin: Any, glyph: Any, token: str, axis: str) -> Any: + """One axis stated twice must state the same thing.""" + if pin is not None and glyph is not None and pin != glyph: + raise SystemExit( + f"selection token {token!r} pins two different {axis} values; " + f"drop one of them" + ) + return glyph if pin is None else pin + + +def parse(token: str) -> Pin: + """One selection token as a :class:`Pin`. + + Args: + token: label form or ASCII form; a bare role id or display name pins + nothing and selects every row of that role. + + Raises: + SystemExit: the token is unparsable, or names a mode or onion state + that does not exist. A typo must abort the run rather than narrow + it to nothing. + """ + text, glyph_mode, glyph_tor = _glyphs(_VARIATION.sub("", token.strip())) + match = _TOKEN.match(text) + if match is None: + raise SystemExit(f"unparsable selection token {token!r}; expected {_SYNTAX}") + + mode = match.group("mode") + if mode is not None and mode not in MODES: + raise SystemExit( + f"selection token {token!r} names unknown deploy mode {mode!r}; " + f"expected {', '.join(MODES)}" + ) + word = match.group("tor") + if word is not None and word not in TOR_WORDS: + raise SystemExit( + f"selection token {token!r} names unknown onion state {word!r}; " + f"expected {', '.join(TOR_WORDS)}" + ) + + name = match.group("name") + variants = match.group("variants") + return Pin( + display_names().decode(name) or name, + tuple(int(index) for index in variants.split(",")) if variants else (), + _agree(mode, glyph_mode, token, "mode"), + _agree(TOR_WORDS[word] if word else None, glyph_tor, token, "onion"), + ) + + +def parse_list(tokens: str) -> list[Pin]: + """Every token of a space-separated ``whitelist``/``priority`` input.""" + return [parse(token) for token in tokens.split()] + + +def names(pins: Iterable[Pin]) -> str: + """The role ids the pins select, deduplicated, in the order given -- what + the discovery query filters on. The axes are applied afterwards, on the + rows the query returned.""" + return " ".join(dict.fromkeys(pin.app for pin in pins)) + + +def apply( + rows: Sequence[Mapping[str, Any]], pins: Sequence[Pin] +) -> list[dict[str, Any]]: + """Keep the rows the pins select and stamp the pinned axes onto them. + + Args: + rows: discovery rows of one line, in query order. + pins: that line's selection tokens; empty means "no selection", and + every row passes through untouched. + + Returns: + the surviving rows, each carrying ``pin_mode`` and ``pin_tor`` for + :func:`utils.github.variant.axes.assign` to honour. Row order is the + query's -- a selection narrows what runs, it never re-ranks it. + + Raises: + SystemExit: a token that pins something matched no row at all. Silently + deploying nothing is how a mistyped variant index turns into a + green run that tested nothing. + """ + if not pins: + return [dict(row) for row in rows] + kept: list[dict[str, Any]] = [] + matched: set[int] = set() + for row in rows: + for index, pin in enumerate(pins): + if pin.app != row["name"]: + continue + if pin.variants and row.get("variant") not in pin.variants: + continue + matched.add(index) + kept.append({**row, "pin_mode": pin.mode, "pin_tor": pin.tor}) + break + for index, pin in enumerate(pins): + if index not in matched and pin.pinned: + raise SystemExit( + f"selection {describe(pin)!r} matches no discovered row; " + f"check the variant index and the run's lifecycle/mode filters" + ) + return kept diff --git a/utils/roles/display.py b/utils/roles/display.py index f8326b5cd9..4d4510102c 100644 --- a/utils/roles/display.py +++ b/utils/roles/display.py @@ -40,6 +40,20 @@ _HEADING = re.compile(r"^#\s+(.+?)\s*$", re.MULTILINE) _VARIANT_SUFFIX = re.compile(re.escape(VARIANT_SEPARATOR) + r"[\d,]+$") _ROLE_ID = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)+") _VARIATION = re.compile("[︎️]") +_AXIS_START = re.compile(r"[#@+]") + + +def split_axes(token: str) -> tuple[str, str]: + """Split a CI selection token into its name and its axis suffix. + + ``#``, ``@`` and ``+`` introduce an axis and appear in neither a role id + nor a display name, so the first of them is the seam. + + Args: + token: e.g. ``'web-app-nextcloud#0,2@swarm+tor'``. + """ + match = _AXIS_START.search(token) + return (token[: match.start()], token[match.start() :]) if match else (token, "") class RoleDisplayName: @@ -168,11 +182,19 @@ class RoleDisplayName: def decode_list(self, names: str) -> str: """Space-separated display names rendered as space-separated role ids. + The axis suffix a CI selection token may carry (``#0,2@swarm+tor``) is + split off before the lookup and re-attached after it, so translating a + list never drops what the operator pinned on it. + Args: names: space-separated display names or role ids; anything that names no role passes through untouched. """ - return " ".join(self.decode(token) or token for token in names.split()) + decoded = [] + for token in names.split(): + name, axes = split_axes(token) + decoded.append((self.decode(name) or name) + axes) + return " ".join(decoded) @lru_cache(maxsize=1)