fix(ci): cut a row only when its coverer really deploys it

The complexity plan cut a role#0 row as covered whenever a greener row
pulled the role as a service, even when that coverer's round never
deployed the role at variant 0: peertube#0 was cut by openproject#3,
which never deploys it, and 36 such rows ran in no job at all.

A cut row now needs a coverer whose round deploys the role at variant 0
in every mode and network state the row can take (the row's modes and
networks must be subsets of the coverer's). reach.py, split out of
cli.py, walks the deploy CLI's own path for that answer
(find_provider_roles, the round's service overrides, the orphan prune,
and the swarm include derivation). Today's discovery cuts 61 rows
instead of 70; semaphore#0, n8n#0 and jenkins#0 deploy again. An
integration guard checks every cut row against its coverer per mode and
network, with a constructed loss from real rows as its negative control.

discover_rows captures only stdout, so a planner error reaches the
caller's stderr by name. call-test-deploy.yml warns on a direct
dispatch that passes disable, which the plan did not account for when
it cut rows; the echoed value is stripped of ':', '%', CR and LF, and a
lint pins the step.

Cost: discovery CPU rises from about 1.9 s to about 6 s per run.

🎯 Fix: 92 %
💥 Break: 4 %
💸 Cost: 100 %
⏱️ Time: 100 %
🛡️ Security: 100 %
🏆 Score: 88
🚦 Gate: ✅ 90/5, cost and time <= 100, security 100 %

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
kevinveenbirkenbachandClaude Opus 5.5 committed 2026-11-06 10:19:38 +00:00
1 parent b06c526c8c
commit 36deb3e6f4
9 files changed
+802 -21

No files matched your search

+9
View File
@@ -261,6 +261,15 @@ jobs:
--offset "${PLAN_OFFSET}" \
>> "$GITHUB_STEP_SUMMARY"
- name: ⚠️ Warn that the passed disable can orphan a covered row
if: ${{ inputs.disable != '' }}
shell: bash
env:
PASSED_DISABLE: ${{ inputs.disable }}
run: |
passed="$(printf '%s' "${PASSED_DISABLE}" | tr -d ':%\r\n')"
echo "::warning title=disable can orphan covered rows::disable=${passed} is added to every row, but the plan cut its covered rows without it; a covered row whose coverer's deploy this disable prunes runs in no job of this run."
deploy:
name: "${{ matrix.label }}"
if: needs.discover.outputs.apps != '' && needs.discover.outputs.apps != '[]'
+6 -2
View File
@@ -124,7 +124,11 @@ def discover_rows(
lifecycles: str = "",
) -> list[dict]:
"""The ordered candidate rows, each the complexity payload of one
``role#variant``. Uncapped: the chunker decides what a sweep spends."""
``role#variant``. Uncapped: the chunker decides what a sweep spends.
Only stdout is captured: a planner error in the subprocess (an unsettled
variant pin, a provider-override conflict) reaches the caller's stderr by
name instead of collapsing into ``exit status 1``."""
out = subprocess.run(
_query_argv(
modes,
@@ -134,7 +138,7 @@ def discover_rows(
fmt=["--format", "json"],
),
cwd=PROJECT_ROOT,
capture_output=True,
stdout=subprocess.PIPE,
text=True,
check=True,
).stdout
+36 -10
View File
@@ -14,6 +14,8 @@ from utils.roles.applications.topics import overridden_providers
if TYPE_CHECKING:
from collections.abc import Mapping
from .reach import Rounds
from .filter import FilterError, compile_predicate
from .model import (
TESTED_LIFECYCLES,
@@ -22,6 +24,7 @@ from .model import (
compute_complexity_rows,
compute_variant_complexity_rows,
)
from .reach import rounds
from .render import render_json, render_string, render_table, render_yaml
_SORT_KEYS = {
@@ -281,6 +284,8 @@ def _mark_covered(
rows: list[ComplexityRow],
overridden: Mapping[tuple[str, int], set[str]] | None = None,
variant_counts: Mapping[str, int] | None = None,
*,
planner: Rounds,
) -> list[ComplexityRow]:
"""Assign each sorted row its numeric ``id`` (its position in sort order)
and its ``covered_by`` via a greedy set-cover: the first row is green, and
@@ -288,10 +293,21 @@ def _mark_covered(
already-green predecessor OF A DIFFERENT ROLE that actually embeds this row
(its role name is in the predecessor's transitive ``services``); a row with
no such predecessor becomes green itself, leaving ``covered_by`` at the
sentinel ``0`` (no real ``id`` is 0). Because ``services`` is the
transitive closure, embedding the row pulls its whole subtree, so the
coverer's deploy genuinely brings this row up. Two variants of the same
role never cover each other (a role never embeds itself).
sentinel ``0`` (no real ``id`` is 0). Two variants of the same role never
cover each other (a role never embeds itself).
``services`` alone does not prove the coverer's deploy brings the row up:
the closure walks every provider's base ``meta/services.yml``, while the
round runs each provider in a variant that may switch the edge off, and
leaves the primary-only guide and Semaphore edges off for every provider, so
a coverer can name a role its round never deploys. ``planner`` is the deploy
planner's answer, and a coverer must run the row's role in variant 0 there
too, in every network mode the sweep may rotate the coverer to: the deploy
and network axes are assigned after this cut, and a network's ``disable``
drops the Tor provider from a clearnet node and a clearnet-only partner from
a Tor node. A coverer must also offer every deploy mode and network mode the
row offers, or the sweep never deploys the row in the ones it lacks; such a
row stays green.
Coverage is variant-aware: only a row's variant-0 (or whole-role) form can
be covered, because a coverer only ever brings a provider up at variant 0.
@@ -314,6 +330,7 @@ def _mark_covered(
no variant dictates anything.
variant_counts: ``{role: how many variants it declares}``. A role
missing from it counts as one, which is the whole-role case.
planner: the deploy planner's :class:`~.reach.Rounds` (:func:`rounds`).
"""
demands = overridden or {}
counts = variant_counts or {}
@@ -322,7 +339,14 @@ def _mark_covered(
index = coverer_variant or 0
return index == 0 or index >= counts.get(provider, 1)
green: list[tuple[int, str, int | None, set[str]]] = []
def deploys_at_zero(coverer: ComplexityRow, row: ComplexityRow) -> bool:
return (
planner.modes(row) <= planner.modes(coverer)
and planner.networks(row) <= planner.networks(coverer)
and planner.runs(coverer).get(row.name) == 0
)
green: list[tuple[int, ComplexityRow, set[str]]] = []
out: list[ComplexityRow] = []
for index, row in enumerate(rows, start=1):
coverable = row.variant in (None, 0)
@@ -330,11 +354,12 @@ def _mark_covered(
next(
(
gid
for gid, gname, gvariant, gset in green
if gname != row.name
for gid, grow, gset in green
if grow.name != row.name
and row.name in gset
and row.name not in demands.get((gname, gvariant or 0), ())
and pulls_at_zero(gvariant, row.name)
and row.name not in demands.get((grow.name, grow.variant or 0), ())
and pulls_at_zero(grow.variant, row.name)
and deploys_at_zero(grow, row)
),
None,
)
@@ -342,7 +367,7 @@ def _mark_covered(
else None
)
if coverer is None:
green.append((index, row.name, row.variant, set(row.services)))
green.append((index, row, set(row.services)))
out.append(row._replace(id=index, covered_by=coverer or 0))
return out
@@ -398,6 +423,7 @@ def main(argv: list[str] | None = None) -> int:
role: max(1, len(entries or [{}]))
for role, entries in get_variants(roles_dir=roles_dir).items()
},
planner=rounds(roles_dir),
)
_apply_sort(rows, sort_spec)
@@ -0,0 +1,150 @@
"""What a row's deploy brings up, as the deploy planner settles it."""
from __future__ import annotations
import functools
from pathlib import Path
from typing import TYPE_CHECKING, NamedTuple
from cli.administration.deploy.development.inventory.legacy_resolver import (
prune_orphans_after_disable,
)
from cli.administration.inventory.provision.services.disabler import (
find_provider_roles,
parse_services_disabled,
)
from utils.cache.applications import get_variants
from utils.github.variant import network
from utils.github.variant.pools import MODES
from utils.roles.applications.variants import resolve_round
if TYPE_CHECKING:
from collections.abc import Callable, Mapping
from utils.roles.applications.variants import ResolvedRound
from .model import ComplexityRow
class Rounds(NamedTuple):
"""The deploy planner's answers the coverage cut asks of a row, cheapest
first, so the cut can stop at the first that rules a coverer out.
Attributes:
modes: the deploy modes the row is tested in.
networks: the node network modes those deploy modes can take it to.
runs: ``{role: variant it runs in}`` for every role the row's round
deploys in each of its network modes.
"""
modes: Callable[[ComplexityRow], frozenset[str]]
networks: Callable[[ComplexityRow], frozenset[str]]
runs: Callable[[ComplexityRow], Mapping[str, int]]
@functools.cache
def _round_of(roles_dir: str, app: str, variant: int) -> ResolvedRound:
"""The round of ``app#variant``, settled as the deploy planner settles it
(``plan_dev_inventory_matrix`` resolves the same round, but every round of
the app, which a row asking for one of fourteen does not need).
Args:
roles_dir: the roles tree the round is read from.
app: the round's only primary app.
variant: the primary's variant, which is also the round index.
"""
return resolve_round(
roles_dir=roles_dir,
round_index=variant,
primary_app_variants={app: variant},
variants_per_app=get_variants(roles_dir=roles_dir, readonly=True),
)
@functools.cache
def _networks(
roles_dir: str, app: str, variant: int, modes: frozenset[str]
) -> frozenset[str]:
"""The node network modes ``app#variant`` can be deployed in.
Args:
roles_dir: the roles tree the round is read from.
app: the round's only primary app.
variant: the primary's variant, which is also the round index.
modes: the deploy modes the row is tested in.
"""
states = network.row_states(
app,
variant,
get_variants(roles_dir=roles_dir, readonly=True),
pulls_tor=network.tor_provider() in _round_of(roles_dir, app, variant).include,
)
return frozenset(
state
for mode in sorted(modes)
for state in network.network_states(
mode, states=states, network_input=network.AUTO
)
)
@functools.cache
def _runs(
roles_dir: str, app: str, variant: int, networks: frozenset[str]
) -> Mapping[str, int]:
"""What ``app#variant`` deploys in every one of ``networks``.
A network mode deploys with ``disable`` set as the matrix entry sets it
(:func:`utils.github.variant.network.disabled_services`), and the deploy
cuts those roles and every dependency only they pulled in
(``prune_orphans_after_disable``).
Args:
roles_dir: the roles tree the round is read from.
app: the round's only primary app.
variant: the primary's variant, which is also the round index.
networks: the node network modes the row can be deployed in.
"""
resolved = _round_of(roles_dir, app, variant)
kept = set(resolved.include)
for state in sorted(networks):
tokens = network.disabled_services(state, resolved.include)
if not tokens:
continue
kept &= set(
prune_orphans_after_disable(
include=resolved.include,
primary_apps=[app],
disabled_app_ids=set(
find_provider_roles(
parse_services_disabled(tokens), Path(roles_dir)
).values()
),
services_overrides=resolved.services_overrides,
)[0]
)
running = {**resolved.active_index, app: variant}
return {role: running.get(role, 0) for role in resolved.include if role in kept}
def rounds(roles_dir: Path) -> Rounds:
"""The planner's answers for the coverage cut, read from ``roles_dir``.
Args:
roles_dir: the roles tree the rounds are read from.
Returns:
:class:`Rounds` over that tree; a whole-role row is round 0.
"""
root = str(roles_dir)
def modes(row: ComplexityRow) -> frozenset[str]:
return frozenset(mode for mode in MODES if getattr(row, f"test_{mode}"))
def networks(row: ComplexityRow) -> frozenset[str]:
return _networks(root, row.name, row.variant or 0, modes(row))
def runs(row: ComplexityRow) -> Mapping[str, int]:
return _runs(root, row.name, row.variant or 0, networks(row))
return Rounds(modes, networks, runs)
@@ -0,0 +1,259 @@
"""Integration: a row the sweep cuts as covered is deployed by its coverer.
The cut drops a ``role#0`` row because an earlier row already brings that role
up in variant 0. When the claim is wrong, no job of the sweep deploys the row
and the plan still reads as complete. The complexity closure over-approximates
a round (it walks every provider's base ``meta/services.yml``), so the claim is
checked here against what the deploy jobs themselves run: the planner's include
pruned by ``disable`` as the compose and host deploy prunes it, and the include
a swarm job derives (``utils.tests.swarm.derive_includes``). The deploy and
network axes are assigned after the cut, so the claim must hold in every deploy
mode and network mode the coverer can rotate to.
"""
from __future__ import annotations
import functools
import os
import unittest
from unittest import mock
from cli.administration.deploy.development.inventory import (
_build_services_overrides_for_round as build_services_overrides_for_round,
)
from cli.administration.deploy.development.inventory import (
plan_dev_inventory_matrix,
prune_orphans_after_disable,
)
from cli.administration.inventory.provision.services.disabler import (
find_provider_roles,
parse_services_disabled,
)
from cli.meta.ci import query
from utils.cache.applications import get_variants
from utils.cache.files import PROJECT_ROOT
from utils.github.variant import network
from utils.github.variant.pools import MODES
from utils.tests.swarm.derive_includes import derive_includes
ROLES = PROJECT_ROOT / "roles"
@functools.cache
def _rounds(app: str) -> tuple[tuple[dict[str, int], tuple[str, ...]], ...]:
return tuple(
(dict(variants), tuple(include))
for _index, _dir, variants, include, _purge in plan_dev_inventory_matrix(
roles_dir=str(ROLES),
primary_apps=[app],
base_inventory_dir="plan",
)
)
@functools.cache
def _rows() -> tuple[dict, ...]:
return tuple(query.discover_rows(query.resolve_modes(query.ALL_MODES)))
@functools.cache
def _covered() -> tuple[tuple[dict, dict], ...]:
by_id = {row["id"]: row for row in _rows()}
return tuple(
(row, by_id[row["covered_by"]]) for row in _rows() if row["covered_by"] in by_id
)
def _row(name: str, variant: int) -> dict:
return next(
row for row in _rows() if (row["name"], row["variant"] or 0) == (name, variant)
)
def _modes(row: dict) -> set[str]:
return {mode for mode in MODES if row.get(f"test_{mode}")}
def _networks_by_mode(row: dict) -> dict[str, tuple[str, ...]]:
"""The node network modes each deploy mode of ``row`` can take it to.
Args:
row: a discovered row.
Returns:
``{deploy mode: network modes}`` for every mode ``row`` is tested in.
"""
include = _rounds(row["name"])[row["variant"] or 0][1]
states = network.row_states(
row["name"],
row["variant"],
get_variants(roles_dir=str(ROLES), readonly=True),
pulls_tor=network.tor_provider() in include,
)
return {
mode: tuple(
network.network_states(mode, states=states, network_input=network.AUTO)
)
for mode in sorted(_modes(row))
}
def _network_losses(row: dict, coverer: dict) -> list[str]:
"""Every ``mode/network`` the sweep can give ``row`` but never ``coverer``.
Args:
row: the cut row.
coverer: the row it is cut for.
"""
offered = _networks_by_mode(coverer)
return [
f"{mode}/{state}"
for mode, states in _networks_by_mode(row).items()
for state in states
if state not in offered.get(mode, ())
]
@functools.cache
def _deployed(app: str, index: int, mode: str, tokens: str) -> frozenset[str]:
"""The roles a ``mode`` job of ``app#index`` deploys under ``disable``.
Args:
app: the job's primary role.
index: the job's round index.
mode: the job's deploy mode.
tokens: the job's ``disable`` value.
"""
variants, include = _rounds(app)[index]
if mode == "swarm":
with mock.patch.dict(os.environ, {"disable": tokens}):
return frozenset(derive_includes(app, variants=variants))
if not tokens:
return frozenset(include)
disabled = set(find_provider_roles(parse_services_disabled(tokens), ROLES).values())
return frozenset(
prune_orphans_after_disable(
include=include,
primary_apps=[app] if app not in disabled else [],
disabled_app_ids=disabled,
services_overrides=build_services_overrides_for_round(
roles_dir=str(ROLES),
round_index=index,
primary_app_variants={app: variants.get(app, index)},
),
)[0]
)
def _losses(row: dict, coverer: dict) -> list[str]:
"""Every deploy mode and network mode of ``coverer`` whose job leaves
``row`` out.
Args:
row: the cut row.
coverer: the row it is cut for.
Returns:
``mode/network disable=...`` per such job.
"""
index = coverer["variant"] or 0
include = _rounds(coverer["name"])[index][1]
return [
f"{mode}/{state} disable={tokens!r}"
for mode, states in _networks_by_mode(coverer).items()
for state in states
for tokens in (network.disabled_services(state, include),)
if row["name"] not in _deployed(coverer["name"], index, mode, tokens)
]
class TestCoveredRowsAreDeployed(unittest.TestCase):
def test_every_cut_row_runs_in_variant_zero_in_its_coverers_round(self) -> None:
findings = [
f" - {query.token(row)} cut for {query.token(coverer)}, whose round "
f"runs it as {variants.get(row['name'], 0) if row['name'] in include else 'nothing'!r}"
for row, coverer in _covered()
for variants, include in (
_rounds(coverer["name"])[coverer["variant"] or 0],
)
if row["name"] not in include or variants.get(row["name"], 0) != 0
]
self.assertFalse(
findings,
f"{len(findings)} row(s) are cut as covered by a row whose deploy "
"never brings them up in variant 0, so no job deploys them:\n"
+ "\n".join(findings),
)
def test_every_job_the_coverer_can_get_deploys_the_cut_row(self) -> None:
findings = [
f" - {query.token(row)} cut for {query.token(coverer)}, whose "
f"{loss} job leaves it out"
for row, coverer in _covered()
for loss in _losses(row, coverer)
]
self.assertFalse(
findings,
f"{len(findings)} cut row(s) are left out of a job their coverer can "
"rotate to, so that sweep deploys them nowhere:\n" + "\n".join(findings),
)
def test_every_cut_row_is_tested_only_in_modes_its_coverer_is_tested_in(
self,
) -> None:
findings = [
f" - {query.token(row)} cut for {query.token(coverer)}, which is "
f"never deployed in {sorted(_modes(row) - _modes(coverer))}"
for row, coverer in _covered()
if not _modes(row) <= _modes(coverer)
]
self.assertFalse(
findings,
f"{len(findings)} cut row(s) offer a deploy mode their coverer does "
"not, so no job deploys them in it:\n" + "\n".join(findings),
)
def test_every_network_mode_of_a_cut_row_is_one_its_coverer_takes(
self,
) -> None:
findings = [
f" - {query.token(row)} cut for {query.token(coverer)}, which never "
f"deploys in {loss}"
for row, coverer in _covered()
for loss in _network_losses(row, coverer)
]
self.assertFalse(
findings,
f"{len(findings)} cut row(s) can be given a network mode their coverer "
"never is, so no job deploys them in it:\n" + "\n".join(findings),
)
def test_the_network_guard_reports_a_network_the_coverer_never_takes(
self,
) -> None:
self.assertIn(
"swarm/multi",
_network_losses(
_row("svc-ai-libretranslate-engine", 0), _row("web-svc-translate", 4)
),
)
def test_the_guard_reports_a_disable_that_drops_the_cut_row(self) -> None:
row, coverer = next(
(row, coverer)
for row, coverer in _covered()
if _modes(coverer) & {"compose", "host"}
)
with mock.patch.object(
network, "disabled_services", lambda state, include: row["name"]
):
self.assertTrue(_losses(row, coverer))
def test_the_scan_finds_cut_rows_to_judge(self) -> None:
self.assertTrue(
_covered(), "no discovered row is cut as covered; the check is vacuous"
)
if __name__ == "__main__":
unittest.main()
@@ -1,8 +1,12 @@
from __future__ import annotations
import os
import re
import subprocess
import unittest
import yaml
from cli.administration.inventory.provision.services.disabler import (
parse_services_disabled,
)
@@ -71,6 +75,44 @@ class TestDeployDisableMerge(unittest.TestCase):
def test_the_old_fallback_drops_the_passed_list(self) -> None:
self.assertEqual(evaluate(OLD_EXPRESSION, "tor", "docs,matomo"), ["tor"])
def test_discovery_warns_when_a_passed_list_can_orphan_a_covered_row(
self,
) -> None:
self.assertTrue(
warning_steps(),
"the covered-row cut ignores the passed disable, so discovery must "
"warn whenever one is passed",
)
def test_the_passed_list_cannot_inject_a_workflow_command(self) -> None:
for step in warning_steps():
with self.subTest(step=step["name"]):
printed = subprocess.run(
["bash", "-c", step["run"]],
env={
**os.environ,
"PASSED_DISABLE": "docs\n::error::forged%0A::add-mask::x\r",
},
capture_output=True,
text=True,
check=True,
).stdout
self.assertEqual(printed.count("\n"), 1, printed)
self.assertEqual(printed.count("::"), 2, printed)
self.assertNotIn("%", printed)
self.assertIn("disable=docserrorforged0Aadd-maskx ", printed)
def warning_steps() -> list[dict]:
"""The discover steps that warn about a passed ``disable``."""
steps = yaml.safe_load(read_text(str(DEPLOY_WORKFLOW)))["jobs"]["discover"]["steps"]
return [
step
for step in steps
if "inputs.disable" in str(step.get("if", ""))
and "::warning" in str(step.get("run", ""))
]
if __name__ == "__main__":
unittest.main()
@@ -1,6 +1,9 @@
from __future__ import annotations
import subprocess
import sys
import unittest
from unittest import mock
from cli.meta.ci import query
@@ -103,5 +106,25 @@ class TestQueryArgv(unittest.TestCase):
self.assertIn("test_compose == true", argv[argv.index("--filter") + 1])
class TestDiscoverRows(unittest.TestCase):
def _discover_with(self, script: str) -> list[dict]:
with mock.patch.object(
query, "_query_argv", return_value=[sys.executable, "-c", script]
):
return query.discover_rows(("compose",))
def test_a_failing_query_leaves_its_error_on_stderr(self) -> None:
with self.assertRaises(subprocess.CalledProcessError) as raised:
self._discover_with(
"import sys; sys.stderr.write('VariantPinError: x\\n'); sys.exit(1)"
)
self.assertIsNone(raised.exception.stderr)
def test_the_rows_are_read_from_stdout(self) -> None:
self.assertEqual(
self._discover_with('print(\'[{"name": "r"}]\')'), [{"name": "r"}]
)
if __name__ == "__main__":
unittest.main()
@@ -17,6 +17,7 @@ from cli.meta.roles.applications.complexity.model import (
compute_complexity_rows,
compute_variant_complexity_rows,
)
from cli.meta.roles.applications.complexity.reach import Rounds
from cli.meta.roles.applications.complexity.render import (
_bool_cell,
_dwidth,
@@ -725,6 +726,12 @@ class TestSortByCoveredBy(unittest.TestCase):
"cli.meta.roles.applications.complexity.cli.PROJECT_ROOT",
Path(td),
),
# Limitation: the deploy planner resolves includes against the
# project's own roles/, so it cannot plan this fixture tree.
mock.patch(
"cli.meta.roles.applications.complexity.cli.rounds",
lambda _roles_dir: _planner(),
),
redirect_stdout(buf),
):
rc = main(
@@ -895,11 +902,11 @@ def _row(
class TestCoveredBy(unittest.TestCase):
def test_id_is_numeric_sort_position(self) -> None:
marked = _mark_covered([_row("A", []), _row("B", [])])
marked = _mark_covered([_row("A", []), _row("B", [])], planner=_planner())
self.assertEqual([m.id for m in marked], [1, 2])
def test_green_rows_get_covered_by_zero(self) -> None:
marked = _mark_covered([_row("A", ["B"]), _row("C", [])])
marked = _mark_covered([_row("A", ["B"]), _row("C", [])], planner=_planner())
self.assertEqual([m.covered_by for m in marked], [0, 0])
def test_embedded_row_records_its_embedder_id(self) -> None:
@@ -908,7 +915,8 @@ class TestCoveredBy(unittest.TestCase):
_row("Z", []),
_row("A", ["B"]),
_row("B", []),
]
],
planner=_planner(),
)
self.assertEqual([m.covered_by for m in marked], [0, 0, 2])
@@ -918,7 +926,8 @@ class TestCoveredBy(unittest.TestCase):
_row("Z", []),
_row("A", ["X", "Y"]),
_row("B", ["X"]),
]
],
planner=_planner(),
)
self.assertEqual([m.covered_by for m in marked], [0, 0, 0])
@@ -929,7 +938,8 @@ class TestCoveredBy(unittest.TestCase):
_row("A", ["X"]),
_row("B", ["X"]),
_row("X", []),
]
],
planner=_planner(),
)
self.assertEqual([m.covered_by for m in marked], [0, 0, 0, 2])
@@ -940,7 +950,8 @@ class TestCoveredBy(unittest.TestCase):
_row("A", ["B", "C"]),
_row("B", [], variant=0),
_row("C", [], variant=1),
]
],
planner=_planner(),
)
self.assertEqual([m.covered_by for m in marked], [0, 0, 2, 0])
@@ -952,6 +963,7 @@ class TestCoveredBy(unittest.TestCase):
_row("B", [], variant=0),
],
variant_counts={"B": 1},
planner=_planner(),
)
self.assertEqual([m.covered_by for m in marked], [0, 0, 2])
@@ -963,6 +975,7 @@ class TestCoveredBy(unittest.TestCase):
_row("B", [], variant=0),
],
variant_counts={"B": 5},
planner=_planner(),
)
self.assertEqual([m.covered_by for m in marked], [0, 0, 0])
@@ -974,24 +987,139 @@ class TestCoveredBy(unittest.TestCase):
_row("B", [], variant=0),
],
variant_counts={"B": 9},
planner=_planner(),
)
self.assertEqual([m.covered_by for m in marked], [0, 0, 2])
def test_a_variant_that_overrides_a_provider_does_not_cover_it(self) -> None:
rows = [_row("A", ["B", "C"], variant=0), _row("B", []), _row("C", [])]
marked = _mark_covered(rows, {("A", 0): {"B"}})
marked = _mark_covered(rows, {("A", 0): {"B"}}, planner=_planner())
self.assertEqual([m.covered_by for m in marked], [0, 0, 1])
def test_the_override_only_bars_the_provider_it_names(self) -> None:
rows = [_row("A", ["B"], variant=0), _row("B", [])]
marked = _mark_covered(rows, {("A", 0): {"C"}})
marked = _mark_covered(rows, {("A", 0): {"C"}}, planner=_planner())
self.assertEqual([m.covered_by for m in marked], [0, 1])
def test_an_override_in_another_variant_leaves_coverage_alone(self) -> None:
rows = [_row("A", ["B"], variant=0), _row("B", [])]
marked = _mark_covered(rows, {("A", 2): {"B"}})
marked = _mark_covered(rows, {("A", 2): {"B"}}, planner=_planner())
self.assertEqual([m.covered_by for m in marked], [0, 1])
def test_a_row_whose_round_never_deploys_the_provider_does_not_cover_it(
self,
) -> None:
rows = [_row("A", ["B"], variant=3), _row("B", [], variant=0)]
marked = _mark_covered(rows, planner=_planner({("A", 3): {"A": 3}}))
self.assertEqual([m.covered_by for m in marked], [0, 0])
def test_a_row_whose_round_deploys_the_provider_at_zero_covers_it(self) -> None:
rows = [_row("A", ["B"], variant=3), _row("B", [], variant=0)]
marked = _mark_covered(rows, planner=_planner({("A", 3): {"B": 0, "A": 3}}))
self.assertEqual([m.covered_by for m in marked], [0, 1])
def test_a_round_that_runs_the_provider_in_another_variant_does_not_cover(
self,
) -> None:
rows = [_row("A", ["B"], variant=3), _row("B", [], variant=0)]
marked = _mark_covered(rows, planner=_planner({("A", 3): {"B": 1, "A": 3}}))
self.assertEqual([m.covered_by for m in marked], [0, 0])
def test_the_next_green_row_that_deploys_the_provider_covers_it(self) -> None:
rows = [
_row("A", ["B"], variant=3),
_row("C", ["B"], variant=0),
_row("B", [], variant=0),
]
marked = _mark_covered(
rows,
planner=_planner({("A", 3): {"A": 3}, ("C", 0): {"B": 0, "C": 0}}),
)
self.assertEqual([m.covered_by for m in marked], [0, 0, 2])
def test_the_deploy_check_never_widens_what_services_covers(self) -> None:
rows = [_row("A", [], variant=0), _row("B", [], variant=0)]
marked = _mark_covered(rows, planner=_planner({("A", 0): {"B": 0, "A": 0}}))
self.assertEqual([m.covered_by for m in marked], [0, 0])
def test_a_row_taking_a_network_its_coverer_never_takes_is_not_covered(
self,
) -> None:
rows = [_row("A", ["B"], variant=0), _row("B", [], variant=0)]
marked = _mark_covered(
rows,
planner=_planner(
{("A", 0): {"B": 0, "A": 0}},
networks={("A", 0): CLEARNET_ONLY, ("B", 0): CLEARNET_AND_TOR},
),
)
self.assertEqual([m.covered_by for m in marked], [0, 0])
def test_a_coverer_offering_every_network_the_row_takes_covers_it(self) -> None:
rows = [_row("A", ["B"], variant=0), _row("B", [], variant=0)]
marked = _mark_covered(
rows,
planner=_planner(
{("A", 0): {"B": 0, "A": 0}},
networks={("A", 0): CLEARNET_AND_TOR, ("B", 0): CLEARNET_ONLY},
),
)
self.assertEqual([m.covered_by for m in marked], [0, 1])
def test_a_row_tested_in_a_mode_its_coverer_is_not_is_not_covered(self) -> None:
rows = [_row("A", ["B"], variant=0), _row("B", [], variant=0)]
marked = _mark_covered(
rows,
planner=_planner(modes={("B", 0): COMPOSE_AND_HOST}),
)
self.assertEqual([m.covered_by for m in marked], [0, 0])
def test_a_coverer_tested_in_every_mode_of_the_row_covers_it(self) -> None:
rows = [_row("A", ["B"], variant=0), _row("B", [], variant=0)]
marked = _mark_covered(
rows,
planner=_planner(modes={("A", 0): COMPOSE_AND_HOST}),
)
self.assertEqual([m.covered_by for m in marked], [0, 1])
CLEARNET_ONLY = frozenset({"clearnet"})
CLEARNET_AND_TOR = frozenset({"clearnet", "tor"})
COMPOSE_ONLY = frozenset({"compose"})
COMPOSE_AND_HOST = frozenset({"compose", "host"})
def _planner(
runs: dict[tuple[str, int], dict[str, int]] | None = None,
*,
networks: dict[tuple[str, int], frozenset[str]] | None = None,
modes: dict[tuple[str, int], frozenset[str]] | None = None,
) -> Rounds:
"""A ``planner`` stub answering from fixed tables.
Args:
runs: ``{(role, variant): {role: variant}}`` per coverer; a row absent
from it runs every role of its ``services`` in variant 0.
networks: ``{(role, variant): network modes}``; a row absent from it
takes clearnet only.
modes: ``{(role, variant): deploy modes}``; a row absent from it is
tested in compose only.
Returns:
:class:`Rounds` answering from those tables.
"""
def key(row: ComplexityRow) -> tuple[str, int]:
return (row.name, row.variant or 0)
return Rounds(
lambda row: (modes or {}).get(key(row), COMPOSE_ONLY),
lambda row: (networks or {}).get(key(row), CLEARNET_ONLY),
lambda row: (runs or {}).get(
key(row), {**dict.fromkeys(row.services, 0), row.name: row.variant or 0}
),
)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,140 @@
"""The coverage cut's view of a round: the networks a row takes and the roles
its round still runs once each network's ``disable`` is applied."""
from __future__ import annotations
import unittest
from types import SimpleNamespace
from unittest import mock
from cli.meta.roles.applications.complexity import reach
APP = "web-app-a"
ROUND = SimpleNamespace(
include=("svc-db", "svc-net-tor", "web-svc-partner", APP),
active_index={"svc-db": 2},
services_overrides={},
)
DISABLE = {"clearnet": "tor", "tor": "web-svc-partner", "multi": ""}
PROVIDERS = {"tor": "svc-net-tor", "web-svc-partner": "web-svc-partner"}
ORPHANS = {
"svc-net-tor": {"svc-net-tor"},
"web-svc-partner": {"web-svc-partner", "svc-db"},
}
STATES = {"compose": ("clearnet",), "swarm": ("tor", "multi"), "host": ("clearnet",)}
def _prune(
*,
include: tuple[str, ...],
primary_apps: list[str],
disabled_app_ids: set[str],
services_overrides: dict,
) -> tuple[tuple[str, ...], tuple[str, ...]]:
"""A ``prune_orphans_after_disable`` stub cutting each disabled role with
the dependencies listed for it in ``ORPHANS``.
Args:
include: the round's include.
primary_apps: the round's primaries, unused.
disabled_app_ids: the roles ``disable`` cuts.
services_overrides: the round's service maps, unused.
Returns:
``(kept, pruned)`` in include order.
"""
gone = set().union(*(ORPHANS[role] for role in disabled_app_ids))
return tuple(r for r in include if r not in gone), tuple(
r for r in include if r in gone
)
class _Fixture(unittest.TestCase):
def setUp(self) -> None:
caches = (reach._round_of, reach._networks, reach._runs)
for fn in caches:
fn.cache_clear()
self.addCleanup(fn.cache_clear)
self.row_states = mock.Mock(return_value=("clearnet", "tor", "multi"))
for patch in (
mock.patch.object(reach, "_round_of", return_value=ROUND),
mock.patch.object(reach, "get_variants", return_value={}),
mock.patch.object(reach.network, "row_states", self.row_states),
mock.patch.object(
reach.network, "tor_provider", return_value="svc-net-tor"
),
mock.patch.object(
reach.network,
"network_states",
side_effect=lambda mode, states, network_input: STATES[mode],
),
mock.patch.object(
reach.network,
"disabled_services",
side_effect=lambda state, include: DISABLE[state],
),
mock.patch.object(
reach,
"find_provider_roles",
side_effect=lambda services, roles_dir: {
s: PROVIDERS[s] for s in services
},
),
mock.patch.object(reach, "prune_orphans_after_disable", side_effect=_prune),
):
patch.start()
self.addCleanup(patch.stop)
class TestRuns(_Fixture):
def test_a_network_without_disable_runs_the_whole_round(self) -> None:
self.assertEqual(
reach._runs("roles", APP, 3, frozenset({"multi"})),
{"svc-db": 2, "svc-net-tor": 0, "web-svc-partner": 0, APP: 3},
)
def test_a_network_cuts_its_disabled_role_and_the_orphans_it_leaves(
self,
) -> None:
self.assertEqual(
reach._runs("roles", APP, 3, frozenset({"tor"})),
{"svc-net-tor": 0, APP: 3},
)
def test_a_role_any_network_cuts_is_not_run(self) -> None:
self.assertEqual(
reach._runs("roles", APP, 3, frozenset({"clearnet", "tor"})), {APP: 3}
)
class TestNetworks(_Fixture):
def test_the_networks_are_those_of_every_tested_mode(self) -> None:
self.assertEqual(
reach._networks("roles", APP, 0, frozenset({"compose", "swarm"})),
{"clearnet", "tor", "multi"},
)
def test_a_row_tested_in_no_mode_takes_no_network(self) -> None:
self.assertEqual(reach._networks("roles", APP, 0, frozenset()), frozenset())
def test_the_round_decides_whether_the_row_pulls_tor(self) -> None:
reach._networks("roles", APP, 0, frozenset({"compose"}))
self.assertTrue(self.row_states.call_args.kwargs["pulls_tor"])
class TestRounds(_Fixture):
def test_the_modes_are_the_tested_ones(self) -> None:
row = SimpleNamespace(
name=APP, variant=None, test_compose=True, test_swarm=False, test_host=True
)
self.assertEqual(reach.rounds("roles").modes(row), {"compose", "host"})
def test_a_whole_role_row_runs_round_zero(self) -> None:
row = SimpleNamespace(
name=APP, variant=None, test_compose=True, test_swarm=False, test_host=False
)
self.assertEqual(reach.rounds("roles").runs(row)[APP], 0)
if __name__ == "__main__":
unittest.main()