add app-server protocol compatibility check

This commit is contained in:
Will Wang
2026-06-22 17:29:40 -07:00
parent 0f89dd768c
commit 98750aa0f6
5 changed files with 744 additions and 0 deletions
@@ -0,0 +1,35 @@
name: app-server-protocol-compatibility
on:
pull_request: {}
jobs:
check:
name: App-server protocol compatibility
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ github.event.pull_request.head.sha }}
fetch-depth: 0
persist-credentials: false
- uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0
- uses: taiki-e/install-action@44c6d64aa62cd779e873306675c7a58e86d6d532 # v2.62.49
with:
tool: just
- name: Test compatibility checker
run: python3 -m unittest discover -s scripts -p 'test_check_app_server_protocol_compatibility.py'
- name: Generate stable app-server schema
run: just write-app-server-schema --schema-root "$RUNNER_TEMP/app-server-schema"
- name: Check backwards compatibility
env:
BASE_SHA: ${{ github.event.pull_request.base.sha }}
run: >-
python3 scripts/check_app_server_protocol_compatibility.py
--base "$BASE_SHA"
--head-schema-root "$RUNNER_TEMP/app-server-schema"
+4
View File
@@ -2158,4 +2158,8 @@ For server-initiated request payloads, annotate the field the same way so schema
```bash
just test -p codex-app-server-protocol
just check-app-server-protocol-compatibility
```
The compatibility check compares the stable generated protocol against
`origin/main`. Experimental methods and fields are excluded.
+5
View File
@@ -148,6 +148,11 @@ write-config-schema:
write-app-server-schema *args:
cargo run -p codex-app-server-protocol --bin write_schema_fixtures -- {args}
# Compare the stable app-server protocol schema against a git revision.
[no-cd]
check-app-server-protocol-compatibility base="origin/main" head="HEAD":
{{ python }} scripts/check_app_server_protocol_compatibility.py --base "{{base}}" --head "{{head}}"
[no-cd]
write-hooks-schema:
cargo run --manifest-path {{ justfile_directory() }}/codex-rs/Cargo.toml -p codex-hooks --bin write_hooks_schema_fixtures
@@ -0,0 +1,477 @@
#!/usr/bin/env python3
import argparse
import io
import json
import subprocess
import sys
import tarfile
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
from typing import Any
REPO_SCHEMA_ROOT = "codex-rs/app-server-protocol/schema"
ROOT_SCHEMAS = {
"json/ClientNotification.json": "input",
"json/ClientRequest.json": "input",
"json/ServerNotification.json": "output",
"json/ServerRequest.json": "output",
}
OUTBOUND_ROOT_RESPONSES = {"json/FuzzyFileSearchResponse.json"}
TYPESCRIPT_INDEXES = ("typescript/index.ts", "typescript/v2/index.ts")
class Direction(Enum):
INPUT = "client -> server"
OUTPUT = "server -> client"
@dataclass(frozen=True, order=True)
class Violation:
code: str
path: str
detail: str
def load_git_tree(revision: str) -> dict[str, str]:
prefix = f"{REPO_SCHEMA_ROOT}/"
archive = subprocess.run(
["git", "archive", "--format=tar", revision, REPO_SCHEMA_ROOT],
check=True,
capture_output=True,
).stdout
files = {}
with tarfile.open(fileobj=io.BytesIO(archive), mode="r:") as contents:
for member in contents.getmembers():
if not member.isfile() or not member.name.startswith(prefix):
continue
extracted = contents.extractfile(member)
if extracted is not None:
files[member.name.removeprefix(prefix)] = extracted.read().decode(
"utf-8"
)
return files
def load_schema_tree(root: Path) -> dict[str, str]:
return {
path.relative_to(root).as_posix(): path.read_text(encoding="utf-8")
for path in root.rglob("*")
if path.is_file()
}
def schema_direction(path: str) -> Direction | None:
root_direction = ROOT_SCHEMAS.get(path)
if root_direction is not None:
return Direction.INPUT if root_direction == "input" else Direction.OUTPUT
schema_path = Path(path)
if schema_path.suffix != ".json" or not schema_path.name.endswith("Response.json"):
return None
if schema_path.parts[:2] == ("json", "v2"):
return Direction.OUTPUT
if schema_path.parent == Path("json"):
if path in OUTBOUND_ROOT_RESPONSES:
return Direction.OUTPUT
if schema_path.name.startswith("JSONRPC"):
return None
return Direction.INPUT
return None
def parse_json_schema(raw: str, path: str) -> Any:
try:
return json.loads(raw)
except json.JSONDecodeError as error:
raise ValueError(f"invalid JSON schema {path}: {error}") from error
def resolve_ref(schema: Any, document: Any) -> Any:
seen: set[str] = set()
while isinstance(schema, dict) and isinstance(schema.get("$ref"), str):
reference = schema["$ref"]
if not reference.startswith("#/") or reference in seen:
break
seen.add(reference)
target = document
for component in reference[2:].split("/"):
key = component.replace("~1", "/").replace("~0", "~")
if not isinstance(target, dict) or key not in target:
return schema
target = target[key]
schema = target
return schema
def schema_types(schema: dict[str, Any]) -> set[str] | None:
value = schema.get("type")
if isinstance(value, str):
return {value}
if isinstance(value, list) and all(isinstance(item, str) for item in value):
return set(value)
return None
def variant_key(schema: Any, index: int) -> str:
if not isinstance(schema, dict):
return f"index:{index}"
if isinstance(schema.get("$ref"), str):
return f"ref:{schema['$ref'].rsplit('/', 1)[-1]}"
for property_name in ("method", "type"):
property_schema = schema.get("properties", {}).get(property_name, {})
values = (
property_schema.get("enum") if isinstance(property_schema, dict) else None
)
if isinstance(values, list) and len(values) == 1:
return f"{property_name}:{values[0]}"
if isinstance(schema.get("title"), str):
return f"title:{schema['title']}"
if schema.get("type") == "null":
return "type:null"
if "enum" in schema:
return "enum"
return f"index:{index}"
class SchemaComparator:
def __init__(
self,
base_document: Any,
head_document: Any,
direction: Direction,
root_path: str,
) -> None:
self.base_document = base_document
self.head_document = head_document
self.direction = direction
self.root_path = root_path
self.violations: set[Violation] = set()
self.seen: set[tuple[int, int, Direction]] = set()
def compare(self) -> set[Violation]:
self._compare(self.base_document, self.head_document, "#")
return self.violations
def _add(self, code: str, path: str, detail: str) -> None:
self.violations.add(
Violation(
code, f"{self.root_path}{path}", f"{self.direction.value}: {detail}"
)
)
def _compare(self, base: Any, head: Any, path: str) -> None:
base = resolve_ref(base, self.base_document)
head = resolve_ref(head, self.head_document)
pair = (id(base), id(head), self.direction)
if pair in self.seen:
return
self.seen.add(pair)
if isinstance(base, bool) or isinstance(head, bool):
if base is True and head is not True and self.direction is Direction.INPUT:
self._add(
"schema_narrowed",
path,
"an unrestricted input schema became restricted",
)
elif (
head is True and base is not True and self.direction is Direction.OUTPUT
):
self._add(
"schema_widened", path, "an output schema became unrestricted"
)
return
if not isinstance(base, dict) or not isinstance(head, dict):
if base != head:
self._add("schema_changed", path, "schema shape changed")
return
base_types = schema_types(base)
head_types = schema_types(head)
if base_types is not None and head_types is not None:
incompatible = (
base_types - head_types
if self.direction is Direction.INPUT
else head_types - base_types
)
if incompatible:
self._add(
"type_changed",
path,
f"incompatible type(s) {sorted(incompatible)}; before={sorted(base_types)}, after={sorted(head_types)}",
)
self._compare_enum(base, head, path)
self._compare_union(base, head, path)
self._compare_all_of(base, head, path)
self._compare_object(base, head, path)
if "items" in base and "items" in head:
self._compare(base["items"], head["items"], f"{path}/items")
def _compare_enum(
self, base: dict[str, Any], head: dict[str, Any], path: str
) -> None:
base_values = base.get("enum")
head_values = head.get("enum")
if not isinstance(base_values, list) or not isinstance(head_values, list):
narrowed_input = not isinstance(base_values, list) and isinstance(
head_values, list
)
widened_output = isinstance(base_values, list) and not isinstance(
head_values, list
)
if (self.direction is Direction.INPUT and narrowed_input) or (
self.direction is Direction.OUTPUT and widened_output
):
self._add("enum_changed", path, "enum constraint was added or removed")
return
base_set = {json.dumps(value, sort_keys=True) for value in base_values}
head_set = {json.dumps(value, sort_keys=True) for value in head_values}
incompatible = (
base_set - head_set
if self.direction is Direction.INPUT
else head_set - base_set
)
if incompatible:
self._add(
"enum_changed",
path,
f"incompatible enum value(s) {sorted(incompatible)}",
)
def _compare_union(
self, base: dict[str, Any], head: dict[str, Any], path: str
) -> None:
for keyword in ("oneOf", "anyOf"):
base_variants = base.get(keyword)
head_variants = head.get(keyword)
if not isinstance(base_variants, list) or not isinstance(
head_variants, list
):
narrowed_input = not isinstance(base_variants, list) and isinstance(
head_variants, list
)
widened_output = isinstance(base_variants, list) and not isinstance(
head_variants, list
)
if (self.direction is Direction.INPUT and narrowed_input) or (
self.direction is Direction.OUTPUT and widened_output
):
self._add(
"union_changed",
f"{path}/{keyword}",
"union constraint was added or removed",
)
continue
base_by_key = {
variant_key(variant, index): variant
for index, variant in enumerate(base_variants)
}
head_by_key = {
variant_key(variant, index): variant
for index, variant in enumerate(head_variants)
}
required_keys = (
base_by_key.keys()
if self.direction is Direction.INPUT
else head_by_key.keys()
)
for key in required_keys:
if key not in base_by_key or key not in head_by_key:
self._add(
"union_variant_changed",
f"{path}/{keyword}/{key}",
"union variant is not understood by both protocol versions",
)
continue
self._compare(
base_by_key[key],
head_by_key[key],
f"{path}/{keyword}/{key}",
)
for key in base_by_key.keys() - head_by_key.keys():
if key.startswith("method:"):
self._add(
"method_removed",
f"{path}/{keyword}/{key}",
"method was removed",
)
def _compare_all_of(
self, base: dict[str, Any], head: dict[str, Any], path: str
) -> None:
base_parts = base.get("allOf")
head_parts = head.get("allOf")
if not isinstance(base_parts, list) or not isinstance(head_parts, list):
return
if len(base_parts) != len(head_parts):
self._add("all_of_changed", f"{path}/allOf", "allOf shape changed")
return
for index, (base_part, head_part) in enumerate(zip(base_parts, head_parts)):
self._compare(base_part, head_part, f"{path}/allOf/{index}")
def _compare_object(
self, base: dict[str, Any], head: dict[str, Any], path: str
) -> None:
base_properties = base.get("properties")
head_properties = head.get("properties")
if not isinstance(base_properties, dict) and not isinstance(
head_properties, dict
):
return
base_properties = base_properties if isinstance(base_properties, dict) else {}
head_properties = head_properties if isinstance(head_properties, dict) else {}
for name in base_properties.keys() - head_properties.keys():
self._add(
"property_removed", f"{path}/properties/{name}", "property was removed"
)
base_required = set(base.get("required", []))
head_required = set(head.get("required", []))
common_properties = base_properties.keys() & head_properties.keys()
incompatible_required = (
head_required - base_required
if self.direction is Direction.INPUT
else (base_required - head_required) & common_properties
)
for name in incompatible_required:
detail = (
"property became required"
if self.direction is Direction.INPUT
else "required output property became optional"
)
self._add("required_changed", f"{path}/properties/{name}", detail)
for name in common_properties:
self._compare(
base_properties[name],
head_properties[name],
f"{path}/properties/{name}",
)
base_additional = base.get("additionalProperties", True)
head_additional = head.get("additionalProperties", True)
if self.direction is Direction.INPUT:
if base_additional is not False and head_additional is False:
self._add(
"additional_properties_narrowed",
path,
"input object stopped accepting additional properties",
)
elif base_additional is False:
for name in head_properties.keys() - base_properties.keys():
self._add(
"property_added_to_closed_output",
f"{path}/properties/{name}",
"output property was added to an object that rejected unknown fields",
)
if head_additional is not False:
self._add(
"additional_properties_widened",
path,
"output object may now emit additional properties",
)
if isinstance(base_additional, dict) and isinstance(head_additional, dict):
self._compare(
base_additional,
head_additional,
f"{path}/additionalProperties",
)
def exported_types(raw: str) -> set[str]:
exports = set()
for line in raw.splitlines():
prefix = "export type { "
if line.startswith(prefix) and " }" in line:
exports.add(line[len(prefix) : line.index(" }")])
return exports
def compare_protocol_trees(
base_tree: dict[str, str], head_tree: dict[str, str]
) -> list[Violation]:
violations: set[Violation] = set()
paths = sorted(set(base_tree) | set(head_tree))
for path in paths:
direction = schema_direction(path)
if direction is None:
continue
if path not in head_tree:
violations.add(Violation("schema_removed", path, "schema file was removed"))
continue
if path not in base_tree:
continue
base_document = parse_json_schema(base_tree[path], path)
head_document = parse_json_schema(head_tree[path], path)
violations.update(
SchemaComparator(base_document, head_document, direction, path).compare()
)
for path in TYPESCRIPT_INDEXES:
if path not in base_tree or path not in head_tree:
continue
for removed in exported_types(base_tree[path]) - exported_types(
head_tree[path]
):
violations.add(
Violation(
"typescript_export_removed",
f"{path}#{removed}",
"generated TypeScript export was removed or renamed",
)
)
return sorted(violations)
def main() -> int:
parser = argparse.ArgumentParser(
description="Check the stable app-server protocol for backwards-incompatible changes."
)
parser.add_argument(
"--base", required=True, help="Git revision containing the baseline schema."
)
head = parser.add_mutually_exclusive_group()
head.add_argument(
"--head", default="HEAD", help="Git revision containing the candidate schema."
)
head.add_argument(
"--head-schema-root",
type=Path,
help="Generated candidate schema root containing json/ and typescript/.",
)
args = parser.parse_args()
base_tree = load_git_tree(args.base)
head_tree = (
load_schema_tree(args.head_schema_root)
if args.head_schema_root is not None
else load_git_tree(args.head)
)
violations = compare_protocol_trees(base_tree, head_tree)
if not violations:
print("No backwards-incompatible stable app-server protocol changes detected.")
return 0
print(
f"Detected {len(violations)} backwards-incompatible app-server protocol change(s):"
)
for violation in violations:
print(f"- [{violation.code}] {violation.path}: {violation.detail}")
print(
"\nPreserve the old stable shape, introduce the change additively, or place unstable "
"surface behind experimentalApi. Repository owners may bypass this required check for "
"an emergency merge."
)
return 1
if __name__ == "__main__":
sys.exit(main())
@@ -0,0 +1,223 @@
import json
import unittest
from check_app_server_protocol_compatibility import compare_protocol_trees
def schema_file(
*,
properties=None,
required=None,
enum=None,
one_of=None,
):
schema = {"type": "object"}
if properties is not None:
schema["properties"] = properties
if required is not None:
schema["required"] = required
if enum is not None:
schema = {"type": "string", "enum": enum}
if one_of is not None:
schema = {"oneOf": one_of}
return json.dumps(schema)
def method(method_name):
return {
"type": "object",
"properties": {
"method": {"type": "string", "enum": [method_name]},
},
"required": ["method"],
}
class AppServerProtocolCompatibilityTest(unittest.TestCase):
def test_removed_output_field_is_breaking(self):
path = "json/v2/PluginReadResponse.json"
base = {
path: json.dumps(
{
"definitions": {
"AppSummary": {
"type": "object",
"properties": {
"id": {"type": "string"},
"needsAuth": {"type": "boolean"},
},
"required": ["id", "needsAuth"],
}
},
"type": "object",
"properties": {
"app": {"$ref": "#/definitions/AppSummary"},
},
"required": ["app"],
},
)
}
head = {
path: json.dumps(
{
"definitions": {
"AppSummary": {
"type": "object",
"properties": {"id": {"type": "string"}},
"required": ["id"],
}
},
"type": "object",
"properties": {
"app": {"$ref": "#/definitions/AppSummary"},
},
"required": ["app"],
},
)
}
violations = compare_protocol_trees(base, head)
self.assertIn("property_removed", {violation.code for violation in violations})
self.assertTrue(any("needsAuth" in violation.path for violation in violations))
def test_new_required_input_field_is_breaking(self):
path = "json/ClientRequest.json"
base = {path: schema_file(properties={"method": {"type": "string"}})}
head = {
path: schema_file(
properties={
"method": {"type": "string"},
"newField": {"type": "string"},
},
required=["newField"],
)
}
violations = compare_protocol_trees(base, head)
self.assertEqual(
{violation.code for violation in violations}, {"required_changed"}
)
def test_optional_input_field_and_enum_value_are_additive(self):
path = "json/ClientRequest.json"
base = {
path: schema_file(properties={"mode": {"type": "string", "enum": ["one"]}})
}
head = {
path: schema_file(
properties={
"mode": {"type": "string", "enum": ["one", "two"]},
"optional": {"type": ["string", "null"]},
}
)
}
self.assertEqual(compare_protocol_trees(base, head), [])
def test_new_output_enum_value_is_breaking(self):
path = "json/v2/ExampleResponse.json"
base = {path: schema_file(enum=["one"])}
head = {path: schema_file(enum=["one", "two"])}
violations = compare_protocol_trees(base, head)
self.assertEqual({violation.code for violation in violations}, {"enum_changed"})
def test_removing_output_enum_constraint_is_breaking(self):
path = "json/v2/ExampleResponse.json"
base = {path: schema_file(enum=["one"])}
head = {path: json.dumps({"type": "string"})}
violations = compare_protocol_trees(base, head)
self.assertEqual({violation.code for violation in violations}, {"enum_changed"})
def test_required_output_field_becoming_optional_is_breaking(self):
path = "json/v2/ExampleResponse.json"
properties = {"value": {"type": "string"}}
base = {path: schema_file(properties=properties, required=["value"])}
head = {path: schema_file(properties=properties)}
violations = compare_protocol_trees(base, head)
self.assertEqual(
{violation.code for violation in violations},
{"required_changed"},
)
def test_input_type_narrowing_is_breaking(self):
path = "json/ClientRequest.json"
base = {path: schema_file(properties={"value": {"type": ["string", "null"]}})}
head = {path: schema_file(properties={"value": {"type": "string"}})}
violations = compare_protocol_trees(base, head)
self.assertEqual({violation.code for violation in violations}, {"type_changed"})
def test_new_property_on_closed_output_is_breaking(self):
path = "json/v2/ExampleResponse.json"
base_schema = {
"type": "object",
"additionalProperties": False,
"properties": {"old": {"type": "string"}},
}
head_schema = {
**base_schema,
"properties": {
**base_schema["properties"],
"new": {"type": "string"},
},
}
violations = compare_protocol_trees(
{path: json.dumps(base_schema)},
{path: json.dumps(head_schema)},
)
self.assertEqual(
{violation.code for violation in violations},
{"property_added_to_closed_output"},
)
def test_new_client_method_is_additive(self):
path = "json/ClientRequest.json"
base = {path: schema_file(one_of=[method("thread/read")])}
head = {
path: schema_file(one_of=[method("thread/read"), method("thread/archive")])
}
self.assertEqual(compare_protocol_trees(base, head), [])
def test_new_server_notification_is_breaking(self):
path = "json/ServerNotification.json"
base = {path: schema_file(one_of=[method("thread/started")])}
head = {
path: schema_file(
one_of=[method("thread/started"), method("thread/replaced")]
)
}
violations = compare_protocol_trees(base, head)
self.assertEqual(
{violation.code for violation in violations},
{"union_variant_changed"},
)
def test_removed_typescript_export_is_breaking(self):
path = "typescript/v2/index.ts"
base = {path: 'export type { OldName } from "./OldName";\n'}
head = {path: 'export type { NewName } from "./NewName";\n'}
violations = compare_protocol_trees(base, head)
self.assertEqual(
{violation.code for violation in violations},
{"typescript_export_removed"},
)
if __name__ == "__main__":
unittest.main()