diff --git a/.github/dependabot.yml b/.github/dependabot.yml index f4e2da25b6..b51f38680d 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -15,6 +15,7 @@ updates: rebase-strategy: "auto" labels: - "dependencies" + - "update" - "python" # ------------------------------------------------------------ @@ -29,6 +30,7 @@ updates: time: "00:00" labels: - "dependencies" + - "update" - "ci" # ------------------------------------------------------------ @@ -43,6 +45,7 @@ updates: time: "00:00" labels: - "dependencies" + - "update" - "docker" # ------------------------------------------------------------ @@ -57,6 +60,7 @@ updates: time: "00:00" labels: - "dependencies" + - "update" - "docker" # ------------------------------------------------------------ @@ -75,6 +79,7 @@ updates: time: "00:00" labels: - "dependencies" + - "update" - "ci" # ------------------------------------------------------------ @@ -90,6 +95,7 @@ updates: time: "00:00" labels: - "dependencies" + - "update" - "javascript" # ------------------------------------------------------------ @@ -104,6 +110,7 @@ updates: time: "00:00" labels: - "dependencies" + - "update" - "php" # ------------------------------------------------------------ @@ -188,6 +195,7 @@ updates: time: "00:00" labels: - "dependencies" + - "update" - "ruby" # cargo: no Cargo.toml found diff --git a/.github/workflows/README.md b/.github/workflows/README.md index 3afca0f735..bff53e3419 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -86,6 +86,14 @@ can outlast it โ€” so the estimate can only overshoot the real drain time. With the current constants that is 4 waves of 20 runners, so 80 rows per chunk, and the last job of a chunk starts around t=18h, well inside the 24h window. +The repository variable `INFINITO_CI_CONCURRENCY` overrides the `default.env` +value; unset or empty keeps it. `call-validation.yml` and `call-test-deploy.yml` +forward it in their workflow-level `env:`, so the batch count and every chunk's +cut use the same size. An account that runs 500 jobs at once (GitHub +Enterprise) gets a chunk larger than `available` below, so a sweep needs one +chunk, two with a priority line, and only the run's job cap bounds it. See +[configuration.md](../../docs/contributing/tools/github/actions/configuration.md). + ### How many chunks a sweep spends The run's 256-job cap is the second ceiling. `slots` counts every non-deploy diff --git a/.github/workflows/call-test-deploy.yml b/.github/workflows/call-test-deploy.yml index b2ee79e5c7..d9cb405b8d 100644 --- a/.github/workflows/call-test-deploy.yml +++ b/.github/workflows/call-test-deploy.yml @@ -170,6 +170,7 @@ env: INFINITO_ARCHITECTURES: ${{ inputs.architectures }} INFINITO_LIFECYCLES: ${{ inputs.lifecycles }} INFINITO_DISCOVERY_SEED: ${{ github.run_id }} + INFINITO_CI_CONCURRENCY: ${{ vars.INFINITO_CI_CONCURRENCY }} jobs: discover: diff --git a/.github/workflows/call-validation.yml b/.github/workflows/call-validation.yml index 9171c80a82..0129e213d7 100644 --- a/.github/workflows/call-validation.yml +++ b/.github/workflows/call-validation.yml @@ -105,6 +105,9 @@ on: permissions: contents: read +env: + INFINITO_CI_CONCURRENCY: ${{ vars.INFINITO_CI_CONCURRENCY }} + jobs: validation: name: โœ… Validation diff --git a/.github/workflows/cron-update.yml b/.github/workflows/cron-update.yml index 479e3a900c..9be204fb75 100644 --- a/.github/workflows/cron-update.yml +++ b/.github/workflows/cron-update.yml @@ -249,7 +249,7 @@ jobs: UPDATE_BRANCH_PREFIX: update/repository-refs UPDATE_COMMIT_MESSAGE: "update(repos): bump git refs to latest tags and commits" UPDATE_PR_TITLE: "update(repos): bump git refs to latest tags and commits" - UPDATE_PR_BODY: "Automated update of git `ref:` values in `roles/*/meta/services.yml` and `roles/*/meta/addons/*.yml`. A semver ref moves to the latest upstream tag (`git ls-remote --tags`), a commit SHA to the tip of the default branch (`git ls-remote HEAD`)." + UPDATE_PR_BODY: "Automated update of git `ref:` values in `roles/*/meta/services.yml` and `roles/*/meta/addons/*.yml`. A semver ref moves to the latest upstream tag (`git ls-remote --tags`), a commit SHA to the newest release tag that contains it, or to the tip of the default branch (`git ls-remote HEAD`) when no release does." UPDATE_BASE_BRANCH: main run: bash scripts/github/update/open/role_prs.sh roles diff --git a/.github/workflows/entry-pr-change-dependabot-label.yml b/.github/workflows/entry-pr-change-dependabot-label.yml new file mode 100644 index 0000000000..8acf9116bc --- /dev/null +++ b/.github/workflows/entry-pr-change-dependabot-label.yml @@ -0,0 +1,40 @@ +name: "๐Ÿ”„ Dependabot: Label update level" + +on: + pull_request_target: + types: [opened, reopened, synchronize] + +permissions: {} + +jobs: + label: + name: ๐Ÿท๏ธ Label the Dependabot PR + if: github.event.pull_request.user.login == 'dependabot[bot]' && vars.CI_ENABLE_AUTO_UPDATES == 'true' + runs-on: ubuntu-26.04 + timeout-minutes: 10 + permissions: + contents: read + pull-requests: write + steps: + - name: ๐Ÿ”Ž Read Dependabot metadata + id: metadata + uses: dependabot/fetch-metadata@25dd0e34f4fe68f24cc83900b1fe3fe149efef98 # v3.1.0 + + - name: โฌ‡๏ธ Checkout the base branch + uses: actions/checkout@v7.0.0 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + + - name: ๐Ÿ”ง Set up Python + uses: actions/setup-python@v6 + with: + python-version: "3.12" + + - name: ๐Ÿท๏ธ Label update and semver level + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + REPOSITORY: ${{ github.repository }} + PR_NUMBER: ${{ github.event.pull_request.number }} + UPDATE_TYPE: ${{ steps.metadata.outputs.update-type }} + run: python3 -m cli.contributing.update.label --repo "$REPOSITORY" --pr "$PR_NUMBER" --update-type "$UPDATE_TYPE" diff --git a/.github/workflows/entry-pr-green-update-merge.yml b/.github/workflows/entry-pr-green-update-merge.yml new file mode 100644 index 0000000000..9091ebb92b --- /dev/null +++ b/.github/workflows/entry-pr-green-update-merge.yml @@ -0,0 +1,69 @@ +name: "๐Ÿ”„ Update: Merge proven PRs" +run-name: "๐Ÿ”„ Merge check for ${{ github.event.workflow_run.head_branch }}" + +on: + workflow_run: + workflows: ["๐Ÿ”€ Pull Request"] + types: [completed] + +permissions: {} + +jobs: + merge: + name: ๐Ÿ”€ Merge a proven update PR + if: >- + vars.CI_ENABLE_AUTO_UPDATES == 'true' + && github.event.workflow_run.event == 'pull_request' + && github.event.workflow_run.conclusion == 'success' + && (startsWith(github.event.workflow_run.head_branch, 'update/') + || startsWith(github.event.workflow_run.head_branch, 'dependabot/')) + runs-on: ubuntu-26.04 + timeout-minutes: 15 + permissions: + actions: read + checks: read + contents: read + pull-requests: read + statuses: read + steps: + - name: โฌ‡๏ธ Checkout + uses: actions/checkout@v7.0.0 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + + - name: ๐Ÿ”ง Set up Python + uses: actions/setup-python@v6 + with: + python-version: "3.12" + + - name: ๐Ÿ”Ž Check the merge gate + id: gate + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + REPOSITORY: ${{ github.repository }} + HEAD_SHA: ${{ github.event.workflow_run.head_sha }} + RUN_ID: ${{ github.event.workflow_run.id }} + OWN_RUN_ID: ${{ github.run_id }} + BASE_BRANCH: ${{ github.event.repository.default_branch }} + run: >- + python3 -m cli.contributing.update.merge + --repo "$REPOSITORY" --sha "$HEAD_SHA" --run-id "$RUN_ID" + --own-run-id "$OWN_RUN_ID" --base "$BASE_BRANCH" --output "$GITHUB_OUTPUT" + + - name: โš™๏ธ Generate app token + if: steps.gate.outputs.merge == 'true' + id: app-token + uses: actions/create-github-app-token@v3 + with: + client-id: ${{ secrets.BOT_APP_CLIENT_ID }} + private-key: ${{ secrets.BOT_APP_PRIVATE_KEY }} + + - name: ๐Ÿ”€ Merge the update PR at its tested head + if: steps.gate.outputs.merge == 'true' + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + REPOSITORY: ${{ github.repository }} + PR_NUMBER: ${{ steps.gate.outputs.pr }} + HEAD_SHA: ${{ steps.gate.outputs.sha }} + run: gh api --method PUT "repos/${REPOSITORY}/pulls/${PR_NUMBER}/merge" -f merge_method=merge -f sha="${HEAD_SHA}" diff --git a/cli/contributing/update/README.md b/cli/contributing/update/README.md index 7e8f2f564c..8d2d2f9fa5 100644 --- a/cli/contributing/update/README.md +++ b/cli/contributing/update/README.md @@ -10,12 +10,15 @@ Every role-scoped updater (`docker`, `source`, `pip`, `repository`) and the addo `python -m cli.contributing.update.repository` bumps every `ref:` that sits next to a `repository:` in `roles/*/meta/services.yml` or `roles/*/meta/addons/*.yml`, at any depth, an addon's `config` included: -| `ref:` | Moves to | Reads | -| ---------------------- | ------------------------------------------- | ----------------------------------- | -| semver, e.g. `v0.8.5` | the latest tag of the same depth and flavor | `git ls-remote --tags ` | -| full 40-hex commit SHA | the tip of the default branch | `git ls-remote HEAD` | +| `ref:` | Moves to | Reads | +| ---------------------- | ------------------------------------------- | -------------------------------------------- | +| semver, e.g. `v0.8.5` | the latest tag of the same depth and flavor | `git ls-remote --tags ` | +| full 40-hex commit SHA | the newest release tag that contains it | `git ls-remote --tags`, treeless `git fetch` | +| same, no such release | the tip of the default branch | `git ls-remote HEAD` | -A branch name and a short SHA stay as they are. `# nocheck: repository-version` on the line above `ref:` freezes a pin. Each repository is queried once per run and lookup, and a failed query leaves its pins untouched. The `update-repository-refs` job of `.github/workflows/cron-update.yml` opens one PR per changed role, and `tests/external/update/repository/` warns about pending bumps. +A branch name and a short SHA stay as they are. `# nocheck: repository-version` on the line above `ref:` freezes a pin. Each repository is queried once per run and lookup, and a failed query leaves its pins untouched. The `update-repository-refs` job of `.github/workflows/cron-update.yml` opens one PR per changed role, and `tests/external/update/repository/` warns about pending bumps and fails on a commit SHA that a release tag already contains. A pin newer than the newest release keeps following the tip, so no pin moves back to an older release. + +Every update PR carries the label `update` and one of `major`, `minor` or `patch`: the highest step among its changed versions, read by [level.py](../../../utils/update/level.py). A change that is no number step (a commit SHA, a SHA moving to a tag) counts as `major`. ## Declared version sources diff --git a/cli/contributing/update/label/__init__.py b/cli/contributing/update/label/__init__.py new file mode 100644 index 0000000000..ead172a6cf --- /dev/null +++ b/cli/contributing/update/label/__init__.py @@ -0,0 +1,30 @@ +"""Labels an update pull request carries: ``update`` plus its semver level.""" + +from __future__ import annotations + +from typing import NamedTuple + + +class Label(NamedTuple): + """One repository label. + + Args: + name: the label name. + color: the six-digit hex colour, without ``#``. + description: the text the repository's label list shows. + """ + + name: str + color: str + description: str + + +UPDATE = Label("update", "0366D6", "Automated dependency or version update") +MAJOR = Label( + "major", "B60205", "Update raises a major version, or one of unknown reach" +) +MINOR = Label("minor", "FBCA04", "Update raises a minor version") +PATCH = Label("patch", "0E8A16", "Update raises a patch version") +LEVELS = (MAJOR, MINOR, PATCH) + +__all__ = ["LEVELS", "MAJOR", "MINOR", "PATCH", "UPDATE", "Label"] diff --git a/cli/contributing/update/label/__main__.py b/cli/contributing/update/label/__main__.py new file mode 100755 index 0000000000..460c355ccb --- /dev/null +++ b/cli/contributing/update/label/__main__.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import subprocess +from typing import TYPE_CHECKING +from urllib.parse import quote + +from . import LEVELS, MAJOR, MINOR, PATCH, UPDATE + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Sequence + + from . import Label + +GH_TIMEOUT_SECONDS = 120 +_LEVEL_OF_UPDATE_TYPE = { + "version-update:semver-major": MAJOR, + "version-update:semver-minor": MINOR, + "version-update:semver-patch": PATCH, +} + + +def level(update_type: str) -> Label: + """The semver label of a Dependabot update. + + Args: + update_type: the ``update-type`` output of ``dependabot/fetch-metadata``. + + Returns: + ``minor`` or ``patch`` for those semver levels, ``major`` for everything + else, so an update of unknown reach is never filed as a small one. + """ + return _LEVEL_OF_UPDATE_TYPE.get(update_type.strip(), MAJOR) + + +def run_gh(args: Sequence[str]) -> str: + return subprocess.run( + ["gh", *args], + capture_output=True, + text=True, + check=True, + timeout=GH_TIMEOUT_SECONDS, + ).stdout + + +def names(gh: Callable[[Sequence[str]], str], path: str) -> set[str]: + """The ``name`` of every label a paginated REST list returns. + + Args: + gh: runs ``gh`` with the given arguments and returns its stdout. + path: the REST path listing the labels. + + Returns: + the label names. + """ + out = gh(["api", "--paginate", path, "--jq", ".[].name"]) + return {line for line in out.splitlines() if line} + + +def ensure_labels( + gh: Callable[[Sequence[str]], str], repo: str, labels: Iterable[Label] +) -> list[str]: + """Create the labels the repository lacks, leaving existing ones untouched. + + Args: + gh: runs ``gh`` with the given arguments and returns its stdout. + repo: ``owner/name``. + labels: the labels that must exist. + + Returns: + the names created. A create that fails because a parallel run created + the label first counts as done; any other failure raises. + """ + existing = names(gh, f"repos/{repo}/labels") + created: list[str] = [] + for label in labels: + if label.name in existing: + continue + try: + gh( + [ + "label", + "create", + label.name, + "--repo", + repo, + "--color", + label.color, + "--description", + label.description, + ] + ) + except subprocess.CalledProcessError: + if label.name not in names(gh, f"repos/{repo}/labels"): + raise + continue + created.append(label.name) + return created + + +def sync( + gh: Callable[[Sequence[str]], str], repo: str, pr: int, update_type: str +) -> list[str]: + """Leave *pr* carrying ``update`` and exactly one semver label. + + Args: + gh: runs ``gh`` with the given arguments and returns its stdout. + repo: ``owner/name``. + pr: the pull request number. + update_type: the ``update-type`` output of ``dependabot/fetch-metadata``. + + Returns: + what was done, one line per action. A label the pull request already + carries is not added again: a ``labeled`` event restarts its CI run. + """ + wanted = (UPDATE, level(update_type)) + actions = [f"created label {name}" for name in ensure_labels(gh, repo, wanted)] + current = names(gh, f"repos/{repo}/issues/{pr}/labels") + for stale in LEVELS: + if stale not in wanted and stale.name in current: + gh( + [ + "api", + "--method", + "DELETE", + f"repos/{repo}/issues/{pr}/labels/{quote(stale.name)}", + ] + ) + actions.append(f"removed {stale.name}") + missing = [label.name for label in wanted if label.name not in current] + if missing: + args = ["api", "--method", "POST", f"repos/{repo}/issues/{pr}/labels"] + for name in missing: + args += ["-f", f"labels[]={name}"] + gh(args) + actions.append(f"added {', '.join(missing)}") + return actions + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description=( + "Label a Dependabot pull request `update` plus exactly one of " + "`major`, `minor` and `patch`, creating labels the repository lacks." + ) + ) + parser.add_argument("--repo", required=True, help="owner/name") + parser.add_argument( + "--ensure-only", + action="store_true", + help="Only create the update labels the repository lacks", + ) + parser.add_argument("--pr", type=int, help="Pull request number") + parser.add_argument( + "--update-type", + help="update-type output of dependabot/fetch-metadata, possibly empty", + ) + args = parser.parse_args(argv) + if args.ensure_only: + for name in ensure_labels(run_gh, args.repo, (UPDATE, *LEVELS)): + print(f"created label {name}") + return 0 + if args.pr is None or args.update_type is None: + parser.error("--pr and --update-type are required without --ensure-only") + actions = sync(run_gh, args.repo, args.pr, args.update_type) + for line in actions or [f"#{args.pr} already carries its labels"]: + print(line) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/cli/contributing/update/merge/__init__.py b/cli/contributing/update/merge/__init__.py new file mode 100644 index 0000000000..cad4397f40 --- /dev/null +++ b/cli/contributing/update/merge/__init__.py @@ -0,0 +1 @@ +"""Merge gate of update pull requests: green checks plus a deploy of every changed role.""" diff --git a/cli/contributing/update/merge/__main__.py b/cli/contributing/update/merge/__main__.py new file mode 100755 index 0000000000..3733277479 --- /dev/null +++ b/cli/contributing/update/merge/__main__.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import re +from pathlib import Path +from typing import TYPE_CHECKING, Any + +from . import gate, github + +if TYPE_CHECKING: + from collections.abc import Sequence + + from .github import Gh + +_SHA = re.compile(r"[0-9a-f]{40}") + + +def evaluate( + gh: Gh, repo: str, sha: str, run_id: int, own_run_id: int, base: str +) -> tuple[dict[str, Any] | None, list[str]]: + """Judge the update pull request whose CI run *run_id* went green on *sha*. + + Args: + gh: runs ``gh`` with the given arguments and returns its stdout. + repo: ``owner/name``. + sha: the head commit the run tested. + run_id: the green ``๐Ÿ”€ Pull Request`` run of that commit. + own_run_id: the run deciding the merge. + base: the branch an update pull request must target. + + Returns: + the pull request, ``None`` unless exactly one open pull request has + that head, and the reasons refusing the merge, empty when it may + merge. The stages run in order and stop at the first that refuses: + pull request, checks, deployed roles. + """ + prs = github.open_pull_requests(gh, repo, sha) + if len(prs) != 1: + return None, [f"{len(prs)} open pull requests have head {sha}, not one"] + pr = prs[0] + refusals = gate.pull_request_refusals(pr, repo, base) + if refusals: + return pr, refusals + refusals = gate.check_refusals( + github.check_runs(gh, repo, sha), github.statuses(gh, repo, sha), own_run_id + ) + if refusals: + return pr, refusals + changed = gate.changed_roles(github.changed_paths(gh, repo, pr["number"])) + csv_texts = github.role_runtime_csvs(gh, repo, run_id) if changed else [] + return pr, gate.role_refusals(changed, csv_texts) + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description=( + "Decide whether an update pull request merges itself: a bot opened " + "it, it carries the update label, every check on its head is green " + "and CI deployed every role it changes." + ) + ) + parser.add_argument("--repo", required=True, help="owner/name") + parser.add_argument("--sha", required=True, help="Head commit the CI run tested") + parser.add_argument("--run-id", required=True, type=int, help="Green CI run id") + parser.add_argument( + "--own-run-id", required=True, type=int, help="Run id deciding the merge" + ) + parser.add_argument("--base", required=True, help="Branch the PR must target") + parser.add_argument( + "--output", + required=True, + type=Path, + help="File the merge, pr and sha step outputs are appended to", + ) + args = parser.parse_args(argv) + if not _SHA.fullmatch(args.sha): + parser.error(f"--sha is no full commit SHA: {args.sha!r}") + + pr, refusals = evaluate( + github.run_gh, args.repo, args.sha, args.run_id, args.own_run_id, args.base + ) + merge = pr is not None and not refusals + label = f"#{pr['number']}" if pr is not None else args.sha + if merge: + print(f"{label} merges: checks green, every changed role deployed.") + else: + print(f"{label} stays open for a manual merge:") + for reason in refusals: + print(f"- {reason}") + with args.output.open("a", encoding="utf-8") as handle: + handle.write(f"merge={'true' if merge else 'false'}\n") + if merge: + handle.write(f"pr={pr['number']}\nsha={args.sha}\n") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/cli/contributing/update/merge/gate.py b/cli/contributing/update/merge/gate.py new file mode 100644 index 0000000000..7bc0051116 --- /dev/null +++ b/cli/contributing/update/merge/gate.py @@ -0,0 +1,154 @@ +"""Decide whether an update pull request has earned an automatic merge. + +Each check returns the reasons that refuse the merge; an empty list passes it. +""" + +from __future__ import annotations + +import csv +import io +import re +from typing import TYPE_CHECKING, Any + +from cli.contributing.update.label import UPDATE + +if TYPE_CHECKING: + from collections.abc import Iterable, Mapping + +BOT_BRANCH_PREFIXES = { + "infinito-nexus-updater[bot]": "update/", + "dependabot[bot]": "dependabot/", +} +GREEN_CONCLUSIONS = frozenset({"success", "skipped", "neutral"}) +ROLE_COLUMN = "role" +_ROLE_PATH = re.compile(r"^roles/(?P[^/]+)/") + + +def pull_request_refusals(pr: Mapping[str, Any], repo: str, base: str) -> list[str]: + """Why *pr* is no update pull request a bot may merge. + + Args: + pr: the pull request as the REST API returns it. + repo: ``owner/name`` the head branch must live in. + base: the branch the pull request must target. + + Returns: + one line per unmet condition: an author outside the update bots, a + head branch outside that bot's prefix or repository, a draft, another + base branch, a missing ``update`` label. + """ + refusals: list[str] = [] + author = pr["user"]["login"] + head = pr["head"]["ref"] + prefix = BOT_BRANCH_PREFIXES.get(author) + if prefix is None: + refusals.append(f"author {author} is no update bot") + elif not head.startswith(prefix): + refusals.append(f"branch {head} lacks the {prefix} prefix of {author}") + head_repo = pr["head"]["repo"] + if head_repo is None or head_repo["full_name"] != repo: + refusals.append(f"head branch {head} lives outside {repo}") + if pr["draft"]: + refusals.append("pull request is a draft") + if pr["base"]["ref"] != base: + refusals.append(f"base branch is {pr['base']['ref']}, not {base}") + if UPDATE.name not in {label["name"] for label in pr["labels"]}: + refusals.append(f"label {UPDATE.name} is missing") + return refusals + + +def check_refusals( + check_runs: Iterable[Mapping[str, Any]], + statuses: Iterable[Mapping[str, Any]], + own_run_id: int, +) -> list[str]: + """Why the checks on the head commit are not all green. + + Args: + check_runs: the commit's latest check runs, each with ``name``, + ``status``, ``conclusion`` and ``details_url``. + statuses: the commit's latest status per context, each with + ``context`` and ``state``. + own_run_id: the run deciding the merge; its own check runs are still + in progress and do not count. + + Returns: + one line per check run that has not completed as success, skipped or + neutral, one per status that is not success, and one when no check + run is left to judge. + """ + own = f"/actions/runs/{own_run_id}/" + refusals: list[str] = [] + judged = 0 + for run in check_runs: + if own in (run["details_url"] or ""): + continue + judged += 1 + if run["status"] != "completed": + refusals.append(f"check {run['name']} is {run['status']}") + elif run["conclusion"] not in GREEN_CONCLUSIONS: + refusals.append(f"check {run['name']} concluded {run['conclusion']}") + if not judged: + refusals.append("no check run on the head commit") + refusals.extend( + f"status {status['context']} is {status['state']}" + for status in statuses + if status["state"] != "success" + ) + return refusals + + +def changed_roles(paths: Iterable[str]) -> set[str]: + """The roles whose files *paths* touch. + + Args: + paths: repository-relative paths, old names of renamed files included. + + Returns: + ```` of every ``roles//...`` path. + """ + return {match["role"] for path in paths if (match := _ROLE_PATH.match(path))} + + +def deployed_roles(csv_texts: Iterable[str]) -> set[str]: + """The roles the deploy rows ran, read from ``role-runtimes-*`` CSVs. + + The CSVs come out of a pull request's CI run, so they are parsed as data + and their values only ever compared, never executed or used as paths. + + Args: + csv_texts: the text of each CSV ``cli.meta.ci.roles.runtime`` wrote. + + Returns: + every non-empty value of the ``role`` column, dependencies included. + """ + roles: set[str] = set() + for text in csv_texts: + for row in csv.DictReader(io.StringIO(text)): + role = (row.get(ROLE_COLUMN) or "").strip() + if role: + roles.add(role) + return roles + + +def role_refusals(changed: set[str], csv_texts: list[str]) -> list[str]: + """Why the deploy rows do not prove every changed role. + + Args: + changed: the roles the pull request changes. + csv_texts: the ``role-runtimes-*`` CSVs of the pull request's CI run. + + Returns: + nothing when no role changed; one line when no CSV was uploaded, + since an upload that found no file is silent; otherwise one line per + changed role no deploy row ran. + """ + if not changed: + return [] + if not csv_texts: + return [f"no role-runtimes artifact proves {', '.join(sorted(changed))}"] + deployed = deployed_roles(csv_texts) + return [ + f"role {role} changed, but no deploy row ran it" + for role in sorted(changed - deployed) + ] diff --git a/cli/contributing/update/merge/github.py b/cli/contributing/update/merge/github.py new file mode 100644 index 0000000000..b8fba0b6b2 --- /dev/null +++ b/cli/contributing/update/merge/github.py @@ -0,0 +1,137 @@ +"""Read what the merge gate judges from the GitHub REST API through ``gh``.""" + +from __future__ import annotations + +import io +import json +import subprocess +import zipfile +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + Gh = Callable[[Sequence[str]], bytes] + +GH_TIMEOUT_SECONDS = 120 +ROLE_RUNTIMES_PREFIX = "role-runtimes-" +MAX_ARTIFACT_BYTES = 16 * 1024 * 1024 +MAX_CSV_BYTES = 4 * 1024 * 1024 + + +def run_gh(args: Sequence[str]) -> bytes: + return subprocess.run( + ["gh", *args], + capture_output=True, + check=True, + timeout=GH_TIMEOUT_SECONDS, + ).stdout + + +def items(gh: Gh, path: str, jq: str) -> list[dict[str, Any]]: + """Every object a paginated REST list yields through *jq*. + + Args: + gh: runs ``gh`` with the given arguments and returns its stdout. + path: the REST path, query string included. + jq: a filter emitting one JSON object per item. + + Returns: + the objects, across all pages. + """ + out = gh(["api", "--paginate", path, "--jq", jq]).decode("utf-8") + return [json.loads(line) for line in out.splitlines() if line.strip()] + + +def open_pull_requests(gh: Gh, repo: str, sha: str) -> list[dict[str, Any]]: + """The open pull requests whose head commit is *sha*.""" + return [ + pr + for pr in items(gh, f"repos/{repo}/commits/{sha}/pulls?per_page=100", ".[]") + if pr["state"] == "open" and pr["head"]["sha"] == sha + ] + + +def check_runs(gh: Gh, repo: str, sha: str) -> list[dict[str, Any]]: + """The latest check run per name on *sha*.""" + return items( + gh, + f"repos/{repo}/commits/{sha}/check-runs?filter=latest&per_page=100", + ".check_runs[] | {name, status, conclusion, details_url}", + ) + + +def statuses(gh: Gh, repo: str, sha: str) -> list[dict[str, Any]]: + """The latest commit status per context on *sha*.""" + return items( + gh, + f"repos/{repo}/commits/{sha}/status?per_page=100", + ".statuses[] | {context, state}", + ) + + +def changed_paths(gh: Gh, repo: str, number: int) -> list[str]: + """Every path pull request *number* touches, old names of renamed files included.""" + paths: list[str] = [] + for entry in items( + gh, + f"repos/{repo}/pulls/{number}/files?per_page=100", + ".[] | {filename, previous_filename}", + ): + paths.append(entry["filename"]) + if entry["previous_filename"]: + paths.append(entry["previous_filename"]) + return paths + + +def csv_members(blob: bytes) -> list[str]: + """The CSV files inside an artifact zip, read in memory. + + The zip is never extracted to disk, so its member names cannot reach a + path, and a member larger than ``MAX_CSV_BYTES`` is left out. + + Args: + blob: the artifact zip as the REST API serves it. + + Returns: + the text of each ``*.csv`` member. + """ + texts: list[str] = [] + with zipfile.ZipFile(io.BytesIO(blob)) as archive: + for member in archive.infolist(): + if member.is_dir() or not member.filename.endswith(".csv"): + continue + if member.file_size > MAX_CSV_BYTES: + continue + with archive.open(member) as handle: + data = handle.read(MAX_CSV_BYTES + 1) + if len(data) <= MAX_CSV_BYTES: + texts.append(data.decode("utf-8", errors="replace")) + return texts + + +def role_runtime_csvs(gh: Gh, repo: str, run_id: int) -> list[str]: + """The ``role-runtimes-*`` CSVs workflow run *run_id* uploaded. + + Args: + gh: runs ``gh`` with the given arguments and returns its stdout. + repo: ``owner/name``. + run_id: the pull request run whose deploy rows uploaded them. + + Returns: + the text of every CSV in every unexpired ``role-runtimes-*`` artifact + of at most ``MAX_ARTIFACT_BYTES``. + """ + texts: list[str] = [] + for artifact in items( + gh, + f"repos/{repo}/actions/runs/{run_id}/artifacts?per_page=100", + ".artifacts[] | {id, name, expired, size_in_bytes}", + ): + if not artifact["name"].startswith(ROLE_RUNTIMES_PREFIX): + continue + if artifact["expired"] or artifact["size_in_bytes"] > MAX_ARTIFACT_BYTES: + continue + blob = gh(["api", f"repos/{repo}/actions/artifacts/{artifact['id']}/zip"]) + texts.extend(csv_members(blob)) + return texts diff --git a/default.env b/default.env index 9bf1183b89..de48167700 100644 --- a/default.env +++ b/default.env @@ -139,7 +139,7 @@ INFINITO_CI_CHUNK=0 # Rows one deploy chunk holds, overriding the concurrency-times-waves derivation; 0 derives it. INFINITO_CI_CHUNK_SIZE=0 -# Runner slots a deploy chunk may assume are free; with the job timeout it sizes a chunk in cli.meta.ci.slots. +# Runner slots a deploy chunk may assume are free (cli.meta.ci.slots); a set repository variable of this name overrides it in CI. INFINITO_CI_CONCURRENCY=20 # Budget distros.sh spends before skipping the rest; stays under the 350-min step cap, which stays under the 355-min job cap. diff --git a/docs/contributing/artefact/git/pipeline.md b/docs/contributing/artefact/git/pipeline.md index 1bbe1b25a9..865aebd255 100644 --- a/docs/contributing/artefact/git/pipeline.md +++ b/docs/contributing/artefact/git/pipeline.md @@ -127,6 +127,8 @@ The `test-workspace` stage runs the workspace workflow listed in the `Infrastruc The final `done` job aggregates all deploy, install, and development gates. CI is considered green only when this job succeeds. +A green `done` does not prove a deploy, since a skipped chunk passes it too. For an update PR the green run therefore hands over to [entry-pr-green-update-merge.yml](../../../../.github/workflows/entry-pr-green-update-merge.yml), which merges only when the run's `role-runtimes-*` artifacts list every role the PR changes; see the automatic merge section of [configuration.md](../../tools/github/actions/configuration.md). + ## Concurrency ๐Ÿ”€ - PR pipelines use `cancel-in-progress: true` so only the newest run per PR and event type is active. The group does not always reap a long orchestrator sweep, which then leaves the newer run parked on `pending`; [entry-cancel-superseded.yml](../../../../.github/workflows/entry-cancel-superseded.yml) cancels those leftovers through the API, see [cancel/README.md](../../../../scripts/github/cancel/README.md). diff --git a/docs/contributing/tools/github/actions/configuration.md b/docs/contributing/tools/github/actions/configuration.md index 18fd9633bd..9e0f1d2eb5 100644 --- a/docs/contributing/tools/github/actions/configuration.md +++ b/docs/contributing/tools/github/actions/configuration.md @@ -10,7 +10,7 @@ Repository variables are set under **Settings โ†’ Secrets and variables โ†’ Acti |---|---|---|---| | `CI_SYNC_MAIN_SOURCE_REPOSITORY` | [entry-push-latest.yml](../../../../../.github/workflows/entry-push-latest.yml) | Syncs `main` from `infinito-nexus/core` before CI scope discovery | `/` to use another source, or `false`, empty, or the current repository to skip | | `CI_RUN_ON_MAIN` | [entry-push-latest.yml](../../../../../.github/workflows/entry-push-latest.yml) | Pushes to `main` skip CI | `true` to run CI on `main` pushes too | -| `CI_ENABLE_AUTO_UPDATES` | [cron-update.yml](../../../../../.github/workflows/cron-update.yml), [entry-pr-open-dependabot-close.yml](../../../../../.github/workflows/entry-pr-open-dependabot-close.yml) | Update jobs skipped; Dependabot PRs auto-closed | `true` to allow update PRs (workflow-driven and Dependabot) | +| `CI_ENABLE_AUTO_UPDATES` | [cron-update.yml](../../../../../.github/workflows/cron-update.yml), [entry-pr-open-dependabot-close.yml](../../../../../.github/workflows/entry-pr-open-dependabot-close.yml), [entry-pr-change-dependabot-label.yml](../../../../../.github/workflows/entry-pr-change-dependabot-label.yml), [entry-pr-green-update-merge.yml](../../../../../.github/workflows/entry-pr-green-update-merge.yml) | Update jobs skipped; Dependabot PRs auto-closed; no update PR is labelled or merged automatically | `true` to allow update PRs (workflow-driven and Dependabot) and their automatic merge | | `CI_ENABLE_AUTO_TRANSLATIONS` | [entry-pr-translate.yml](../../../../../.github/workflows/entry-pr-translate.yml) | Pull requests against `main` open no translation PRs | `true` to machine-translate the entries a PR leaves empty or fuzzy, one PR per language | | `PLAYWRIGHT_KEEP_ALL` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | Playwright keeps trace, screenshot and video only when a test fails | `true` to keep them for every test (passing runs included); the workflow forwards it as `INFINITO_PLAYWRIGHT_KEEP` | | `API_OPENAI_KEY` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | The gateway publishes no `openai/*` model, and the CLI test asserts their absence | An OpenAI key, to deploy and test the route | @@ -18,6 +18,7 @@ Repository variables are set under **Settings โ†’ Secrets and variables โ†’ Acti | `API_OPENROUTER_KEY` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | The gateway publishes no `openrouter/auto` model | An OpenRouter key | | `INFINITO_MAIL_PRODUCTION_HOST` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | The read-only production mail assertions are skipped, because the task that runs them is gated on this host being set | The public hostname of a deployed mail server, to assert its MX, SPF, DKIM, DMARC and PTR records and its SMTP greeting after a deploy; nothing is sent and nothing is mutated | | `INFINITO_MAIL_PRODUCTION_RESOLVER` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | Those assertions resolve through the runner's own resolver | A DNS server address, to resolve the records against it instead; ignored while `INFINITO_MAIL_PRODUCTION_HOST` is unset | +| `INFINITO_CI_CONCURRENCY` | [call-validation.yml](../../../../../.github/workflows/call-validation.yml), [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | Deploy chunks are sized from the runner slots [default.env](../../../../../default.env) declares | The jobs the account runs at once, e.g. `500` on GitHub Enterprise; once the derived chunk size exceeds the run's job budget, a sweep needs one chunk (two with a priority line) and only `INFINITO_CI_JOB_LIMIT` bounds it. Both workflows forward it, so the batch count and every chunk's cut agree | ## Provider keys: variable or secret? ๐Ÿ”‘ @@ -160,6 +161,19 @@ Dependabot cannot read repository variables itself, so [entry-pr-open-dependabot | `true` | Run โœ“ | Stay open โœ“ | | any other value | Skipped โœ“ | Auto-closed on open โœ“ | +The same guard sits on [entry-pr-change-dependabot-label.yml](../../../../../.github/workflows/entry-pr-change-dependabot-label.yml), which labels Dependabot PRs `update` plus `major`, `minor` or `patch`, and on [entry-pr-green-update-merge.yml](../../../../../.github/workflows/entry-pr-green-update-merge.yml), which merges an update PR once CI proved it. With the variable unset, neither labels nor merges anything. + +### Automatic merge ๐Ÿ”€ + +An update PR merges itself only when all of these hold; otherwise the job prints the failing condition and the PR waits for a manual merge: + +1. Its `๐Ÿ”€ Pull Request` run of the `pull_request` event concluded `success`. +2. `infinito-nexus-updater[bot]` opened it from `update/*`, or `dependabot[bot]` from `dependabot/*`, in this repository, against the default branch, not as a draft, and it carries the `update` label. +3. Every latest check run on its head commit completed as `success`, `skipped` or `neutral`, and every commit status is `success`. A check still running counts as not green; no later run retries the merge. +4. Every role under `roles//` the PR changes appears in the `role` column of a `role-runtimes-*` artifact of that run. A PR that changes no role needs no artifact; a missing artifact proves nothing. + +The merge goes through `PUT /repos/{owner}/{repo}/pulls/{number}/merge` with `merge_method=merge` and the tested head `sha`, so a commit pushed after the run makes it fail instead of merging untested code. `gh pr merge` is not used because it refuses a PR the ruleset still blocks before the server can apply the App's bypass. The App MUST be a bypass actor of the `Main` ruleset in `pull_request` mode; without that the merge step fails and the PR stays open. + ## `INFINITO_PLAYWRIGHT_KEEP` ๐ŸŽฌ Controls whether Playwright keeps trace, screenshot, and video for every test or only for failing tests in the deploy-test workflow ([call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml)). diff --git a/docs/contributing/tools/github/actions/secrets.md b/docs/contributing/tools/github/actions/secrets.md index 25a0d0398a..816df5a001 100644 --- a/docs/contributing/tools/github/actions/secrets.md +++ b/docs/contributing/tools/github/actions/secrets.md @@ -8,8 +8,8 @@ Repository secrets MUST be set under **Settings โ†’ Secrets and variables โ†’ Ac | Secret | Workflow | Purpose | Required when | |---|---|---|---| -| `BOT_APP_CLIENT_ID` | [cron-update.yml](../../../../../.github/workflows/cron-update.yml) | GitHub App Client ID (OAuth-style `Ivโ€ฆ` identifier shown on the App's General page) used to mint a short-lived installation token for the update PR. | `CI_ENABLE_AUTO_UPDATES == 'true'` | -| `BOT_APP_PRIVATE_KEY` | [cron-update.yml](../../../../../.github/workflows/cron-update.yml) | PEM-encoded private key of the same GitHub App. Used to sign the JWT that exchanges for the installation token. | `CI_ENABLE_AUTO_UPDATES == 'true'` | +| `BOT_APP_CLIENT_ID` | [cron-update.yml](../../../../../.github/workflows/cron-update.yml), [entry-pr-green-update-merge.yml](../../../../../.github/workflows/entry-pr-green-update-merge.yml) | GitHub App Client ID (OAuth-style `Ivโ€ฆ` identifier shown on the App's General page) used to mint a short-lived installation token for the update PR and for its automatic merge. | `CI_ENABLE_AUTO_UPDATES == 'true'` | +| `BOT_APP_PRIVATE_KEY` | [cron-update.yml](../../../../../.github/workflows/cron-update.yml), [entry-pr-green-update-merge.yml](../../../../../.github/workflows/entry-pr-green-update-merge.yml) | PEM-encoded private key of the same GitHub App. Used to sign the JWT that exchanges for the installation token. | `CI_ENABLE_AUTO_UPDATES == 'true'` | | `API_OPENAI_KEY` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | Publishes the `openai/*` models on the LiteLLM gateway and lets the CLI test exercise the route. | Never. Unset leaves the route unpublished. | | `API_ANTHROPIC_KEY` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | Publishes the `anthropic/*` models. | Never. | | `API_OPENROUTER_KEY` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | Publishes `openrouter/auto`. | Never. | @@ -99,6 +99,8 @@ A classic personal access token MAY be used as a fallback for unrelated automati Each PR-opening job in [cron-update.yml](../../../../../.github/workflows/cron-update.yml) runs an `actions/create-github-app-token@v2` step gated on `steps.diff.outputs.changed == 'true'`, then forwards the minted token as `GH_TOKEN` and the resolved `APP_SLUG` to the subsequent PR step. The job's `permissions:` block keeps the workflow-provided `GITHUB_TOKEN` read-only; write access is provided exclusively by the App token, scoped to the App's repository permissions. +[entry-pr-green-update-merge.yml](../../../../../.github/workflows/entry-pr-green-update-merge.yml) mints the App token only after its merge gate passed, and uses it for the merge call alone; the gate itself reads with the read-only `GITHUB_TOKEN`. Merging needs the App's `Contents` and `Pull requests` write permissions plus a bypass of the `Main` ruleset; a PR that changes `.github/workflows/` additionally needs `Workflows`: **Read and write**, or its merge fails and it stays open. + ### Commit identity propagation ๐Ÿชช [pr.sh](../../../../../scripts/github/update/open/pr.sh) reads `APP_SLUG` from the environment and resolves the App's bot user via `gh api /users/[bot]`. The resolved login and numeric user ID are written into `git config user.name` and `git config user.email` in the `+[bot]@users.noreply.github.com` form that GitHub accepts for verified commits. When `APP_SLUG` is unset, the script falls back to the `github-actions[bot]` identity. That branch is reached only when the script is invoked outside the workflow, for example a local smoke test where the caller has set `GH_TOKEN` to something other than an App token. diff --git a/docs/contributing/tools/github/actions/workflows.md b/docs/contributing/tools/github/actions/workflows.md index 5a826a3a23..d3063aa350 100644 --- a/docs/contributing/tools/github/actions/workflows.md +++ b/docs/contributing/tools/github/actions/workflows.md @@ -86,6 +86,8 @@ Trigger column legend: **auto** = fires automatically (push, pull_request, sched | [cron-update.yml](../../../../../.github/workflows/cron-update.yml): `๐Ÿ”„ Update versions` | Updates Docker image versions and other pinned dependencies; opens an update PR via a GitHub App installation token so PR-lifecycle events fire on the resulting PR. Both jobs are gated behind the `CI_ENABLE_AUTO_UPDATES` repository variable, see [configuration.md](configuration.md). Requires the `BOT_APP_CLIENT_ID` and `BOT_APP_PRIVATE_KEY` repository secrets, see [secrets.md](secrets.md). | auto (`push` to `main`, `schedule`: daily 00:30 UTC), manual | none | | [entry-pr-translate.yml](../../../../../.github/workflows/entry-pr-translate.yml): `๐ŸŒ Translate catalogs` | Merges the source strings of the `core` and `docs` domains into `locale/`, then machine-translates what a pull request leaves empty or fuzzy, one runner per language LibreTranslate supports. Each runner opens its own PR against the head branch of the triggering PR. Gated behind the `CI_ENABLE_AUTO_TRANSLATIONS` repository variable, see [configuration.md](configuration.md); pull requests from a fork are skipped. Requires the `BOT_APP_CLIENT_ID` and `BOT_APP_PRIVATE_KEY` repository secrets, see [secrets.md](secrets.md). | auto (`pull_request` against `main`: opened, synchronize, reopened) | none | | [entry-pr-open-dependabot-close.yml](../../../../../.github/workflows/entry-pr-open-dependabot-close.yml): `๐Ÿšซ Dependabot: Close while auto-updates disabled` | Auto-closes Dependabot PRs while `CI_ENABLE_AUTO_UPDATES` is not set to `true`, so Dependabot honours the same gate as the workflow-driven update jobs. See [configuration.md](configuration.md). | auto (`pull_request_target`: opened, reopened) | none | +| [entry-pr-change-dependabot-label.yml](../../../../../.github/workflows/entry-pr-change-dependabot-label.yml): `๐Ÿ”„ Dependabot: Label update level` | Labels every Dependabot PR `update` plus exactly one of `major`, `minor` and `patch`, read from the `update-type` of `dependabot/fetch-metadata`; a type that names no semver level counts as `major`. Creates a missing label, adds only labels the PR lacks and checks out the base branch only. Gated behind `CI_ENABLE_AUTO_UPDATES`, see [configuration.md](configuration.md). | auto (`pull_request_target`: opened, reopened, synchronize) | none | +| [entry-pr-green-update-merge.yml](../../../../../.github/workflows/entry-pr-green-update-merge.yml): `๐Ÿ”„ Update: Merge proven PRs` | Runs when a `๐Ÿ”€ Pull Request` run of the `pull_request` event succeeds on an `update/*` or `dependabot/*` branch. [cli.contributing.update.merge](../../../../../cli/contributing/update/merge/__main__.py) merges the PR only when the `infinito-nexus-updater[bot]` App or `dependabot[bot]` opened it, it carries `update`, every check run and commit status on its head is green, and the run's `role-runtimes-*` artifacts list every role the PR changes. Otherwise it prints why and the PR stays open for a manual merge. The merge pins the tested head and uses the App token, so the App MUST be a bypass actor of the `Main` ruleset. Gated behind `CI_ENABLE_AUTO_UPDATES`, see [configuration.md](configuration.md); requires the `BOT_APP_CLIENT_ID` and `BOT_APP_PRIVATE_KEY` repository secrets, see [secrets.md](secrets.md). | auto (`workflow_run` of `๐Ÿ”€ Pull Request`: completed) | none | ## Changing workflows โœ๏ธ diff --git a/roles/dsk-gnt-claude/meta/services.yml b/roles/dsk-gnt-claude/meta/services.yml index 4b1a036aae..03be74f17d 100644 --- a/roles/dsk-gnt-claude/meta/services.yml +++ b/roles/dsk-gnt-claude/meta/services.yml @@ -9,7 +9,7 @@ claude: host: enabled: true lifecycle: alpha - npm_version: 2.1.329 + npm_version: 2.1.330 update: key: npm_version type: npm diff --git a/roles/dsk-gnt-pi/meta/services.yml b/roles/dsk-gnt-pi/meta/services.yml index 739567b37b..77f36b0fb1 100644 --- a/roles/dsk-gnt-pi/meta/services.yml +++ b/roles/dsk-gnt-pi/meta/services.yml @@ -9,7 +9,7 @@ pi: host: enabled: true lifecycle: alpha - npm_version: 1.5.2 + npm_version: 1.6.0 update: key: npm_version type: npm diff --git a/roles/svc-ai-ltengine/meta/services.yml b/roles/svc-ai-ltengine/meta/services.yml index 9b8091c72a..b2e2662f64 100644 --- a/roles/svc-ai-ltengine/meta/services.yml +++ b/roles/svc-ai-ltengine/meta/services.yml @@ -36,7 +36,7 @@ ltengine: custom: true gpu: true repository: https://github.com/LibreTranslate/LTEngine - ref: 3fa19f8b6d3eecbacbdbf79406e0f877ebe11e26 + ref: v0.1.1 # nocheck: min-storage-headroom Reason: the CUDA runtime base the binary is built on, plus the GGUF weights the server downloads into its models volume on first start min_storage: 5GB model: gemma3-1b diff --git a/roles/svc-ai-mcp-adapter/README.md b/roles/svc-ai-mcp-adapter/README.md index fa2eda928f..789559fb58 100644 --- a/roles/svc-ai-mcp-adapter/README.md +++ b/roles/svc-ai-mcp-adapter/README.md @@ -47,6 +47,8 @@ The deployment renders one `ADAPTER_CONTRACT` JSON document per instance: `files/python/policy.py` validates it at startup. A contract missing a limit, carrying an empty allowlist, naming a wildcard path or lacking a pinned schema hash is refused before the process serves anything. +An optional `upstream_host` is sent as the `Host` header of every upstream request, for a provider that answers only its canonical domain; without it the request carries the host of `upstream_url`. + ## Endpoints | Path | Method | Purpose | diff --git a/roles/svc-ai-mcp-adapter/files/python/policy.py b/roles/svc-ai-mcp-adapter/files/python/policy.py index b527da2b6c..d9f606be43 100644 --- a/roles/svc-ai-mcp-adapter/files/python/policy.py +++ b/roles/svc-ai-mcp-adapter/files/python/policy.py @@ -63,6 +63,8 @@ DURATION_UNITS = { READ_METHODS = frozenset({"GET", "HEAD"}) +HOST_PATTERN = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?(?::[0-9]{1,5})?") + class ContractError(ValueError): """The rendered contract is not one this adapter may serve.""" @@ -92,6 +94,30 @@ def upstream_url(base: str, path_key: str = "", path_suffix: str = "") -> str: return "/".join(parts) +def upstream_host(contract: Mapping[str, Any]) -> str: + """ + Args: + contract: the loaded contract. + + Returns: + ``upstream_host`` as declared, or "" when the contract declares none + and the request keeps the host of ``upstream_url``. + + Raises: + ContractError: ``upstream_host`` is declared but is not a host name, + optionally followed by a port. + """ + host = contract.get("upstream_host") + if host is None: + return "" + if not isinstance(host, str) or not HOST_PATTERN.fullmatch(host): + raise ContractError( + f"contract upstream_host {host!r} must be a host name, " + f"optionally followed by a port" + ) + return host + + def load_contract(raw: str) -> dict[str, Any]: """Return the validated adapter contract. @@ -146,6 +172,8 @@ def load_contract(raw: str) -> dict[str, Any]: if not str(contract.get("schema_sha256") or "").startswith(SHA256_PREFIX): raise ContractError("contract must pin tools.schema_sha256") + upstream_host(contract) + return contract @@ -363,6 +391,23 @@ def authorize_call( return method, str(spec["path"]) +def request_length(header: str | None) -> int: + """ + Args: + header: the raw ``Content-Length`` value, ``None`` when the client sent + none. + + Returns: + the announced body size in bytes; ``0`` without a header, since RFC 9112 + reads such a request as bodiless; a negative number when the value is + negative or no integer. + """ + try: + return int(header or 0) + except ValueError: + return -1 + + def clamp_page(contract: Mapping[str, Any], requested: Any) -> int: """Return a page size no larger than the contract allows. diff --git a/roles/svc-ai-mcp-adapter/files/python/server.py b/roles/svc-ai-mcp-adapter/files/python/server.py index b3b1d01468..420070bd88 100644 --- a/roles/svc-ai-mcp-adapter/files/python/server.py +++ b/roles/svc-ai-mcp-adapter/files/python/server.py @@ -61,6 +61,7 @@ UPSTREAM_URL = policy.upstream_url( os.environ.get("ADAPTER_UPSTREAM_PATH_KEY", ""), os.environ.get("ADAPTER_UPSTREAM_PATH_SUFFIX", ""), ) +UPSTREAM_HOST = policy.upstream_host(CONTRACT) PORT = int(os.environ["ADAPTER_PORT"]) policy.assert_no_drift(CONTRACT) @@ -82,6 +83,30 @@ def log(event): sys.stdout.flush() +def upstream_headers(): + """ + Returns: + ``Host`` when the contract declares ``upstream_host``, then the + credential header when ``ADAPTER_UPSTREAM_KEY`` is set, in that order. + """ + headers = {} + if UPSTREAM_HOST: + headers["Host"] = UPSTREAM_HOST + if UPSTREAM_KEY: + headers[UPSTREAM_AUTH_HEADER] = UPSTREAM_AUTH_FORMAT.format(key=UPSTREAM_KEY) + return headers + + +def add_upstream_headers(request): + """ + Args: + request: the ``urllib.request.Request`` that receives + :func:`upstream_headers`. + """ + for name, value in upstream_headers().items(): + request.add_header(name, value) + + def call_upstream(method, path, arguments): """Return the upstream response body for one authorised tool call. @@ -107,10 +132,7 @@ def call_upstream(method, path, arguments): f"{UPSTREAM_URL}{resolved}", method=method ) request.add_header("Accept", "application/json") - if UPSTREAM_KEY: - request.add_header( - UPSTREAM_AUTH_HEADER, UPSTREAM_AUTH_FORMAT.format(key=UPSTREAM_KEY) - ) + add_upstream_headers(request) with OPENER.open( request, timeout=CONTRACT["limits"]["timeout_seconds"] @@ -147,10 +169,7 @@ def post_upstream(envelope): request.add_header("MCP-Protocol-Version", PROTOCOL_VERSION) if UPSTREAM_SESSION["id"]: request.add_header(SESSION_HEADER, UPSTREAM_SESSION["id"]) - if UPSTREAM_KEY: - request.add_header( - UPSTREAM_AUTH_HEADER, UPSTREAM_AUTH_FORMAT.format(key=UPSTREAM_KEY) - ) + add_upstream_headers(request) with OPENER.open( request, timeout=CONTRACT["limits"]["timeout_seconds"] @@ -174,14 +193,9 @@ def sse_session(): adapter rather than being reopened per call. """ if SSE["session"] is None: - headers = {} - if UPSTREAM_KEY: - headers[UPSTREAM_AUTH_HEADER] = UPSTREAM_AUTH_FORMAT.format( - key=UPSTREAM_KEY - ) SSE["session"] = sse.SseSession( UPSTREAM_URL, - headers=headers, + headers=upstream_headers(), timeout=CONTRACT["limits"]["timeout_seconds"], ).open() return SSE["session"] @@ -399,7 +413,10 @@ class Handler(BaseHTTPRequestHandler): self._respond(401, {"error": policy.DENY_UNAUTHENTICATED}) return - length = int(self.headers.get("Content-Length") or 0) + length = policy.request_length(self.headers.get("Content-Length")) + if length < 0: + self._respond(400, {"error": "invalid_content_length"}) + return if length > CONTRACT["limits"]["request_bytes"]: self._respond(413, {"error": policy.DENY_REQUEST_TOO_LARGE}) return diff --git a/roles/web-app-discourse/meta/addons/discourse-activity-pub.yml b/roles/web-app-discourse/meta/addons/discourse-activity-pub.yml index 5e0c01dc53..4b562f4960 100644 --- a/roles/web-app-discourse/meta/addons/discourse-activity-pub.yml +++ b/roles/web-app-discourse/meta/addons/discourse-activity-pub.yml @@ -12,4 +12,4 @@ update: upstream_id: discourse-activity-pub config: repository: https://github.com/discourse/discourse-activity-pub.git - ref: d89d1b0131bbce4dc4102b1409f797be39b41961 + ref: bc08202aa94cdb74159c0aec1e3d2c47b88a8f66 diff --git a/roles/web-app-mattermost/files/playwright/test-design.js b/roles/web-app-mattermost/files/playwright/test-design.js index 2403418d9f..070eee6866 100644 --- a/roles/web-app-mattermost/files/playwright/test-design.js +++ b/roles/web-app-mattermost/files/playwright/test-design.js @@ -31,7 +31,9 @@ const POSTS = "#post-list"; const POST = `${POSTS} .post:not(.post--system)`; const CONTENT = "#app-content"; const HEADER = "#global-header"; -const HEADER_LOGO = `${HEADER} [aria-controls='product-switcher-menu'] > span > svg`; +const PRODUCT_MENU_BUTTON = "#switchProductMenuButton"; +const PRODUCT_MENU = "#switchProductMenu"; +const HEADER_LOGO = `${HEADER} ${PRODUCT_MENU_BUTTON} > span > svg`; const SIDEBAR = "#SidebarContainer"; const SETTINGS = "#accountSettingsModal"; const THEMES = "#premadeThemesSection"; @@ -278,8 +280,8 @@ exports.register = function (shared) { await page.locator("#navbar .navbar-toggle").first().click(); await settled(page, SIDEBAR); } else { - await page.locator("#product_switch_menu").click(); - await settled(page, "#product-switcher-menu-dropdown"); + await page.locator(PRODUCT_MENU_BUTTON).click(); + await settled(page, PRODUCT_MENU); } }), view("settings-notifications", showcase, openSettings), @@ -390,7 +392,7 @@ exports.register = function (shared) { await loaded(EDITOR)(page); const onFrame = await tokenValue(page, "--design-on-frame", "color"); const seen = []; - await page.locator(`${HEADER} #product_switch_menu`).focus(); + await page.locator(`${HEADER} ${PRODUCT_MENU_BUTTON}`).focus(); for (let step = 0; step < 24; step += 1) { await page.keyboard.press("Tab"); const stop = await page.evaluate( diff --git a/roles/web-app-mattermost/meta/services.yml b/roles/web-app-mattermost/meta/services.yml index 947be002df..c7eb89313e 100644 --- a/roles/web-app-mattermost/meta/services.yml +++ b/roles/web-app-mattermost/meta/services.yml @@ -50,7 +50,7 @@ mattermost: version: 13.7-slim custom: true repository: https://github.com/mattermost/mattermost.git - ref: v11.11.4 + ref: v12.1.0 min_storage: 659MB backup: stop_required: false diff --git a/roles/web-app-mattermost/templates/style.css.j2 b/roles/web-app-mattermost/templates/style.css.j2 index 0ac08d079c..4298f5460e 100644 --- a/roles/web-app-mattermost/templates/style.css.j2 +++ b/roles/web-app-mattermost/templates/style.css.j2 @@ -4595,9 +4595,6 @@ html:not([data-design-app-theme="custom"]) .Menu .dropdown-menu li a { html:not([data-design-app-theme="custom"]) .Menu .styleSelectableItem .sorting-menu-checkbox i { color: var(--button-bg); } -html:not([data-design-app-theme="custom"]) .Menu>.product-switcher-menu .MenuItem a .icon { - color: rgba(var(--center-channel-color-rgb), 0.64); -} @media screen and (max-width: 768px) { html:not([data-design-app-theme="custom"]) #submenuModal .mobile-sub-menu .modal-content .modal-body .MenuWrapper .Menu.dropdown-menu .MenuGroup.menu-divider { background-color: var(--design-surface-2); @@ -9029,7 +9026,7 @@ html:not([data-design-app-theme="custom"]) body .header-footer-route .header-foo } {% if design.logo is string %} -html:not([data-design-app-theme="custom"]) body #global-header [aria-controls="product-switcher-menu"] > span > svg { +html:not([data-design-app-theme="custom"]) body #global-header #switchProductMenuButton > span > svg { width: {{ (24 * design.slots['logo-frame'].width / design.slots['logo-frame'].height) | round | int }}px; height: 24px; background: url("{{ design.urls['logo-frame'].svg }}") left center / contain no-repeat; @@ -9041,7 +9038,7 @@ body .hfroute-header .header-main .header-logo-link > svg { background: url("{{ design.urls.logo.svg }}") left center / contain no-repeat; } -html:not([data-design-app-theme="custom"]) body #global-header [aria-controls="product-switcher-menu"] > span > svg > *, +html:not([data-design-app-theme="custom"]) body #global-header #switchProductMenuButton > span > svg > *, body .hfroute-header .header-logo-link > svg > * { visibility: hidden; } diff --git a/roles/web-app-meta/meta/services.yml b/roles/web-app-meta/meta/services.yml index 58a824671b..44062a07fc 100644 --- a/roles/web-app-meta/meta/services.yml +++ b/roles/web-app-meta/meta/services.yml @@ -36,7 +36,7 @@ meta: swarm: enabled: true image: ghcr.io/infinito-nexus/meta - version: 2.1.0 + version: 2.2.0 name: meta min_storage: 1040MB ports: diff --git a/roles/web-app-snipe-it/files/custom_css.css b/roles/web-app-snipe-it/files/custom_css.css deleted file mode 100644 index 77fb1f7306..0000000000 --- a/roles/web-app-snipe-it/files/custom_css.css +++ /dev/null @@ -1,50 +0,0 @@ -html[data-theme] { - --color-bg: var(--design-surface-1); - --color-fg: var(--design-text); - --header-color: var(--design-text); - --box-bg: var(--design-surface-2); - --table-stripe-bg: var(--design-surface-2); - --table-stripe-bg-alt: var(--design-surface-3); - --input-group-bg: var(--design-surface-3); - --input-group-fg: var(--design-text); - --callout-bg-color: var(--design-surface-3); - --callout-left-border: var(--design-border-strong); - --main-footer-bg-color: var(--design-surface-2); - --main-footer-text-color: var(--design-text-muted); - --main-footer-top-border-color: var(--design-border); - --text-help: var(--design-text-muted); - --text-legend-help: var(--design-text-muted); - --text-danger: var(--design-danger); - --text-info: var(--design-info); - --text-success: var(--design-success); - --text-warning: var(--design-warning); - --link-hover: var(--design-link); - --table-border-row-color: var(--design-border); - --table-border-row-top: 1px solid var(--design-border); - --table-border-row: 1px solid var(--design-border); - --box-header-bottom-border-color: var(--design-border); - --box-header-bottom-border: 1px solid var(--design-border); - --box-header-top-border-color: var(--design-border); - --box-header-top-border: 3px solid var(--design-border); - --tab-bottom-border: 1px solid var(--design-border); - --default-label-link-bg: var(--design-surface-1); - --default-label-link-border: 1px solid var(--design-border); - --input-border-color: var(--design-border-strong); - --search-highlight: var(--design-warning-subtle); - --main-theme-color: var(--design-frame); - --main-theme-hover: var(--design-frame-hover); - --btn-theme-base: var(--design-frame); - --btn-theme-border: var(--design-frame-active); - --btn-theme-hover: var(--design-frame-hover); - --sidenav-hover-color-bg: var(--design-frame-active); - --sidenav-text-hover-color: var(--design-on-frame); - --sidenav-text-nohover-color: var(--design-on-frame); -} -html[data-theme] .fc { - --fc-border-color: var(--design-border); - --fc-page-bg-color: var(--design-surface-2); - --fc-neutral-bg-color: var(--design-surface-3); - --fc-neutral-text-color: var(--design-text); - --fc-list-event-hover-bg-color: var(--design-surface-hover); - --fc-today-bg-color: var(--design-surface-active); -} diff --git a/roles/web-app-snipe-it/files/php/apply/design_config.php b/roles/web-app-snipe-it/files/php/apply/design_config.php index f3ef6349b0..8b17e99c22 100644 --- a/roles/web-app-snipe-it/files/php/apply/design_config.php +++ b/roles/web-app-snipe-it/files/php/apply/design_config.php @@ -40,7 +40,7 @@ if ($wanted !== []) { $target[$field] = $name; } $block = OPEN . " infinito-design:" . base64_encode(json_encode($previous)) . " " . CLOSE . "\n" - . $wanted["custom_css"] . "\n" . OPEN . " /infinito-design " . CLOSE . "\n"; + . OPEN . " /infinito-design " . CLOSE . "\n"; } $target["custom_css"] = $block . $foreign === "" ? null : $block . $foreign; diff --git a/roles/web-app-snipe-it/files/php/provision_mcp_identity.php b/roles/web-app-snipe-it/files/php/provision_mcp_identity.php index 18feec12ca..95a8f4d454 100644 --- a/roles/web-app-snipe-it/files/php/provision_mcp_identity.php +++ b/roles/web-app-snipe-it/files/php/provision_mcp_identity.php @@ -18,6 +18,7 @@ * MCP_PASSWORD: password to pin on it. * MCP_TOKEN_NAME: personal access token name to converge. * MCP_CURRENT_TOKEN: token the adapter holds today, or "" for none. + * MCP_API_HOST: APP_URL host the loopback API probe sends as Host. */ // nocheck: mirrored-unit-test - boots Snipe-IT's Laravel kernel through @@ -35,6 +36,11 @@ $username = getenv("MCP_USER"); $password = getenv("MCP_PASSWORD"); $tokenName = getenv("MCP_TOKEN_NAME"); $currentToken = trim((string) getenv("MCP_CURRENT_TOKEN")); +$apiHost = trim((string) getenv("MCP_API_HOST")); +if ($apiHost === "") { + fwrite(STDERR, "MCP_API_HOST is not set\n"); + exit(1); +} $permissions = json_encode([ "self.api" => "1", @@ -42,12 +48,13 @@ $permissions = json_encode([ "licenses.view" => "1", ]); -function apiStatus(string $token): int +function apiStatus(string $token, string $host): int { $probe = curl_init("http://127.0.0.1/api/v1/hardware?limit=1"); curl_setopt_array($probe, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ + "Host: " . $host, "Authorization: Bearer " . $token, "Accept: application/json", ], @@ -57,7 +64,7 @@ function apiStatus(string $token): int return (int) curl_getinfo($probe, CURLINFO_HTTP_CODE); } -if ($currentToken !== "" && apiStatus($currentToken) === 200) { +if ($currentToken !== "" && apiStatus($currentToken, $apiHost) === 200) { echo "UNCHANGED\n"; echo $currentToken . "\n"; exit(0); @@ -118,7 +125,7 @@ $changed = $changed || $revoked > 0; $token = $user->createToken($tokenName)->accessToken; -$status = apiStatus($token); +$status = apiStatus($token, $apiHost); if ($status !== 200) { fwrite(STDERR, "Snipe-IT's own API answered {$status} to the token it just minted\n"); exit(1); diff --git a/roles/web-app-snipe-it/files/style.css b/roles/web-app-snipe-it/files/style.css index 72826e5ca9..bc7a0b7b2e 100644 --- a/roles/web-app-snipe-it/files/style.css +++ b/roles/web-app-snipe-it/files/style.css @@ -1,3 +1,53 @@ +html[data-theme] { + --color-bg: var(--design-surface-1); + --color-fg: var(--design-text); + --header-color: var(--design-text); + --box-bg: var(--design-surface-2); + --table-stripe-bg: var(--design-surface-2); + --table-stripe-bg-alt: var(--design-surface-3); + --input-group-bg: var(--design-surface-3); + --input-group-fg: var(--design-text); + --callout-bg-color: var(--design-surface-3); + --callout-left-border: var(--design-border-strong); + --main-footer-bg-color: var(--design-surface-2); + --main-footer-text-color: var(--design-text-muted); + --main-footer-top-border-color: var(--design-border); + --text-help: var(--design-text-muted); + --text-legend-help: var(--design-text-muted); + --text-danger: var(--design-danger); + --text-info: var(--design-info); + --text-success: var(--design-success); + --text-warning: var(--design-warning); + --link-hover: var(--design-link); + --table-border-row-color: var(--design-border); + --table-border-row-top: 1px solid var(--design-border); + --table-border-row: 1px solid var(--design-border); + --box-header-bottom-border-color: var(--design-border); + --box-header-bottom-border: 1px solid var(--design-border); + --box-header-top-border-color: var(--design-border); + --box-header-top-border: 3px solid var(--design-border); + --tab-bottom-border: 1px solid var(--design-border); + --default-label-link-bg: var(--design-surface-1); + --default-label-link-border: 1px solid var(--design-border); + --input-border-color: var(--design-border-strong); + --search-highlight: var(--design-warning-subtle); + --main-theme-color: var(--design-frame); + --main-theme-hover: var(--design-frame-hover); + --btn-theme-base: var(--design-frame); + --btn-theme-border: var(--design-frame-active); + --btn-theme-hover: var(--design-frame-hover); + --sidenav-hover-color-bg: var(--design-frame-active); + --sidenav-text-hover-color: var(--design-on-frame); + --sidenav-text-nohover-color: var(--design-on-frame); +} +html[data-theme] .fc { + --fc-border-color: var(--design-border); + --fc-page-bg-color: var(--design-surface-2); + --fc-neutral-bg-color: var(--design-surface-3); + --fc-neutral-text-color: var(--design-text); + --fc-list-event-hover-bg-color: var(--design-surface-hover); + --fc-today-bg-color: var(--design-surface-active); +} .main-header, .main-sidebar, .basic-page-header { diff --git a/roles/web-app-snipe-it/meta/services.yml b/roles/web-app-snipe-it/meta/services.yml index 5f6908c819..09ff84b6b2 100644 --- a/roles/web-app-snipe-it/meta/services.yml +++ b/roles/web-app-snipe-it/meta/services.yml @@ -51,7 +51,7 @@ snipe-it: backup: stop_required: false healthcheck: - test: ["CMD", "wget", "-q", "-O-", "http://localhost/health"] + test: ["CMD", "wget", "-q", "-O-", "--header", "Host: {{ lookup('domain', 'web-app-snipe-it') }}", "http://localhost/health"] retries: 12 enabled: true shared: true diff --git a/roles/web-app-snipe-it/tasks/04_sso.yml b/roles/web-app-snipe-it/tasks/04_sso.yml index 033ed7dd06..1b93fbf3f8 100644 --- a/roles/web-app-snipe-it/tasks/04_sso.yml +++ b/roles/web-app-snipe-it/tasks/04_sso.yml @@ -31,8 +31,8 @@ ansible.builtin.shell: cmd: >- container exec {{ SNIPE_IT_CONTAINER_ADDRESS }} sh -c - '{{ 30 | curl }} -s -o /dev/null -w "%{http_code}" -H "X-Forwarded-Preferred-Username: $1" {{ item.proxy_header }} http://localhost/login' - _ {{ lookup('users', IAM_PLATFORM_ADMIN_USER_KEY).username | quote }} + '{{ 30 | curl }} -s -o /dev/null -w "%{http_code}" -H "Host: $2" -H "X-Forwarded-Preferred-Username: $1" {{ item.proxy_header }} http://localhost/login' + _ {{ lookup('users', IAM_PLATFORM_ADMIN_USER_KEY).username | quote }} {{ SNIPE_IT_DOMAIN | quote }} loop: - { label: "forged header without the proxy secret", proxy_header: "", expected: "200" } - { label: "header with the proxy secret", proxy_header: '-H "{{ SNIPE_IT_SSO_PROXY_HEADER }}: $INFINITO_SSO_PROXY_SECRET"', expected: "302" } diff --git a/roles/web-app-snipe-it/tasks/utils/mcp_mint.yml b/roles/web-app-snipe-it/tasks/utils/mcp_mint.yml index c0768af954..73ba388374 100644 --- a/roles/web-app-snipe-it/tasks/utils/mcp_mint.yml +++ b/roles/web-app-snipe-it/tasks/utils/mcp_mint.yml @@ -37,6 +37,8 @@ - -e - "MCP_TOKEN_NAME={{ SNIPEIT_MCP_UPSTREAM_TOKEN_NAME }}" - -e + - "MCP_API_HOST={{ SNIPE_IT_DOMAIN }}" + - -e - MCP_CURRENT_TOKEN - "{{ SNIPEIT_IDENTITY_LOCAL_CID }}" # nocheck: container-exec-resolver - php diff --git a/roles/web-app-snipe-it/vars/main.yml b/roles/web-app-snipe-it/vars/main.yml index 34449e0f5b..285e293a11 100644 --- a/roles/web-app-snipe-it/vars/main.yml +++ b/roles/web-app-snipe-it/vars/main.yml @@ -7,6 +7,7 @@ swarm_stack_converge_retries: 600 database_password: "{{ lookup('config', application_id, 'secrets.credentials.database_password') }}" # nocheck: lookup-config-path SNIPE_IT_URL: "{{ lookup('tls', application_id, 'url.base') }}" +SNIPE_IT_DOMAIN: "{{ lookup('domain', application_id) }}" SNIPE_IT_CONTAINER: "{{ lookup('config', application_id, 'services.snipe-it.name') }}" SNIPE_IT_IMAGE: "{{ lookup('config', application_id, 'services.snipe-it.image') }}" SNIPE_IT_VERSION: "{{ lookup('config', application_id, 'services.snipe-it.version') }}" @@ -47,7 +48,6 @@ SNIPE_IT_DESIGN_COLORS: nav_link_color: "{{ SNIPE_IT_DESIGN_PALETTE.light['--design-on-frame'] }}" link_light_color: "{{ SNIPE_IT_DESIGN_PALETTE.light['--design-link'] }}" link_dark_color: "{{ SNIPE_IT_DESIGN_PALETTE.dark['--design-link'] }}" - custom_css: "{{ lookup('file', 'custom_css.css', rstrip=False) }}" SNIPE_IT_DESIGN_SETTINGS: >- {{ SNIPE_IT_DESIGN_COLORS @@ -70,6 +70,7 @@ SNIPEIT_MCP_UPSTREAM_URL: "http://{{ SNIPEIT_MCP_UPSTREAM_HOST }}:{{ SNIPEIT_MCP SNIPEIT_MCP_CONTRACT: provider: "{{ application_id }}" upstream_url: "{{ SNIPEIT_MCP_UPSTREAM_URL }}" + upstream_host: "{{ SNIPE_IT_DOMAIN }}" auth_subject: "{{ lookup('config', application_id, 'mcp.auth_subject') }}" mutating_tools_enabled: "{{ lookup('config', application_id, 'mcp.tools.mutating_tools_enabled') | bool }}" tools: "{{ lookup('file', 'mcp/tools.json') | from_json }}" diff --git a/roles/web-app-socialhome/meta/services.yml b/roles/web-app-socialhome/meta/services.yml index 8c994315b3..0706f5342a 100644 --- a/roles/web-app-socialhome/meta/services.yml +++ b/roles/web-app-socialhome/meta/services.yml @@ -16,7 +16,7 @@ socialhome: placement: manager name: socialhome image: ghcr.io/social-home-io/socialhome - version: "2026.11.19" + version: "2026.11.21" ports: local: http: 8089 diff --git a/scripts/github/update/open/pr.sh b/scripts/github/update/open/pr.sh index c99fa9170f..d59abbc00d 100755 --- a/scripts/github/update/open/pr.sh +++ b/scripts/github/update/open/pr.sh @@ -44,6 +44,9 @@ fi git commit -m "${UPDATE_COMMIT_MESSAGE}" +UPDATE_LEVEL="$(python3 -m utils.update.level HEAD~1 HEAD)" +echo "Update level: ${UPDATE_LEVEL}" + fingerprint_ref() { local ref="$1" shift @@ -115,6 +118,8 @@ git push --force \ "https://x-access-token:${GH_TOKEN}@github.com/${REPO}.git" \ "HEAD:refs/heads/${BRANCH}" +python3 -m cli.contributing.update.label --repo "${REPO}" --ensure-only + PR_NUMBER="$( gh pr list \ --repo "${REPO}" \ @@ -129,7 +134,9 @@ if [[ -n "${PR_NUMBER}" ]]; then gh pr edit "${PR_NUMBER}" \ --repo "${REPO}" \ --title "${UPDATE_PR_TITLE}" \ - --body "${UPDATE_PR_BODY}" + --body "${UPDATE_PR_BODY}" \ + --add-label update \ + --add-label "${UPDATE_LEVEL}" else echo "Creating PR for ${BRANCH}" PR_URL="$( @@ -138,7 +145,9 @@ else --title "${UPDATE_PR_TITLE}" \ --body "${UPDATE_PR_BODY}" \ --base "${UPDATE_BASE_BRANCH}" \ - --head "${OWNER}:${BRANCH}" + --head "${OWNER}:${BRANCH}" \ + --label update \ + --label "${UPDATE_LEVEL}" )" PR_NUMBER="${PR_URL##*/}" echo "Created PR #${PR_NUMBER}: ${PR_URL}" diff --git a/tests/external/update/repository/test_sha_pins_follow_tags.py b/tests/external/update/repository/test_sha_pins_follow_tags.py new file mode 100644 index 0000000000..78c6084cda --- /dev/null +++ b/tests/external/update/repository/test_sha_pins_follow_tags.py @@ -0,0 +1,32 @@ +"""Fail when a `ref:` pins a commit SHA that its upstream's newest release +tag contains. + +A failed ``git ls-remote`` or ``git fetch`` counts as no such release, so an +unreachable remote never fails it. + +Suppress a check by placing ``# nocheck: repository-version`` on the line +directly above the ``ref:`` key. +""" + +from __future__ import annotations + +import unittest + +from utils.update.repository import find_outdated_updates, is_commit_sha + +from . import PROJECT_ROOT + + +class TestShaPinsFollowTags(unittest.TestCase): + def test_no_sha_pin_where_the_upstream_publishes_a_release(self) -> None: + offenders = [ + f"{u.entry.config_path.relative_to(PROJECT_ROOT)}:{u.entry.line}: " + f"{u.entry.repository} pins {u.entry.ref}, use the tag {u.latest}" + for u in find_outdated_updates(PROJECT_ROOT) + if is_commit_sha(u.entry.ref) and not is_commit_sha(u.latest) + ] + self.assertEqual(offenders, [], "\n".join(offenders)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/integration/meta/workflows/test_ci_concurrency_variable_forwarded.py b/tests/integration/meta/workflows/test_ci_concurrency_variable_forwarded.py new file mode 100644 index 0000000000..252b16551c --- /dev/null +++ b/tests/integration/meta/workflows/test_ci_concurrency_variable_forwarded.py @@ -0,0 +1,70 @@ +"""Every workflow that sizes deploy chunks forwards the runner-slot variable. + +The validation job counts the priority batches and every chunk's discover job +cuts its rows from the same ``cli.meta.ci.slots`` arithmetic. A workflow that +sizes chunks without ``vars.INFINITO_CI_CONCURRENCY`` cuts a different plan +than its siblings, so rows are skipped or deployed twice. +""" + +from __future__ import annotations + +import unittest +from typing import TYPE_CHECKING + +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any + +from . import PROJECT_ROOT + +if TYPE_CHECKING: + from pathlib import Path + +WORKFLOWS = PROJECT_ROOT / ".github" / "workflows" +KEY = "INFINITO_CI_CONCURRENCY" +FORWARD = "${{ vars.INFINITO_CI_CONCURRENCY }}" +_SIZERS = ( + "cli.meta.ci.matrix", + "cli.meta.ci.plan", + "cli.meta.ci.slots", + "scripts/github/resolve/output_apps.sh", + "scripts/github/resolve/priority_batches.sh", +) + + +def _sizing_workflows() -> list[Path]: + return [ + path + for path in sorted(WORKFLOWS.glob("*.yml")) + if any(marker in read_text(str(path)) for marker in _SIZERS) + ] + + +def _forwarded(path: Path) -> str | None: + workflow = load_yaml_any(str(path), default_if_missing={}) or {} + env = workflow.get("env") if isinstance(workflow, dict) else None + return env.get(KEY) if isinstance(env, dict) else None + + +class TestCiConcurrencyVariableForwarded(unittest.TestCase): + def test_every_chunk_sizing_workflow_forwards_the_variable(self) -> None: + offenders = [ + path.name for path in _sizing_workflows() if _forwarded(path) != FORWARD + ] + self.assertEqual( + offenders, + [], + f"declare `{KEY}: {FORWARD}` in the workflow-level env of every " + "workflow that sizes deploy chunks", + ) + + def test_the_guard_finds_the_chunk_sizing_workflows(self) -> None: + self.assertGreaterEqual( + len(_sizing_workflows()), + 2, + "the validation and deploy workflows both size chunks; finding " + "fewer means the markers drifted and the guard passes vacuously", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/contributing/update/__init__.py b/tests/unit/python/cli/contributing/update/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/cli/contributing/update/label/__init__.py b/tests/unit/python/cli/contributing/update/label/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/cli/contributing/update/label/test_main.py b/tests/unit/python/cli/contributing/update/label/test_main.py new file mode 100644 index 0000000000..4d9327e77f --- /dev/null +++ b/tests/unit/python/cli/contributing/update/label/test_main.py @@ -0,0 +1,137 @@ +from __future__ import annotations + +import io +import subprocess +import unittest +from contextlib import redirect_stdout +from unittest.mock import patch + +import cli.contributing.update.label.__main__ as label_main + +REPO = "infinito-nexus/core" + + +class FakeGh: + """Answers the label reads and records every write. + + Args: + repository: label names the repository has. + pull_request: label names pull request 4 carries. + racing: names whose create fails because a parallel run made them. + """ + + def __init__(self, repository, pull_request, racing=()): + self.repository = set(repository) + self.pull_request = set(pull_request) + self.racing = set(racing) + self.writes = [] + + def __call__(self, args): + if args[:2] == ["api", "--paginate"]: + names = self.pull_request if "/issues/" in args[2] else self.repository + return "".join(f"{name}\n" for name in sorted(names)) + self.writes.append(list(args)) + if args[:2] == ["label", "create"] and args[2] in self.racing: + self.repository.add(args[2]) + raise subprocess.CalledProcessError(1, ["gh", *args]) + return "" + + +class TestLevel(unittest.TestCase): + def test_semver_levels_map_to_their_label(self): + self.assertEqual( + [ + label_main.level(f"version-update:semver-{name}").name + for name in ("major", "minor", "patch") + ], + ["major", "minor", "patch"], + ) + + def test_an_unknown_or_empty_type_counts_as_major(self): + self.assertEqual( + {label_main.level(kind).name for kind in ("", "security", "semver-minor")}, + {"major"}, + ) + + +class TestSync(unittest.TestCase): + def test_a_bare_pull_request_gets_update_and_its_level(self): + gh = FakeGh({"update", "minor"}, set()) + actions = label_main.sync(gh, REPO, 4, "version-update:semver-minor") + self.assertEqual(actions, ["added update, minor"]) + self.assertEqual( + gh.writes, + [ + [ + "api", + "--method", + "POST", + f"repos/{REPO}/issues/4/labels", + "-f", + "labels[]=update", + "-f", + "labels[]=minor", + ] + ], + ) + + def test_labels_already_present_cause_no_write(self): + gh = FakeGh({"update", "patch"}, {"update", "patch", "dependencies"}) + self.assertEqual( + label_main.sync(gh, REPO, 4, "version-update:semver-patch"), [] + ) + self.assertEqual(gh.writes, []) + + def test_a_stale_level_is_removed(self): + gh = FakeGh({"update", "major", "minor"}, {"update", "minor"}) + actions = label_main.sync(gh, REPO, 4, "version-update:semver-major") + self.assertEqual(actions, ["removed minor", "added major"]) + + def test_missing_repository_labels_are_created_first(self): + gh = FakeGh(set(), set()) + label_main.sync(gh, REPO, 4, "version-update:semver-patch") + created = [write[2] for write in gh.writes if write[:2] == ["label", "create"]] + self.assertEqual(created, ["update", "patch"]) + + def test_a_label_a_parallel_run_created_counts_as_done(self): + gh = FakeGh({"patch"}, set(), racing={"update"}) + actions = label_main.sync(gh, REPO, 4, "version-update:semver-patch") + self.assertEqual(actions, ["added update, patch"]) + + def test_a_create_failure_that_leaves_the_label_missing_raises(self): + gh = FakeGh(set(), set()) + + def failing(args): + if args[:2] == ["label", "create"]: + raise subprocess.CalledProcessError(1, ["gh", *args]) + return gh(args) + + with self.assertRaises(subprocess.CalledProcessError): + label_main.sync(failing, REPO, 4, "") + + +class TestMain(unittest.TestCase): + def test_main_reports_when_nothing_changes(self): + gh = FakeGh({"update", "major"}, {"update", "major"}) + out = io.StringIO() + with patch.object(label_main, "run_gh", gh), redirect_stdout(out): + code = label_main.main(["--repo", REPO, "--pr", "4", "--update-type", ""]) + self.assertEqual((code, out.getvalue()), (0, "#4 already carries its labels\n")) + + def test_ensure_only_creates_the_missing_labels_and_touches_no_pr(self): + gh = FakeGh({"update", "minor"}, set()) + out = io.StringIO() + with patch.object(label_main, "run_gh", gh), redirect_stdout(out): + code = label_main.main(["--repo", REPO, "--ensure-only"]) + created = [w[2] for w in gh.writes if w[:2] == ["label", "create"]] + self.assertEqual((code, created), (0, ["major", "patch"])) + self.assertEqual(len(gh.writes), 2) + + def test_without_ensure_only_the_pr_and_type_are_required(self): + with self.assertRaises(SystemExit) as raised, redirect_stdout(io.StringIO()): + label_main.main(["--repo", REPO, "--pr", "4"]) + self.assertEqual(raised.exception.code, 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/contributing/update/merge/__init__.py b/tests/unit/python/cli/contributing/update/merge/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/cli/contributing/update/merge/test_gate.py b/tests/unit/python/cli/contributing/update/merge/test_gate.py new file mode 100644 index 0000000000..826aa062d0 --- /dev/null +++ b/tests/unit/python/cli/contributing/update/merge/test_gate.py @@ -0,0 +1,131 @@ +from __future__ import annotations + +import unittest + +from cli.contributing.update.merge import gate +from utils.roles.mapping import ROLE_FILE_META_SERVICES + +REPO = "infinito-nexus/core" + + +def pull_request(**overrides): + pr = { + "draft": False, + "user": {"login": "dependabot[bot]"}, + "head": {"ref": "dependabot/npm/left-pad-1.3.0", "repo": {"full_name": REPO}}, + "base": {"ref": "main"}, + "labels": [{"name": "update"}], + } + pr.update(overrides) + return pr + + +def check(**overrides): + run = { + "name": "๐Ÿงน Lint", + "status": "completed", + "conclusion": "success", + "details_url": "https://github.example/o/r/actions/runs/1/job/2", + } + run.update(overrides) + return run + + +class TestPullRequestRefusals(unittest.TestCase): + def test_an_update_bot_pull_request_passes(self): + self.assertEqual(gate.pull_request_refusals(pull_request(), REPO, "main"), []) + + def test_a_bot_outside_its_branch_prefix_is_refused(self): + head = {"ref": "update/sneaky", "repo": {"full_name": REPO}} + self.assertEqual( + gate.pull_request_refusals(pull_request(head=head), REPO, "main"), + ["branch update/sneaky lacks the dependabot/ prefix of dependabot[bot]"], + ) + + def test_a_head_in_another_repository_is_refused(self): + head = {"ref": "dependabot/npm/x", "repo": {"full_name": "fork/core"}} + refusals = gate.pull_request_refusals(pull_request(head=head), REPO, "main") + self.assertEqual( + refusals, [f"head branch dependabot/npm/x lives outside {REPO}"] + ) + + def test_a_deleted_head_repository_is_refused(self): + head = {"ref": "dependabot/npm/x", "repo": None} + refusals = gate.pull_request_refusals(pull_request(head=head), REPO, "main") + self.assertEqual(len(refusals), 1) + + def test_a_draft_is_refused(self): + refusals = gate.pull_request_refusals(pull_request(draft=True), REPO, "main") + self.assertEqual(refusals, ["pull request is a draft"]) + + def test_another_base_branch_is_refused(self): + base = {"ref": "release"} + refusals = gate.pull_request_refusals(pull_request(base=base), REPO, "main") + self.assertEqual(refusals, ["base branch is release, not main"]) + + +class TestCheckRefusals(unittest.TestCase): + def test_skipped_and_neutral_count_as_green(self): + runs = [check(conclusion="skipped"), check(conclusion="neutral")] + self.assertEqual(gate.check_refusals(runs, [], own_run_id=9), []) + + def test_no_check_run_at_all_refuses(self): + self.assertEqual( + gate.check_refusals([], [], own_run_id=9), + ["no check run on the head commit"], + ) + + def test_only_the_own_run_left_refuses(self): + own = check(details_url="https://github.example/o/r/actions/runs/9/job/3") + self.assertEqual( + gate.check_refusals([own], [], own_run_id=9), + ["no check run on the head commit"], + ) + + def test_a_pending_status_refuses(self): + statuses = [{"context": "ci/external", "state": "pending"}] + self.assertEqual( + gate.check_refusals([check()], statuses, own_run_id=9), + ["status ci/external is pending"], + ) + + +class TestRoles(unittest.TestCase): + def test_changed_roles_reads_the_role_directory(self): + paths = [ + f"roles/web-app-nextcloud/{ROLE_FILE_META_SERVICES}", + f"roles/sys-lint/{ROLE_FILE_META_SERVICES}", + "pyproject.toml", + "docs/roles/web-app-matomo.md", + ] + self.assertEqual(gate.changed_roles(paths), {"web-app-nextcloud", "sys-lint"}) + + def test_deployed_roles_unions_the_role_column(self): + first = "role,seconds\nweb-app-nextcloud,3.0\nsvc-db-postgres,1.0\n" + second = "round,role,seconds\n1,web-app-matomo,2.0\n1,,0.5\n" + self.assertEqual( + gate.deployed_roles([first, second]), + {"web-app-nextcloud", "svc-db-postgres", "web-app-matomo"}, + ) + + def test_a_csv_without_a_role_column_proves_nothing(self): + self.assertEqual(gate.deployed_roles(["name,seconds\nweb-app-x,1\n"]), set()) + + def test_no_changed_role_needs_no_proof(self): + self.assertEqual(gate.role_refusals(set(), []), []) + + def test_every_missing_role_is_named(self): + csv_text = "role,seconds\nweb-app-nextcloud,1.0\n" + self.assertEqual( + gate.role_refusals( + {"web-app-nextcloud", "web-app-a", "web-app-b"}, [csv_text] + ), + [ + "role web-app-a changed, but no deploy row ran it", + "role web-app-b changed, but no deploy row ran it", + ], + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/contributing/update/merge/test_github.py b/tests/unit/python/cli/contributing/update/merge/test_github.py new file mode 100644 index 0000000000..effd757495 --- /dev/null +++ b/tests/unit/python/cli/contributing/update/merge/test_github.py @@ -0,0 +1,119 @@ +from __future__ import annotations + +import io +import json +import unittest +import zipfile +from unittest.mock import Mock + +from cli.contributing.update.merge import github +from utils.roles.mapping import ROLE_FILE_META_MAIN + +REPO = "infinito-nexus/core" +SHA = "b" * 40 + + +def lines(*objects): + return "\n".join(json.dumps(item) for item in objects).encode() + + +def archive(members): + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w") as zipped: + for name, data in members.items(): + zipped.writestr(name, data) + return buffer.getvalue() + + +class TestReads(unittest.TestCase): + def test_items_paginates_and_parses_one_object_per_line(self): + gh = Mock(return_value=lines({"a": 1}, {"a": 2}) + b"\n") + self.assertEqual(github.items(gh, "repos/x", ".[]"), [{"a": 1}, {"a": 2}]) + gh.assert_called_once_with(["api", "--paginate", "repos/x", "--jq", ".[]"]) + + def test_open_pull_requests_drop_closed_ones_and_other_heads(self): + prs = [ + {"number": 1, "state": "open", "head": {"sha": SHA}}, + {"number": 2, "state": "closed", "head": {"sha": SHA}}, + {"number": 3, "state": "open", "head": {"sha": "c" * 40}}, + ] + gh = Mock(return_value=lines(*prs)) + found = github.open_pull_requests(gh, REPO, SHA) + self.assertEqual([pr["number"] for pr in found], [1]) + + def test_changed_paths_keep_the_old_name_of_a_rename(self): + files = [ + { + "filename": f"roles/web-app-new/{ROLE_FILE_META_MAIN}", + "previous_filename": f"roles/web-app-old/{ROLE_FILE_META_MAIN}", + }, + {"filename": "pyproject.toml", "previous_filename": None}, + ] + gh = Mock(return_value=lines(*files)) + self.assertEqual( + github.changed_paths(gh, REPO, 5), + [ + f"roles/web-app-new/{ROLE_FILE_META_MAIN}", + f"roles/web-app-old/{ROLE_FILE_META_MAIN}", + "pyproject.toml", + ], + ) + + +class TestCsvMembers(unittest.TestCase): + def test_only_csv_members_are_read(self): + blob = archive({"a.csv": "role\nx\n", "notes.txt": "role\ny\n"}) + self.assertEqual(github.csv_members(blob), ["role\nx\n"]) + + def test_an_oversized_member_is_left_out(self): + big = "role\n" + "x" * (github.MAX_CSV_BYTES + 1) + blob = archive({"big.csv": big, "small.csv": "role\nx\n"}) + self.assertEqual(github.csv_members(blob), ["role\nx\n"]) + + def test_a_traversing_member_name_is_only_read_in_memory(self): + blob = archive({"../../etc/evil.csv": "role\nx\n"}) + self.assertEqual(github.csv_members(blob), ["role\nx\n"]) + + +class TestRoleRuntimeCsvs(unittest.TestCase): + def test_only_unexpired_role_runtimes_artifacts_are_downloaded(self): + artifacts = [ + { + "id": 1, + "name": "role-runtimes-web-app-a", + "expired": False, + "size_in_bytes": 10, + }, + { + "id": 2, + "name": "role-runtimes-web-app-b", + "expired": True, + "size_in_bytes": 10, + }, + { + "id": 3, + "name": "inventory-web-app-a", + "expired": False, + "size_in_bytes": 10, + }, + { + "id": 4, + "name": "role-runtimes-web-app-c", + "expired": False, + "size_in_bytes": github.MAX_ARTIFACT_BYTES + 1, + }, + ] + downloads = [] + + def gh(args): + if args[1] == "--paginate": + return lines(*artifacts) + downloads.append(args[1]) + return archive({"r.csv": "role\nweb-app-a\n"}) + + self.assertEqual(github.role_runtime_csvs(gh, REPO, 77), ["role\nweb-app-a\n"]) + self.assertEqual(downloads, [f"repos/{REPO}/actions/artifacts/1/zip"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/contributing/update/merge/test_main.py b/tests/unit/python/cli/contributing/update/merge/test_main.py new file mode 100644 index 0000000000..4a2522c5ac --- /dev/null +++ b/tests/unit/python/cli/contributing/update/merge/test_main.py @@ -0,0 +1,234 @@ +from __future__ import annotations + +import io +import json +import tempfile +import unittest +import zipfile +from contextlib import redirect_stderr, redirect_stdout +from pathlib import Path +from unittest.mock import patch + +import cli.contributing.update.merge.__main__ as merge_main +from cli.contributing.update.merge import github +from utils.roles.mapping import ROLE_FILE_META_SERVICES + +REPO = "infinito-nexus/core" +SHA = "a" * 40 +RUN_ID = 111 +OWN_RUN_ID = 222 +CSV_HEADER = "round,rounds_total,pass,pass_mode,role,seconds,hosts\n" + + +def pull_request(**overrides): + pr = { + "number": 7, + "state": "open", + "draft": False, + "user": {"login": "infinito-nexus-updater[bot]"}, + "head": { + "sha": SHA, + "ref": "update/docker-image-versions-20261121-abc1234", + "repo": {"full_name": REPO}, + }, + "base": {"ref": "main"}, + "labels": [{"name": "update"}, {"name": "minor"}], + } + pr.update(overrides) + return pr + + +def check(name="๐Ÿ”€ Pull Request / ๐Ÿ Finish pipeline", **overrides): + run = { + "name": name, + "status": "completed", + "conclusion": "success", + "details_url": f"https://github.com/{REPO}/actions/runs/{RUN_ID}/job/1", + } + run.update(overrides) + return run + + +def role_runtimes(*roles): + rows = "".join(f",,,,{role},1.00,localhost=executed\n" for role in roles) + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w") as archive: + archive.writestr("role-runtimes-web-app-nextcloud.csv", CSV_HEADER + rows) + return buffer.getvalue() + + +class FakeGh: + """Answers the REST paths the merge gate reads, recording every call. + + Args: + prs: pull requests associated with ``SHA``. + checks: check runs on ``SHA``. + statuses: commit statuses on ``SHA``. + files: ``filename`` paths the pull request touches. + artifacts: ``{name: zip bytes}`` of the CI run's artifacts. + """ + + def __init__(self, prs, checks, statuses, files, artifacts): + self.routes = { + f"repos/{REPO}/commits/{SHA}/pulls": prs, + f"repos/{REPO}/commits/{SHA}/check-runs": checks, + f"repos/{REPO}/commits/{SHA}/status": statuses, + f"repos/{REPO}/pulls/7/files": [ + {"filename": path, "previous_filename": None} for path in files + ], + f"repos/{REPO}/actions/runs/{RUN_ID}/artifacts": [ + {"id": index, "name": name, "expired": False, "size_in_bytes": 512} + for index, name in enumerate(artifacts) + ], + } + self.blobs = dict(enumerate(artifacts.values())) + self.calls = [] + + def __call__(self, args): + self.calls.append(list(args)) + if args[1] == "--paginate": + route = args[2].split("?")[0] + return "\n".join(json.dumps(item) for item in self.routes[route]).encode() + artifact_id = int(args[1].split("/")[-2]) + return self.blobs[artifact_id] + + +def green_gh(**overrides): + fields = { + "prs": [pull_request()], + "checks": [check()], + "statuses": [{"context": "codecov", "state": "success"}], + "files": [f"roles/web-app-nextcloud/{ROLE_FILE_META_SERVICES}"], + "artifacts": { + "role-runtimes-web-app-nextcloud": role_runtimes( + "web-app-nextcloud", "svc-db-postgres" + ) + }, + } + fields.update(overrides) + return FakeGh(**fields) + + +def evaluate(gh): + return merge_main.evaluate(gh, REPO, SHA, RUN_ID, OWN_RUN_ID, "main") + + +class TestEvaluate(unittest.TestCase): + def test_all_green_and_every_changed_role_deployed_merges(self): + pr, refusals = evaluate(green_gh()) + self.assertEqual((pr["number"], refusals), (7, [])) + + def test_a_dependabot_pull_request_merges_like_the_updater(self): + dependabot = pull_request( + user={"login": "dependabot[bot]"}, + head={ + "sha": SHA, + "ref": "dependabot/pip/roles/web-app-nextcloud/files/requests-2.32.0", + "repo": {"full_name": REPO}, + }, + ) + self.assertEqual(evaluate(green_gh(prs=[dependabot]))[1], []) + + def test_a_non_bot_author_is_refused(self): + human = pull_request(user={"login": "octocat"}) + refusals = evaluate(green_gh(prs=[human]))[1] + self.assertEqual(refusals, ["author octocat is no update bot"]) + + def test_a_missing_update_label_is_refused(self): + unlabeled = pull_request(labels=[{"name": "minor"}]) + refusals = evaluate(green_gh(prs=[unlabeled]))[1] + self.assertEqual(refusals, ["label update is missing"]) + + def test_a_pending_check_refuses(self): + pending = check("๐ŸŒ Translate catalogs", status="in_progress", conclusion=None) + refusals = evaluate(green_gh(checks=[check(), pending]))[1] + self.assertEqual(refusals, ["check ๐ŸŒ Translate catalogs is in_progress"]) + + def test_a_failed_check_refuses(self): + failed = check("๐Ÿ” CodeQL", conclusion="failure") + refusals = evaluate(green_gh(checks=[check(), failed]))[1] + self.assertEqual(refusals, ["check ๐Ÿ” CodeQL concluded failure"]) + + def test_a_failed_commit_status_refuses(self): + statuses = [{"context": "codecov", "state": "failure"}] + refusals = evaluate(green_gh(statuses=statuses))[1] + self.assertEqual(refusals, ["status codecov is failure"]) + + def test_the_deciding_run_own_check_does_not_count(self): + own = check( + "๐Ÿ”€ Merge a proven update PR", + status="in_progress", + conclusion=None, + details_url=f"https://github.com/{REPO}/actions/runs/{OWN_RUN_ID}/job/9", + ) + self.assertEqual(evaluate(green_gh(checks=[check(), own]))[1], []) + + def test_a_changed_role_absent_from_role_runtimes_refuses(self): + artifacts = {"role-runtimes-web-app-matomo": role_runtimes("web-app-matomo")} + refusals = evaluate(green_gh(artifacts=artifacts))[1] + self.assertEqual( + refusals, ["role web-app-nextcloud changed, but no deploy row ran it"] + ) + + def test_no_role_runtimes_artifact_refuses(self): + artifacts = {"inventory-web-app-nextcloud": role_runtimes("web-app-nextcloud")} + refusals = evaluate(green_gh(artifacts=artifacts))[1] + self.assertEqual( + refusals, ["no role-runtimes artifact proves web-app-nextcloud"] + ) + + def test_a_pull_request_touching_no_role_needs_no_artifact(self): + gh = green_gh(files=[".github/workflows/call-lint.yml"], artifacts={}) + self.assertEqual(evaluate(gh)[1], []) + self.assertFalse(any("artifacts" in " ".join(call) for call in gh.calls)) + + def test_no_open_pull_request_for_the_head_refuses(self): + closed = pull_request(state="closed") + pr, refusals = evaluate(green_gh(prs=[closed])) + self.assertIsNone(pr) + self.assertEqual(refusals, [f"0 open pull requests have head {SHA}, not one"]) + + +class TestMain(unittest.TestCase): + def run_main(self, gh, sha=SHA): + with tempfile.TemporaryDirectory() as tmp: + output = Path(tmp) / "github_output" + argv = [ + "--repo", + REPO, + "--sha", + sha, + "--run-id", + str(RUN_ID), + "--own-run-id", + str(OWN_RUN_ID), + "--base", + "main", + "--output", + str(output), + ] + stdout = io.StringIO() + with patch.object(github, "run_gh", gh), redirect_stdout(stdout): + code = merge_main.main(argv) + with output.open(encoding="utf-8") as handle: + return code, handle.read(), stdout.getvalue() + + def test_a_merge_verdict_writes_pr_and_sha(self): + code, outputs, _ = self.run_main(green_gh()) + self.assertEqual((code, outputs), (0, f"merge=true\npr=7\nsha={SHA}\n")) + + def test_a_refusal_writes_merge_false_and_exits_zero(self): + gh = green_gh(checks=[check(conclusion="cancelled")]) + code, outputs, printed = self.run_main(gh) + self.assertEqual((code, outputs), (0, "merge=false\n")) + self.assertIn("stays open for a manual merge", printed) + + def test_a_short_sha_is_rejected_before_any_call(self): + gh = green_gh() + with self.assertRaises(SystemExit), redirect_stderr(io.StringIO()): + self.run_main(gh, sha="abc1234") + self.assertEqual(gh.calls, []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/gha/test_split_runner_apps.py b/tests/unit/python/cli/gha/test_split_runner_apps.py index a3762f029f..a3ea8b7910 100644 --- a/tests/unit/python/cli/gha/test_split_runner_apps.py +++ b/tests/unit/python/cli/gha/test_split_runner_apps.py @@ -12,11 +12,25 @@ from . import PROJECT_ROOT SCRIPT = PROJECT_ROOT / "scripts" / "github" / "split_runner_apps.sh" -def _run(apps: list, self_hosted_count: int) -> dict: +def _fresh_step_env(**values: str) -> dict[str, str]: + """The environment of a new CI step: nothing the env loader exported. + + Args: + values: keys the step sets itself, as a workflow ``env:`` would. + + Returns: + The process environment without ``INFINITO_*`` keys, plus *values*. + """ + env = {k: v for k, v in os.environ.items() if not k.startswith("INFINITO_")} + env.update(values) + return env + + +def _run(apps: list, self_hosted_count: int, env: dict[str, str] | None = None) -> dict: with tempfile.NamedTemporaryFile(mode="r", suffix=".env", delete=False) as out_f: out_path = out_f.name try: - env = os.environ.copy() + env = os.environ.copy() if env is None else dict(env) env["APPS_JSON"] = json.dumps(apps) env["CI_SELF_HOSTED_RUNNER_COUNT"] = str(self_hosted_count) env["GITHUB_OUTPUT"] = out_path @@ -60,6 +74,17 @@ class TestSplitRunnerApps(unittest.TestCase): combined = out["apps_github"] + out["apps_self_hosted"] self.assertEqual(combined, ["only-app"]) + def test_an_empty_concurrency_splits_like_an_unset_one(self): + apps = list(range(40)) + self.assertEqual( + _run(apps, 20, _fresh_step_env(INFINITO_CI_CONCURRENCY="")), + _run(apps, 20, _fresh_step_env()), + ) + + def test_a_set_concurrency_drives_the_split(self): + out = _run(list(range(40)), 20, _fresh_step_env(INFINITO_CI_CONCURRENCY="500")) + self.assertEqual(len(out["apps_github"]), 40 * 500 // (500 + 20)) + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/cli/meta/ci/test_chunks.py b/tests/unit/python/cli/meta/ci/test_chunks.py index e35b73192b..8317250209 100644 --- a/tests/unit/python/cli/meta/ci/test_chunks.py +++ b/tests/unit/python/cli/meta/ci/test_chunks.py @@ -102,5 +102,24 @@ class TestPlan(unittest.TestCase): self.assertEqual(chunks.plan([], [], size=80, blocks=3, budget=211), []) +class TestChunkBeyondTheBudget(unittest.TestCase): + def test_the_whole_budget_goes_into_one_regular_chunk(self) -> None: + plan = chunks.plan([], list(range(500)), size=2000, blocks=4, budget=203) + self.assertEqual([len(c) for c in plan], [203]) + + def test_a_short_priority_chunk_strands_no_row_of_the_budget(self) -> None: + plan = chunks.plan( + list(range(7)), list(range(100, 600)), size=2000, blocks=4, budget=203 + ) + self.assertEqual([len(c) for c in plan], [7, 196]) + self.assertEqual(plan[0], list(range(7))) + + def test_priority_beyond_the_budget_fills_one_chunk_up_to_the_cap(self) -> None: + plan = chunks.plan( + list(range(300)), list(range(50)), size=2000, blocks=4, budget=203 + ) + self.assertEqual([len(c) for c in plan], [203]) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/cli/meta/ci/test_slots.py b/tests/unit/python/cli/meta/ci/test_slots.py index 6beeff7b76..4097b64377 100644 --- a/tests/unit/python/cli/meta/ci/test_slots.py +++ b/tests/unit/python/cli/meta/ci/test_slots.py @@ -8,6 +8,8 @@ from pathlib import Path from tempfile import TemporaryDirectory from cli.meta.ci import slots +from utils.cache.files import PROJECT_ROOT +from utils.env.parser import parse_static_env _SETTINGS = { "INFINITO_CI_JOB_LIMIT": "256", @@ -185,6 +187,42 @@ class TestChunkArithmetic(unittest.TestCase): root = Path(tmp) self.assertLessEqual(slots.rows_per_sweep(root), slots.available(root)) + def test_enterprise_concurrency_leaves_the_job_cap_as_the_only_limit( + self, + ) -> None: + with ( + _tree() as tmp, + mock.patch.dict( + "os.environ", + { + **_SETTINGS, + "INFINITO_CI_CONCURRENCY": "500", + "INFINITO_CI_CHUNK_SIZE": "0", + }, + ), + ): + root = Path(tmp) + self.assertGreater(slots.chunk_size(root), slots.available(root)) + self.assertEqual(slots.chunk_count(root), 1) + self.assertEqual(slots.rows_per_sweep(root), slots.available(root)) + + +class TestConcurrencySetting(unittest.TestCase): + def test_an_empty_or_blank_value_falls_back_to_default_env(self) -> None: + declared = int( + parse_static_env(PROJECT_ROOT / "default.env")["INFINITO_CI_CONCURRENCY"] + ) + for raw in ("", " "): + with ( + self.subTest(raw=raw), + mock.patch.dict("os.environ", {"INFINITO_CI_CONCURRENCY": raw}), + ): + self.assertEqual(slots.setting("INFINITO_CI_CONCURRENCY"), declared) + + def test_a_set_value_wins_over_default_env(self) -> None: + with mock.patch.dict("os.environ", {"INFINITO_CI_CONCURRENCY": "500"}): + self.assertEqual(slots.setting("INFINITO_CI_CONCURRENCY"), 500) + class TestRenderMatrix(unittest.TestCase): def test_table_lists_every_job_and_the_chunk_arithmetic(self) -> None: diff --git a/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_policy.py b/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_policy.py index c04c092e7a..6c25e26256 100644 --- a/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_policy.py +++ b/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_policy.py @@ -111,6 +111,28 @@ class TestLoadContract(unittest.TestCase): ) +class TestUpstreamHost(unittest.TestCase): + def test_an_undeclared_host_keeps_the_url_host(self): + self.assertEqual("", policy.upstream_host(contract())) + + def test_a_declared_host_is_returned(self): + loaded = policy.load_contract( + json.dumps(contract(upstream_host="assets.example.org")) + ) + self.assertEqual("assets.example.org", policy.upstream_host(loaded)) + + def test_a_host_with_a_port_is_accepted(self): + self.assertEqual( + "assets.example.org:8443", + policy.upstream_host(contract(upstream_host="assets.example.org:8443")), + ) + + def test_a_malformed_host_is_refused_at_startup(self): + for host in ("", "assets.example.org\r\nX-Injected: 1", "a.org/path", 7): + with self.subTest(host=host), self.assertRaises(policy.ContractError): + policy.load_contract(json.dumps(contract(upstream_host=host))) + + class TestDrift(unittest.TestCase): def test_a_matching_hash_passes(self): policy.assert_no_drift(contract()) @@ -190,6 +212,17 @@ class TestLimits(unittest.TestCase): self.assertEqual(5, len(policy.truncate_results(contract(), list(range(50))))) +class TestRequestLength(unittest.TestCase): + def test_a_missing_header_announces_no_body(self): + self.assertEqual(policy.request_length(None), 0) + + def test_a_numeric_header_is_the_byte_count(self): + self.assertEqual(policy.request_length("12"), 12) + + def test_a_non_numeric_header_is_negative(self): + self.assertLess(policy.request_length("abc"), 0) + + class TestDeclaredArguments(unittest.TestCase): """A published input schema is enforced, not merely advertised. diff --git a/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_server.py b/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_server.py index 5d767bbd8f..3fc0a71c94 100644 --- a/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_server.py +++ b/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_server.py @@ -29,11 +29,14 @@ LIMITS = { } -def load(): +def load(**overrides): """Import the adapter server the way the image lays it out. ``server.py`` imports ``policy`` as a sibling, so its own directory has to be importable before the module body runs. + + Args: + overrides: contract keys added to or replacing the default contract. """ spec = importlib.util.spec_from_file_location("adapter_server", MODULE_PATH) module = importlib.util.module_from_spec(spec) @@ -48,6 +51,7 @@ def load(): "tools": TOOLS, "limits": LIMITS, "schema_sha256": policy.schema_digest(TOOLS), + **overrides, } env = { "ADAPTER_CONTRACT": json.dumps(contract), @@ -180,6 +184,33 @@ class TestFixedTarget(unittest.TestCase): ) +class TestUpstreamHost(unittest.TestCase): + def _sent(self, module): + seen = {} + + def fake_open(request, **_kwargs): + seen["host"] = request.get_header("Host") + seen["url"] = request.full_url + return FakeResponse() + + spec = module.CONTRACT["tools"]["example_list"] + with patch.object(module.OPENER, "open", fake_open): + module.call_upstream(spec["method"], spec["path"], {}) + return seen + + def test_a_declared_upstream_host_is_sent_as_the_host_header(self): + seen = self._sent(load(upstream_host="assets.example.org")) + self.assertEqual("assets.example.org", seen["host"]) + self.assertEqual("http://example:80/api/things", seen["url"]) + + def test_without_upstream_host_no_host_header_is_forced(self): + self.assertIsNone(self._sent(load())["host"]) + + def test_a_malformed_upstream_host_refuses_to_start(self): + with self.assertRaises(ValueError): + load(upstream_host="assets.example.org\r\nX-Injected: 1") + + class TestConcurrencyCeiling(unittest.TestCase): """The declared ``concurrent_requests`` is refused past, not just declared. @@ -257,5 +288,35 @@ class TestConcurrencyCeiling(unittest.TestCase): self.assertEqual(200, recorder.status) +class TestContentLength(unittest.TestCase): + def setUp(self): + self.module = load() + + def _handle(self, content_length): + handler = self.module.Handler.__new__(self.module.Handler) + recorder = Recorder() + handler.send_response = recorder.send_response + handler.send_header = recorder.send_header + handler.end_headers = recorder.end_headers + handler.wfile = type("W", (), {"write": lambda _s, _data: None})() + handler.path = self.module.ENDPOINT + reads = [] + handler.rfile = type( + "R", (), {"read": lambda _s, n: reads.append(n) or b"{}"} + )() + handler.headers = { + "Content-Length": content_length, + "Authorization": "Bearer real", + } + handler.do_POST() + return recorder.status, reads + + def test_a_negative_length_is_refused_before_any_read(self): + self.assertEqual(self._handle("-1"), (400, [])) + + def test_a_non_numeric_length_is_refused_before_any_read(self): + self.assertEqual(self._handle("abc"), (400, [])) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/roles/svc-opt-ssd-hdd/test_storage_optimizer.py b/tests/unit/python/roles/svc-opt-ssd-hdd/test_storage_optimizer.py index 7b9c2942a1..cb47632431 100644 --- a/tests/unit/python/roles/svc-opt-ssd-hdd/test_storage_optimizer.py +++ b/tests/unit/python/roles/svc-opt-ssd-hdd/test_storage_optimizer.py @@ -1,5 +1,6 @@ import importlib.util import sys +import time import unittest from unittest.mock import patch @@ -28,8 +29,8 @@ storage_optimizer = load_optimizer_module() class TestHealthCheckLogic(unittest.TestCase): def setUp(self): patcher = patch("storage_optimizer.time.sleep", return_value=None) - self.sleep_patcher = patcher.start() - self.addCleanup(self.sleep_patcher.stop) + patcher.start() + self.addCleanup(patcher.stop) @patch("storage_optimizer.run_command") def test_has_healthcheck_true(self, mock_run): @@ -84,5 +85,12 @@ class TestIsDatabase(unittest.TestCase): ) +class TestSleepPatchEndsWithItsTest(unittest.TestCase): + def test_time_sleep_is_real_again_after_a_health_check_test(self): + real_sleep = time.sleep + TestHealthCheckLogic("test_has_healthcheck_true").run() + self.assertIs(time.sleep, real_sleep) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/utils/update/test_level.py b/tests/unit/python/utils/update/test_level.py new file mode 100644 index 0000000000..e90e0f7c6e --- /dev/null +++ b/tests/unit/python/utils/update/test_level.py @@ -0,0 +1,68 @@ +from __future__ import annotations + +import unittest + +from utils.update.level import bump_level, diff_level, line_level + +SHA_A = "3fa19f8b6d3eecbacbdbf79406e0f877ebe11e26" +SHA_B = "dc95a4d7e7e5531b1fdaa59528121afcffb8b3f0" + + +class TestBumpLevel(unittest.TestCase): + def test_the_first_changed_number_sets_the_level(self) -> None: + self.assertEqual(bump_level("1.2.3", "2.0.0"), "major") + self.assertEqual(bump_level("v8.8.3-alpine", "v8.9.0-alpine"), "minor") + self.assertEqual(bump_level("6.8.0", "6.8.1"), "patch") + self.assertEqual(bump_level("2026.05.18.0", "2026.05.18.1"), "patch") + self.assertEqual(bump_level("24.04", "26.04"), "major") + + def test_a_sha_or_a_numberless_side_is_major(self) -> None: + self.assertEqual(bump_level(SHA_A, SHA_B), "major") + self.assertEqual(bump_level(SHA_A, "v0.1.1"), "major") + self.assertEqual(bump_level("latest", "1.0.0"), "major") + + def test_a_longer_version_with_the_same_prefix_is_patch(self) -> None: + self.assertEqual(bump_level("1.2", "1.2.1"), "patch") + + +class TestLineLevel(unittest.TestCase): + def test_the_first_differing_token_decides(self) -> None: + self.assertEqual( + line_level(' version: "1.2.3"', ' version: "1.3.0"'), "minor" + ) + self.assertEqual(line_level("pkg==4.0.1", "pkg==4.0.2"), "patch") + self.assertEqual( + line_level(" runs-on: ubuntu-24.04", " runs-on: ubuntu-26.04"), + "major", + ) + self.assertEqual(line_level(f" ref: {SHA_A}", " ref: v0.1.1"), "major") + + def test_unpaired_tokens_are_major(self) -> None: + self.assertEqual(line_level("ref: main", "ref: v1.0.0"), "major") + + +class TestDiffLevel(unittest.TestCase): + def test_the_highest_level_of_every_hunk_wins(self) -> None: + diff = ( + "diff --git a/roles/a/meta/services.yml b/roles/a/meta/services.yml\n" + "--- a/roles/a/meta/services.yml\n" + "+++ b/roles/a/meta/services.yml\n" + "@@ -3 +3 @@\n" + '- version: "1.2.3"\n' + '+ version: "1.2.4"\n' + "@@ -9 +9 @@\n" + '- version: "4.1.0"\n' + '+ version: "4.2.0"\n' + ) + self.assertEqual(diff_level(diff), "minor") + + def test_a_hunk_with_unequal_sides_is_major(self) -> None: + diff = "@@ -3 +3,2 @@\n- version: 1.0.0\n+ version: 1.0.1\n+ extra: 1\n" + self.assertEqual(diff_level(diff), "major") + + def test_an_empty_diff_is_major(self) -> None: + self.assertEqual(diff_level(""), "major") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/update/test_repository.py b/tests/unit/python/utils/update/test_repository.py index 56e5e380f4..5a042c2e47 100644 --- a/tests/unit/python/utils/update/test_repository.py +++ b/tests/unit/python/utils/update/test_repository.py @@ -1,5 +1,6 @@ from __future__ import annotations +import os import subprocess import tempfile import unittest @@ -18,6 +19,8 @@ from utils.update.repository import ( git_ls_remote_head, git_ref_resolves, is_commit_sha, + latest_release, + release_contains, suppressed_ref_lines, update_config_refs, walk_repo_ref_pairs, @@ -373,10 +376,41 @@ def _write_role( return config -def _find(root: Path, ls_remote: _LsRemote) -> list[RepositoryRefUpdate]: +class _Contains: + """Stand-in for :func:`release_contains`. + + Args: + answer: what every call reports; ``None`` fails any call. + """ + + def __init__(self, answer: bool | None) -> None: + self.answer = answer + self.calls: list[tuple[str, str, str]] = [] + + def __call__(self, url: str, sha: str, tag: str) -> bool: + if self.answer is None: + raise AssertionError(f"release_contains({url}, {sha}, {tag}) called") + self.calls.append((url, sha, tag)) + return self.answer + + +def _find( + root: Path, ls_remote: _LsRemote, contains: _Contains | None = None +) -> list[RepositoryRefUpdate]: + """Run :func:`find_outdated_updates` against stand-ins. + + Args: + root: the repository root holding ``roles/``. + ls_remote: answers every ``git ls-remote``. + contains: answers :func:`release_contains`; ``None`` asserts it is + never called. + """ + if contains is None: + contains = _Contains(answer=None) with ( unittest.mock.patch.object(module, "resolve_max_fetch_workers", return_value=2), unittest.mock.patch.object(module.subprocess, "run", side_effect=ls_remote), + unittest.mock.patch.object(module, "release_contains", side_effect=contains), ): return find_outdated_updates(root) @@ -412,6 +446,69 @@ class TestIsCommitSha(unittest.TestCase): self.assertFalse(is_commit_sha("v1.0.0")) +class TestLatestRelease(unittest.TestCase): + def test_the_newest_unflavored_semver_tag_wins(self) -> None: + self.assertEqual( + latest_release(["v0.1.0", "v0.1.1", "v0.2.0-rc.1", "nightly"]), "v0.1.1" + ) + self.assertEqual(latest_release(["6.8.0", "6.9.0", "6.10.0"]), "6.10.0") + + def test_no_release_tag_yields_none(self) -> None: + self.assertIsNone(latest_release([])) + self.assertIsNone(latest_release(["v1.0.0-rc.1", "nightly"])) + + +_ISOLATED_GIT = {"GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1"} + + +class TestReleaseContains(unittest.TestCase): + def setUp(self) -> None: + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + upstream = Path(tmp.name) / "upstream" + upstream.mkdir() + self.env = { + **{k: v for k, v in os.environ.items() if not k.startswith("GIT_")}, + **_ISOLATED_GIT, + "GIT_AUTHOR_NAME": "test", + "GIT_AUTHOR_EMAIL": "test@example.invalid", + "GIT_COMMITTER_NAME": "test", + "GIT_COMMITTER_EMAIL": "test@example.invalid", + } + self._git(upstream, "init", "--quiet") + self.released = self._commit(upstream, "released") + self._git(upstream, "tag", "-a", "v1.0.0", "-m", "v1.0.0") + self.unreleased = self._commit(upstream, "after the release") + self.url = upstream.as_uri() + + def _git(self, cwd: Path, *args: str) -> str: + return subprocess.run( + ["git", *args], + cwd=cwd, + env=self.env, + capture_output=True, + text=True, + check=True, + ).stdout.strip() + + def _commit(self, repo: Path, message: str) -> str: + self._git(repo, "commit", "--quiet", "--allow-empty", "-m", message) + return self._git(repo, "rev-parse", "HEAD") + + def _contains(self, sha: str, tag: str) -> bool: + with unittest.mock.patch.dict(os.environ, _ISOLATED_GIT): + return release_contains(self.url, sha, tag) + + def test_a_commit_the_release_carries_is_contained(self) -> None: + self.assertTrue(self._contains(self.released, "v1.0.0")) + + def test_a_commit_after_the_release_is_not_contained(self) -> None: + self.assertFalse(self._contains(self.unreleased, "v1.0.0")) + + def test_a_missing_tag_proves_nothing(self) -> None: + self.assertFalse(self._contains(self.released, "v9.9.9")) + + class TestGitLsRemoteHead(unittest.TestCase): def test_returns_the_head_commit(self) -> None: ls_remote = _LsRemote(heads={SHA_REPO: TIP_SHA}) @@ -508,6 +605,54 @@ class TestCommitShaPins(unittest.TestCase): written, SHA_PINNED.replace(f'"{OLD_SHA}"', f'"{TIP_SHA}"') ) + def test_a_sha_contained_in_the_newest_release_moves_to_that_tag( + self, + ) -> None: + with tempfile.TemporaryDirectory() as tmpdir: + root = Path(tmpdir) + config = _write_role(root, SHA_PINNED) + ls_remote = _LsRemote( + heads={SHA_REPO: TIP_SHA}, + tags={SHA_REPO: ["v1.0.0", "v1.2.0", "v2.0.0-rc.1"]}, + ) + contains = _Contains(answer=True) + + updates = _find(root, ls_remote, contains) + + self.assertEqual([u.latest for u in updates], ["v1.2.0"]) + self.assertEqual(contains.calls, [(SHA_REPO, OLD_SHA, "v1.2.0")]) + self.assertEqual(ls_remote.calls, [("--tags", SHA_REPO)]) + apply_updates(updates) + written = config.read_text() # nocheck: cache-read just rewritten here + self.assertIn('ref: "v1.2.0"', written) + + def test_a_sha_newer_than_the_newest_release_follows_the_tip(self) -> None: + with tempfile.TemporaryDirectory() as tmpdir: + root = Path(tmpdir) + _write_role(root, SHA_PINNED) + ls_remote = _LsRemote( + heads={SHA_REPO: TIP_SHA}, tags={SHA_REPO: ["v1.0.0", "v1.2.0"]} + ) + + updates = _find(root, ls_remote, _Contains(answer=False)) + + self.assertEqual([u.latest for u in updates], [TIP_SHA]) + self.assertEqual( + sorted(ls_remote.calls), [("--tags", SHA_REPO), (SHA_REPO, "HEAD")] + ) + + def test_a_sha_whose_upstream_has_only_flavored_tags_follows_the_tip( + self, + ) -> None: + with tempfile.TemporaryDirectory() as tmpdir: + root = Path(tmpdir) + _write_role(root, SHA_PINNED) + ls_remote = _LsRemote( + heads={SHA_REPO: TIP_SHA}, tags={SHA_REPO: ["v2.0.0-rc.1"]} + ) + + self.assertEqual([u.latest for u in _find(root, ls_remote)], [TIP_SHA]) + def test_a_current_sha_is_left_alone(self) -> None: with tempfile.TemporaryDirectory() as tmpdir: root = Path(tmpdir) @@ -576,7 +721,7 @@ class TestCommitShaPins(unittest.TestCase): ) self.assertEqual(_find(root, ls_remote), []) - self.assertEqual(len(ls_remote.calls), 2) + self.assertEqual(len(ls_remote.calls), 3) def test_each_repository_is_queried_once_per_lookup_kind(self) -> None: with tempfile.TemporaryDirectory() as tmpdir: @@ -595,7 +740,7 @@ class TestCommitShaPins(unittest.TestCase): self.assertEqual( sorted(ls_remote.calls), - [("--tags", TAG_REPO), (SHA_REPO, "HEAD")], + [("--tags", TAG_REPO), ("--tags", SHA_REPO), (SHA_REPO, "HEAD")], ) self.assertEqual( sorted((u.entry.entity_path, u.latest) for u in updates), diff --git a/utils/update/level.py b/utils/update/level.py new file mode 100644 index 0000000000..2af98890af --- /dev/null +++ b/utils/update/level.py @@ -0,0 +1,122 @@ +"""Classify the version step an update commit makes as major, minor or patch. + +Standard library only: the runner-label update job installs no dependencies. + +Usage: ``python3 -m utils.update.level `` prints the highest +level of every version changed between the two revisions. +""" + +from __future__ import annotations + +import re +import subprocess +import sys + +LEVELS = ("patch", "minor", "major") +_SHA_RE = re.compile(r"[0-9a-f]{40}") +_VERSION_TOKEN_RE = re.compile(r"[0-9a-f]{40}|\d+(?:\.\d+)*") + + +def bump_level(old: str, new: str) -> str: + """Return the level of the step between two versions. + + Args: + old: version before the update. + new: version after it. + + Returns: + ``major`` when the first number changes or either side is a commit + SHA or carries no number, ``minor`` when the second changes, else + ``patch``. + """ + if _SHA_RE.fullmatch(old) or _SHA_RE.fullmatch(new): + return "major" + old_parts = re.findall(r"\d+", old) + new_parts = re.findall(r"\d+", new) + if not old_parts or not new_parts: + return "major" + for index, (before, after) in enumerate(zip(old_parts, new_parts, strict=False)): + if int(before) != int(after): + return LEVELS[max(0, 2 - index)] + return "patch" + + +def line_level(old: str, new: str) -> str: + """Return the level of one rewritten line. + + Args: + old: the line before the update. + new: the line after it. + + Returns: + The level of the first version token that differs; ``major`` when + the lines carry a different number of version tokens or none differs. + """ + old_tokens = _VERSION_TOKEN_RE.findall(old) + new_tokens = _VERSION_TOKEN_RE.findall(new) + if len(old_tokens) != len(new_tokens): + return "major" + for before, after in zip(old_tokens, new_tokens, strict=True): + if before != after: + return bump_level(before, after) + return "major" + + +def diff_level(diff: str) -> str: + """Return the highest level of every line pair a ``-U0`` diff rewrites. + + Args: + diff: output of ``git diff -U0``. + + Returns: + The highest level; ``major`` when a hunk removes and adds a different + number of lines or the diff rewrites nothing. + """ + levels: list[str] = [] + removed: list[str] = [] + added: list[str] = [] + + def flush() -> None: + if len(removed) != len(added): + levels.append("major") + levels.extend(line_level(o, n) for o, n in zip(removed, added, strict=False)) + removed.clear() + added.clear() + + for line in diff.splitlines(): + if line.startswith(("--- ", "+++ ")): + continue + if line.startswith("@@"): + flush() + elif line.startswith("-"): + removed.append(line[1:]) + elif line.startswith("+"): + added.append(line[1:]) + flush() + return max(levels, key=LEVELS.index, default="major") + + +def main(argv: list[str]) -> int: + """Print the level of the update between two revisions. + + Args: + argv: ``[base, head]`` revisions passed to ``git diff``. + + Returns: + Exit status 0, or 2 on a usage error. + """ + if len(argv) != 2: + print("usage: python3 -m utils.update.level ", file=sys.stderr) + return 2 + diff = subprocess.run( + ["git", "diff", "-U0", argv[0], argv[1]], + capture_output=True, + text=True, + check=True, + ).stdout + print(diff_level(diff)) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/utils/update/repository.py b/utils/update/repository.py index 5cff7aad24..327c31f839 100644 --- a/utils/update/repository.py +++ b/utils/update/repository.py @@ -12,8 +12,10 @@ sub-entity, plugin map, an addon's ``config``, ...) that declares BOTH - a semver ref moves to the newest tag of the same depth and flavor, read with ``git ls-remote --tags ``; -- a full 40-hex commit SHA moves to the tip of the repository's default - branch, read with ``git ls-remote HEAD``. +- a full 40-hex commit SHA moves to the newest release tag when that tag + contains it, else to the tip of the repository's default branch, read + with ``git ls-remote HEAD``; a pin never moves back to an + older release. Branches (`master`, `main`, `stable`) and short SHAs are skipped. @@ -33,6 +35,7 @@ from __future__ import annotations import concurrent.futures import re import subprocess +import tempfile from dataclasses import dataclass from typing import TYPE_CHECKING @@ -58,6 +61,7 @@ if TYPE_CHECKING: _NOCHECK_MARKER = "repository-version" _COMMIT_SHA_RE = re.compile(r"^[0-9a-f]{40}$") +_FETCH_TIMEOUT_SECONDS = 120 _REF_VALUE_RE = re.compile( r"^(?P\s*ref\s*:\s*)" @@ -141,6 +145,64 @@ def _ls_remote(*args: str) -> str | None: return proc.stdout +def latest_release(tags: list[str]) -> str | None: + """Return the newest unflavored semver tag, so ``-rc.1`` never wins. + + Args: + tags: tag names of one repository. + """ + return max( + (tag for tag in tags if is_semver(tag) and not version_flavor(tag)), + key=version_key, + default=None, + ) + + +def _git_succeeds(git_dir: str, *args: str) -> bool: + try: + proc = subprocess.run( + ["git", *args], + cwd=git_dir, + capture_output=True, + text=True, + timeout=_FETCH_TIMEOUT_SECONDS, + check=False, + ) + except (FileNotFoundError, subprocess.TimeoutExpired): + return False + return proc.returncode == 0 + + +def release_contains(url: str, sha: str, tag: str) -> bool: + """Report whether release *tag* of *url* contains commit *sha*, so a pin + never moves back to a release older than itself. + + Args: + url: the upstream repository. + sha: the pinned commit. + tag: the release tag the pin would move to. + + Returns: + ``True`` only when a treeless fetch of the tag proves *sha* its + ancestor; a failed fetch proves nothing and yields ``False``. + """ + ref = f"refs/tags/{tag}" + with tempfile.TemporaryDirectory() as git_dir: + return ( + _git_succeeds(git_dir, "init", "--bare", "--quiet") + and _git_succeeds( + git_dir, + "fetch", + "--quiet", + "--no-tags", + "--filter=tree:0", + url, + f"{ref}:{ref}", + ) + and _git_succeeds(git_dir, "merge-base", "--is-ancestor", sha, ref) + ) + + def git_ls_remote_head(url: str) -> str | None: """Return the commit the remote's ``HEAD`` (its default branch) points at, or ``None`` when the lookup fails.""" @@ -294,6 +356,7 @@ def _target_ref( entry: RepositoryRefEntry, repo_tags: dict[str, list[str]], repo_heads: dict[str, str | None], + released: dict[tuple[str, str], str], ) -> str | None: """Return the ref *entry* should move to, or ``None`` when it stays. @@ -302,8 +365,13 @@ def _target_ref( repo_tags: tag names per repository, empty when the lookup failed. repo_heads: default-branch tip per repository, ``None`` when the lookup failed. + released: the newest release tag per ``(repository, sha)`` pin that + the tag contains. """ if is_commit_sha(entry.ref): + release = released.get((entry.repository, entry.ref)) + if release: + return release tip = repo_heads.get(entry.repository) return tip if tip and tip != entry.ref else None tags = repo_tags.get(entry.repository, []) @@ -322,23 +390,44 @@ def _target_ref( def find_outdated_updates(repo_root: Path) -> list[RepositoryRefUpdate]: """Cross-reference every collected entry against its upstream and return the entries that are behind: a semver ref older than the latest - tag with the same depth and flavor (``git ls-remote --tags``), or a - commit SHA that is not the default branch's tip - (``git ls-remote HEAD``).""" + tag with the same depth and flavor (``git ls-remote --tags``), a commit + SHA contained in its upstream's newest release tag + (:func:`release_contains`), or any other commit SHA that is not the + default branch's tip (``git ls-remote HEAD``).""" entries = collect_entries(repo_root) - sha_repos = sorted({e.repository for e in entries if is_commit_sha(e.ref)}) - tag_repos = sorted({e.repository for e in entries if not is_commit_sha(e.ref)}) + repos = sorted({e.repository for e in entries}) with concurrent.futures.ThreadPoolExecutor( max_workers=resolve_max_fetch_workers() ) as pool: - tags = pool.map(git_ls_remote_tags, tag_repos) + tags = pool.map(git_ls_remote_tags, repos) + repo_tags: dict[str, list[str]] = dict(zip(repos, tags, strict=True)) + candidates = sorted( + { + (e.repository, e.ref, release) + for e in entries + if is_commit_sha(e.ref) + and (release := latest_release(repo_tags[e.repository])) + } + ) + contained = pool.map(lambda c: release_contains(*c), candidates) + released = { + (repo, sha): tag + for (repo, sha, tag), ok in zip(candidates, contained, strict=True) + if ok + } + sha_repos = sorted( + { + e.repository + for e in entries + if is_commit_sha(e.ref) and (e.repository, e.ref) not in released + } + ) heads = pool.map(git_ls_remote_head, sha_repos) - repo_tags: dict[str, list[str]] = dict(zip(tag_repos, tags, strict=True)) repo_heads: dict[str, str | None] = dict(zip(sha_repos, heads, strict=True)) updates: list[RepositoryRefUpdate] = [] for entry in entries: - target = _target_ref(entry, repo_tags, repo_heads) + target = _target_ref(entry, repo_tags, repo_heads, released) if target: updates.append(RepositoryRefUpdate(entry=entry, latest=target)) return updates