feat(import): complete OpenAPI onboarding and verify delivery
CI / Rust Checks (pull_request) Failing after 1s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped

This commit is contained in:
bsodfather committed 2026-10-09 17:50:38 +03:00
1 parent bb3e376767
commit e93de7015a
244 files changed
+57020 -5139

No files matched your search

@@ -0,0 +1,271 @@
import json
import subprocess
import tempfile
import unittest
from pathlib import Path
SCRIPT = Path(__file__).parents[2] / "scripts" / "check-openapi-matrix-compatibility.py"
MATRIX_PATH = "crates/crank-import/tests/support-matrix.yaml"
MANIFEST_PATH = "crates/crank-import/tests/corpus/manifest.json"
DOCS_PATH = "docs/openapi-import.md"
BASE_MATRIX = """matrix_version: '1.0.0'
constructs:
- id: baseline
"""
BASE_DOC = "Матрица версии `1.0.0`; corpus version — `1.0.0`.\n"
def base_manifest() -> dict:
return {
"corpus_version": "1.0.0",
"matrix_version": "1.0.0",
"compatibility_impact": "initial contract",
"documents": [
{
"id": "rep-00",
"file": "representative-00.json",
"sha256": "a" * 64,
"origin": "synthetic:cc0",
"license": "CC0-1.0",
"specification_version": "OpenAPI 3.0",
"classification": "representative",
"expected_preview": {},
}
],
}
class OpenApiMatrixCompatibilityGuardTests(unittest.TestCase):
def setUp(self) -> None:
self._directory = tempfile.TemporaryDirectory()
self.root = Path(self._directory.name)
subprocess.run(
["git", "init", "-q"], cwd=self.root, check=True, capture_output=True
)
for relative in (MATRIX_PATH, MANIFEST_PATH, DOCS_PATH):
target = self.root / relative
target.parent.mkdir(parents=True, exist_ok=True)
(self.root / MATRIX_PATH).write_text(BASE_MATRIX, encoding="utf-8")
(self.root / MANIFEST_PATH).write_text(
json.dumps(base_manifest()), encoding="utf-8"
)
(self.root / DOCS_PATH).write_text(BASE_DOC, encoding="utf-8")
self.commit("base")
self.base = self.head()
def tearDown(self) -> None:
self._directory.cleanup()
def self_git(self, *args: str) -> None:
subprocess.run(
["git", "-c", "user.email=guard@test", "-c", "user.name=guard", *args],
cwd=self.root,
check=True,
capture_output=True,
)
def commit(self, message: str) -> None:
self.self_git("add", "-A")
self.self_git("commit", "-m", message)
def head(self) -> str:
result = subprocess.run(
["git", "rev-parse", "HEAD"],
cwd=self.root,
check=True,
capture_output=True,
text=True,
)
return result.stdout.strip()
def run_guard(self) -> subprocess.CompletedProcess[str]:
return subprocess.run(
["python3", str(SCRIPT), "--base", self.base],
cwd=self.root,
text=True,
capture_output=True,
check=False,
)
def test_rejects_docs_only_edit_with_stale_version(self) -> None:
# matrix and manifest are untouched relative to the base, but a docs
# edit that pins a stale contract version must still be rejected
(self.root / DOCS_PATH).write_text(
"Матрица версии `0.9.0`; corpus version — `0.9.0`.\n", encoding="utf-8"
)
result = self.run_guard()
self.assertEqual(result.returncode, 1, result.stderr)
self.assertIn(
"must state the current support matrix and corpus versions", result.stderr
)
def test_rejects_docs_with_reversed_matrix_and_corpus_versions(self) -> None:
(self.root / MATRIX_PATH).write_text(
BASE_MATRIX.replace("'1.0.0'", "'1.1.0'") + " - id: addition\n",
encoding="utf-8",
)
manifest = base_manifest()
manifest["matrix_version"] = "1.1.0"
manifest["corpus_version"] = "1.0.1"
manifest["compatibility_impact"] = "bumped release"
(self.root / MANIFEST_PATH).write_text(json.dumps(manifest), encoding="utf-8")
(self.root / DOCS_PATH).write_text(
"Матрица версии `1.0.1`; corpus version — `1.1.0`.\n", encoding="utf-8"
)
result = self.run_guard()
self.assertEqual(result.returncode, 1, result.stderr)
self.assertIn(
"matrix version declaration must state matrix_version 1.1.0", result.stderr
)
def test_rejects_contract_change_without_version_bump_on_existing_base(self) -> None:
# The base already contains the contract: appending a matrix row must be
# rejected even though the versions and impact note stay untouched.
(self.root / MATRIX_PATH).write_text(
BASE_MATRIX + " - id: addition\n", encoding="utf-8"
)
result = self.run_guard()
self.assertEqual(result.returncode, 1, result.stderr)
self.assertIn("changed without a matrix_version bump", result.stderr)
self.assertIn("without updating compatibility_impact", result.stderr)
def test_rejects_matrix_version_downgrade(self) -> None:
(self.root / MATRIX_PATH).write_text(
BASE_MATRIX.replace("'1.0.0'", "'0.9.0'") + " - id: addition\n",
encoding="utf-8",
)
manifest = base_manifest()
manifest["matrix_version"] = "0.9.0"
manifest["compatibility_impact"] = "downgraded matrix"
(self.root / MANIFEST_PATH).write_text(json.dumps(manifest), encoding="utf-8")
(self.root / DOCS_PATH).write_text(
"Матрица версии `0.9.0`; corpus version — `1.0.0`.\n", encoding="utf-8"
)
result = self.run_guard()
self.assertEqual(result.returncode, 1, result.stderr)
self.assertIn("matrix_version bump (must increase SemVer)", result.stderr)
def test_rejects_manifest_change_without_corpus_bump_on_existing_base(self) -> None:
manifest = base_manifest()
manifest["documents"][0]["file"] = "representative-99.json"
(self.root / MANIFEST_PATH).write_text(json.dumps(manifest), encoding="utf-8")
result = self.run_guard()
self.assertEqual(result.returncode, 1, result.stderr)
self.assertIn("without a corpus_version bump", result.stderr)
self.assertIn("without updating compatibility_impact", result.stderr)
def test_rejects_corpus_version_downgrade(self) -> None:
manifest = base_manifest()
manifest["corpus_version"] = "0.9.0"
manifest["compatibility_impact"] = "downgraded corpus"
manifest["documents"][0]["file"] = "representative-99.json"
(self.root / MANIFEST_PATH).write_text(json.dumps(manifest), encoding="utf-8")
(self.root / DOCS_PATH).write_text(
"Матрица версии `1.0.0`; corpus version — `0.9.0`.\n", encoding="utf-8"
)
result = self.run_guard()
self.assertEqual(result.returncode, 1, result.stderr)
self.assertIn("corpus_version bump (must increase SemVer)", result.stderr)
def test_rejects_stale_versions_in_published_docs(self) -> None:
matrix = BASE_MATRIX.replace("'1.0.0'", "'1.1.0'") + " - id: addition\n"
(self.root / MATRIX_PATH).write_text(matrix, encoding="utf-8")
manifest = base_manifest()
manifest["matrix_version"] = "1.1.0"
manifest["corpus_version"] = "1.0.1"
manifest["compatibility_impact"] = "matrix 1.1.0 release"
(self.root / MANIFEST_PATH).write_text(json.dumps(manifest), encoding="utf-8")
# docs still pin the previous `1.0.0` release
result = self.run_guard()
self.assertEqual(result.returncode, 1, result.stderr)
self.assertIn("must state the current support matrix and corpus versions", result.stderr)
def test_rejects_docs_citing_versions_missing_from_release(self) -> None:
(self.root / MATRIX_PATH).write_text(
BASE_MATRIX + " - id: addition\n", encoding="utf-8"
)
manifest = base_manifest()
manifest["matrix_version"] = "1.1.0"
manifest["corpus_version"] = "1.1.0"
manifest["compatibility_impact"] = "matrix 1.1.0 release"
(self.root / MANIFEST_PATH).write_text(json.dumps(manifest), encoding="utf-8")
(self.root / DOCS_PATH).write_text(
"Матрица версии `1.1.0`; corpus version — `0.9.0`.\n", encoding="utf-8"
)
result = self.run_guard()
self.assertEqual(result.returncode, 1, result.stderr)
self.assertIn("must state the current support matrix and corpus versions", result.stderr)
def test_allows_other_semver_in_docs(self) -> None:
(self.root / DOCS_PATH).write_text(
"Матрица версии `1.0.0`; corpus version — `1.0.0`. OpenAPI `3.1.0`.\n",
encoding="utf-8",
)
result = self.run_guard()
self.assertEqual(result.returncode, 0, result.stderr)
def test_rejects_conflicting_second_version_declaration(self) -> None:
(self.root / DOCS_PATH).write_text(
BASE_DOC + "Матрица версии `0.9.0`; corpus version — `0.9.0`.\n",
encoding="utf-8",
)
result = self.run_guard()
self.assertEqual(result.returncode, 1, result.stderr)
self.assertIn("must state the current support matrix and corpus versions", result.stderr)
def test_rejects_leading_zero_in_contract_version(self) -> None:
(self.root / MATRIX_PATH).write_text(
BASE_MATRIX.replace("'1.0.0'", "'01.0.1'") + " - id: addition\n",
encoding="utf-8",
)
manifest = base_manifest()
manifest["matrix_version"] = "01.0.1"
manifest["compatibility_impact"] = "invalid version"
(self.root / MANIFEST_PATH).write_text(json.dumps(manifest), encoding="utf-8")
(self.root / DOCS_PATH).write_text(
"Матрица версии `01.0.1`; corpus version — `1.0.0`.\n",
encoding="utf-8",
)
result = self.run_guard()
self.assertEqual(result.returncode, 1, result.stderr)
self.assertIn("matrix_version bump (must increase SemVer)", result.stderr)
def test_rejects_manifest_metadata_change_without_bump(self) -> None:
manifest = base_manifest()
manifest["canonical_digest_definition"] = "changed contract"
(self.root / MANIFEST_PATH).write_text(json.dumps(manifest), encoding="utf-8")
result = self.run_guard()
self.assertEqual(result.returncode, 1, result.stderr)
self.assertIn("without a corpus_version bump", result.stderr)
def test_rejects_corpus_version_only_downgrade(self) -> None:
manifest = base_manifest()
manifest["corpus_version"] = "0.9.0"
manifest["compatibility_impact"] = "downgrade"
(self.root / MANIFEST_PATH).write_text(json.dumps(manifest), encoding="utf-8")
result = self.run_guard()
self.assertEqual(result.returncode, 1, result.stderr)
self.assertIn("corpus_version bump (must increase SemVer)", result.stderr)
def test_passes_consistent_bumped_release_with_updated_docs(self) -> None:
(self.root / MATRIX_PATH).write_text(
BASE_MATRIX.replace("'1.0.0'", "'1.1.0'") + " - id: addition\n",
encoding="utf-8",
)
manifest = base_manifest()
manifest["matrix_version"] = "1.1.0"
manifest["corpus_version"] = "1.0.1"
manifest["compatibility_impact"] = "matrix 1.1.0 release"
(self.root / MANIFEST_PATH).write_text(json.dumps(manifest), encoding="utf-8")
(self.root / DOCS_PATH).write_text(
"Матрица версии `1.1.0`; corpus version — `1.0.1`.\n", encoding="utf-8"
)
result = self.run_guard()
self.assertEqual(result.returncode, 0, result.stderr)
if __name__ == "__main__":
unittest.main()
+159
View File
@@ -0,0 +1,159 @@
import json
import os
import subprocess
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
DEPLOY = ROOT / "scripts" / "deploy-community.sh"
class DeployCommunityMigrationGuardTests(unittest.TestCase):
def run_deploy(
self,
*,
version: int = 15,
preflight: str | None = None,
apply_success: bool = True,
plan: str | None = None,
) -> tuple[subprocess.CompletedProcess[str], list[list[str]], Path]:
temporary = tempfile.TemporaryDirectory()
self.addCleanup(temporary.cleanup)
root = Path(temporary.name)
bin_dir = root / "bin"
bin_dir.mkdir()
tmp_dir = root / "tmp"
tmp_dir.mkdir()
log = root / "docker.jsonl"
if preflight is None:
preflight = json.dumps(
{"status": "current", "version": version}, separators=(",", ":")
)
(root / ".env").write_text(
"POSTGRES_HOST=postgres\nPOSTGRES_PASSWORD=test-password\nCRANK_ADMIN_API_IMAGE=crank:test\n",
encoding="utf-8",
)
(root / "docker-compose.yml").write_text("services: {}\n", encoding="utf-8")
docker = r'''#!/usr/bin/env python3
import json, os, pathlib, sys
args = sys.argv[1:]
with open(os.environ["FAKE_DOCKER_LOG"], "a", encoding="utf-8") as stream:
stream.write(json.dumps(args) + "\n")
if args[:2] == ["compose", "config"] and args[2:3] == ["--services"]:
print("admin-api")
elif args[:2] == ["compose", "ps"]:
pass
elif args[:2] == ["compose", "up"]:
pass
elif args[:2] == ["network", "create"]:
print(args[2])
elif args[:2] == ["network", "rm"] or args[:2] == ["rm", "-fv"]:
pass
elif args[:1] == ["logs"]:
print("PostgreSQL init process complete")
elif args[:1] == ["exec"] and "pg_isready" in args:
pass
elif args[:1] == ["exec"] and "psql" in args:
pass
elif args[:1] == ["run"]:
if "pg_dump" in args:
mount = next(value for value in args if value.startswith("/") and ":/backup" in value)
pathlib.Path(mount.split(":/backup", 1)[0], "postgres.dump").write_bytes(b"fake dump")
elif "crank-migrate" in args:
command = args[args.index("crank-migrate") + 1:]
if command == ["apply"]:
sys.exit(0 if os.environ.get("FAKE_APPLY_SUCCESS") == "1" else 1)
if command == ["plan", "--target-version"]:
sys.stdout.write(os.environ["FAKE_PLAN_OUTPUT"] + "\n")
elif command == ["preflight"]:
sys.stdout.write(os.environ["FAKE_PREFLIGHT"] + "\n")
elif args[:1] == ["inspect"] and args[1:2] == ["--format"]:
print("")
sys.exit(0)
'''
curl = "#!/bin/sh\nexit 0\n"
sleep = "#!/bin/sh\nexit 0\n"
for name, contents in (("docker", docker), ("curl", curl), ("sleep", sleep)):
path = bin_dir / name
path.write_text(contents, encoding="utf-8")
path.chmod(0o755)
env = os.environ.copy()
env.update(
{
"PATH": f"{bin_dir}:{env['PATH']}",
"FAKE_DOCKER_LOG": str(log),
"FAKE_PREFLIGHT": preflight,
"FAKE_APPLY_SUCCESS": "1" if apply_success else "0",
"FAKE_PLAN_OUTPUT": plan if plan is not None else str(version),
"TMPDIR": str(tmp_dir),
}
)
result = subprocess.run(
["sh", str(DEPLOY), str(root)],
text=True,
capture_output=True,
env=env,
check=False,
)
calls = [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines()]
return result, calls, root
def test_current_v13_shadow_migration_allows_compose_up(self) -> None:
result, calls, root = self.run_deploy(version=13)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertTrue(any(call[:2] == ["compose", "up"] for call in calls))
self.assertTrue(any(call[:2] == ["rm", "-fv"] for call in calls))
self.assertTrue(any(call[:2] == ["network", "rm"] for call in calls))
self.assertEqual(list((root / "tmp").iterdir()), [])
def test_current_v15_shadow_migration_allows_compose_up(self) -> None:
result, calls, root = self.run_deploy(version=15)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertTrue(any(call[:2] == ["compose", "up"] for call in calls))
self.assertEqual(list((root / "tmp").iterdir()), [])
def test_future_current_shadow_migration_allows_compose_up(self) -> None:
result, calls, root = self.run_deploy(version=27)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertTrue(any(call[:2] == ["compose", "up"] for call in calls))
self.assertEqual(list((root / "tmp").iterdir()), [])
def test_invalid_preflight_responses_and_failed_apply_never_start_compose(self) -> None:
cases = (
("", True),
("not-json", True),
('noise\n{"status":"current","version":15}', True),
('{"status":"current","version":15}\nnoise', True),
('{"status":"current","version":15}\n', True),
('{"status":"applied","version":15}', True),
('{"status":"current","version":13}', True),
('{"status":"current","version":15,"extra":true}', True),
('{"status":"current","version":"15"}', True),
('{"status":"current","version":15}', False),
)
for preflight, apply_success in cases:
with self.subTest(preflight=preflight, apply_success=apply_success):
result, calls, root = self.run_deploy(
version=15, preflight=preflight, apply_success=apply_success
)
self.assertNotEqual(result.returncode, 0)
self.assertFalse(any(call[:2] == ["compose", "up"] for call in calls))
self.assertTrue(any(call[:2] == ["rm", "-fv"] for call in calls))
self.assertTrue(any(call[:2] == ["network", "rm"] for call in calls))
self.assertEqual(list((root / "tmp").iterdir()), [])
def test_invalid_target_version_is_rejected_before_shadow_database(self) -> None:
for target in ("", "0", "-1", "version", "15\n16", "15\n", "015"):
with self.subTest(target=target):
result, calls, _ = self.run_deploy(version=15, plan=target)
self.assertNotEqual(result.returncode, 0)
self.assertFalse(any(call[:2] == ["compose", "up"] for call in calls))
self.assertFalse(any(call[:2] == ["network", "create"] for call in calls))
if __name__ == "__main__":
unittest.main()
@@ -81,6 +81,36 @@ class CapabilityRunValidatorTests(unittest.TestCase):
self.assertNotEqual(result.returncode, 0)
self.assertIn("duplicate JSON key", result.stderr)
def test_nonfinite_json_constants_are_rejected(self) -> None:
for constant, token in (
(float("nan"), "NaN"),
(float("inf"), "Infinity"),
(float("-inf"), "-Infinity"),
):
with self.subTest(constant=token):
value = candidate()
value["summary"] = {"passed": 1, "anomaly": constant}
result = self.validate(json.dumps(value))
self.assertNotEqual(result.returncode, 0)
self.assertIn("INVALID_CAPABILITY_RUN", result.stderr)
self.assertIn("invalid JSON constant", result.stderr)
self.assertNotIn("Traceback", result.stderr)
self.assertNotIn(token, result.stderr)
def test_deep_malformed_json_is_rejected_without_raw_input(self) -> None:
malformed_deep_value = "[" * 1_500 + "RAW_DEEP_SENTINEL"
encoded = json.dumps(candidate()).replace(
'"summary": {"passed": 1}',
f'"summary": {{"passed": 1, "deep": {malformed_deep_value}}}',
)
self.assertLess(len(encoded.encode("utf-8")), 65_536)
result = self.validate(encoded)
self.assertNotEqual(result.returncode, 0)
self.assertIn("INVALID_CAPABILITY_RUN", result.stderr)
self.assertIn("invalid JSON", result.stderr)
self.assertNotIn("Traceback", result.stderr)
self.assertNotIn("RAW_DEEP_SENTINEL", result.stderr)
def test_oversized_candidate_is_rejected(self) -> None:
result = self.validate(b" " * (65_536 + 1))
self.assertNotEqual(result.returncode, 0)