From 34b0528d90669e7d758393d6c7df7bafcbfb4c8d Mon Sep 17 00:00:00 2001 From: Vianney Mixtur Date: Tue, 24 Nov 2026 22:56:40 +0100 Subject: [PATCH] Report Clairic schema drift as an issue and a pull request Cloudflare does not announce Clairic schema changes, and the weekly check's only output was a 500-line diff in the job log. - check_schema_drift.py compares the schemas property by property and prints a Markdown summary (removed, changed, added, descriptions) before the full diff; --report writes it to a file. - The workflow shows the summary on the run page. When the schemas changed, it pushes the new copies to schema-drift/update, opens or updates a pull request, and opens or comments on a schema-drift issue. It builds on an open pull request instead of replacing it. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/schema-drift.yml | 120 +++++++++++++- README.md | 6 + pyproject.toml | 2 + scripts/check_schema_drift.py | 250 ++++++++++++++++++++++++++--- tests/test_check_schema_drift.py | 108 +++++++++++++ 5 files changed, 466 insertions(+), 20 deletions(-) create mode 100644 tests/test_check_schema_drift.py diff --git a/.github/workflows/schema-drift.yml b/.github/workflows/schema-drift.yml index 3862134..acbb1ab 100644 --- a/.github/workflows/schema-drift.yml +++ b/.github/workflows/schema-drift.yml @@ -1,10 +1,29 @@ name: Clairic schema drift +# Cloudflare does not announce Clairic schema changes, so this compares the published schemas +# with the copies in tests/fixtures/schemas every week. When they differ, it: +# 1. writes a summary of the changes on the run page, +# 2. pushes the new copies to the schema-drift/update branch and opens a pull request, +# 3. opens an issue (or comments on the open one) with the same summary. +# Push the SDK changes to that branch; merging the pull request closes the issue. + on: schedule: - cron: "0 6 * * 1" workflow_dispatch: +permissions: + contents: write # push the schema-drift/update branch + pull-requests: write # open or update the pull request + issues: write # open or comment on the issue + +concurrency: + group: schema-drift + +env: + BRANCH: schema-drift/update + LABEL: schema-drift + jobs: drift: runs-on: ubuntu-latest @@ -12,4 +31,103 @@ jobs: - uses: actions/checkout@v4 - uses: astral-sh/setup-uv@v6 - run: uv sync --locked - - run: uv run python scripts/check_schema_drift.py + + - name: Compare the published schemas with the vendored copies + id: check + run: | + uv run python scripts/check_schema_drift.py --update --report "$RUNNER_TEMP/report.md" + cat "$RUNNER_TEMP/report.md" >> "$GITHUB_STEP_SUMMARY" + if git diff --quiet -- tests/fixtures/schemas; then + echo "changed=false" >> "$GITHUB_OUTPUT" + else + echo "changed=true" >> "$GITHUB_OUTPUT" + mkdir "$RUNNER_TEMP/published" + cp tests/fixtures/schemas/*.json "$RUNNER_TEMP/published/" + git checkout -- tests/fixtures/schemas + fi + + - name: Push the new schemas to the drift branch + id: push + if: steps.check.outputs.changed == 'true' + env: + GH_TOKEN: ${{ github.token }} + run: | + git config user.name "github-actions[bot]" + git config user.email "41898283+github-actions[bot]@users.noreply.github.com" + + pr=$(gh pr list --head "$BRANCH" --state open --json number --jq '.[0].number // empty') + echo "pr=$pr" >> "$GITHUB_OUTPUT" + if [ -n "$pr" ]; then + # The open pull request may already hold SDK fixes: add to it, never replace it. + git fetch --depth=1 origin "$BRANCH" + git switch -c "$BRANCH" FETCH_HEAD + else + git switch -c "$BRANCH" + fi + + cp "$RUNNER_TEMP"/published/*.json tests/fixtures/schemas/ + if git diff --quiet -- tests/fixtures/schemas; then + echo "new=false" >> "$GITHUB_OUTPUT" + echo "Already reported in #$pr; nothing new since." >> "$GITHUB_STEP_SUMMARY" + exit 0 + fi + echo "new=true" >> "$GITHUB_OUTPUT" + git add tests/fixtures/schemas + git commit -m "Update the vendored Clairic schemas ($(date -u +%F))" + if [ -n "$pr" ]; then + git push origin "$BRANCH" + else + # No open pull request: a leftover branch from an earlier round is stale. + git push --force origin "$BRANCH" + fi + + - name: Open or update the issue and the pull request + if: steps.push.outputs.new == 'true' + env: + GH_TOKEN: ${{ github.token }} + PR: ${{ steps.push.outputs.pr }} + BASE: ${{ github.event.repository.default_branch }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + COMPARE_URL: ${{ github.server_url }}/${{ github.repository }}/compare + run: | + report="$RUNNER_TEMP/report.md" + today=$(date -u +%F) + gh label create "$LABEL" --color fbca04 \ + --description "Cloudflare changed the published Clairic schemas" 2>/dev/null || true + + issue=$(gh issue list --label "$LABEL" --state open --json number --jq '.[0].number // empty') + if [ -n "$issue" ]; then + { echo "Cloudflare changed the schemas again ($today, [run]($RUN_URL))."; echo; cat "$report"; } \ + > "$RUNNER_TEMP/comment.md" + gh issue comment "$issue" --body-file "$RUNNER_TEMP/comment.md" + else + { echo "Found by the scheduled schema drift check on $today ([run]($RUN_URL))."; echo; cat "$report"; } \ + > "$RUNNER_TEMP/issue.md" + url=$(gh issue create --title "Cloudflare changed the Clairic schemas" \ + --label "$LABEL" --label preview-api --body-file "$RUNNER_TEMP/issue.md") + issue=${url##*/} + fi + + { + echo "Closes #$issue." + echo + echo "This branch holds Cloudflare's new schemas. Before merging:" + echo + echo "- [ ] Update the answer models and specs in \`src/clairic/\` to match" + echo "- [ ] Fix docstrings and the README where the meaning changed" + echo "- [ ] Push those changes to \`$BRANCH\`" + echo + echo "CI does not run on the workflow's own commit; it runs once you push to this branch." + echo + cat "$report" + } > "$RUNNER_TEMP/pr.md" + + if [ -n "$PR" ]; then + gh pr edit "$PR" --body-file "$RUNNER_TEMP/pr.md" + gh pr comment "$PR" --body "Cloudflare changed the schemas again ($today). This branch now has the latest copies; the description shows every change since \`$BASE\`." + elif ! gh pr create --head "$BRANCH" --base "$BASE" --label "$LABEL" \ + --title "Update the vendored Clairic schemas ($today)" --body-file "$RUNNER_TEMP/pr.md"; then + msg="Could not open the pull request. Allow it under Settings > Actions > General > Workflow permissions > Allow GitHub Actions to create and approve pull requests." + echo "::warning::$msg" + gh issue comment "$issue" --body "The new schemas are on \`$BRANCH\`, but the workflow could not open a pull request: [open it here]($COMPARE_URL/$BASE...$BRANCH?expand=1). $msg" + fi diff --git a/README.md b/README.md index 93d9c88..0db038b 100644 --- a/README.md +++ b/README.md @@ -240,6 +240,12 @@ uv run pytest -m live # real API, needs credentials uv run python scripts/check_schema_drift.py # compare Cloudflare's schemas with the vendored ones ``` +Cloudflare does not announce Clairic schema changes while the model is in preview. The +`Clairic schema drift` workflow checks every Monday. When the published schemas change, it opens an +issue labelled `schema-drift` with a summary of the changes, and a pull request from the +`schema-drift/update` branch with the new copies in `tests/fixtures/schemas/`. Push the SDK changes +to that branch; merging the pull request closes the issue. + ## License and attribution MIT. clairic is a community project, independent from Cloudflare. Docstrings adapt text from diff --git a/pyproject.toml b/pyproject.toml index e2a462f..5dca35a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -76,8 +76,10 @@ convention = "google" include = ["src", "tests", "scripts", "examples"] pythonVersion = "3.10" typeCheckingMode = "strict" +extraPaths = ["scripts"] [tool.pytest.ini_options] testpaths = ["tests", "src"] +pythonpath = ["scripts"] markers = ["live: calls the real Cloudflare API (needs CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN)"] addopts = "-m 'not live' --doctest-modules" diff --git a/scripts/check_schema_drift.py b/scripts/check_schema_drift.py index 8cdecf1..b5b6f4b 100644 --- a/scripts/check_schema_drift.py +++ b/scripts/check_schema_drift.py @@ -1,50 +1,262 @@ """Compare Cloudflare's published Clairic schemas with the copies vendored in tests/fixtures. -Exits with status 1 and prints a diff when a schema changed. Clairic is in preview, so a change -means the answer models or specs may need an update; refresh the vendored copy with `--update` -once the SDK matches it. +Prints a summary of what changed, property by property, then the full line diff. Exits with +status 1 when a schema changed. Clairic is in preview and Cloudflare does not announce schema +changes, so a change here means the answer models or specs may need an update. + +Options: + --update Overwrite the vendored copies with the published schemas and exit 0. + --report PATH Also write the summary as Markdown to PATH. + +The scheduled workflow (.github/workflows/schema-drift.yml) runs it with both options and turns +the report into an issue and a pull request. """ from __future__ import annotations +import argparse import difflib import json import sys +from dataclasses import dataclass, field from pathlib import Path +from typing import Any, Literal, cast import httpx SCHEMAS = Path(__file__).resolve().parent.parent / "tests" / "fixtures" / "schemas" BASE_URL = "https://developers.cloudflare.com/workers-ai/models/clairic" +NAMES = ("schema-input.json", "schema-output.json") + +Kind = Literal["added", "removed", "changed", "values_added", "values_removed"] + + +@dataclass(frozen=True) +class Change: + """One difference between two JSON documents, located by its key path.""" + + kind: Kind + path: tuple[str, ...] + old: Any = None + new: Any = None + + +def diff(old: Any, new: Any, path: tuple[str, ...] = ()) -> list[Change]: + """Return the differences between two JSON values, as precise as their structure allows. + + Objects are compared key by key. Lists of plain values (enums, `required`, `type` unions) + are compared as sets, so a new enum member shows up as one added value. Lists of objects + of the same length are compared item by item. + """ + if isinstance(old, dict) and isinstance(new, dict): + old_obj, new_obj = cast("dict[str, Any]", old), cast("dict[str, Any]", new) + changes: list[Change] = [] + for key in sorted(old_obj.keys() | new_obj.keys()): + if key not in new_obj: + changes.append(Change("removed", (*path, key), old=old_obj[key])) + elif key not in old_obj: + changes.append(Change("added", (*path, key), new=new_obj[key])) + else: + changes.extend(diff(old_obj[key], new_obj[key], (*path, key))) + return changes + if isinstance(old, list) and isinstance(new, list): + old_list, new_list = cast("list[Any]", old), cast("list[Any]", new) + if all(_is_scalar(v) for v in (*old_list, *new_list)): + removed = [v for v in old_list if v not in new_list] + added = [v for v in new_list if v not in old_list] + changes = [] + if removed: + changes.append(Change("values_removed", path, old=removed)) + if added: + changes.append(Change("values_added", path, new=added)) + if not changes and old_list != new_list: + changes.append(Change("changed", path, old=old_list, new=new_list)) + return changes + if len(old_list) == len(new_list): + return [ + change + for i, (o, n) in enumerate(zip(old_list, new_list, strict=True)) + for change in diff(o, n, (*path, str(i))) + ] + return [Change("changed", path, old=old_list, new=new_list)] + if _same(cast("object", old), cast("object", new)): + return [] + return [Change("changed", path, old=old, new=new)] + + +def _same(old: object, new: object) -> bool: + # `True == 1` in Python, but a schema that swaps one for the other has changed. + return type(old) is type(new) and old == new + + +def _is_scalar(value: Any) -> bool: + return value is None or isinstance(value, (str, int, float, bool)) + + +@dataclass +class _Path: + text: str = "" + names_property: bool = False # the last segment is a property name, not a schema keyword + keyword: str = "" # the last segment when it is a schema keyword + + +def _readable(path: tuple[str, ...]) -> _Path: + """Turn a JSON Schema key path into the property path a reader expects. + + `properties.answers.additionalProperties.properties.span.type` becomes `answers.*.span.type`: + `properties` introduces a property name, `additionalProperties` is any key (`*`), `items` is + a list item (`[]`) and a number is a position in a list. + """ + out = _Path() + i = 0 + while i < len(path): + segment = path[i] + if segment == "properties" and i + 1 < len(path): + out.text += f".{path[i + 1]}" if out.text else path[i + 1] + out.names_property, out.keyword = True, "" + i += 2 + continue + if segment == "additionalProperties": + token = ".*" if out.text else "*" + elif segment == "items": + token = "[]" + elif segment.isdigit(): + token = f"[{segment}]" + else: + token = f".{segment}" if out.text else segment + out.text += token + out.names_property, out.keyword = False, segment + i += 1 + if not out.text: + out.text = "(root)" + return out + + +def _value(value: Any, limit: int = 100) -> str: + text = json.dumps(value, ensure_ascii=False) + return f"`{text if len(text) <= limit else text[: limit - 1] + '…'}`" + + +def _values(values: list[Any]) -> str: + return ", ".join(_value(v) for v in values) + + +def _describe_new_property(schema: Any) -> str: + if isinstance(schema, dict): + description = cast("dict[str, Any]", schema).get("description") + if isinstance(description, str): + return description + return _value(schema) + + +@dataclass +class _Sections: + removed: list[str] = field(default_factory=list[str]) + changed: list[str] = field(default_factory=list[str]) + added: list[str] = field(default_factory=list[str]) + descriptions: list[str] = field(default_factory=list[str]) + + +def summarize(name: str, changes: list[Change]) -> str: + """Render the changes of one schema file as a Markdown section, most disruptive first.""" + sections = _Sections() + for change in changes: + where = _readable(change.path) + path = f"`{where.text}`" + if where.keyword == "additionalProperties" and _is_scalar(change.new or change.old): + owner = f"`{_readable(change.path[:-1]).text}`" + rule = {True: "extra keys allowed", False: "extra keys rejected"}.get(change.new) + sections.changed.append(f"- {owner}: {rule or 'extra-keys rule removed'}") + elif where.keyword == "description": + owner = f"`{_readable(change.path[:-1]).text}`" + if change.kind == "added": + sections.descriptions.append(f"- {owner} (new): {change.new}") + elif change.kind == "removed": + sections.descriptions.append(f"- {owner} (removed): was {change.old}") + else: + sections.descriptions.append( + f"- {owner}:\n - was: {change.old}\n - now: {change.new}" + ) + elif change.kind == "added" and where.names_property: + sections.added.append(f"- {path}: {_describe_new_property(change.new)}") + elif change.kind == "added": + sections.added.append(f"- {path}: {_value(change.new)}") + elif change.kind == "values_added": + sections.added.append(f"- {path}: new values {_values(change.new)}") + elif change.kind == "removed": + what = "property removed" if where.names_property else "was" + sections.removed.append(f"- {path}: {what} {_value(change.old)}") + elif change.kind == "values_removed": + sections.removed.append(f"- {path}: values removed {_values(change.old)}") + else: + sections.changed.append(f"- {path}: {_value(change.old)} → {_value(change.new)}") + + lines = [f"### `{name}`: {len(changes)} change{'s' if len(changes) != 1 else ''}"] + for title, items in ( + ("Removed", sections.removed), + ("Changed", sections.changed), + ("Added", sections.added), + ("Descriptions", sections.descriptions), + ): + if items: + lines += ["", f"**{title}**", "", *items] + return "\n".join(lines) + "\n" + + +def report(sections: list[str]) -> str: + """Render the full Markdown report from the per-file sections.""" + if not sections: + return "## Clairic schema drift\n\nThe published schemas match the vendored copies.\n" + return "\n".join( + [ + "## Clairic schema drift", + "", + f"Cloudflare's published schemas ({BASE_URL}/) differ from the copies in " + "`tests/fixtures/schemas/`. Paths read like the request and response: " + "`*` is any field name, `[]` a list item.", + "", + *sections, + ] + ) def _normalized(text: str) -> str: return json.dumps(json.loads(text), indent=2, sort_keys=True) + "\n" -def main(update: bool) -> int: - changed = False - for name in ("schema-input.json", "schema-output.json"): +def main(argv: list[str]) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0] if __doc__ else None) + parser.add_argument("--update", action="store_true", help="overwrite the vendored copies") + parser.add_argument("--report", type=Path, help="also write the summary as Markdown here") + args = parser.parse_args(argv) + + sections: list[str] = [] + line_diffs: list[str] = [] + for name in NAMES: published = _normalized(httpx.get(f"{BASE_URL}/{name}", timeout=30).raise_for_status().text) vendored_path = SCHEMAS / name vendored = _normalized(vendored_path.read_text()) if published == vendored: - print(f"{name}: unchanged") continue - changed = True - print(f"{name}: changed") - sys.stdout.writelines( - difflib.unified_diff( - vendored.splitlines(keepends=True), - published.splitlines(keepends=True), - fromfile=f"vendored/{name}", - tofile=f"published/{name}", - ) + sections.append(summarize(name, diff(json.loads(vendored), json.loads(published)))) + line_diffs += difflib.unified_diff( + vendored.splitlines(keepends=True), + published.splitlines(keepends=True), + fromfile=f"vendored/{name}", + tofile=f"published/{name}", ) - if update: + if args.update: vendored_path.write_text(published) - return 1 if changed and not update else 0 + + summary = report(sections) + print(summary) + if line_diffs: + print("## Full diff\n") + sys.stdout.writelines(line_diffs) + if args.report: + args.report.write_text(summary) + return 1 if sections and not args.update else 0 if __name__ == "__main__": - sys.exit(main(update="--update" in sys.argv[1:])) + sys.exit(main(sys.argv[1:])) diff --git a/tests/test_check_schema_drift.py b/tests/test_check_schema_drift.py new file mode 100644 index 0000000..dc4dddb --- /dev/null +++ b/tests/test_check_schema_drift.py @@ -0,0 +1,108 @@ +from typing import Any + +from check_schema_drift import Change, diff, report, summarize + + +def _field_schema(field: dict[str, Any]) -> dict[str, Any]: + return {"properties": {"fields": {"additionalProperties": {"properties": field}}}} + + +def test_identical_documents_have_no_changes() -> None: + schema = _field_schema({"decimals": {"type": "integer"}}) + assert diff(schema, schema) == [] + + +def test_added_and_removed_keys() -> None: + old = {"a": 1, "b": 2} + new = {"b": 2, "c": 3} + assert diff(old, new) == [ + Change("removed", ("a",), old=1), + Change("added", ("c",), new=3), + ] + + +def test_enum_members_are_compared_as_values() -> None: + old = {"enum": ["text", "number"]} + new = {"enum": ["text", "compute", "boolean"]} + assert diff(old, new) == [ + Change("values_removed", ("enum",), old=["number"]), + Change("values_added", ("enum",), new=["compute", "boolean"]), + ] + + +def test_reordered_values_are_a_change() -> None: + assert diff(["a", "b"], ["b", "a"]) == [Change("changed", (), old=["a", "b"], new=["b", "a"])] + + +def test_type_widened_to_a_union_is_a_change() -> None: + assert diff({"type": "array"}, {"type": ["array", "null"]}) == [ + Change("changed", ("type",), old="array", new=["array", "null"]) + ] + + +def test_lists_of_objects_are_compared_item_by_item() -> None: + old = {"anyOf": [{"type": "string"}, {"type": "object"}]} + new = {"anyOf": [{"type": "string"}, {"type": "object", "title": "Object"}]} + assert diff(old, new) == [Change("added", ("anyOf", "1", "title"), new="Object")] + + +def test_bool_and_int_are_not_equal() -> None: + assert diff({"x": True}, {"x": 1}) == [Change("changed", ("x",), old=True, new=1)] + + +def test_summary_uses_request_paths_and_sections() -> None: + old = _field_schema( + { + "type": {"enum": ["text", "number"]}, + "scale": {"default": "linear", "type": "string"}, + "unit": {"description": "Unit label.", "type": "string"}, + } + ) + new = _field_schema( + { + "type": {"enum": ["text", "number", "compute"]}, + "scale": {"type": "string"}, + "unit": {"description": "number and duration only.", "type": "string"}, + "documents": {"description": "Optional embedded PDFs.", "type": "array"}, + "properties": {"type": "object"}, + } + ) + text = summarize("schema-input.json", diff(old, new)) + + assert text.startswith("### `schema-input.json`: 5 changes\n") + assert '**Removed**\n\n- `fields.*.scale.default`: was `"linear"`' in text + assert "- `fields.*.documents`: Optional embedded PDFs." in text + assert '- `fields.*.properties`: `{"type": "object"}`' in text + assert '- `fields.*.type.enum`: new values `"compute"`' in text + assert "- `fields.*.unit`:\n - was: Unit label.\n - now: number and duration only." in text + assert text.index("**Removed**") < text.index("**Added**") < text.index("**Descriptions**") + + +def test_summary_of_list_items_and_extra_keys() -> None: + old = { + "properties": { + "answers": { + "additionalProperties": { + "properties": {"spans": {"items": {"type": "array"}}}, + } + } + } + } + new = { + "properties": { + "answers": { + "additionalProperties": { + "additionalProperties": True, + "properties": {"spans": {"items": {"type": ["array", "null"]}}}, + } + } + } + } + text = summarize("schema-output.json", diff(old, new)) + + assert "- `answers.*`: extra keys allowed" in text + assert '- `answers.*.spans[].type`: `"array"` → `["array", "null"]`' in text + + +def test_report_without_changes() -> None: + assert "match the vendored copies" in report([])