Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
ci(release): stamp OpenAPI versions in the release pull request (#300)
Krisztian Gajdar1ce0afd918bf
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 48250233f..c8fb2a353 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -85,7 +85,7 @@ jobs:version: 2026.5.5install_args: --jobs=1if: steps.release.outputs.prs != '' && steps.release.outputs.prs != '[]'- - name: Refresh coupled locks on the release pull request+ - name: Refresh coupled locks and OpenAPI versions on the release pull requestif: steps.release.outputs.prs != '' && steps.release.outputs.prs != '[]'env:GH_TOKEN: ${{ steps.app-token.outputs.token }}@@ -99,13 +99,14 @@ jobs:mise exec -- uv lock --project .mise exec -- pnpm install --lockfile-onlymise exec -- cargo metadata --format-version 1 > /dev/null- if git diff --quiet -- uv.lock pnpm-lock.yaml Cargo.lock; then+ mise exec -- python -I tools/ci/release_openapi.py+ if git diff --quiet -- uv.lock pnpm-lock.yaml Cargo.lock packages/sie_server/openapi.json packages/sie_gateway/openapi.json; thenexit 0figit config user.name github-actions[bot]git config user.email 41898282+github-actions[bot]@users.noreply.github.com- git add uv.lock pnpm-lock.yaml Cargo.lock- git commit -m 'chore: refresh release locks'+ git add uv.lock pnpm-lock.yaml Cargo.lock packages/sie_server/openapi.json packages/sie_gateway/openapi.json+ git commit -m 'chore: refresh release locks and OpenAPI versions'git push origin "HEAD:refs/heads/$branch"- id: release-pr-headname: Verify the release PR final head after the App-authored pushdiff --git a/RELEASE.md b/RELEASE.mdindex d1fd076a7..408f8a7d5 100644--- a/RELEASE.md+++ b/RELEASE.md@@ -20,10 +20,14 @@ commits generate `CHANGELOG.md`. No old changelog sections are rewritten.The release PR updates the coordinated Python/npm package versions, gateway,sidecar and audio release fields, TypeScript runtime version, and Helm metadata.-It also refreshes the coupled public locks. Config and MCP join this train for-their first PyPI publication. Independently versioned implementation crates are-not silently renumbered: a Rust worker image follows the release image tag even-where its crate has an independent version.+It also refreshes the coupled public locks and stamps the new version into the+committed server and gateway OpenAPI documents. CI regenerates those documents+and requires identical bytes, so they are not release-please extra files: its+JSON rewrite changes number formatting and precision, string escapes, and key+order. Config and MCP join this train for their first PyPI publication.+Independently versioned implementation crates are not silently renumbered: a+Rust worker image follows the release image tag even where its crate has an+independent version.Release PRs receive the same mandatory CI checks as other PRs. Release-pleaseand its lock refresh use a repository-scoped GitHub App so their PR updatesdiff --git a/tools/ci/check_release_contract.py b/tools/ci/check_release_contract.pyindex d2f328730..38fa5fdd6 100755--- a/tools/ci/check_release_contract.py+++ b/tools/ci/check_release_contract.py@@ -12,7 +12,7 @@ import tomllibfrom pathlib import Pathfrom typing import Any-from tools.ci import distributions+from tools.ci import distributions, release_openapifrom tools.ci.release_guard import SEED_VERSION, stable_versionROOT = Path(__file__).resolve().parents[2]@@ -73,6 +73,50 @@ EXTRA_VERSION_PATHS = {"packages/sie_audio_prep/build_wheel.py","deploy/helm/sie-cluster/Chart.yaml",}+OPENAPI_VERSION_PATHS = {+ "packages/sie_server/openapi.json",+ "packages/sie_gateway/openapi.json",+}+OPENAPI_STAMP_COMMAND = "mise exec -- python -I tools/ci/release_openapi.py"+PLAIN_PATHS = r"((?:[\w.][\w./-]* )*[\w.][\w./-]*)"+CONTRACTS_OPENAPI_COMMANDS = (+ ("mise run openapi", re.compile(re.escape("- run: mise run openapi"))),+ ("git diff", re.compile(rf"- run: git diff --exit-code -- {PLAIN_PATHS}")),+)+REFRESH_OPENAPI_COMMANDS = (+ ("git checkout", re.compile(re.escape('git checkout -B "$branch" FETCH_HEAD'))),+ ("tools/ci/release_openapi.py", re.compile(re.escape(OPENAPI_STAMP_COMMAND))),+ ("git diff", re.compile(rf"if git diff --quiet -- {PLAIN_PATHS}; then")),+ ("git add", re.compile(rf"git add {PLAIN_PATHS}")),+ ("git commit", re.compile(r"git commit -m '[^'\\]*'")),+ ("git push", re.compile(re.escape('git push origin "HEAD:refs/heads/$branch"'))),+)+SHELL_CONTROL_FLOW = frozenset(+ {+ "if",+ "elif",+ "else",+ "fi",+ "while",+ "until",+ "for",+ "do",+ "done",+ "case",+ "esac",+ "function",+ "exit",+ "return",+ "trap",+ "eval",+ "source",+ ".",+ "{",+ "}",+ "(",+ ")",+ }+)ACTION_PIN = re.compile(r"^[^@\s]+@[0-9a-f]{40}$")JOB_FIELD_INDENT = 4ARTIFACT_RETENTION_DAYS = 30@@ -329,6 +373,95 @@ def release_config_errors() -> list[str]:for path in extra_paths:if not (ROOT / path).is_file():errors.append(f"release-please extra file does not exist: {path}")+ if extra_paths & OPENAPI_VERSION_PATHS:+ errors.append("generated OpenAPI documents must be stamped, not rewritten by release-please")+ errors.extend(+ release_openapi_errors(+ workflow_job_blocks(".github/workflows/release.yml").get("release-please", ""),+ workflow_job_blocks(".github/workflows/ci.yml").get("contracts", ""),+ set(release_openapi.OPENAPI_VERSION_SOURCES),+ )+ )+ return errors+++def step_lines(block: str) -> list[str]:+ """Strip workflow lines, joining each folded `>-` scalar onto its key line."""+ lines: list[str] = []+ continuation: int | None = None+ for raw in block.splitlines():+ indent = len(raw) - len(raw.lstrip())+ if continuation is not None and raw.strip() and indent >= continuation:+ lines[-1] = f"{lines[-1]} {raw.strip()}"+ continue+ continuation = None+ line = raw.strip()+ if line.endswith(": >-"):+ continuation = indent + (4 if line.startswith("- ") else 2)+ line = line.removesuffix(" >-")+ lines.append(line)+ return lines+++def exact_commands(+ lines: list[str], commands: tuple[tuple[str, re.Pattern[str]], ...]+) -> list[tuple[int, re.Match[str]]] | None:+ """Match each command on the only line that mentions it, requiring the commands in order."""+ found: list[tuple[int, re.Match[str]]] = []+ for marker, command in commands:+ indexes = [index for index, line in enumerate(lines) if marker in line]+ match = command.fullmatch(lines[indexes[0]]) if len(indexes) == 1 else None+ if match is None or (found and indexes[0] <= found[-1][0]):+ return None+ found.append((indexes[0], match))+ return found+++def step_bounds(lines: list[str], index: int) -> tuple[int, int]:+ """Return the line range of the workflow step holding the given line."""+ start = next((position for position in range(index, -1, -1) if lines[position].startswith("- ")), 0)+ end = next((position for position in range(index + 1, len(lines)) if lines[position].startswith("- ")), len(lines))+ return start, end+++def refresh_control_flow(lines: list[str], commands: list[tuple[int, re.Match[str]]]) -> list[str]:+ """Return the shell control-flow lines of every step that runs one of the commands."""+ steps = sorted({step_bounds(lines, index) for index, _ in commands})+ shell = [line for start, end in steps for line in lines[start:end]]+ return [line for line in shell if line.split(" ")[0].removesuffix(";") in SHELL_CONTROL_FLOW]+++def release_openapi_errors(refresh: str, contracts: str, stamped: set[str]) -> list[str]:+ def documents(match: re.Match[str]) -> set[str]:+ return set(re.findall(r"[\w/]+/openapi\.json", match.group(1)))++ def ends_step(lines: list[str], index: int) -> bool:+ return index + 1 == len(lines) or not lines[index + 1] or lines[index + 1].startswith("- ")++ errors: list[str] = []+ if stamped != OPENAPI_VERSION_PATHS:+ errors.append("release OpenAPI version stamping differs from the public contract")+ contract_lines = step_lines(contracts)+ regenerated = exact_commands(contract_lines, CONTRACTS_OPENAPI_COMMANDS)+ if (+ regenerated is None+ or documents(regenerated[-1][1]) != OPENAPI_VERSION_PATHS+ or not all(ends_step(contract_lines, index) for index, _ in regenerated)+ or any(line.startswith("continue-on-error") for line in contract_lines)+ ):+ errors.append("CI / Contracts must regenerate and then diff exactly the stamped OpenAPI documents")+ refresh_lines = step_lines(refresh)+ refreshed = exact_commands(refresh_lines, REFRESH_OPENAPI_COMMANDS)+ if (+ refreshed is None+ or any(documents(match) != OPENAPI_VERSION_PATHS for _, match in refreshed[2:4])+ or any(line.startswith(("set +", "shell:", "continue-on-error")) for line in refresh_lines)+ or refresh_control_flow(refresh_lines, refreshed) != [refresh_lines[refreshed[2][0]], "exit 0", "fi"]+ ):+ errors.append(+ "release PR refresh must run checkout, OpenAPI stamp, diff, add, commit, and push once each, "+ "in order, as exact commands without failure suppression"+ )return errorsdiff --git a/tools/ci/release_openapi.py b/tools/ci/release_openapi.pynew file mode 100755index 000000000..29199d4d8--- /dev/null+++ b/tools/ci/release_openapi.py@@ -0,0 +1,40 @@+#!/usr/bin/env python3+"""Stamp each package version into the committed OpenAPI document generated from it."""++from __future__ import annotations++import json+import re+import tomllib+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+OPENAPI_VERSION_SOURCES = {+ "packages/sie_server/openapi.json": ("packages/sie_server/pyproject.toml", "project"),+ "packages/sie_gateway/openapi.json": ("packages/sie_gateway/Cargo.toml", "package"),+}+INFO_VERSION = re.compile(r'^( "version": )"[^"\\]*"(,?)$', re.MULTILINE)+++def stamp(document: str, version: str) -> str:+ stamped, members = INFO_VERSION.subn(lambda match: f"{match[1]}{json.dumps(version)}{match[2]}", document)+ expected = json.loads(document)+ expected["info"]["version"] = version+ if members != 1 or json.loads(stamped) != expected:+ raise ValueError("OpenAPI document must carry exactly one pretty-printed info.version member")+ return stamped+++def manifest_version(document: str) -> str:+ manifest, table = OPENAPI_VERSION_SOURCES[document]+ return tomllib.loads((ROOT / manifest).read_text(encoding="utf-8"))[table]["version"]+++def main() -> None:+ for document in OPENAPI_VERSION_SOURCES:+ path = ROOT / document+ path.write_text(stamp(path.read_text(encoding="utf-8"), manifest_version(document)), encoding="utf-8")+++if __name__ == "__main__":+ main()diff --git a/tools/ci/tests/test_release_contract.py b/tools/ci/tests/test_release_contract.pyindex 287d36c80..d85201a17 100644--- a/tools/ci/tests/test_release_contract.py+++ b/tools/ci/tests/test_release_contract.py@@ -13,6 +13,7 @@ from pathlib import Pathimport pytestfrom tools.ci import check_release_contract as contract+from tools.ci import release_openapidef run_audio_uploader(@@ -112,6 +113,194 @@ def test_release_please_rejects_any_other_bootstrap_boundary(monkeypatch, bootstassert "release-please bootstrap-sha must be the exact public v0.7.3 commit" in contract.release_config_errors()+def openapi_surfaces() -> tuple[str, str, set[str]]:+ refresh = contract.workflow_job_blocks(".github/workflows/release.yml")["release-please"]+ contracts = contract.workflow_job_blocks(".github/workflows/ci.yml")["contracts"]+ return refresh, contracts, set(release_openapi.OPENAPI_VERSION_SOURCES)++[email protected]("document", sorted(contract.OPENAPI_VERSION_PATHS))+def test_release_pr_stamps_every_openapi_version_ci_regenerates(document) -> None:+ refresh, contracts, stamped = openapi_surfaces()+ assert contract.release_openapi_errors(refresh, contracts, stamped) == []++ assert contract.release_openapi_errors(refresh, contracts, stamped - {document})+ assert contract.release_openapi_errors(refresh, contracts.replace(document, ""), stamped)+ for command in ("git diff --quiet --", "git add"):+ unstaged = re.sub(rf"({re.escape(command)} .*) {re.escape(document)}", r"\1", refresh)+ assert unstaged != refresh+ assert contract.release_openapi_errors(unstaged, contracts, stamped)+ unstamped = refresh.replace(contract.OPENAPI_STAMP_COMMAND, "")+ assert contract.release_openapi_errors(unstamped, contracts, stamped)+++ ("anchor", "offset", "valid"),+ [+ ('git checkout -B "$branch" FETCH_HEAD', 1, True),+ ("mise exec -- cargo metadata", 1, True),+ ('git checkout -B "$branch" FETCH_HEAD', 0, False),+ ("git diff --quiet --", 1, False),+ ("git add ", 1, False),+ ],+)+def test_release_pr_stamps_openapi_versions_after_checkout_and_before_commit(anchor, offset, valid) -> None:+ refresh, contracts, stamped = openapi_surfaces()+ lines = refresh.splitlines()+ stamp = next(line for line in lines if line.strip() == contract.OPENAPI_STAMP_COMMAND)+ lines.remove(stamp)+ lines.insert(next(index for index, line in enumerate(lines) if anchor in line) + offset, stamp)+ assert (contract.release_openapi_errors("\n".join(lines), contracts, stamped) == []) is valid+++ "stamp",+ [+ f"{contract.OPENAPI_STAMP_COMMAND} || true",+ f"# {contract.OPENAPI_STAMP_COMMAND}",+ contract.OPENAPI_STAMP_COMMAND.replace(" -I ", " "),+ ],+)+def test_release_pr_stamp_fails_closed_in_isolated_python(stamp) -> None:+ refresh, contracts, stamped = openapi_surfaces()+ weakened = refresh.replace(contract.OPENAPI_STAMP_COMMAND, stamp)+ assert weakened != refresh+ assert contract.release_openapi_errors(weakened, contracts, stamped)+++def line_index(lines: list[str], text: str) -> int:+ return next(index for index, line in enumerate(lines) if text in line)+++def duplicate_diff_check(lines: list[str]) -> None:+ start = line_index(lines, "git diff --quiet --")+ lines[start:start] = lines[start : start + 3]+++def duplicate_staging(lines: list[str]) -> None:+ stage = line_index(lines, "git add ")+ lines.insert(stage, lines[stage])+++def move_before(lines: list[str], moved: str, anchor: str) -> None:+ line = lines.pop(line_index(lines, moved))+ lines.insert(line_index(lines, anchor), line)+++ "rewrite",+ [+ duplicate_diff_check,+ duplicate_staging,+ lambda lines: move_before(lines, "git add ", "git diff --quiet --"),+ lambda lines: move_before(lines, "git commit ", "git add "),+ lambda lines: move_before(lines, "git push origin ", "git commit "),+ ],+ ids=["duplicate-diff", "duplicate-add", "add-before-diff", "commit-before-add", "push-before-commit"],+)+def test_release_pr_refresh_diffs_adds_commits_and_pushes_once_in_order(rewrite) -> None:+ refresh, contracts, stamped = openapi_surfaces()+ lines = refresh.splitlines()+ rewrite(lines)+ assert lines != refresh.splitlines()+ assert contract.release_openapi_errors("\n".join(lines), contracts, stamped)+++REFRESH_RUN = " run: |\n set -euo pipefail\n branch="+++ ("surface", "old", "new"),+ [+ ("contracts", "- run: mise run openapi\n", "# - run: mise run openapi\n"),+ ("contracts", "- run: mise run openapi\n", "- run: echo mise run openapi\n"),+ ("contracts", "- run: mise run openapi\n", "- run: mise run openapi\n if: false\n"),+ ("contracts", "packages/sie_gateway/openapi.json\n", "packages/sie_gateway/openapi.json\n || true\n"),+ (+ "contracts",+ "packages/sie_gateway/openapi.json\n",+ "packages/sie_gateway/openapi.json\n continue-on-error: true\n",+ ),+ ("contracts", " timeout-minutes: 25\n", " timeout-minutes: 25\n continue-on-error: true\n"),+ ("refresh", "if git diff --quiet --", "if echo git diff --quiet --"),+ ("refresh", "git add uv.lock", "git add --dry-run uv.lock"),+ ("refresh", "packages/sie_gateway/openapi.json\n", "packages/sie_gateway/openapi.json || true\n"),+ ("refresh", "OpenAPI versions'\n", "OpenAPI versions' || true\n"),+ ("refresh", '"HEAD:refs/heads/$branch"\n', '"HEAD:refs/heads/$branch" || true\n'),+ ("refresh", f"{contract.OPENAPI_STAMP_COMMAND}\n", f"set +e\n {contract.OPENAPI_STAMP_COMMAND}\n"),+ ("refresh", f"{contract.OPENAPI_STAMP_COMMAND}\n", f"exit 0\n {contract.OPENAPI_STAMP_COMMAND}\n"),+ ("refresh", REFRESH_RUN, f" continue-on-error: true\n{REFRESH_RUN}"),+ ("refresh", REFRESH_RUN, f" shell: bash {{0}}\n{REFRESH_RUN}"),+ ],+ ids=[+ "commented-regeneration",+ "echoed-regeneration",+ "skipped-regeneration",+ "diff-or-true",+ "diff-continue-on-error",+ "contracts-job-continue-on-error",+ "echoed-refresh-diff",+ "dry-run-add",+ "add-or-true",+ "commit-or-true",+ "push-or-true",+ "set-plus-e",+ "early-exit",+ "refresh-continue-on-error",+ "refresh-shell-without-errexit",+ ],+)+def test_release_openapi_contract_rejects_inactive_or_suppressed_commands(surface, old, new) -> None:+ refresh, contracts, stamped = openapi_surfaces()+ surfaces = {"refresh": refresh, "contracts": contracts}+ assert surfaces[surface].count(old) == 1+ surfaces[surface] = surfaces[surface].replace(old, new)+ assert contract.release_openapi_errors(surfaces["refresh"], surfaces["contracts"], stamped)+++ ("opened", "closed"),+ [("if false; then", "fi"), ("while false; do", "done")],+ ids=["if-false", "while-false"],+)+def test_release_pr_refresh_rejects_inactive_shell_wrappers(opened, closed) -> None:+ refresh, contracts, stamped = openapi_surfaces()+ opening = f" run: |\n set -euo pipefail\n {opened}\n branch="+ wrapped = refresh.replace(REFRESH_RUN, opening).replace(+ '"HEAD:refs/heads/$branch"\n', f'"HEAD:refs/heads/$branch"\n {closed}\n'+ )+ assert wrapped != refresh+ assert contract.release_openapi_errors(wrapped, contracts, stamped)+++def test_release_pr_refresh_rejects_commands_moved_into_another_step() -> None:+ refresh, contracts, stamped = openapi_surfaces()+ lines = refresh.splitlines()+ lines.insert(line_index(lines, 'pr_number="$(jq'), lines.pop(line_index(lines, "git push origin")))+ moved = "\n".join(lines)+ assert moved != refresh+ assert contract.release_openapi_errors(moved, contracts, stamped)++[email protected]("document", sorted(contract.OPENAPI_VERSION_PATHS))+def test_release_please_must_not_rewrite_generated_openapi(monkeypatch, document) -> None:+ real_load_json = contract.load_json++ def load_json(path):+ loaded = real_load_json(path)+ if path == "release-please-config.json":+ loaded = deepcopy(loaded)+ extra_file = {"type": "json", "path": document, "jsonpath": "$.info.version"}+ loaded["packages"]["."]["extra-files"].append(extra_file)+ return loaded++ monkeypatch.setattr(contract, "load_json", load_json)+ monkeypatch.setattr(contract, "EXTRA_VERSION_PATHS", contract.EXTRA_VERSION_PATHS | {document})+ assert contract.release_config_errors() == [+ "generated OpenAPI documents must be stamped, not rewritten by release-please"+ ]++def test_option_ext_mpl_exception_is_exact_and_cannot_broaden() -> None:policy = tomllib.loads((contract.ROOT / "deny.toml").read_text())assert contract._license_policy_errors(policy) == []diff --git a/tools/ci/tests/test_release_openapi.py b/tools/ci/tests/test_release_openapi.pynew file mode 100644index 000000000..96452aff6--- /dev/null+++ b/tools/ci/tests/test_release_openapi.py@@ -0,0 +1,64 @@+from __future__ import annotations++import json+import shutil+import tomllib+from pathlib import Path++import pytest++from tools.ci import release_openapi++DOCUMENTS = sorted(release_openapi.OPENAPI_VERSION_SOURCES)++[email protected]("document", DOCUMENTS)+def test_stamp_rewrites_only_the_info_version_line(document) -> None:+ committed = (release_openapi.ROOT / document).read_text(encoding="utf-8")+ version = release_openapi.manifest_version(document)+ assert json.loads(committed)["info"]["version"] == version+ assert release_openapi.stamp(committed, version) == committed++ stamped = release_openapi.stamp(committed, "99.100.101")+ changed = [+ (before, after)+ for before, after in zip(committed.split("\n"), stamped.split("\n"), strict=True)+ if before != after+ ]+ assert len(changed) == 1+ before, after = changed[0]+ assert before.startswith(f' "version": "{version}"')+ assert after == before.replace(version, "99.100.101")+++ "document",+ [+ '{"info": {"version": "0.7.3"}}\n',+ '{\n "info": {\n "title": "SIE"\n },\n "x-other": {\n "version": "0.7.3"\n }\n}\n',+ ],+)+def test_stamp_rejects_documents_without_one_pretty_printed_info_version(document) -> None:+ with pytest.raises(ValueError, match=r"info\.version"):+ release_openapi.stamp(document, "0.8.0")+++def test_main_stamps_each_document_from_its_own_manifest(monkeypatch, tmp_path: Path) -> None:+ for document, (manifest, _) in release_openapi.OPENAPI_VERSION_SOURCES.items():+ for relative in (document, manifest):+ (tmp_path / relative).parent.mkdir(parents=True, exist_ok=True)+ shutil.copyfile(release_openapi.ROOT / relative, tmp_path / relative)+ monkeypatch.setattr(release_openapi, "ROOT", tmp_path)+ releases = dict(zip(DOCUMENTS, ("98.0.1", "98.0.2"), strict=True))+ for document, release in releases.items():+ manifest, table = release_openapi.OPENAPI_VERSION_SOURCES[document]+ path = tmp_path / manifest+ text = path.read_text(encoding="utf-8")+ current = tomllib.loads(text)[table]["version"]+ path.write_text(text.replace(f'version = "{current}"', f'version = "{release}"', 1), encoding="utf-8")+ assert release_openapi.manifest_version(document) == release++ release_openapi.main()++ for document, release in releases.items():+ assert json.loads((tmp_path / document).read_text(encoding="utf-8"))["info"]["version"] == release