diff --git a/.github/workflows/compatibility-ci.yml b/.github/workflows/compatibility-ci.yml new file mode 100644 index 0000000..dc764dd --- /dev/null +++ b/.github/workflows/compatibility-ci.yml @@ -0,0 +1,47 @@ +name: Compatibility infrastructure + +on: + workflow_dispatch: + push: + branches: + - main + paths: + - "compatibility/**" + - ".github/workflows/compatibility*" + - ".github/aw/actions-lock.json" + pull_request: + types: [opened, reopened, synchronize, ready_for_review] + paths: + - "compatibility/**" + - ".github/workflows/compatibility*" + - ".github/aw/actions-lock.json" + +concurrency: + group: compatibility-infrastructure-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + compatibility-unit-tests: + name: Compatibility infrastructure + runs-on: ubuntu-24.04 + permissions: + contents: read + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + persist-credentials: false + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: "3.12" + - name: Install compatibility development dependencies + run: python -m pip install -r compatibility/requirements-dev.txt + - name: Check scoped Python formatting and types + run: | + python -m black --check --config compatibility/pyproject.toml compatibility + python -m isort --check-only --settings-path compatibility/pyproject.toml compatibility + python -m flake8 --max-line-length=100 --extend-ignore=E203 compatibility + python -m mypy --config-file compatibility/pyproject.toml compatibility + - name: Run compatibility unit tests + run: python -m pytest -c compatibility/pyproject.toml compatibility/unit + - name: Check the README dashboard publisher + run: shellcheck compatibility/publish-readme.sh diff --git a/.github/workflows/compatibility-readme.yml b/.github/workflows/compatibility-readme.yml new file mode 100644 index 0000000..1a62305 --- /dev/null +++ b/.github/workflows/compatibility-readme.yml @@ -0,0 +1,100 @@ +name: Compatibility README dashboard + +on: + workflow_run: + workflows: ["Ecosystem compatibility"] + types: [completed] + workflow_dispatch: + inputs: + run_id: + description: Completed compatibility workflow run ID, or blank to refresh stored evidence + type: string + required: false + push: + branches: [main] + paths: + - ".github/workflows/compatibility-readme.yml" + - "compatibility/**" + - "README.md" + schedule: + - cron: "17 * * * *" + +permissions: + contents: read + +concurrency: + # Distinct runs must not evict each other's pending publications. + group: compatibility-readme-${{ github.repository }}-${{ github.event.workflow_run.id || inputs.run_id || github.run_id }}-${{ github.event.workflow_run.run_attempt || github.run_attempt }} + cancel-in-progress: false + +jobs: + publish: + name: Publish README status + if: >- + github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && + (github.event_name != 'workflow_run' || + ((github.event.workflow_run.event == 'workflow_dispatch' || + github.event.workflow_run.event == 'schedule') && + github.event.workflow_run.head_repository.full_name == github.repository && + github.event.workflow_run.head_branch == github.event.repository.default_branch)) + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + actions: read + contents: write + steps: + - name: Check out trusted publisher code + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + ref: ${{ github.sha }} + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: "3.12" + - name: Install trusted publication dependencies + run: python -m pip install -r compatibility/requirements.txt + - name: Validate source workflow identity + id: source + env: + GH_TOKEN: ${{ github.token }} + EVENT_NAME: ${{ github.event_name }} + DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} + SOURCE_RUN_ID: ${{ inputs.run_id }} + run: | + python -m compatibility.readme prepare \ + --repository "$GITHUB_REPOSITORY" --branch "$DEFAULT_BRANCH" \ + --event-name "$EVENT_NAME" --event-file "$GITHUB_EVENT_PATH" \ + --run-id "$SOURCE_RUN_ID" --output "$RUNNER_TEMP/compatibility-source.json" + - name: Read reviewed source execution inputs + if: steps.source.outputs.action == 'publish' + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + ref: ${{ steps.source.outputs.source_sha }} + path: .compatibility-source + persist-credentials: false + - name: Download this source attempt's combined evidence + if: steps.source.outputs.action == 'publish' + id: evidence + continue-on-error: true + uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7 + with: + name: ${{ steps.source.outputs.artifact }} + run-id: ${{ steps.source.outputs.run_id }} + github-token: ${{ github.token }} + path: .compatibility-report + - name: Record unavailable artifacts + if: steps.source.outputs.action == 'publish' && steps.evidence.outcome != 'success' + run: | + echo "::warning::Source report unavailable; the dashboard will expose missing evidence, not a compatibility pass." + - name: Persist evidence and publish the status snapshot + if: steps.source.outputs.action != 'ignore' + run: | + bash compatibility/publish-readme.sh \ + "$RUNNER_TEMP/compatibility-source.json" \ + "$GITHUB_WORKSPACE/.compatibility-source" \ + "$GITHUB_WORKSPACE/.compatibility-report" + { + echo "## README compatibility status" + echo + echo "Execution timestamps and outcomes are published on the compatibility-data branch." + echo "https://github.com/$GITHUB_REPOSITORY/blob/compatibility-data/site/README.md" + } >> "$GITHUB_STEP_SUMMARY" diff --git a/README.md b/README.md index dbf1bd9..b9f808c 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,14 @@ that your driver of choice behaves the way you expect. Others may target different environments (for example Kubernetes or a cloud deployment); each playground's README states what it needs. +## Compatibility status + +[![PyMongo compatibility](/../compatibility-data/site/badges/pymongo.svg)](/../compatibility-data/site/README.md#pymongo) + +[Run details and accessible results](/../compatibility-data/site/README.md) +show tested versions, actual execution timestamps, and the latest attempt +separately from the last conclusive compatibility evidence. + ## Playgrounds | Playground | Language / Stack | What it shows | diff --git a/compatibility/.gitignore b/compatibility/.gitignore new file mode 100644 index 0000000..50240a0 --- /dev/null +++ b/compatibility/.gitignore @@ -0,0 +1,8 @@ +!requirements*.txt +!integrations/*/requirements.txt +__pycache__/ +.pytest_cache/ +.mypy_cache/ +.venv/ +.test-results/ +node_modules/ diff --git a/compatibility/README.md b/compatibility/README.md new file mode 100644 index 0000000..bdf208c --- /dev/null +++ b/compatibility/README.md @@ -0,0 +1,180 @@ +# Ecosystem compatibility + +This registry-driven runner tests ecosystem integration profiles against reviewed +DocumentDB releases. Execution, artifact verification, and result contracts are +shared; each integration adapter implements its own scenario suite. + +## Profiles and reviewed artifacts + +[`registry.yaml`](registry.yaml) defines profiles, enablement, default package +versions, version policies, required scenarios, and reviewed DocumentDB releases. +Adapter directories under [`integrations/`](integrations/) contain runtime recipes +and scenario suites. These definitions identify the package, runtime, and database +combination for a run, not the newest upstream releases. Database and client base +images are pinned by digest. + +Runs target the newest reviewed DocumentDB release by default. +`--documentdb-version` selects another release listed in the registry. + +Version overrides must match the integration's registry policy and have eligible +artifacts for its runtime. PyMongo versions use three numeric components, such as +`--version 4.9.0`; equivalent published versions such as `4.9` are matched using +package-version semantics. A version without an eligible Python 3.12 Linux x64 +wheel is Not tested, not Working. + +Before executing scenarios, the controller checks the actual extension and +PostgreSQL major versions. It verifies the selected wheel's filename and SHA-256 +against non-yanked PyPI metadata. The client records installed package and +dependency versions and hashes, its runtime version, and its image identity. +An execution-input digest includes the suite, controller, schemas, and runtime +recipe, including uncommitted local changes. + +## Coverage + +The PyMongo profile exercises synchronous driver APIs. Its required scenarios are +declared in the registry's `expected_tests` list and cover the following behavior: + +| Area | Behavior | +| --- | --- | +| Connection | Authenticated administrative ping over TLS | +| Inserts and reads | `insert_one`, `insert_many`, `find_one`, filters, projection, sorting, limits, and exact readback | +| Cursor and counts | Observed `getMore` with bounded batches and exact document counts | +| Updates and deletes | `update_one`, `find_one_and_update`, `delete_one`, `delete_many`, result objects, and persisted effects | +| Aggregation and indexes | Aggregation results, index creation/listing/removal, and duplicate-key rejection | +| BSON | ObjectId, integers, Decimal128, dates, binary values, arrays, booleans, and nested documents | + +Each scenario has a fresh disposable database. Required cases cannot be silently +skipped or exempted. A result applies only to its exact version pair, runtime, +execution inputs, and declared scenarios. It does not establish compatibility +for async APIs, transactions, vector search, or other unlisted features. + +## Run locally + +Use a Python 3.12 virtual environment or a prepared Python 3.12 tooling container, +with access to a Linux Docker daemon capable of running Linux x64 images. Run +these commands from the repository root and install trusted controller dependencies +in that environment, not in the disposable integration client: + +```bash +python -m pip install -r compatibility/requirements.txt +python -m compatibility.runner --integration pymongo \ + --output compatibility/.test-results/pymongo-001/result.json +python -m compatibility.runner --integration pymongo --version 4.9.0 \ + --output compatibility/.test-results/pymongo-4.9.0/result.json +``` + +Each invocation requires a fresh output path and creates fresh credentials, +containers, an internal Docker network, and disposable databases. Only the +controller has Docker access. The integration client receives no checkout mount, +Docker socket, publication credential, or external network access. + +The runner builds the client without build-time network access after downloading +verified wheels. `--wheelhouse /path/to/wheels` reuses downloaded wheels, but PyPI +metadata verification still requires network access. Do not disable TLS +verification for package downloads. + +The output includes `result.json`, a sanitized `result.log`, and `result.xml` +when tests execute. Setup failures still produce a validated JSON envelope and +diagnostics. Cleanup targets only the invocation's labeled Docker resources. +The runner refuses to overwrite existing results or diagnostic files. + +To verify the nonpassing path: + +```bash +python -m compatibility.runner --integration pymongo --demonstration \ + --output compatibility/.test-results/pymongo-demo-001/result.json +``` + +This runs the normal scenarios plus one labeled intentional assertion failure +and must exit nonzero. Demonstration evidence cannot replace a compatibility +verdict. Use only synthetic data; do not supply production credentials. + +## Interpret results + +Working requires verified identities and every required scenario to pass. +A conclusive assertion or operation failure produces Failing. Missing, skipped, +incomplete, or infrastructure-failed execution cannot become Working and is +reported as Not tested unless a conclusive compatibility failure is present. + +Inspect the scenario diagnostics and declared coverage before reporting a +compatibility problem. Distinguish an operation mismatch from a package-download, +readiness, or cleanup failure. Include a minimal synthetic reproduction, the +integration and database versions, the profile, and sanitized result/log details. +Never share credentials or customer data. + +Runs emit runtime-neutral schema version 2. Schema-version-1 Python records remain +readable without rewriting their immutable provenance. + +## README dashboard + +The repository README embeds compact integration badges from the `compatibility-data` +branch. Each badge links to that integration's accessible results table, including +the source workflow runs and their detailed report artifacts. The publisher generates +`site/badges/.svg`, per-integration sections in `site/README.md`, and the +full status card in `site/status.svg` from the shared status snapshot. + +Badges summarize the integration's published version and profile rows, using +Failing before Not tested, Stale, and Working. A missing latest result prevents a +green badge even when an earlier pass remains available in the details. A workflow +that fails before its profile selection is known also prevents a green badge. +Freshness and intentional-failure exclusion follow the same rules as the details. + +The dashboard shows client and DocumentDB versions, the last conclusive evidence, +the latest attempt's outcome and execution timestamp, and verified scenario +counts. An incomplete attempt cannot acquire an earlier attempt's success. +Evidence is ordered by its workflow attempt rather than by test start time, so an +older run that starts its tests late cannot mask a newer attempt's outcome. +Workflow failures without usable profile artifacts remain visible separately +from older conclusive evidence. Synthetic demonstrations are excluded. + +`Compatibility README dashboard` consumes completed dispatched or scheduled +`Ecosystem compatibility` runs from the same repository's default branch. Test +execution remains read-only; only the trusted publisher can write the data branch. +The publisher checks the source run, workflow path, repository, branch, artifact +attempt, and reviewed execution inputs. It reads source files to verify their +digests but never executes source-run code or downloaded artifact content. + +Result JSON files remain immutable. Workflow-attempt identity and execution time +cannot be rewritten, while a later publication can recover previously unavailable +artifacts for that same attempt. Non-force updates preserve concurrent data +writers. The workflow refreshes the snapshot when default-branch inputs change +and hourly for freshness; it commits only when the published content changes. +It does not activate AI, create issues, or deploy a public website. + +For manual recovery, dispatch `Compatibility README dashboard` on the default +branch with a completed compatibility `run_id`. Leave that input empty to render +stored evidence without launching tests. The source report artifact must still +be available. Before a completed run is published, the initialized dashboard +shows Not tested. + +GitHub may cache embedded images. The accessible results and `site/status.json` +on the data branch expose the same snapshot. Execution timestamps always refer +to actual runs, never to rendering or refresh time. + +## Extend and maintain + +When adding an integration, include its badge in the root README. Use +`/../compatibility-data/site/badges/.svg` for the image and +`/../compatibility-data/site/README.md#` for the details link. + +Add a reviewed adapter directory, pinned image and package requirements, normal +and deliberate-failure suites, and a registry entry naming every required +scenario. Keep package preparation, runtime validation, and provenance support +with any new runtime. Enable an integration only when its real adapter exists. +A registry entry alone does not implement runtime support. + +Run infrastructure checks in a prepared Python 3.12 tooling container: + +```bash +python -m pip install -r compatibility/requirements-dev.txt +python -m black --check --config compatibility/pyproject.toml compatibility +python -m isort --check-only --settings-path compatibility/pyproject.toml compatibility +python -m flake8 --max-line-length=100 --extend-ignore=E203 compatibility +python -m mypy --config-file compatibility/pyproject.toml compatibility +python -m pytest -c compatibility/pyproject.toml compatibility/unit +``` + +Also exercise normal and deliberate-failure runs against the selected released +database image. Assertions and fixtures should derive selected configuration +from the registry rather than duplicate version pins. No unchanged database or +gateway build is required for compatibility-only changes. diff --git a/compatibility/__init__.py b/compatibility/__init__.py new file mode 100644 index 0000000..151c029 --- /dev/null +++ b/compatibility/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: MIT + +"""Version-pinned ecosystem compatibility automation.""" diff --git a/compatibility/client.py b/compatibility/client.py new file mode 100644 index 0000000..f5c9372 --- /dev/null +++ b/compatibility/client.py @@ -0,0 +1,109 @@ +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: MIT + +"""Isolated pytest entry point; stdout is a single machine-readable report.""" + +from __future__ import annotations + +import contextlib +import importlib.metadata +import json +import os +import platform +import sys +from pathlib import Path + +import pytest +from pymongo.errors import OperationFailure, ProtocolError, PyMongoError + + +class Reports: + """Preserve setup/call/teardown failures instead of counting only passing calls.""" + + def __init__(self) -> None: + self.tests: dict[str, dict[str, str]] = {} + + def pytest_collection_modifyitems(self, items): + identifiers = [item.originalname or item.name for item in items] + if len(identifiers) != len(set(identifiers)): + raise pytest.UsageError( + "Each registered scenario must have a unique test function name" + ) + + @pytest.hookimpl(hookwrapper=True) + def pytest_runtest_makereport(self, item, call): + report = (yield).get_result() + identifier = item.originalname or item.name + outcome = "passed" + if report.failed: + error = call.excinfo.value if call.excinfo is not None else None + incompatible = isinstance( + error, (AssertionError, pytest.fail.Exception, OperationFailure, ProtocolError) + ) + timed_out = isinstance(error, PyMongoError) and error.timeout + outcome = ( + "failed" if report.when == "call" and incompatible and not timed_out else "error" + ) + elif report.skipped: + outcome = "skipped" + elif report.when != "call": + return + severity = {"passed": 0, "skipped": 1, "error": 2, "failed": 3} + previous = self.tests.get(identifier) + if previous is None or severity[outcome] > severity[previous["outcome"]]: + self.tests[identifier] = { + "id": identifier, + "outcome": outcome, + "message": str(report.longrepr)[:2000] if outcome != "passed" else "", + } + + +def main() -> int: + """Execute only the selected adapter file, never the entire engine corpus.""" + package = os.environ["COMPATIBILITY_PACKAGE"] + report = json.loads(Path("/install-report.json").read_text()) + installed = next( + entry + for entry in report["install"] + if entry["metadata"]["name"].lower().replace("-", "_") == package.replace("-", "_") + ) + collector = Reports() + paths = [os.environ["COMPATIBILITY_TEST_FILE"]] + if os.environ.get("COMPATIBILITY_DEMONSTRATION") == "1": + paths.append(os.environ["COMPATIBILITY_DEMONSTRATION_FILE"]) + with contextlib.redirect_stdout(sys.stderr): + exit_code = pytest.main( + [ + "-c", + "compatibility/pyproject.toml", + "-q", + "--tb=short", + "-p", + "no:cacheprovider", + "--junitxml=/tmp/tests.xml", + *paths, + ], + plugins=[collector], + ) + payload = { + "version": importlib.metadata.version(package), + "runtime": {"name": "python", "version": platform.python_version()}, + "artifact_sha256": installed["download_info"]["archive_info"]["hashes"]["sha256"], + "dependencies": [ + { + "name": entry["metadata"]["name"], + "version": entry["metadata"]["version"], + "sha256": entry["download_info"]["archive_info"]["hashes"]["sha256"], + } + for entry in report["install"] + ], + "exit_code": int(exit_code), + "tests": list(collector.tests.values()), + "junit": Path("/tmp/tests.xml").read_text(), + } + print(json.dumps(payload, allow_nan=False)) + return int(exit_code) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/compatibility/contracts.py b/compatibility/contracts.py new file mode 100644 index 0000000..cd19158 --- /dev/null +++ b/compatibility/contracts.py @@ -0,0 +1,211 @@ +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: MIT + +"""Validated registry, immutable result, and coverage contracts.""" + +from __future__ import annotations + +import hashlib +import json +import re +from datetime import datetime, timedelta, timezone +from pathlib import Path +from typing import Any + +import yaml +from jsonschema import Draft202012Validator, FormatChecker +from packaging.version import Version + +ROOT = Path(__file__).resolve().parent.parent +DEMONSTRATION_TEST = "test_failure_demonstration" +RUNTIME_PREFIXES = {"python": "3.12.", "nodejs": "24."} + + +def validate_schema(value: Any, name: str) -> None: + """Reject unknown fields and malformed values without echoing input secrets.""" + schema = json.loads((ROOT / "compatibility" / "schemas" / f"{name}.json").read_text()) + validator = Draft202012Validator(schema, format_checker=FormatChecker()) + error = next(validator.iter_errors(value), None) + if error is not None: + location = ".".join(map(str, error.absolute_path)) or "" + raise ValueError(f"Invalid {name} field {location}: {error.validator}") + + +def read_registry( + path: Path = ROOT / "compatibility" / "registry.yaml", *, root: Path = ROOT +) -> dict[str, Any]: + """Load the reviewed registry and validate adapter locations and defaults.""" + registry = yaml.safe_load(path.read_text()) + validate_schema(registry, "registry") + for name, integration in registry["integrations"].items(): + if not re.fullmatch(integration["version_pattern"], integration["default_version"]): + raise ValueError(f"Default version is outside the policy for {name}") + for key in ("test_file", "demonstration_file"): + test_file = (root / integration[key]).resolve() + allowed = (root / "compatibility" / "integrations" / name).resolve() + if ( + not allowed.is_relative_to(root.resolve()) + or test_file.parent != allowed + or not test_file.is_file() + or test_file.suffix != (".py" if integration["runtime"] == "python" else ".cjs") + ): + raise ValueError(f"Invalid adapter location for {name}") + return dict(registry) + + +def default_documentdb_version(registry: dict[str, Any]) -> str: + """Return the newest reviewed DocumentDB release using version ordering.""" + return str(max(registry["documentdb"], key=Version)) + + +def timestamp(value: str) -> datetime: + """Parse an explicitly zoned timestamp into UTC.""" + parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) + if parsed.tzinfo is None: + raise ValueError("Timestamps require an explicit timezone") + return parsed.astimezone(timezone.utc) + + +def expected_tests(spec: dict[str, Any], demonstration: bool) -> list[str]: + """Return the exact scenario contract, including an explicitly labeled demonstration.""" + return list(spec["expected_tests"]) + ([DEMONSTRATION_TEST] if demonstration else []) + + +def validate_result(result: dict[str, Any], spec: dict[str, Any] | None = None) -> None: + """Validate raw records before either persistence or rendering.""" + validate_schema(result, "result") + if timestamp(result["finished_at"]) < timestamp(result["started_at"]): + raise ValueError("Result finishes before it starts") + if timestamp(result["finished_at"]) > datetime.now(timezone.utc) + timedelta(minutes=5): + raise ValueError("Result timestamp is implausibly far in the future") + identifiers = [test["id"] for test in result["tests"]] + if len(set(identifiers)) != len(identifiers): + raise ValueError("Duplicate test outcomes") + if not set(identifiers).issubset(result["expected_tests"]): + raise ValueError("Result contains an undeclared scenario") + runtime = result_runtime(result) + if runtime["version"] is not None and not runtime["version"].startswith( + RUNTIME_PREFIXES[runtime["name"]] + ): + raise ValueError("Result has an unsupported runtime version") + if spec is not None: + if runtime["name"] != spec["runtime"]: + raise ValueError("Result runtime does not match the reviewed registry") + if result["expected_tests"] != expected_tests(spec, result["demonstration"]): + raise ValueError("Result coverage does not match the reviewed registry") + for key in ("repository", "owner", "profile"): + if result[key] != spec[key]: + raise ValueError(f"Result {key} does not match the reviewed registry") + + +def validate_client_report(value: Any, runtime_name: str = "python") -> None: + """Validate the untrusted container's envelope before reading or retaining its fields.""" + result_schema = json.loads((ROOT / "compatibility" / "schemas" / "result.json").read_text()) + properties = { + "version": {"type": "string", "pattern": r"^[0-9]+\.[0-9]+(?:\.[0-9]+)?$"}, + "runtime": result_schema["$defs"]["runtime"], + "artifact_sha256": {"type": "string", "pattern": "^[a-f0-9]{64}$"}, + "exit_code": {"type": "integer", "minimum": 0, "maximum": 5}, + "tests": result_schema["properties"]["tests"], + "junit": {"type": "string", "maxLength": 1024 * 1024}, + "dependencies": result_schema["properties"]["upstream"]["properties"]["dependencies"], + } + validator = Draft202012Validator( + { + "type": "object", + "additionalProperties": False, + "required": list(properties), + "properties": properties, + } + ) + if next(validator.iter_errors(value), None) is not None: + raise ValueError("Invalid isolated-client report") + runtime = value["runtime"] + if ( + runtime["name"] != runtime_name + or runtime["version"] is None + or not runtime["version"].startswith(RUNTIME_PREFIXES[runtime_name]) + ): + raise ValueError("Isolated-client runtime does not match the selected profile") + + +def artifact_sha256(result: dict[str, Any]) -> str | None: + """Read either historical wheel provenance or the runtime-neutral artifact hash.""" + key = "wheel_sha256" if result["schema_version"] == 1 else "artifact_sha256" + value: str | None = result["upstream"][key] + return value + + +def result_runtime(result: dict[str, Any]) -> dict[str, Any]: + """Keep version-one history readable without rewriting immutable records.""" + if result["schema_version"] == 1: + return {"name": "python", "version": result["upstream"]["python_version"]} + return dict(result["upstream"]["runtime"]) + + +def compatibility_state(result: dict[str, Any]) -> str: + """A conclusive assertion failure wins; incomplete execution never becomes Working.""" + if any(test["outcome"] == "failed" for test in result["tests"]): + return "Failing" + if ( + result["execution_error"] + or not result["documentdb"]["actual_extension_version"] + or not result["documentdb"]["actual_postgres_version"] + or result["upstream"]["actual_version"] is None + or Version(result["upstream"]["actual_version"]) != Version(result["upstream"]["version"]) + or not artifact_sha256(result) + or not result["upstream"]["client_image"] + or not result_runtime(result)["version"] + or not result["upstream"]["dependencies"] + ): + return "Not tested" + outcomes = {test["id"]: test["outcome"] for test in result["tests"]} + if all(outcomes.get(name) == "passed" for name in result["expected_tests"]): + return "Working" + return "Not tested" + + +def suite_files(integration: str, root: Path = ROOT) -> list[Path]: + """Use the same explicit source set for provenance and the isolated client build.""" + adapter = root / "compatibility" / "integrations" / integration + files = [ + root / "compatibility" / "pyproject.toml", + root / "compatibility" / "requirements.txt", + root / "compatibility" / "__init__.py", + root / "compatibility" / "client.py", + root / "compatibility" / "contracts.py", + root / "compatibility" / "runner.py", + root / "compatibility" / "schemas" / "registry.json", + root / "compatibility" / "schemas" / "result.json", + adapter / "Dockerfile", + ] + for pattern in ("*.py", "requirements.txt"): + files.extend(adapter.glob(pattern)) + for path in files: + if path.is_symlink(): + raise ValueError("Suite files must not be symbolic links") + return sorted(files) + + +def suite_digest(integration: str, spec: dict[str, Any], root: Path = ROOT) -> str: + """Hash execution inputs, including the runtime recipe and uncommitted local edits.""" + digest = hashlib.sha256() + execution = { + key: spec[key] + for key in ( + "package", + "runtime", + "profile", + "test_file", + "demonstration_file", + "timeout_seconds", + "expected_tests", + ) + } + digest.update(json.dumps(execution, sort_keys=True, separators=(",", ":")).encode()) + for path in suite_files(integration, root): + digest.update(path.relative_to(root).as_posix().encode()) + digest.update(b"\0") + digest.update(path.read_bytes()) + digest.update(b"\0") + return digest.hexdigest() diff --git a/compatibility/integrations/pymongo/Dockerfile b/compatibility/integrations/pymongo/Dockerfile new file mode 100644 index 0000000..393b7be --- /dev/null +++ b/compatibility/integrations/pymongo/Dockerfile @@ -0,0 +1,18 @@ +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: MIT + +FROM python:3.12-slim-bookworm@sha256:782412e85d0f0984994c290652577d4018aff08145c85b262bb63dc0c7522254 + +COPY wheels /wheels +COPY compatibility/integrations/pymongo/requirements.txt /requirements.txt +COPY integration-requirements.txt /integration-requirements.txt +RUN python -m pip install --no-index --find-links=/wheels \ + --report=/install-report.json --disable-pip-version-check \ + -r /integration-requirements.txt && useradd --create-home --uid 1000 runner +COPY compatibility /app/compatibility +WORKDIR /app +USER 1000:1000 +ENV PYTHONDONTWRITEBYTECODE=1 +ENV PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 +ENV COMPATIBILITY_ACTIVE=1 +ENTRYPOINT ["python", "-m", "compatibility.client"] diff --git a/compatibility/integrations/pymongo/conftest.py b/compatibility/integrations/pymongo/conftest.py new file mode 100644 index 0000000..cc6c259 --- /dev/null +++ b/compatibility/integrations/pymongo/conftest.py @@ -0,0 +1,64 @@ +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: MIT + +"""Disposable namespaces and command-name-only observation for real driver tests.""" + +import os +import uuid +from collections.abc import Iterator +from datetime import timezone +from typing import Any + +import pytest +from bson.codec_options import CodecOptions +from pymongo import MongoClient, monitoring +from pymongo.collection import Collection + + +class CommandNames(monitoring.CommandListener): + def __init__(self) -> None: + self.names: list[str] = [] + + def started(self, event: monitoring.CommandStartedEvent) -> None: + self.names.append(event.command_name) + + def succeeded(self, event: monitoring.CommandSucceededEvent) -> None: + pass + + def failed(self, event: monitoring.CommandFailedEvent) -> None: + pass + + +@pytest.fixture +def command_names() -> CommandNames: + return CommandNames() + + +@pytest.fixture +def collection(command_names: CommandNames) -> Iterator[Collection[dict[str, Any]]]: + client: MongoClient[dict[str, Any]] = MongoClient( + "db", + 10260, + username=os.environ["USERNAME"], + password=os.environ["PASSWORD"], + authSource="admin", + directConnection=True, + tls=True, + tlsAllowInvalidCertificates=True, + serverSelectionTimeoutMS=15000, + connectTimeoutMS=10000, + socketTimeoutMS=15000, + event_listeners=[command_names], + appname="documentdb-pymongo-compatibility", + ) + database = client.get_database( + f"compat_{uuid.uuid4().hex}", + codec_options=CodecOptions(tz_aware=True, tzinfo=timezone.utc), + ) + try: + yield database["items"] + finally: + try: + client.drop_database(database.name) + finally: + client.close() diff --git a/compatibility/integrations/pymongo/requirements.txt b/compatibility/integrations/pymongo/requirements.txt new file mode 100644 index 0000000..a1bfce0 --- /dev/null +++ b/compatibility/integrations/pymongo/requirements.txt @@ -0,0 +1 @@ +pytest>=8.3,<10 diff --git a/compatibility/integrations/pymongo/test_demonstration.py b/compatibility/integrations/pymongo/test_demonstration.py new file mode 100644 index 0000000..b70baef --- /dev/null +++ b/compatibility/integrations/pymongo/test_demonstration.py @@ -0,0 +1,25 @@ +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: MIT + +"""An explicitly labeled failing driver assertion, never a real compatibility verdict.""" + +import os + +import pytest + +pytestmark = [ + pytest.mark.integration, + pytest.mark.skipif( + os.environ.get("COMPATIBILITY_ACTIVE") != "1" + or os.environ.get("COMPATIBILITY_DEMONSTRATION") != "1", + reason="Only an explicitly requested isolated failure demonstration enables this case", + ), +] + + +def test_failure_demonstration(collection): + """An intentionally incorrect count must produce a failed result and nonzero exit.""" + collection.insert_one({"_id": 1}) + assert ( + collection.count_documents({}) == 0 + ), "Intentional failure demonstration; not a compatibility regression" diff --git a/compatibility/integrations/pymongo/test_pymongo.py b/compatibility/integrations/pymongo/test_pymongo.py new file mode 100644 index 0000000..643e326 --- /dev/null +++ b/compatibility/integrations/pymongo/test_pymongo.py @@ -0,0 +1,200 @@ +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: MIT + +"""Synchronous driver API coverage, not a full engine feature specification.""" + +import os +from datetime import datetime, timezone + +import pytest +from bson import Decimal128, Int64, ObjectId +from pymongo import ASCENDING, DESCENDING, IndexModel, ReturnDocument +from pymongo.errors import DuplicateKeyError + +pytestmark = [ + pytest.mark.integration, + pytest.mark.skipif( + os.environ.get("COMPATIBILITY_ACTIVE") != "1", + reason="Run this version-pinned profile through compatibility.runner", + ), +] + + +def test_authenticated_ping(collection): + """The selected client authenticates and receives an administrative reply.""" + assert collection.database.client.admin.command("ping")["ok"] == 1 + + +def test_insert_one(collection): + """InsertOneResult and a subsequent read identify the inserted document.""" + document = {"value": 3} + result = collection.insert_one(document) + assert result.acknowledged + assert isinstance(result.inserted_id, ObjectId) + assert collection.find_one({"_id": result.inserted_id}) == document + + +def test_insert_many(collection): + """InsertManyResult contains every identifier and all documents are readable.""" + documents = [{"_id": 1, "value": 3}, {"_id": 2, "value": 7}] + result = collection.insert_many(documents) + assert result.acknowledged + assert result.inserted_ids == [1, 2] + assert list(collection.find().sort("_id", ASCENDING)) == documents + + +def test_find_one(collection): + """A point lookup returns the exact document, or None for a missing key.""" + document = {"_id": 1, "value": 3} + collection.insert_one(document) + assert collection.find_one({"_id": 1}) == document + assert collection.find_one({"_id": 2}) is None + + +def test_find_filter_projection_sort_limit(collection): + """A driver cursor combines filter, projection, sort, and limit correctly.""" + collection.insert_many( + [{"_id": 1, "price": 3}, {"_id": 2, "price": 7}, {"_id": 3, "price": 11}] + ) + documents = list( + collection.find({"price": {"$gte": 5}}, {"_id": 0, "price": 1}) + .sort("price", DESCENDING) + .limit(1) + ) + assert documents == [{"price": 11}] + + +def test_cursor_batches(collection, command_names): + """Iteration issues getMore and returns every document once across batches.""" + documents = [{"_id": number} for number in range(7)] + collection.insert_many(documents) + command_names.names.clear() + with collection.find().sort("_id", ASCENDING).batch_size(2) as cursor: + actual = list(cursor) + assert actual == documents + assert "find" in command_names.names + assert "getMore" in command_names.names + + +def test_count_documents(collection): + """The driver's count API respects its filter and handles an empty match.""" + collection.insert_many([{"_id": 1, "value": 3}, {"_id": 2, "value": 7}]) + assert collection.count_documents({}) == 2 + assert collection.count_documents({"value": {"$gte": 5}}) == 1 + assert collection.count_documents({"value": 99}) == 0 + + +def test_update_one(collection): + """UpdateResult counts and readback agree on the applied change.""" + collection.insert_one({"_id": 1, "value": 3}) + result = collection.update_one({"_id": 1}, {"$set": {"value": 7}}) + assert result.acknowledged + assert (result.matched_count, result.modified_count, result.upserted_id) == (1, 1, None) + assert collection.find_one({"_id": 1}) == {"_id": 1, "value": 7} + + +def test_find_one_and_update(collection): + """ReturnDocument.AFTER returns the changed document rather than the old one.""" + collection.insert_one({"_id": 1, "tags": ["alpha"]}) + document = collection.find_one_and_update( + {"_id": 1}, {"$push": {"tags": "beta"}}, return_document=ReturnDocument.AFTER + ) + assert document == {"_id": 1, "tags": ["alpha", "beta"]} + assert collection.find_one({"_id": 1}) == document + + +def test_delete_one(collection): + """DeleteResult and the remaining collection agree on a single deletion.""" + collection.insert_many([{"_id": 1}, {"_id": 2}]) + result = collection.delete_one({"_id": 1}) + assert result.acknowledged + assert result.deleted_count == 1 + assert list(collection.find()) == [{"_id": 2}] + + +def test_delete_many(collection): + """A multi-document deletion returns its count and preserves nonmatching data.""" + collection.insert_many([{"_id": number} for number in range(3)]) + result = collection.delete_many({"_id": {"$lt": 2}}) + assert result.acknowledged + assert result.deleted_count == 2 + assert list(collection.find()) == [{"_id": 2}] + + +def test_aggregate(collection): + """The aggregation cursor yields exact grouped counts in the requested order.""" + collection.insert_many([{"_id": 1, "tags": ["alpha", "beta"]}, {"_id": 2, "tags": ["beta"]}]) + documents = list( + collection.aggregate( + [ + {"$unwind": "$tags"}, + {"$group": {"_id": "$tags", "count": {"$sum": 1}}}, + {"$sort": {"_id": 1}}, + ] + ) + ) + assert documents == [{"_id": "alpha", "count": 1}, {"_id": "beta", "count": 2}] + + +def test_create_indexes(collection): + """IndexModel inputs produce the requested scalar and compound index definitions.""" + names = collection.create_indexes( + [ + IndexModel([("sku", ASCENDING)], name="sku_unique", unique=True), + IndexModel([("name", ASCENDING), ("price", DESCENDING)], name="name_price"), + ] + ) + assert names == ["sku_unique", "name_price"] + indexes = collection.index_information() + assert indexes["sku_unique"]["key"] == [("sku", 1)] + assert indexes["sku_unique"]["unique"] is True + assert indexes["name_price"]["key"] == [("name", 1), ("price", -1)] + + +def test_list_indexes(collection): + """The list_indexes cursor exposes the identifier and a created field index.""" + collection.insert_one({"_id": 1, "value": 3}) + collection.create_index("value", name="value_1") + indexes = {entry["name"]: entry for entry in collection.list_indexes()} + assert set(indexes) == {"_id_", "value_1"} + assert dict(indexes["value_1"]["key"]) == {"value": 1} + + +def test_drop_index(collection): + """A dropped field index disappears while the identifier index remains.""" + collection.insert_one({"_id": 1, "value": 3}) + collection.create_index("value", name="value_1") + collection.drop_index("value_1") + assert [entry["name"] for entry in collection.list_indexes()] == ["_id_"] + + +def test_duplicate_key_error(collection): + """A unique-index violation becomes DuplicateKeyError without inserting data.""" + collection.create_index("sku", unique=True) + collection.insert_one({"_id": 1, "sku": "one"}) + with pytest.raises(DuplicateKeyError) as raised: + collection.insert_one({"_id": 2, "sku": "one"}) + assert raised.value.code == 11000 + assert list(collection.find()) == [{"_id": 1, "sku": "one"}] + + +def test_bson_round_trip(collection): + """Values and representative BSON types survive insertion and driver decoding.""" + document = { + "_id": ObjectId(), + "integer": 7, + "long": Int64(2**40), + "double": 2.5, + "decimal": Decimal128("3.14"), + "date": datetime(2024, 1, 1, tzinfo=timezone.utc), + "binary": b"\x00\xff", + "array": [1, "two", None], + "boolean": True, + } + collection.insert_one(document) + actual = collection.find_one({"_id": document["_id"]}) + assert actual == document + assert actual is not None + for name, value in document.items(): + assert type(actual[name]) is type(value), f"BSON type changed for {name}" + assert actual["date"].utcoffset() == document["date"].utcoffset() diff --git a/compatibility/publish-readme.sh b/compatibility/publish-readme.sh new file mode 100644 index 0000000..c4ea0d7 --- /dev/null +++ b/compatibility/publish-readme.sh @@ -0,0 +1,88 @@ +#!/usr/bin/env bash +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: MIT + +set -euo pipefail + +if [[ $# -ne 3 || -z "${GITHUB_REPOSITORY:-}" ]]; then + printf 'Usage: GITHUB_REPOSITORY=owner/repo bash compatibility/publish-readme.sh SOURCE_JSON SOURCE_CHECKOUT REPORT_DIRECTORY\n' >&2 + exit 2 +fi + +source_json=$(realpath --no-symlinks "$1") +source_root=$(realpath --no-symlinks --canonicalize-missing "$2") +incoming=$(realpath --no-symlinks --canonicalize-missing "$3") +repo_root=$(git rev-parse --show-toplevel) +cd "$repo_root" +worktree="" +scratch="" +temporary_branch="" + +cleanup() { + if [[ -n "$worktree" ]]; then + git worktree remove --force "$worktree" + worktree="" + scratch="" + elif [[ -n "$scratch" ]]; then + rmdir "$scratch" + scratch="" + fi + if [[ -n "$temporary_branch" ]] && git show-ref --verify --quiet "refs/heads/$temporary_branch"; then + git branch -D "$temporary_branch" + fi + temporary_branch="" +} +trap cleanup EXIT + +for attempt in 1 2 3 4 5; do + lookup=0 + git ls-remote --exit-code --heads origin refs/heads/compatibility-data >/dev/null || lookup=$? + if [[ $lookup != 0 && $lookup != 2 ]]; then + printf 'Could not look up the compatibility data branch.\n' >&2 + exit "$lookup" + fi + if [[ $lookup == 0 ]]; then + git fetch --no-tags origin refs/heads/compatibility-data + fi + scratch=$(mktemp -d "${RUNNER_TEMP:-${TMPDIR:-/tmp}}/compat-dashboard.XXXXXX") + if [[ $lookup == 0 ]]; then + git worktree add --detach "$scratch" FETCH_HEAD + else + git worktree add --detach "$scratch" HEAD + fi + worktree=$scratch + if [[ $lookup == 2 ]]; then + temporary_branch="dashboard-$(basename "$worktree")" + git -C "$worktree" switch --orphan "$temporary_branch" + fi + + python -m compatibility.readme ingest --source "$source_json" \ + --source-root "$source_root" --incoming "$incoming" \ + --data "$worktree" --repository "$GITHUB_REPOSITORY" + python -m compatibility.readme render --data "$worktree" \ + --site "$worktree/site" --repository "$GITHUB_REPOSITORY" + git -C "$worktree" add -- site + for directory in results attempts; do + if [[ -d "$worktree/$directory" ]]; then + git -C "$worktree" add -- "$directory" + fi + done + if git -C "$worktree" diff --cached --quiet; then + printf 'README status and execution evidence are unchanged.\n' + exit 0 + fi + git -C "$worktree" \ + -c user.name='github-actions[bot]' \ + -c user.email='41898282+github-actions[bot]@users.noreply.github.com' \ + commit -s -m "Update compatibility evidence and README status" + revision=$(git -C "$worktree" rev-parse HEAD) + if git push origin "$revision:refs/heads/compatibility-data"; then + exit 0 + fi + cleanup + printf 'Dashboard push failed; retrying from current history (%s/5).\n' "$attempt" >&2 + sleep "$attempt" +done + +printf 'Could not publish the README dashboard after five conflict-safe attempts.\n' >&2 +exit 1 diff --git a/compatibility/pyproject.toml b/compatibility/pyproject.toml new file mode 100644 index 0000000..65949a3 --- /dev/null +++ b/compatibility/pyproject.toml @@ -0,0 +1,21 @@ +[tool.pytest.ini_options] +testpaths = ["unit"] +markers = [ + "unit: infrastructure tests without a database", + "integration: explicitly selected real-driver scenarios", +] + +[tool.black] +line-length = 100 +target-version = ["py312"] + +[tool.isort] +profile = "black" +line_length = 100 + +[tool.mypy] +python_version = "3.12" +cache_dir = "compatibility/.mypy_cache" +warn_return_any = true +warn_unused_configs = true +ignore_missing_imports = true diff --git a/compatibility/readme.py b/compatibility/readme.py new file mode 100644 index 0000000..bb6aab5 --- /dev/null +++ b/compatibility/readme.py @@ -0,0 +1,690 @@ +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: MIT + +"""Publish a repository-scoped README snapshot from validated execution evidence.""" + +from __future__ import annotations + +import argparse +import html +import json +import os +import re +import subprocess +import sys +from datetime import datetime, timedelta, timezone +from itertools import groupby +from pathlib import Path +from typing import Any +from xml.etree import ElementTree + +from compatibility.contracts import read_registry, timestamp, validate_schema +from compatibility.results import ( + RunKey, + append_result, + dashboard_rows, + read_result, + result_key, + validate_incoming_result, +) + +OFFICIAL_REPOSITORY = "documentdb/documentdb-playground" +WORKFLOW_PATH = ".github/workflows/compatibility.yml" +SOURCE_EVENTS = ("workflow_dispatch", "schedule") +DEMONSTRATION_TITLE = "Ecosystem compatibility (demonstration)" +PROFILE_FIELDS = ("integration", "documentdb_version", "upstream_version", "profile") +COLORS = { + "Working": "#176b2c", + "Failing": "#b42318", + "Not tested": "#667085", + "Stale": "#9a6700", +} + + +def repository_name(value: str) -> str: + if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*/[A-Za-z0-9][A-Za-z0-9_.-]*", value): + raise ValueError("Invalid publication repository") + return value + + +def read_object(path: Path) -> dict[str, Any]: + if path.is_symlink() or not path.is_file() or path.stat().st_size > 4 * 1024 * 1024: + raise ValueError("Publication input must be a bounded regular JSON file") + value = json.loads(path.read_text()) + if not isinstance(value, dict): + raise ValueError("Publication input must be a JSON object") + return value + + +def write_text(path: Path, value: str) -> None: + if path.parent.is_symlink() or path.is_symlink(): + raise ValueError("Publication paths must not be symbolic links") + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(value) + + +def write_object(path: Path, value: dict[str, Any]) -> None: + write_text(path, json.dumps(value, indent=2, sort_keys=True, allow_nan=False) + "\n") + + +def run_url(repository: str, identifier: int, attempt: int) -> str: + return f"https://github.com/{repository}/actions/runs/{identifier}/attempts/{attempt}" + + +def validate_attempt(value: dict[str, Any], repository: str) -> None: + repository_name(repository) + validate_schema(value, "attempt") + if value["repository"] != repository or value["run_url"] != run_url( + repository, value["run_id"], value["run_attempt"] + ): + raise ValueError("Workflow attempt does not belong to this repository") + if timestamp(value["started_at"]) > datetime.now(timezone.utc) + timedelta(minutes=5): + raise ValueError("Workflow attempt starts in the future") + + +def source_attempt( + run: dict[str, Any], workflow: dict[str, Any], repository: str, branch: str +) -> dict[str, Any]: + """Accept only completed, same-repository default-branch integration runs.""" + repository_name(repository) + if ( + run["repository"]["full_name"] != repository + or run["head_repository"]["full_name"] != repository + or run["head_branch"] != branch + or run["event"] not in SOURCE_EVENTS + or run["status"] != "completed" + or workflow["path"] != WORKFLOW_PATH + or workflow["id"] != run["workflow_id"] + ): + raise ValueError("Source is not a trusted completed compatibility workflow run") + attempt = { + "schema_version": 1, + "repository": repository, + "run_id": run["id"], + "run_attempt": run["run_attempt"], + "run_url": run_url(repository, run["id"], run["run_attempt"]), + "head_sha": run["head_sha"], + "started_at": run["run_started_at"], + "conclusion": run["conclusion"], + "profiles": [], + "errors": [], + } + validate_attempt(attempt, repository) + return attempt + + +def github_object(endpoint: str) -> dict[str, Any]: + response = subprocess.run( + ["gh", "api", endpoint], + check=True, + capture_output=True, + text=True, + timeout=60, + ) + value = json.loads(response.stdout) + if not isinstance(value, dict): + raise ValueError("GitHub returned an unexpected response") + return value + + +def prepare( + repository: str, branch: str, event_name: str, event: dict[str, Any], identifier: str +) -> dict[str, Any]: + repository_name(repository) + expected_attempt = None + if event_name == "workflow_run": + identifier = str(event["workflow_run"]["id"]) + expected_attempt = event["workflow_run"]["run_attempt"] + if not identifier: + return {"action": "refresh"} + if not re.fullmatch(r"[1-9][0-9]*", identifier): + raise ValueError("A source run ID must be a positive integer") + endpoint = f"repos/{repository}/actions/runs/{identifier}" + if expected_attempt is not None: + if type(expected_attempt) is not int or expected_attempt < 1: + raise ValueError("A source attempt must be a positive integer") + endpoint += f"/attempts/{expected_attempt}" + run = github_object(endpoint) + if run["id"] != int(identifier) or ( + expected_attempt is not None and run["run_attempt"] != expected_attempt + ): + raise ValueError("GitHub returned a different workflow attempt") + if type(run["workflow_id"]) is not int or run["workflow_id"] < 1: + raise ValueError("Invalid source workflow identity") + workflow = github_object(f"repos/{repository}/actions/workflows/{run['workflow_id']}") + attempt = source_attempt(run, workflow, repository, branch) + if run["display_title"] == DEMONSTRATION_TITLE: + return {"action": "ignore", "reason": "Demonstrations do not update README status"} + return {"action": "publish", "attempt": attempt} + + +def profile_key(profile: dict[str, Any]) -> RunKey: + return ( + profile["integration"], + profile["documentdb_version"], + profile["upstream_version"], + profile["profile"], + False, + ) + + +def profile_from_result(result: dict[str, Any]) -> dict[str, Any]: + integration, database, upstream, profile, _ = result_key(result) + return { + "integration": integration, + "documentdb_version": database, + "upstream_version": upstream, + "profile": profile, + } + + +def selected_profiles( + summary: dict[str, Any], registry: dict[str, Any] +) -> tuple[list[dict[str, Any]], bool]: + if ( + summary.get("schema_version") != 1 + or type(summary.get("success")) is not bool + or not isinstance(summary.get("integrations"), list) + or not 0 < len(summary["integrations"]) <= 100 + ): + raise ValueError("Invalid combined report envelope") + profiles = [] + modes = set() + for row in summary["integrations"]: + if not isinstance(row, dict) or type(row.get("demonstration")) is not bool: + raise ValueError("Invalid combined report profile") + profile = {name: row[name] for name in PROFILE_FIELDS} + spec = registry["integrations"][profile["integration"]] + if ( + profile["profile"] != spec["profile"] + or profile["documentdb_version"] not in registry["documentdb"] + or not re.fullmatch(spec["version_pattern"], profile["upstream_version"]) + or profile in profiles + ): + raise ValueError("Combined report does not match the reviewed selection") + profiles.append(profile) + modes.add(row["demonstration"]) + if len(modes) != 1: + raise ValueError("Combined report mixes demonstrations with compatibility evidence") + return profiles, True in modes + + +def save_attempt(data: Path, attempt: dict[str, Any], repository: str) -> None: + """Keep run identity fixed while allowing missing publication evidence to be recovered.""" + validate_attempt(attempt, repository) + path = data / "attempts" / f"{attempt['run_id']}-{attempt['run_attempt']}.json" + if path.exists() or path.is_symlink(): + previous = read_object(path) + validate_attempt(previous, repository) + for key in attempt.keys() - {"profiles", "errors"}: + if previous[key] != attempt[key]: + raise ValueError("Refusing to change an existing workflow attempt's identity") + profiles = {profile_key(profile): profile for profile in previous["profiles"]} + profiles.update({profile_key(profile): profile for profile in attempt["profiles"]}) + attempt = {**attempt, "profiles": [profiles[key] for key in sorted(profiles)]} + write_object(path, attempt) + + +def ingest( + plan: dict[str, Any], + source_root: Path, + incoming: Path, + data: Path, + repository: str, +) -> None: + if plan["action"] == "refresh": + return + if plan["action"] != "publish": + raise ValueError("Unexpected publication action") + attempt = dict(plan["attempt"]) + validate_attempt(attempt, repository) + registry = read_registry(source_root / "compatibility" / "registry.yaml", root=source_root) + if data.is_symlink() or incoming.is_symlink(): + raise ValueError("Publication directories must not be symbolic links") + errors = [] + profiles: list[dict[str, Any]] = [] + try: + profiles, demonstration = selected_profiles( + read_object(incoming / "summary.json"), registry + ) + if demonstration: + print("Demonstration report ignored; normal compatibility evidence is unchanged.") + return + except (OSError, ValueError, KeyError, TypeError) as error: + errors.append(f"Combined report unavailable or rejected: {error}") + results: list[dict[str, Any]] = [] + directory = incoming / "results" + if directory.is_symlink(): + errors.append("Rejected symbolic-link result directory") + elif directory.is_dir(): + paths = sorted(directory.iterdir()) + if len(paths) > 100: + raise ValueError("Too many incoming result files") + for path in paths: + try: + if not re.fullmatch(r"[a-f0-9]{32}\.json", path.name): + raise ValueError("Unexpected result file name") + result = read_result(path) + if path.stem != result["id"] or result["demonstration"]: + raise ValueError("Result identity or mode does not match publication") + validate_incoming_result(result, registry, attempt["run_url"], root=source_root) + profile = profile_from_result(result) + if profiles and profile not in profiles: + raise ValueError("Result is outside the selected profile set") + if any(result_key(prior) == result_key(result) for prior in results): + raise ValueError("More than one result for a selected profile") + results.append(result) + except (OSError, ValueError, KeyError, TypeError) as error: + errors.append(f"Result evidence rejected: {error}") + else: + errors.append("No result evidence was retained by this workflow attempt") + for result in results: + append_result(data / "results", result) + if not profiles: + profiles = [profile_from_result(result) for result in results] + available = {result_key(result) for result in results} + for profile in profiles: + if profile_key(profile) not in available: + errors.append(f"Missing validated result for {profile['integration']}") + attempt["profiles"] = profiles + attempt["errors"] = [message[:1000] for message in errors] + save_attempt(data, attempt, repository) + for message in errors: + print(message, file=sys.stderr) + + +def snapshot( + data: Path, registry: dict[str, Any], repository: str, now: datetime +) -> dict[str, Any]: + repository_name(repository) + if any((data / name).is_symlink() for name in ("results", "attempts", "site")): + raise ValueError("Publication directories must not be symbolic links") + results = [read_result(path) for path in sorted((data / "results").glob("*.json"))] + normal = [result for result in results if not result["demonstration"]] + prefix = f"https://github.com/{repository}/actions/runs/" + if any(not result["run_url"] or not result["run_url"].startswith(prefix) for result in normal): + raise ValueError("README evidence must originate in this repository's Actions runs") + attempts = [] + expected: dict[RunKey, str | None] = { + (name, version, spec["default_version"], spec["profile"], False): None + for name, spec in registry["integrations"].items() + if spec["enabled"] + for version in registry["documentdb"] + } + for path in sorted((data / "attempts").glob("*.json")): + attempt = read_object(path) + validate_attempt(attempt, repository) + if path.stem != f"{attempt['run_id']}-{attempt['run_attempt']}": + raise ValueError("Attempt file does not match its run identity") + attempts.append(attempt) + for profile in attempt["profiles"]: + expected.setdefault(profile_key(profile), None) + attempts.sort( + key=lambda attempt: ( + timestamp(attempt["started_at"]), + attempt["run_id"], + attempt["run_attempt"], + ) + ) + # Rank evidence by its workflow attempt; test start times from overlapping runs can invert. + position = {attempt["run_url"]: index for index, attempt in enumerate(attempts)} + rows = dashboard_rows( + normal, + registry, + now, + expected_runs=expected, + order=lambda result: ( + position.get(result["run_url"], -1), + timestamp(result["started_at"]), + result["id"], + ), + ) + for row in rows: + key = ( + row["integration"], + row["documentdb_version"], + row["upstream_version"], + row["profile"], + False, + ) + selected = [ + index + for index, attempt in enumerate(attempts) + if key in {profile_key(profile) for profile in attempt["profiles"]} + ] + recorded = [position.get(result["run_url"], -1) for result in row.pop("history")] + if selected and selected[-1] > max(recorded, default=-1): + attempt = attempts[selected[-1]] + row.update( + last_attempt=attempt["started_at"], + latest_attempt_state="Not tested", + run_url=attempt["run_url"], + error="No validated profile result in this workflow attempt", + ) + return { + "schema_version": 1, + "repository": repository, + "preview": repository != OFFICIAL_REPOSITORY, + "latest_workflow": attempts[-1] if attempts else None, + "integrations": rows, + } + + +def utc(value: str | None) -> str: + return timestamp(value).strftime("%Y-%m-%d %H:%M:%S UTC") if value else "Never" + + +def markdown_cell(value: str) -> str: + """Keep evidence and diagnostics as text rather than executable Markdown or HTML.""" + escaped = html.escape(value).replace("\r", " ").replace("\n", " ") + return re.sub(r"([\\`*_{}\[\]()|])", r"\\\1", escaped) + + +def markdown(view: dict[str, Any]) -> str: + lines = ["# Compatibility status", ""] + lines += [ + "The latest attempt is separate from the last conclusive compatibility evidence.", + "", + ] + latest = view["latest_workflow"] + if latest: + lines += [ + f"Latest workflow attempt: [{latest['run_id']}, attempt {latest['run_attempt']}]" + f"({latest['run_url']}), started **{utc(latest['started_at'])}**, " + f"workflow conclusion **{latest['conclusion']}**.", + "", + ] + if latest["errors"]: + lines += ["**Publication/evidence needs attention:**", ""] + lines += [f"- {markdown_cell(error)}" for error in latest["errors"]] + lines.append("") + else: + lines += ["**No completed compatibility workflow has been published.**", ""] + for integration, rows in groupby(view["integrations"], key=lambda row: row["integration"]): + lines += [ + f"## {markdown_cell(integration)}", + "", + "| Client / DocumentDB | Profile | Evidence | Verified cases | Last conclusive | " + "Latest attempt | Attempted at | Details |", + "| --- | --- | --- | --- | --- | --- | --- | --- |", + ] + for row in rows: + fields = [ + f"{row['upstream_version']} / {row['documentdb_version']}", + row["profile"], + row["state"], + f"{row['passed']}/{row['expected']}", + utc(row["conclusive_at"]), + row["latest_attempt_state"], + utc(row["last_attempt"]), + ] + details = f"[Run]({row['run_url']})" if row["run_url"] else "No run" + lines.append( + "| " + " | ".join(markdown_cell(field) for field in fields) + f" | {details} |" + ) + lines.append("") + lines += [ + "Timestamps describe executions, not dashboard refreshes. Intentional-failure " + "demonstrations are excluded. Freshness follows the registry and execution-input digests.", + "", + "The JSON snapshot is available in [status.json](status.json). " + "Detailed reports and diagnostics are retained as artifacts of the linked runs.", + "", + ] + return "\n".join(lines) + + +def svg(view: dict[str, Any]) -> str: + rows = view["integrations"] + height = 213 + 96 * max(1, len(rows)) + root = ElementTree.Element( + "svg", + { + "xmlns": "http://www.w3.org/2000/svg", + "width": "1240", + "height": str(height), + "viewBox": f"0 0 1240 {height}", + "role": "img", + "aria-labelledby": "title description", + }, + ) + ElementTree.SubElement(root, "title", {"id": "title"}).text = "DocumentDB compatibility" + ElementTree.SubElement(root, "desc", {"id": "description"}).text = ( + "Compatibility evidence, actual execution timestamps, and latest attempt outcomes. " + "Open the accompanying status details for accessible tables and run links." + ) + ElementTree.SubElement( + root, "rect", {"width": "1240", "height": str(height), "rx": "12", "fill": "#ffffff"} + ) + + def text(x: int, y: int, value: str, size: int = 14, color: str = "#182230") -> None: + ElementTree.SubElement( + root, + "text", + { + "x": str(x), + "y": str(y), + "font-family": "Arial, Helvetica, sans-serif", + "font-size": str(size), + "fill": color, + }, + ).text = value + + text(24, 38, "DocumentDB compatibility", 25) + text(24, 65, view["repository"], 14, "#475467") + latest = view["latest_workflow"] + if latest: + text( + 24, + 91, + f"Latest workflow started {utc(latest['started_at'])} | " + f"Run {latest['run_id']}, attempt {latest['run_attempt']} | " + f"Conclusion: {latest['conclusion']}", + ) + if latest["errors"]: + text( + 24, + 117, + "Latest workflow has missing or rejected evidence; see status details.", + color="#b42318", + ) + else: + text(24, 117, "Only verified profile results determine compatibility.", color="#475467") + else: + text(24, 91, "No completed compatibility workflow has been published.", color="#667085") + text(24, 117, "No data is Not tested, never a compatibility pass.", color="#667085") + for x, label in ( + (24, "Integration / profile"), + (255, "Client"), + (350, "DocumentDB"), + (470, "Evidence"), + (635, "Latest attempt"), + (795, "Attempted at (UTC)"), + (1080, "Verified cases"), + ): + text(x, 156, label, 13, "#475467") + for index, row in enumerate(rows): + top = 171 + index * 96 + ElementTree.SubElement( + root, + "rect", + { + "x": "16", + "y": str(top), + "width": "1208", + "height": "88", + "rx": "6", + "fill": "#f2f4f7" if index % 2 == 0 else "#ffffff", + }, + ) + text(24, top + 25, row["integration"], 18) + text(24, top + 49, row["profile"], 11, "#475467") + text(255, top + 25, row["upstream_version"]) + text(350, top + 25, row["documentdb_version"]) + text(470, top + 25, row["state"], 17, COLORS[row["state"]]) + text(470, top + 49, "Conclusive:", 10, "#475467") + text(470, top + 66, utc(row["conclusive_at"]), 10, "#475467") + text(635, top + 25, row["latest_attempt_state"], 17, COLORS[row["latest_attempt_state"]]) + text(795, top + 25, utc(row["last_attempt"]), 13) + text(1080, top + 25, f"{row['passed']} / {row['expected']}", 17) + text( + 24, + height - 10, + "Execution timestamps do not change when the dashboard is refreshed. " + "Open status details for history and diagnostics.", + 11, + "#475467", + ) + return ElementTree.tostring(root, encoding="unicode") + "\n" + + +def badge_svg(view: dict[str, Any], integration: str) -> str: + rows = [row for row in view["integrations"] if row["integration"] == integration] + states = {row["state"] for row in rows} + latest = view["latest_workflow"] + unknown_selection = latest and latest["errors"] and not latest["profiles"] + if ( + not rows + or unknown_selection + or any(row["latest_attempt_state"] == "Not tested" for row in rows) + ): + states.add("Not tested") + state = next( + value for value in ("Failing", "Not tested", "Stale", "Working") if value in states + ) + left_width = 20 + 7 * len(integration) + right_width = 20 + 7 * len(state) + width = left_width + right_width + root = ElementTree.Element( + "svg", + { + "xmlns": "http://www.w3.org/2000/svg", + "width": str(width), + "height": "24", + "viewBox": f"0 0 {width} 24", + "role": "img", + "aria-labelledby": "title description", + }, + ) + ElementTree.SubElement(root, "title", {"id": "title"}).text = f"{integration}: {state}" + details = [ + f"Client {row['upstream_version']}, DocumentDB {row['documentdb_version']}, " + f"profile {row['profile']}: {row['state']}. " + f"Latest attempt: {row['latest_attempt_state']} at {utc(row['last_attempt'])}." + for row in rows + ] + if unknown_selection: + details.append("The latest workflow has no validated profile selection or evidence.") + ElementTree.SubElement(root, "desc", {"id": "description"}).text = " ".join( + [*details, "Open the integration details for execution timestamps and run links."] + ) + clip = ElementTree.SubElement( + ElementTree.SubElement(root, "defs"), "clipPath", {"id": "rounded"} + ) + ElementTree.SubElement(clip, "rect", {"width": str(width), "height": "24", "rx": "4"}) + background = ElementTree.SubElement(root, "g", {"clip-path": "url(#rounded)"}) + ElementTree.SubElement( + background, "rect", {"width": str(width), "height": "24", "fill": "#475467"} + ) + ElementTree.SubElement( + background, + "rect", + {"x": str(left_width), "width": str(right_width), "height": "24", "fill": COLORS[state]}, + ) + for x, value in ( + (left_width / 2, integration), + (left_width + right_width / 2, state), + ): + ElementTree.SubElement( + root, + "text", + { + "x": str(x), + "y": "16", + "fill": "#ffffff", + "font-family": "Verdana, DejaVu Sans, sans-serif", + "font-size": "12", + "text-anchor": "middle", + "textLength": str(7 * len(value)), + "lengthAdjust": "spacingAndGlyphs", + }, + ).text = value + return ElementTree.tostring(root, encoding="unicode") + "\n" + + +def render(data: Path, site: Path, repository: str, *, now: datetime | None = None) -> None: + view = snapshot(data, read_registry(), repository, now or datetime.now(timezone.utc)) + write_text(site / "status.svg", svg(view)) + for integration in sorted({row["integration"] for row in view["integrations"]}): + write_text(site / "badges" / f"{integration}.svg", badge_svg(view, integration)) + write_text(site / "README.md", markdown(view)) + write_object(site / "status.json", view) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + preparing = commands.add_parser("prepare") + preparing.add_argument("--branch", required=True) + preparing.add_argument( + "--event-name", + required=True, + choices=["workflow_run", "workflow_dispatch", "push", "schedule"], + ) + preparing.add_argument("--event-file", type=Path, required=True) + preparing.add_argument("--run-id", default="") + preparing.add_argument("--output", type=Path, required=True) + ingesting = commands.add_parser("ingest") + ingesting.add_argument("--source", type=Path, required=True) + ingesting.add_argument("--source-root", type=Path, required=True) + ingesting.add_argument("--incoming", type=Path, required=True) + rendering = commands.add_parser("render") + rendering.add_argument("--site", type=Path, required=True) + for command in (preparing, ingesting, rendering): + command.add_argument("--repository", required=True) + for command in (ingesting, rendering): + command.add_argument("--data", type=Path, required=True) + args = parser.parse_args() + try: + if args.command == "prepare": + plan = prepare( + args.repository, + args.branch, + args.event_name, + read_object(args.event_file), + args.run_id, + ) + write_object(args.output, plan) + outputs = {"action": plan["action"]} + if plan["action"] == "publish": + attempt = plan["attempt"] + outputs.update( + run_id=str(attempt["run_id"]), + artifact=f"compatibility-report-{attempt['run_attempt']}", + source_sha=attempt["head_sha"], + ) + if os.environ.get("GITHUB_OUTPUT"): + with Path(os.environ["GITHUB_OUTPUT"]).open("a") as destination: + for key, value in outputs.items(): + destination.write(f"{key}={value}\n") + print(plan.get("reason", f"README publication action: {plan['action']}")) + elif args.command == "ingest": + ingest( + read_object(args.source), + args.source_root, + args.incoming, + args.data, + args.repository, + ) + else: + render(args.data, args.site, args.repository) + except (OSError, ValueError, KeyError, TypeError, subprocess.SubprocessError) as error: + print(f"README publication failed: {error}", file=sys.stderr) + if isinstance(error, subprocess.CalledProcessError) and error.stderr: + print(error.stderr, file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/compatibility/registry.yaml b/compatibility/registry.yaml new file mode 100644 index 0000000..6c878b4 --- /dev/null +++ b/compatibility/registry.yaml @@ -0,0 +1,38 @@ +schema_version: 1 +documentdb: + "0.117.0": + image: ghcr.io/documentdb/documentdb/documentdb-local@sha256:d972e7145da660ad4892ce6f5c22039086ff5148dce7225f20b76af959cd2ce0 + postgres_major: 17 + extension_version: "0.117-0" +integrations: + pymongo: + repository: https://github.com/mongodb/mongo-python-driver + owner: "@documentdb/documentdb-maintainers" + enabled: true + runtime: python + package: pymongo + default_version: "4.18.0" + version_pattern: '^4\.(9|[1-9][0-9]+)\.[0-9]+$' + profile: python312-linux-x64-sync + test_file: compatibility/integrations/pymongo/test_pymongo.py + demonstration_file: compatibility/integrations/pymongo/test_demonstration.py + timeout_seconds: 300 + freshness_days: 7 + expected_tests: + - test_authenticated_ping + - test_insert_one + - test_insert_many + - test_find_one + - test_find_filter_projection_sort_limit + - test_cursor_batches + - test_count_documents + - test_update_one + - test_find_one_and_update + - test_delete_one + - test_delete_many + - test_aggregate + - test_create_indexes + - test_list_indexes + - test_drop_index + - test_duplicate_key_error + - test_bson_round_trip diff --git a/compatibility/requirements-dev.txt b/compatibility/requirements-dev.txt new file mode 100644 index 0000000..8d13dbf --- /dev/null +++ b/compatibility/requirements-dev.txt @@ -0,0 +1,8 @@ +-r requirements.txt +-r integrations/pymongo/requirements.txt +pymongo==4.18.0 +black>=24 +isort>=5.12 +flake8>=6 +mypy>=1.5 +types-PyYAML>=6 diff --git a/compatibility/requirements.txt b/compatibility/requirements.txt new file mode 100644 index 0000000..c80ef4b --- /dev/null +++ b/compatibility/requirements.txt @@ -0,0 +1,3 @@ +PyYAML>=6.0,<7 +jsonschema>=4.18,<5 +packaging>=24.2,<27 diff --git a/compatibility/results.py b/compatibility/results.py new file mode 100644 index 0000000..47cd258 --- /dev/null +++ b/compatibility/results.py @@ -0,0 +1,192 @@ +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: MIT + +"""Immutable result storage and shared compatibility status projections.""" + +from __future__ import annotations + +import json +import os +import re +import tempfile +from collections import defaultdict +from collections.abc import Callable +from datetime import datetime, timedelta +from pathlib import Path +from typing import Any + +from compatibility.contracts import ( + ROOT, + artifact_sha256, + compatibility_state, + expected_tests, + suite_digest, + timestamp, + validate_result, +) + +RunKey = tuple[str, str, str, str, bool] + + +def result_key(result: dict[str, Any]) -> RunKey: + """Identify a version pair and profile without combining demonstration evidence.""" + return ( + result["integration"], + result["documentdb"]["version"], + result["upstream"]["version"], + result["profile"], + result["demonstration"], + ) + + +def read_result(path: Path) -> dict[str, Any]: + """Read bounded regular JSON files, never symlinks from an artifact or data branch.""" + if path.is_symlink() or not path.is_file() or path.stat().st_size > 1024 * 1024: + raise ValueError("Result must be a regular JSON file smaller than one MiB") + value = json.loads(path.read_text()) + validate_result(value) + return dict(value) + + +def validate_incoming_result( + result: dict[str, Any], + registry: dict[str, Any], + expected_run_url: str | None = None, + *, + root: Path = ROOT, +) -> None: + """Validate a result against the reviewed execution inputs of its source revision.""" + if expected_run_url is not None and result["run_url"] != expected_run_url: + raise ValueError("Result does not belong to the publishing workflow run") + spec = registry["integrations"][result["integration"]] + validate_result(result, spec) + if not re.fullmatch(spec["version_pattern"], result["upstream"]["version"]): + raise ValueError("Incoming result is outside the reviewed version policy") + database = registry["documentdb"][result["documentdb"]["version"]] + if result["documentdb"]["image"] != database["image"]: + raise ValueError("Incoming result does not reference the reviewed database artifact") + actual = result["documentdb"]["actual_extension_version"] + if actual is not None and actual != database["extension_version"]: + raise ValueError("Incoming result has an unexpected installed extension version") + if result["suite_digest"] != suite_digest(result["integration"], spec, root): + raise ValueError("Incoming result was generated by a different suite revision") + + +def append_result(store: Path, result: dict[str, Any]) -> Path: + """Publish a complete file atomically without ever replacing an existing run.""" + validate_result(result) + if store.is_symlink(): + raise ValueError("The result store must not be a symbolic link") + store.mkdir(parents=True, exist_ok=True) + destination = store / f"{result['id']}.json" + contents = json.dumps(result, indent=2, allow_nan=False) + "\n" + with tempfile.NamedTemporaryFile(mode="w", dir=store, suffix=".tmp", delete=False) as temporary: + temporary.write(contents) + temporary.flush() + os.fsync(temporary.fileno()) + try: + try: + os.link(temporary.name, destination) + except FileExistsError: + if read_result(destination) != result: + raise ValueError("Refusing to overwrite a different result with the same run ID") + finally: + Path(temporary.name).unlink() + return destination + + +def dashboard_rows( + results: list[dict[str, Any]], + registry: dict[str, Any], + now: datetime, + *, + expected_runs: dict[RunKey, str | None] | None = None, + order: Callable[[dict[str, Any]], Any] | None = None, +) -> list[dict[str, Any]]: + """Keep version pairs and demonstrations separate; retain the last conclusive result. + + `order` ranks results from oldest to newest and defaults to their test start time. + """ + groups: dict[RunKey, list[dict[str, Any]]] = defaultdict(list) + for result in results: + validate_result(result) + groups[result_key(result)].append(result) + if expected_runs is None: + expected_runs = { + (integration, version, spec["default_version"], spec["profile"], False): None + for integration, spec in registry["integrations"].items() + if spec["enabled"] + for version in registry["documentdb"] + } + for key in expected_runs: + groups.setdefault(key, []) + rows = [] + for key, history in sorted(groups.items()): + integration, database_version, upstream_version, profile, demonstration = key + spec = registry["integrations"].get(integration) + if spec is None: + raise ValueError("History references an integration absent from the registry") + history.sort( + key=order or (lambda record: (timestamp(record["started_at"]), record["id"])), + reverse=True, + ) + latest = history[0] if history else None + conclusive = [r for r in history if compatibility_state(r) in ("Working", "Failing")] + current = conclusive[0] if conclusive else None + successful = [r for r in history if compatibility_state(r) == "Working"] + state = compatibility_state(current) if current else "Not tested" + previous_state = state + active_database = registry["documentdb"].get(database_version) + if current and ( + now - timestamp(current["finished_at"]) > timedelta(days=spec["freshness_days"]) + or current["suite_digest"] != suite_digest(integration, spec) + or (active_database and current["documentdb"]["image"] != active_database["image"]) + or ( + latest is not None + and artifact_sha256(latest) + and artifact_sha256(latest) != artifact_sha256(current) + ) + ): + state = "Stale" + coverage_source = current or latest + tests = coverage_source["tests"] if coverage_source else [] + error = expected_runs.get(key) + if latest: + error = latest["execution_error"] or next( + (test["message"] for test in latest["tests"] if test["outcome"] != "passed"), None + ) + rows.append( + { + "integration": integration, + "repository": spec["repository"], + "owner": spec["owner"], + "documentdb_version": database_version, + "upstream_version": upstream_version, + "profile": profile, + "demonstration": demonstration, + "state": state, + "previous_state": previous_state, + "freshness_days": spec["freshness_days"], + "conclusive_at": current["finished_at"] if current else None, + "last_success": successful[0]["finished_at"] if successful else None, + "last_attempt": latest["finished_at"] if latest else None, + "latest_attempt_state": compatibility_state(latest) if latest else "Not tested", + "trigger": latest["trigger"] if latest else None, + "detection_id": latest.get("detection_id") if latest else None, + "run_url": latest["run_url"] if latest else None, + "error": error, + "passed": sum(test["outcome"] == "passed" for test in tests), + "expected": len( + coverage_source["expected_tests"] + if coverage_source + else expected_tests(spec, demonstration) + ), + "scenarios": ( + coverage_source["expected_tests"] + if coverage_source + else expected_tests(spec, demonstration) + ), + "history": history, + } + ) + return rows diff --git a/compatibility/runner.py b/compatibility/runner.py new file mode 100644 index 0000000..db76969 --- /dev/null +++ b/compatibility/runner.py @@ -0,0 +1,491 @@ +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: MIT + +"""Run a reviewed integration against a released image in disposable Docker resources.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import secrets +import shutil +import signal +import subprocess +import sys +import tempfile +import time +import urllib.parse +import urllib.request +import uuid +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +from packaging.utils import parse_wheel_filename +from packaging.version import Version + +from compatibility.contracts import ( + ROOT, + compatibility_state, + default_documentdb_version, + expected_tests, + read_registry, + suite_digest, + suite_files, + validate_client_report, + validate_result, +) + +LABEL = "org.documentdb.compatibility.run" +MAX_COMMAND_OUTPUT = 4 * 1024 * 1024 + + +def command(arguments: list[str], timeout: int = 180, check: bool = True): + """Bound both command duration and captured output; never execute a shell string.""" + with tempfile.TemporaryFile() as stdout, tempfile.TemporaryFile() as stderr: + with subprocess.Popen( + arguments, stdout=stdout, stderr=stderr, start_new_session=True + ) as process: + deadline = time.monotonic() + timeout + while process.poll() is None: + if ( + time.monotonic() > deadline + or os.fstat(stdout.fileno()).st_size > MAX_COMMAND_OUTPUT + or os.fstat(stderr.fileno()).st_size > MAX_COMMAND_OUTPUT + ): + os.killpg(process.pid, signal.SIGKILL) + process.wait() + raise RuntimeError(f"{arguments[0]} exceeded its time or output limit") + time.sleep(0.1) + stdout.seek(0) + stderr.seek(0) + if ( + max(os.fstat(stdout.fileno()).st_size, os.fstat(stderr.fileno()).st_size) + > MAX_COMMAND_OUTPUT + ): + raise RuntimeError(f"{arguments[0]} exceeded its output limit") + result = subprocess.CompletedProcess( + arguments, + process.returncode, + stdout.read(MAX_COMMAND_OUTPUT).decode("utf-8", errors="replace"), + stderr.read(MAX_COMMAND_OUTPUT).decode("utf-8", errors="replace"), + ) + if check and result.returncode != 0: + raise RuntimeError( + f"{arguments[0]} exited {result.returncode}: " + f"{(result.stderr or result.stdout)[-4000:]}" + ) + return result + + +def redact(text: str, password: str) -> str: + """Strip fixture credentials before producing any retained output.""" + text = text.replace(password, "[REDACTED]") + text = text.replace(urllib.parse.quote(password, safe=""), "[REDACTED]") + return re.sub(r"(?i)([a-z][a-z0-9+.-]*://)[^/\s@]+@", r"\1[REDACTED]@", text) + + +def record_error(output: Path, message: str, password: str) -> str: + """Retain controller diagnostics and keep the terminal cause in bounded summaries.""" + sanitized = redact(message, password) + with output.with_suffix(".log").open("a") as log: + log.write(f"\nController error:\n{sanitized}\n") + if len(sanitized) <= 2000: + return sanitized + return sanitized[:200] + "\n...\n" + sanitized[-1795:] + + +def prepare_client( + context: Path, spec: dict[str, Any], version: str, wheelhouse: Path | None +) -> str: + """Download binary wheels only and verify the selected artifact against publisher metadata.""" + wheels = context / "wheels" + wheels.mkdir() + requirements = ROOT / Path(spec["test_file"]).parent / "requirements.txt" + if wheelhouse is not None: + for source in wheelhouse.glob("*.whl"): + if source.is_symlink(): + raise ValueError("Wheel inputs must not be symbolic links") + shutil.copyfile(source, wheels / source.name) + else: + command( + [ + sys.executable, + "-m", + "pip", + "download", + "--disable-pip-version-check", + "--only-binary=:all:", + "--python-version", + "312", + "--implementation", + "cp", + "--abi", + "cp312", + "--platform", + "manylinux_2_28_x86_64", + "--platform", + "manylinux_2_17_x86_64", + "--platform", + "manylinux2014_x86_64", + "--platform", + "manylinux1_x86_64", + "--dest", + str(wheels), + "-r", + str(requirements), + f"{spec['package']}=={version}", + ], + timeout=600, + ) + requested_version = Version(version) + candidates = [ + wheel + for wheel in wheels.glob(f"{spec['package'].replace('-', '_')}-*.whl") + if parse_wheel_filename(wheel.name)[1] == requested_version + ] + if len(candidates) != 1: + raise ValueError("Expected exactly one wheel for the requested integration version") + selected = candidates[0] + digest = hashlib.sha256(selected.read_bytes()).hexdigest() + metadata_url = f"https://pypi.org/pypi/{spec['package']}/{version}/json" + with urllib.request.urlopen(metadata_url, timeout=30) as response: + metadata = json.load(response) + matching = [ + asset + for asset in metadata["urls"] + if asset["filename"] == selected.name + and not asset["yanked"] + and asset["digests"]["sha256"] == digest + ] + if len(matching) != 1: + raise ValueError("Selected wheel does not match an eligible published artifact") + (context / "integration-requirements.txt").write_text( + f"-r /requirements.txt\n{spec['package']}=={version}\n" + ) + for source in suite_files(Path(spec["test_file"]).parent.name): + destination = context / source.relative_to(ROOT) + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, destination) + return digest + + +def cleanup(run_id: str, image: str) -> list[str]: + """Resolve only this invocation's labeled resources; cleanup errors remain visible.""" + errors = [] + for kind, listing, removal in ( + ("containers", ["docker", "ps", "-aq"], ["docker", "rm", "-fv"]), + ("networks", ["docker", "network", "ls", "-q"], ["docker", "network", "rm"]), + ): + try: + identifiers = command(listing + ["--filter", f"label={LABEL}={run_id}"]).stdout.split() + if any(not re.fullmatch("[a-f0-9]{12,64}", identifier) for identifier in identifiers): + raise RuntimeError("Unexpected Docker resource identifier") + if identifiers: + command(removal + identifiers) + except (OSError, RuntimeError) as error: + errors.append(f"Cleanup {kind}: {error}") + if image: + try: + command(["docker", "image", "rm", image]) + except (OSError, RuntimeError) as error: + errors.append(f"Cleanup image: {error}") + return errors + + +def execute( + registry: dict[str, Any], + integration: str, + version: str, + documentdb_version: str, + output: Path, + *, + wheelhouse: Path | None = None, + demonstration: bool = False, + run_url: str | None = None, + trigger: str = "manual", +) -> dict[str, Any]: + """Emit a validated result even when setup, execution, or teardown fails.""" + spec = registry["integrations"][integration] + database = registry["documentdb"][documentdb_version] + if ( + not spec["enabled"] + or len(version) > 40 + or not re.fullmatch(spec["version_pattern"], version) + ): + raise ValueError("Integration is disabled or the requested version is outside its policy") + if spec["runtime"] != "python": + raise ValueError("Only the Python runtime is implemented") + if output.suffix != ".json": + raise ValueError("Result output must use a .json extension") + if any( + path.exists() or path.is_symlink() + for path in (output, output.with_suffix(".log"), output.with_suffix(".xml")) + ): + raise ValueError("Refusing to overwrite an existing result or diagnostic file") + run_id = uuid.uuid4().hex + started = datetime.now(timezone.utc).isoformat() + result: dict[str, Any] = { + "schema_version": 2, + "id": run_id, + "integration": integration, + "repository": spec["repository"], + "owner": spec["owner"], + "profile": spec["profile"], + "suite_digest": suite_digest(integration, spec), + "documentdb": { + "version": documentdb_version, + "image": database["image"], + "actual_extension_version": None, + "actual_postgres_version": None, + }, + "upstream": { + "version": version, + "actual_version": None, + "artifact_sha256": None, + "client_image": None, + "runtime": {"name": spec["runtime"], "version": None}, + "dependencies": [], + }, + "expected_tests": expected_tests(spec, demonstration), + "tests": [], + "started_at": started, + "finished_at": started, + "trigger": trigger, + "run_url": run_url, + "demonstration": demonstration, + "execution_error": None, + } + validate_result(result, spec) + password = secrets.token_urlsafe(24) + "Aa1!" + image = "" + output.parent.mkdir(parents=True, exist_ok=True) + try: + with tempfile.TemporaryDirectory(prefix="docdb-compat-") as directory: + context = Path(directory) / "context" + context.mkdir() + digest = prepare_client(context, spec, version, wheelhouse) + result["upstream"]["artifact_sha256"] = digest + result["suite_digest"] = suite_digest(integration, spec, root=context) + candidate_image = f"docdb-compat-{run_id}" + command( + [ + "docker", + "build", + "--network", + "none", + "--platform", + "linux/amd64", + "-t", + candidate_image, + "-f", + str(context / "compatibility" / "integrations" / integration / "Dockerfile"), + str(context), + ], + timeout=600, + ) + image = candidate_image + result["upstream"]["client_image"] = command( + ["docker", "image", "inspect", image, "--format", "{{.Id}}"] + ).stdout.strip() + network = command( + ["docker", "network", "create", "--internal", "--label", f"{LABEL}={run_id}", image] + ).stdout.strip() + environment = Path(directory) / "fixture.env" + with environment.open("x") as file: + os.chmod(environment, 0o600) + file.write(f"USERNAME=compat_user\nPASSWORD={password}\n") + server = command( + [ + "docker", + "run", + "-d", + "--platform", + "linux/amd64", + "--label", + f"{LABEL}={run_id}", + "--network", + network, + "--network-alias", + "db", + "--env-file", + str(environment), + "--env", + "TLS_MODE=requireTLS", + "--env", + "ENABLE_TELEMETRY=false", + "--memory=2g", + "--cpus=2", + "--shm-size=256m", + database["image"], + ] + ).stdout.strip() + deadline = time.monotonic() + 180 + while True: + running = command( + ["docker", "inspect", server, "--format", "{{.State.Running}}"] + ).stdout.strip() + logs = command(["docker", "logs", server]) + if running != "true": + raise RuntimeError("Database exited before readiness: " + logs.stdout[-2000:]) + if "=== DocumentDB is ready ===" in logs.stdout + logs.stderr: + break + if time.monotonic() > deadline: + raise RuntimeError("Database readiness timed out") + time.sleep(2) + query = ( + "SELECT json_build_object('postgres', current_setting('server_version')," + "'extension', (SELECT extversion FROM pg_extension WHERE extname='documentdb'));" + ) + actual = json.loads( + command( + [ + "docker", + "exec", + server, + "psql", + "-X", + "-p", + "9712", + "-d", + "postgres", + "-Atc", + query, + ] + ).stdout + ) + if ( + actual["extension"] != database["extension_version"] + or int(actual["postgres"].split(".")[0]) != database["postgres_major"] + ): + raise ValueError( + "Actual database versions do not match the selected release profile" + ) + result["documentdb"]["actual_extension_version"] = actual["extension"] + result["documentdb"]["actual_postgres_version"] = actual["postgres"] + process = command( + [ + "docker", + "run", + "--label", + f"{LABEL}={run_id}", + "--network", + network, + "--env-file", + str(environment), + "--read-only", + "--tmpfs", + "/tmp:size=128m", + "--cap-drop=ALL", + "--security-opt=no-new-privileges", + "--memory=512m", + "--cpus=1", + "--env", + f"COMPATIBILITY_PACKAGE={spec['package']}", + "--env", + f"COMPATIBILITY_TEST_FILE={spec['test_file']}", + "--env", + f"COMPATIBILITY_DEMONSTRATION_FILE={spec['demonstration_file']}", + "--env", + f"COMPATIBILITY_DEMONSTRATION={int(demonstration)}", + image, + ], + timeout=spec["timeout_seconds"], + check=False, + ) + output.with_suffix(".log").write_text(redact(process.stderr, password)) + payload = json.loads(process.stdout) + validate_client_report(payload, spec["runtime"]) + if ( + Version(payload["version"]) != Version(version) + or payload["artifact_sha256"] != result["upstream"]["artifact_sha256"] + or not any( + entry["name"].lower().replace("-", "_") == spec["package"].replace("-", "_") + and Version(entry["version"]) == Version(version) + and entry["sha256"] == result["upstream"]["artifact_sha256"] + for entry in payload["dependencies"] + ) + ): + raise ValueError( + "Installed integration artifact or runtime does not match the request" + ) + result["upstream"]["actual_version"] = payload["version"] + result["upstream"]["runtime"] = payload["runtime"] + result["upstream"]["dependencies"] = payload["dependencies"] + result["tests"] = payload["tests"] + for test in result["tests"]: + test["message"] = redact(test["message"], password)[:2000] + validate_result(result, spec) + output.with_suffix(".xml").write_text(redact(payload["junit"], password)) + if process.returncode not in (0, 1) or payload["exit_code"] != process.returncode: + raise RuntimeError("Test process did not complete normally") + if process.returncode and all(t["outcome"] == "passed" for t in result["tests"]): + raise RuntimeError("Test process failed without a corresponding test outcome") + except (OSError, ValueError, RuntimeError, KeyError, StopIteration) as error: + result["execution_error"] = record_error( + output, f"{type(error).__name__}: {error}", password + ) + try: + validate_result(result, spec) + except ValueError: + result["tests"] = [] + finally: + errors = cleanup(run_id, image) + if errors: + combined = "; ".join(filter(None, [result["execution_error"], *errors])) + result["execution_error"] = record_error(output, combined, password) + result["finished_at"] = datetime.now(timezone.utc).isoformat() + validate_result(result, spec) + with output.open("x") as file: + json.dump(result, file, indent=2, allow_nan=False) + file.write("\n") + return result + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--integration", default="pymongo") + parser.add_argument("--version", help="Defaults to the selected integration's registry version") + parser.add_argument( + "--documentdb-version", help="Defaults to the newest reviewed registry release" + ) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--wheelhouse", type=Path) + parser.add_argument("--run-url") + parser.add_argument( + "--trigger", + choices=("manual", "push", "scheduled", "documentdb_release"), + default="manual", + ) + parser.add_argument("--demonstration", action="store_true") + args = parser.parse_args() + try: + registry = read_registry() + version = args.version or registry["integrations"][args.integration]["default_version"] + result = execute( + registry, + args.integration, + version, + args.documentdb_version or default_documentdb_version(registry), + args.output, + wheelhouse=args.wheelhouse, + demonstration=args.demonstration, + run_url=args.run_url, + trigger=args.trigger, + ) + except KeyError: + print("Unknown integration or DocumentDB release", file=sys.stderr) + return 2 + except (OSError, ValueError) as error: + print(f"Invalid compatibility request: {error}", file=sys.stderr) + return 2 + state = compatibility_state(result) + print(f"{state}: {args.output}") + return 0 if state == "Working" and not result["execution_error"] else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/compatibility/schemas/attempt.json b/compatibility/schemas/attempt.json new file mode 100644 index 0000000..ec57318 --- /dev/null +++ b/compatibility/schemas/attempt.json @@ -0,0 +1,45 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "additionalProperties": false, + "required": [ + "schema_version", "repository", "run_id", "run_attempt", "run_url", + "head_sha", "started_at", "conclusion", "profiles", "errors" + ], + "properties": { + "schema_version": {"const": 1}, + "repository": {"type": "string", "pattern": "^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$"}, + "run_id": {"type": "integer", "minimum": 1}, + "run_attempt": {"type": "integer", "minimum": 1}, + "run_url": { + "type": "string", + "pattern": "^https://github\\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/actions/runs/[1-9][0-9]*/attempts/[1-9][0-9]*$" + }, + "head_sha": {"type": "string", "pattern": "^[a-f0-9]{40}$"}, + "started_at": {"type": "string", "format": "date-time"}, + "conclusion": { + "enum": ["success", "failure", "cancelled", "timed_out", "action_required", "neutral", + "skipped", "stale", "startup_failure"] + }, + "profiles": { + "type": "array", + "maxItems": 100, + "uniqueItems": true, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["integration", "documentdb_version", "upstream_version", "profile"], + "properties": { + "integration": {"type": "string", "pattern": "^[a-z][a-z0-9_-]*$"}, + "documentdb_version": {"type": "string", "maxLength": 64}, + "upstream_version": {"type": "string", "maxLength": 64}, + "profile": {"type": "string", "maxLength": 128} + } + } + }, + "errors": { + "type": "array", "maxItems": 200, + "items": {"type": "string", "maxLength": 1000} + } + } +} diff --git a/compatibility/schemas/registry.json b/compatibility/schemas/registry.json new file mode 100644 index 0000000..23e587a --- /dev/null +++ b/compatibility/schemas/registry.json @@ -0,0 +1,52 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "additionalProperties": false, + "required": ["schema_version", "documentdb", "integrations"], + "properties": { + "schema_version": {"const": 1}, + "documentdb": { + "type": "object", + "minProperties": 1, + "propertyNames": {"pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+$"}, + "additionalProperties": { + "type": "object", + "additionalProperties": false, + "required": ["image", "postgres_major", "extension_version"], + "properties": { + "image": {"type": "string", "pattern": "^ghcr\\.io/documentdb/documentdb/documentdb-local@sha256:[a-f0-9]{64}$"}, + "postgres_major": {"type": "integer", "minimum": 15, "maximum": 18}, + "extension_version": {"type": "string", "pattern": "^[0-9]+\\.[0-9]+-[0-9]+$"} + } + } + }, + "integrations": { + "type": "object", + "minProperties": 1, + "propertyNames": {"pattern": "^[a-z][a-z0-9_]{0,39}$"}, + "additionalProperties": { + "type": "object", + "additionalProperties": false, + "required": ["repository", "owner", "enabled", "runtime", "package", "default_version", "version_pattern", "profile", "test_file", "demonstration_file", "timeout_seconds", "freshness_days", "expected_tests"], + "properties": { + "repository": {"type": "string", "pattern": "^https://github\\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$"}, + "owner": {"type": "string", "pattern": "^@[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$"}, + "enabled": {"type": "boolean"}, + "runtime": {"enum": ["python", "nodejs"]}, + "package": {"type": "string", "pattern": "^[a-z][a-z0-9_-]{0,39}$"}, + "default_version": {"type": "string", "pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+$"}, + "version_pattern": {"type": "string", "minLength": 1, "maxLength": 100}, + "profile": {"type": "string", "pattern": "^[a-z0-9_-]{1,80}$"}, + "test_file": {"type": "string", "pattern": "^compatibility/integrations/[a-z0-9_]+/test_[a-z0-9_]+\\.(?:py|cjs)$"}, + "demonstration_file": {"type": "string", "pattern": "^compatibility/integrations/[a-z0-9_]+/test_[a-z0-9_]+\\.(?:py|cjs)$"}, + "timeout_seconds": {"type": "integer", "minimum": 30, "maximum": 1800}, + "freshness_days": {"type": "integer", "minimum": 1, "maximum": 90}, + "expected_tests": { + "type": "array", "minItems": 1, "maxItems": 100, "uniqueItems": true, + "items": {"type": "string", "pattern": "^test_[a-z0-9_]+$"} + } + } + } + } + } +} diff --git a/compatibility/schemas/result.json b/compatibility/schemas/result.json new file mode 100644 index 0000000..bb58bf4 --- /dev/null +++ b/compatibility/schemas/result.json @@ -0,0 +1,99 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "additionalProperties": false, + "required": ["schema_version", "id", "integration", "repository", "owner", "profile", "suite_digest", "documentdb", "upstream", "expected_tests", "tests", "started_at", "finished_at", "trigger", "run_url", "demonstration", "execution_error"], + "$defs": { + "runtime": { + "type": "object", "additionalProperties": false, + "required": ["name", "version"], + "properties": { + "name": {"enum": ["python", "nodejs"]}, + "version": {"type": ["string", "null"], "pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+$"} + } + } + }, + "if": {"properties": {"schema_version": {"const": 1}}}, + "then": { + "properties": { + "upstream": { + "required": ["wheel_sha256", "python_version"], + "properties": {"artifact_sha256": false, "runtime": false} + } + } + }, + "else": { + "properties": { + "upstream": { + "required": ["artifact_sha256", "runtime"], + "properties": {"wheel_sha256": false, "python_version": false} + } + } + }, + "properties": { + "schema_version": {"enum": [1, 2]}, + "id": {"type": "string", "pattern": "^[a-f0-9]{32}$"}, + "integration": {"type": "string", "pattern": "^[a-z][a-z0-9_]{0,39}$"}, + "repository": {"type": "string", "pattern": "^https://github\\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$"}, + "owner": {"type": "string", "pattern": "^@[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$"}, + "profile": {"type": "string", "pattern": "^[a-z0-9_-]{1,80}$"}, + "suite_digest": {"type": "string", "pattern": "^[a-f0-9]{64}$"}, + "documentdb": { + "type": "object", "additionalProperties": false, + "required": ["version", "image", "actual_extension_version", "actual_postgres_version"], + "properties": { + "version": {"type": "string", "pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+$"}, + "image": {"type": "string", "pattern": "^ghcr\\.io/documentdb/documentdb/documentdb-local@sha256:[a-f0-9]{64}$"}, + "actual_extension_version": {"type": ["string", "null"], "maxLength": 40}, + "actual_postgres_version": {"type": ["string", "null"], "maxLength": 120} + } + }, + "upstream": { + "type": "object", "additionalProperties": false, + "required": ["version", "actual_version", "client_image", "dependencies"], + "properties": { + "version": {"type": "string", "pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+$"}, + "actual_version": {"type": ["string", "null"], "pattern": "^[0-9]+\\.[0-9]+(?:\\.[0-9]+)?$"}, + "wheel_sha256": {"type": ["string", "null"], "pattern": "^[a-f0-9]{64}$"}, + "artifact_sha256": {"type": ["string", "null"], "pattern": "^[a-f0-9]{64}$"}, + "runtime": {"$ref": "#/$defs/runtime"}, + "client_image": {"type": ["string", "null"], "pattern": "^sha256:[a-f0-9]{64}$"}, + "python_version": {"type": ["string", "null"], "pattern": "^3\\.12\\.[0-9]+$"}, + "dependencies": { + "type": "array", "maxItems": 100, + "items": { + "type": "object", "additionalProperties": false, + "required": ["name", "version", "sha256"], + "properties": { + "name": {"type": "string", "maxLength": 100, "pattern": "^(?:@[a-z0-9_.-]+/)?[A-Za-z0-9_.-]+$"}, + "version": {"type": "string", "pattern": "^[A-Za-z0-9_.+-]{1,100}$"}, + "sha256": {"type": "string", "pattern": "^[a-f0-9]{64}$"} + } + } + } + } + }, + "expected_tests": { + "type": "array", "minItems": 1, "maxItems": 101, "uniqueItems": true, + "items": {"type": "string", "pattern": "^test_[a-z0-9_]+$"} + }, + "tests": { + "type": "array", "maxItems": 101, + "items": { + "type": "object", "additionalProperties": false, + "required": ["id", "outcome", "message"], + "properties": { + "id": {"type": "string", "pattern": "^test_[a-z0-9_]+$"}, + "outcome": {"enum": ["passed", "failed", "skipped", "error"]}, + "message": {"type": "string", "maxLength": 2000} + } + } + }, + "started_at": {"type": "string", "format": "date-time"}, + "finished_at": {"type": "string", "format": "date-time"}, + "trigger": {"enum": ["manual", "push", "documentdb_release", "upstream_release", "scheduled"]}, + "run_url": {"type": ["string", "null"], "pattern": "^https://github\\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/actions/runs/[0-9]+(?:/attempts/[1-9][0-9]*)?$"}, + "demonstration": {"type": "boolean"}, + "execution_error": {"type": ["string", "null"], "maxLength": 2000} + } +} diff --git a/compatibility/unit/__init__.py b/compatibility/unit/__init__.py new file mode 100644 index 0000000..9bb1143 --- /dev/null +++ b/compatibility/unit/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: MIT + +"""Unit coverage for orchestration and publication, without a database.""" diff --git a/compatibility/unit/conftest.py b/compatibility/unit/conftest.py new file mode 100644 index 0000000..a602013 --- /dev/null +++ b/compatibility/unit/conftest.py @@ -0,0 +1,156 @@ +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: MIT + +"""Validated test records for compatibility infrastructure.""" + +import hashlib +import io +import json +import os +import re +import subprocess +import sys +from copy import deepcopy +from datetime import datetime, timedelta, timezone + +import pytest + +from compatibility import runner +from compatibility.contracts import ROOT, read_registry, suite_digest + + +@pytest.fixture +def collect_report(tmp_path): + """Exercise the production reporting plugin in a fresh, isolated pytest process.""" + + def collect(source): + (tmp_path / "test_profile.py").write_text(source) + output = tmp_path / "report.json" + program = """ +import json +import os +import sys +from pathlib import Path +import pytest +from compatibility.client import Reports +collector = Reports() +code = pytest.main( + ["-q", "-c", os.devnull, "--rootdir", sys.argv[1], "--confcutdir", sys.argv[1], + "-p", "no:cacheprovider", sys.argv[1]], plugins=[collector] +) +Path(sys.argv[2]).write_text(json.dumps( + {"exit_code": int(code), "tests": list(collector.tests.values())} +)) +""" + subprocess.run( + [sys.executable, "-c", program, str(tmp_path), str(output)], + env={**os.environ, "PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1"}, + check=True, + capture_output=True, + text=True, + timeout=30, + ) + return json.loads(output.read_text()) + + return collect + + +@pytest.fixture +def registry(): + return read_registry() + + +@pytest.fixture +def selection(registry): + return { + "integration": "pymongo", + "version": registry["integrations"]["pymongo"]["default_version"], + "documentdb_version": next(iter(registry["documentdb"])), + } + + +@pytest.fixture +def other_version(selection): + major, minor, patch = selection["version"].split(".") + return f"{major}.{minor}.{int(patch) + 1}" + + +@pytest.fixture +def client_python(registry, selection): + adapter = (ROOT / registry["integrations"][selection["integration"]]["test_file"]).parent + version = re.search(r"^FROM python:(\d+\.\d+)", (adapter / "Dockerfile").read_text(), re.M) + assert version is not None, "The client image must declare its Python version" + return version.group(1) + + +@pytest.fixture +def prepared_context(tmp_path, registry, selection, monkeypatch): + """Prepare the real build context while replacing only external wheel metadata.""" + spec = registry["integrations"][selection["integration"]] + version = selection["version"] + context = tmp_path / "context" + context.mkdir() + wheelhouse = tmp_path / "wheelhouse" + wheelhouse.mkdir() + wheel = wheelhouse / f"{spec['package'].replace('-', '_')}-{version}-py3-none-any.whl" + wheel.write_bytes(b"unit fixture; not an executable wheel") + metadata = json.dumps( + { + "urls": [ + { + "filename": wheel.name, + "yanked": False, + "digests": {"sha256": hashlib.sha256(wheel.read_bytes()).hexdigest()}, + } + ] + } + ).encode() + monkeypatch.setattr( + runner.urllib.request, "urlopen", lambda *args, **kwargs: io.BytesIO(metadata) + ) + runner.prepare_client(context, spec, version, wheelhouse) + return context + + +@pytest.fixture +def record(registry, selection, client_python): + """Use reviewed identities with synthetic runtime details, not live release snapshots.""" + integration = selection["integration"] + spec = registry["integrations"][integration] + database_version = selection["documentdb_version"] + database = registry["documentdb"][database_version] + version = selection["version"] + now = datetime.now(timezone.utc) - timedelta(minutes=1) + return { + "schema_version": 2, + "id": "a" * 32, + "integration": integration, + "repository": spec["repository"], + "owner": spec["owner"], + "profile": spec["profile"], + "suite_digest": suite_digest(integration, spec), + "documentdb": { + "version": database_version, + "image": database["image"], + "actual_extension_version": database["extension_version"], + "actual_postgres_version": f"{database['postgres_major']}.0", + }, + "upstream": { + "version": version, + "actual_version": version, + "artifact_sha256": "b" * 64, + "client_image": "sha256:" + "c" * 64, + "runtime": {"name": "python", "version": f"{client_python}.0"}, + "dependencies": [{"name": spec["package"], "version": version, "sha256": "b" * 64}], + }, + "expected_tests": deepcopy(spec["expected_tests"]), + "tests": [ + {"id": name, "outcome": "passed", "message": ""} for name in spec["expected_tests"] + ], + "started_at": (now - timedelta(seconds=5)).isoformat(), + "finished_at": now.isoformat(), + "trigger": "manual", + "run_url": None, + "demonstration": False, + "execution_error": None, + } diff --git a/compatibility/unit/test_client.py b/compatibility/unit/test_client.py new file mode 100644 index 0000000..05f59f1 --- /dev/null +++ b/compatibility/unit/test_client.py @@ -0,0 +1,137 @@ +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: MIT + +"""Report real pytest outcomes, including non-call failures and invalid collection.""" + +import pytest + +pytestmark = pytest.mark.unit + + +@pytest.mark.parametrize( + ("source", "code", "outcome"), + [ + pytest.param("def test_profile(): pass", 0, "passed", id="passed"), + pytest.param("def test_profile(): assert False", 1, "failed", id="assertion"), + pytest.param( + "import pytest\ndef test_profile(): pytest.fail('Explicit mismatch')", + 1, + "failed", + id="explicit-test-failure", + ), + pytest.param( + "import pytest\nfrom pymongo.errors import DuplicateKeyError\n" + "def test_profile():\n with pytest.raises(DuplicateKeyError): pass", + 1, + "failed", + id="required-exception-was-not-raised", + ), + pytest.param( + "def test_profile(): raise RuntimeError('Execution failed')", 1, "error", id="runtime" + ), + pytest.param( + "import pytest\n@pytest.mark.skip(reason='Unavailable')\ndef test_profile(): pass", + 0, + "skipped", + id="skipped", + ), + pytest.param( + "import pytest\n@pytest.mark.xfail(reason='Unavailable')\n" + "def test_profile(): assert False", + 0, + "skipped", + id="expected-failure-is-not-working", + ), + pytest.param( + "import pytest\ndef test_profile(): pytest.xfail('Unavailable')", + 0, + "skipped", + id="explicit-expected-failure-is-not-working", + ), + pytest.param( + "import pytest\n@pytest.fixture\ndef fixture(): raise RuntimeError('Setup failed')\n" + "def test_profile(fixture): pass", + 1, + "error", + id="setup", + ), + pytest.param( + "import pytest\n@pytest.fixture\ndef fixture():\n" + " yield\n raise RuntimeError('Cleanup failed')\n" + "def test_profile(fixture): pass", + 1, + "error", + id="teardown", + ), + pytest.param( + "import pytest\n@pytest.fixture\ndef fixture():\n" + " yield\n raise RuntimeError('Cleanup failed')\n" + "def test_profile(fixture): assert False", + 1, + "failed", + id="assertion-survives-teardown", + ), + ], +) +def test_report_classifies_all_test_phases(collect_report, source, code, outcome): + report = collect_report(source) + assert report["exit_code"] == code and [ + (test["id"], test["outcome"]) for test in report["tests"] + ] == [("test_profile", outcome)] + + +def test_duplicate_parameterized_names_rejected_before_execution(collect_report): + report = collect_report( + "import pytest\n@pytest.mark.parametrize('value', [1, 2])\n" "def test_profile(value): pass" + ) + assert report == {"exit_code": 4, "tests": []} + + +def test_collection_error_cannot_be_reported_as_passed(collect_report): + report = collect_report("raise RuntimeError('Collection failed')") + assert report == {"exit_code": 2, "tests": []} + + +@pytest.mark.parametrize( + ("exception", "outcome"), + [ + ("OperationFailure('Unsupported operation', 115)", "failed"), + ("DuplicateKeyError('Unexpected duplicate', 11000)", "failed"), + ("BulkWriteError({'writeErrors': [{'code': 11000}], 'writeConcernErrors': []})", "failed"), + ("ProtocolError('Invalid response')", "failed"), + ("OperationFailure('Server time limit exceeded', 50)", "error"), + ("ExecutionTimeout('Server time limit exceeded', 50)", "error"), + ("NetworkTimeout('Socket timeout')", "error"), + ("ConnectionFailure('Endpoint unavailable')", "error"), + ("ConfigurationError('Invalid runtime configuration')", "error"), + ], +) +def test_driver_operation_failures_are_distinct_from_execution_errors( + collect_report, exception, outcome +): + report = collect_report( + "from pymongo.errors import (BulkWriteError, ConfigurationError, ConnectionFailure, " + "DuplicateKeyError, ExecutionTimeout, NetworkTimeout, OperationFailure, ProtocolError)\n" + f"def test_profile(): raise {exception}\n" + ) + assert report["exit_code"] == 1 + assert report["tests"][0]["outcome"] == outcome + + +def test_driver_failure_survives_teardown_connection_failure(collect_report): + report = collect_report( + "import pytest\nfrom pymongo.errors import ConnectionFailure, OperationFailure\n" + "@pytest.fixture\ndef fixture():\n" + " yield\n raise ConnectionFailure('Cleanup unavailable')\n" + "def test_profile(fixture): raise OperationFailure('Unsupported operation', 115)\n" + ) + assert report["tests"][0]["outcome"] == "failed" + + +def test_fixture_operation_failure_is_not_an_executed_scenario(collect_report): + report = collect_report( + "import pytest\nfrom pymongo.errors import OperationFailure\n" + "@pytest.fixture\ndef fixture(): raise OperationFailure('Setup failed', 115)\n" + "def test_profile(fixture): pass\n" + ) + assert report["tests"][0]["outcome"] == "error" diff --git a/compatibility/unit/test_contracts.py b/compatibility/unit/test_contracts.py new file mode 100644 index 0000000..f558c7e --- /dev/null +++ b/compatibility/unit/test_contracts.py @@ -0,0 +1,242 @@ +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: MIT + +"""Contract validation and fail-closed compatibility classification.""" + +from copy import deepcopy +from datetime import datetime, timedelta, timezone + +import pytest + +from compatibility.contracts import ( + artifact_sha256, + compatibility_state, + default_documentdb_version, + result_runtime, + suite_digest, + validate_client_report, + validate_result, + validate_schema, +) + +pytestmark = pytest.mark.unit + + +def test_complete_execution_is_working(record): + validate_result(record) + assert compatibility_state(record) == "Working" + + +@pytest.mark.parametrize( + ("requested", "installed"), + [("4.9.0", "4.9"), ("4.11.0", "4.11"), ("4.9.1", "4.9.1")], +) +def test_equivalent_installed_versions_are_working(record, requested, installed): + upstream = record["upstream"] + upstream["version"] = requested + upstream["actual_version"] = installed + upstream["dependencies"][0]["version"] = installed + validate_client_report( + { + "version": installed, + "runtime": upstream["runtime"], + "artifact_sha256": upstream["artifact_sha256"], + "exit_code": 0, + "tests": record["tests"], + "junit": "", + "dependencies": upstream["dependencies"], + } + ) + validate_result(record) + assert compatibility_state(record) == "Working" + + +def test_missing_installed_version_cannot_pass(record): + record["upstream"]["actual_version"] = None + assert compatibility_state(record) == "Not tested" + + +@pytest.mark.parametrize("outcome", ["skipped", "error"]) +def test_incomplete_execution_is_not_tested(record, outcome): + record["tests"][0]["outcome"] = outcome + assert compatibility_state(record) == "Not tested" + + +def test_zero_tests_cannot_pass(record): + record["tests"] = [] + assert compatibility_state(record) == "Not tested" + + +def test_missing_required_test_cannot_pass(record): + record["tests"].pop() + assert compatibility_state(record) == "Not tested" + + +def test_wrong_installed_version_cannot_pass(record, other_version): + record["upstream"]["actual_version"] = other_version + assert compatibility_state(record) == "Not tested" + + +def test_unverified_database_cannot_pass(record): + record["documentdb"]["actual_extension_version"] = None + assert compatibility_state(record) == "Not tested" + + +def test_assertion_failure_survives_cleanup_error(record): + record["tests"][0]["outcome"] = "failed" + record["execution_error"] = "Cleanup failed" + assert compatibility_state(record) == "Failing" + + +def test_duplicate_test_outcomes_rejected(record): + record["tests"].append(deepcopy(record["tests"][0])) + with pytest.raises(ValueError, match="Duplicate"): + validate_result(record) + + +def test_undeclared_test_rejected(record): + record["tests"][0]["id"] = "test_undeclared" + with pytest.raises(ValueError, match="undeclared"): + validate_result(record) + + +def test_coverage_cannot_be_reduced_by_a_report(record, registry): + record["expected_tests"].pop() + record["tests"].pop() + with pytest.raises(ValueError, match="coverage"): + validate_result(record, registry["integrations"][record["integration"]]) + + +@pytest.mark.parametrize( + ("field", "value"), + [ + ("id", "../../outside"), + ("run_url", "javascript:alert(1)"), + ("run_url", "https://example.test/actions/runs/1"), + ("started_at", "2026-01-01T00:00:00"), + ("schema_version", 3), + ], +) +def test_unsafe_or_malformed_fields_rejected(record, field, value): + record[field] = value + with pytest.raises(ValueError): + validate_result(record) + + +@pytest.mark.parametrize("suffix", ["", "/attempts/1", "/attempts/23"]) +def test_pipeline_links_can_identify_a_specific_attempt(record, suffix): + record["run_url"] = "https://github.com/example/project/actions/runs/42" + suffix + validate_result(record) + + +@pytest.mark.parametrize( + "suffix", ["/attempts/0", "/attempts/01", "/attempts/x", "/attempts/1/extra"] +) +def test_malformed_attempt_links_are_rejected(record, suffix): + record["run_url"] = "https://github.com/example/project/actions/runs/42" + suffix + with pytest.raises(ValueError): + validate_result(record) + + +def test_future_result_rejected(record): + record["finished_at"] = (datetime.now(timezone.utc) + timedelta(days=1)).isoformat() + with pytest.raises(ValueError, match="future"): + validate_result(record) + + +def test_unknown_fields_rejected(record): + record["credentials"] = "not-a-real-secret" + with pytest.raises(ValueError, match="additionalProperties"): + validate_result(record) + + +def test_owner_required(registry, selection): + del registry["integrations"][selection["integration"]]["owner"] + with pytest.raises(ValueError): + validate_schema(registry, "registry") + + +def test_mutable_database_image_rejected(registry, selection): + database = registry["documentdb"][selection["documentdb_version"]] + database["image"] = database["image"].split("@", 1)[0] + ":latest" + with pytest.raises(ValueError): + validate_schema(registry, "registry") + + +def test_default_database_is_the_newest_reviewed_release(registry): + database = next(iter(registry["documentdb"].values())) + registry["documentdb"] = {version: database for version in ("0.9.0", "0.117.0", "0.12.0")} + assert default_documentdb_version(registry) == "0.117.0" + + +def test_invalid_client_envelope_rejected(): + with pytest.raises(ValueError, match="client report"): + validate_client_report({"tests": "passed"}) + + +def test_legacy_python_records_remain_unchanged_and_readable(record, registry): + record["schema_version"] = 1 + upstream = record["upstream"] + upstream["wheel_sha256"] = upstream.pop("artifact_sha256") + upstream["python_version"] = upstream.pop("runtime")["version"] + original = deepcopy(record) + validate_result(record, registry["integrations"][record["integration"]]) + assert compatibility_state(record) == "Working" + assert artifact_sha256(record) == upstream["wheel_sha256"] + assert result_runtime(record) == {"name": "python", "version": upstream["python_version"]} + assert record == original + + +@pytest.mark.parametrize("version", ["20.0.0", "3.12.0"]) +def test_node_result_requires_the_reviewed_runtime(record, version): + record["upstream"]["runtime"] = {"name": "nodejs", "version": version} + with pytest.raises(ValueError, match="runtime"): + validate_result(record) + + +def test_python_profile_cannot_accept_node_results(record, registry): + record["upstream"]["runtime"] = {"name": "nodejs", "version": "24.0.0"} + with pytest.raises(ValueError, match="runtime"): + validate_result(record, registry["integrations"][record["integration"]]) + + +def test_result_versions_cannot_mix_legacy_and_current_provenance(record): + record["upstream"]["wheel_sha256"] = "b" * 64 + with pytest.raises(ValueError): + validate_result(record) + + +def test_prepared_build_context_preserves_the_reviewed_suite(prepared_context, registry, selection): + integration = selection["integration"] + spec = registry["integrations"][integration] + assert suite_digest(integration, spec, prepared_context) == suite_digest(integration, spec) + + +@pytest.mark.parametrize( + "filename", + [ + "compatibility/requirements.txt", + "compatibility/pyproject.toml", + "compatibility/schemas/result.json", + "compatibility/runner.py", + "compatibility/integrations/pymongo/Dockerfile", + "compatibility/integrations/pymongo/requirements.txt", + ], +) +def test_runtime_or_configuration_changes_invalidate_results( + prepared_context, registry, selection, filename +): + integration = selection["integration"] + spec = registry["integrations"][integration] + original = suite_digest(integration, spec, prepared_context) + path = prepared_context / filename + path.write_text(path.read_text() + "\n") + assert suite_digest(integration, spec, prepared_context) != original + + +def test_adapter_selection_is_part_of_the_suite_identity(registry, selection): + integration = selection["integration"] + spec = registry["integrations"][integration] + original = suite_digest(integration, spec) + spec["test_file"] = spec["demonstration_file"] + assert suite_digest(integration, spec) != original diff --git a/compatibility/unit/test_profile.py b/compatibility/unit/test_profile.py new file mode 100644 index 0000000..c402b93 --- /dev/null +++ b/compatibility/unit/test_profile.py @@ -0,0 +1,31 @@ +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: MIT + +"""Keep the small public-driver profile aligned with its advertised coverage.""" + +import ast +import re + +import pytest + +from compatibility.contracts import DEMONSTRATION_TEST, ROOT, read_registry + +pytestmark = pytest.mark.unit + + +def scenario_names(path): + if path.suffix == ".cjs": + return re.findall(r"^async function (test_[a-z0-9_]+)\(", path.read_text(), re.M) + tree = ast.parse(path.read_text()) + return [ + node.name + for node in tree.body + if isinstance(node, ast.FunctionDef) and node.name.startswith("test_") + ] + + +@pytest.mark.parametrize("integration", read_registry()["integrations"]) +def test_declared_scenarios_match_real_test_functions(registry, integration): + spec = registry["integrations"][integration] + assert sorted(scenario_names(ROOT / spec["test_file"])) == sorted(spec["expected_tests"]) + assert scenario_names(ROOT / spec["demonstration_file"]) == [DEMONSTRATION_TEST] diff --git a/compatibility/unit/test_readme.py b/compatibility/unit/test_readme.py new file mode 100644 index 0000000..5db3635 --- /dev/null +++ b/compatibility/unit/test_readme.py @@ -0,0 +1,412 @@ +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: MIT + +"""README views preserve execution identity and expose missing evidence.""" + +import json +import shutil +from copy import deepcopy +from datetime import datetime, timedelta, timezone +from xml.etree import ElementTree + +import pytest + +from compatibility import readme +from compatibility.contracts import ROOT, read_registry, suite_digest, timestamp +from compatibility.results import append_result, validate_incoming_result + +pytestmark = pytest.mark.unit +REPOSITORY = "example/project" + + +@pytest.fixture +def published_record(record): + record["run_url"] = readme.run_url(REPOSITORY, 42, 1) + return record + + +@pytest.fixture +def attempt(published_record): + return { + "schema_version": 1, + "repository": REPOSITORY, + "run_id": 42, + "run_attempt": 1, + "run_url": published_record["run_url"], + "head_sha": "a" * 40, + "started_at": ( + timestamp(published_record["started_at"]) - timedelta(seconds=10) + ).isoformat(), + "conclusion": "success", + "profiles": [readme.profile_from_result(published_record)], + "errors": [], + } + + +@pytest.fixture +def source_run(attempt): + return { + "id": attempt["run_id"], + "run_attempt": attempt["run_attempt"], + "head_sha": attempt["head_sha"], + "run_started_at": attempt["started_at"], + "conclusion": attempt["conclusion"], + "head_branch": "main", + "repository": {"full_name": REPOSITORY}, + "head_repository": {"full_name": REPOSITORY}, + "event": "workflow_dispatch", + "status": "completed", + "workflow_id": 123, + "display_title": "Ecosystem compatibility", + } + + +def incoming_report(path, record, *, include_result=True): + path.mkdir() + profile = {**readme.profile_from_result(record), "demonstration": record["demonstration"]} + (path / "summary.json").write_text( + json.dumps({"schema_version": 1, "success": True, "integrations": [profile], "errors": []}) + ) + if include_result: + append_result(path / "results", record) + return path + + +def selected_row(view, record): + return next( + row + for row in view["integrations"] + if ( + row["integration"] == record["integration"] + and row["upstream_version"] == record["upstream"]["version"] + and row["profile"] == record["profile"] + ) + ) + + +def test_empty_dashboard_is_not_tested_and_has_no_execution_timestamp(tmp_path, registry): + view = readme.snapshot(tmp_path, registry, REPOSITORY, datetime.now(timezone.utc)) + assert view["latest_workflow"] is None and view["preview"] + assert all( + row["state"] == "Not tested" and row["last_attempt"] is None for row in view["integrations"] + ) + assert "No completed compatibility workflow" in readme.markdown(view) + assert "Not tested" in "".join(ElementTree.fromstring(readme.svg(view)).itertext()) + assert "pymongo: Not tested" in readme.badge_svg(view, "pymongo") + + +def test_real_profile_evidence_drives_svg_json_and_accessible_details( + tmp_path, registry, published_record, attempt +): + incoming = incoming_report(tmp_path / "incoming", published_record) + data = tmp_path / "data" + readme.ingest({"action": "publish", "attempt": attempt}, ROOT, incoming, data, REPOSITORY) + readme.render(data, data / "site", REPOSITORY) + view = json.loads((data / "site/status.json").read_text()) + row = selected_row(view, published_record) + assert (row["state"], row["latest_attempt_state"]) == ("Working", "Working") + assert row["last_attempt"] == published_record["finished_at"] + assert row["conclusive_at"] == published_record["finished_at"] + assert row["passed"] == row["expected"] == len(published_record["expected_tests"]) + text = "".join(ElementTree.fromstring((data / "site/status.svg").read_text()).itertext()) + assert readme.utc(published_record["finished_at"]) in text + assert "FORK PREVIEW" not in text + assert "Scoped scenario evidence" not in text + badge = ElementTree.fromstring((data / "site/badges/pymongo.svg").read_text()) + assert badge.find("{http://www.w3.org/2000/svg}title").text == "pymongo: Working" + assert readme.utc(published_record["finished_at"]) in "".join(badge.itertext()) + details = (data / "site/README.md").read_text() + assert published_record["run_url"] in details and "Working" in details + assert "## pymongo\n" in details + assert published_record["profile"] in details + assert "Fork preview" not in details + assert "Results apply only" not in details + + +def test_missing_latest_artifact_does_not_inherit_an_earlier_pass( + tmp_path, registry, published_record, attempt +): + append_result(tmp_path / "results", published_record) + later = deepcopy(attempt) + later.update( + run_id=43, + run_url=readme.run_url(REPOSITORY, 43, 1), + started_at=published_record["finished_at"], + conclusion="failure", + ) + missing = deepcopy(published_record) + missing["run_url"] = later["run_url"] + incoming = incoming_report(tmp_path / "incoming", missing, include_result=False) + readme.ingest({"action": "publish", "attempt": later}, ROOT, incoming, tmp_path, REPOSITORY) + view = readme.snapshot(tmp_path, registry, REPOSITORY, datetime.now(timezone.utc)) + row = selected_row(view, published_record) + assert row["state"] == "Working" + assert row["latest_attempt_state"] == "Not tested" + assert row["last_attempt"] == later["started_at"] + assert row["conclusive_at"] == published_record["finished_at"] + assert row["run_url"] == later["run_url"] and view["latest_workflow"]["errors"] + assert view["latest_workflow"]["conclusion"] == "failure" + assert "pymongo: Not tested" in readme.badge_svg(view, "pymongo") + + +@pytest.mark.parametrize("evidence", ["missing", "failed"]) +def test_newer_workflow_attempt_outranks_later_test_start( + tmp_path, registry, published_record, attempt, evidence +): + append_result(tmp_path / "results", published_record) + readme.save_attempt(tmp_path, attempt, REPOSITORY) + newer = deepcopy(attempt) + newer.update( + run_id=43, + run_url=readme.run_url(REPOSITORY, 43, 1), + started_at=(timestamp(published_record["started_at"]) - timedelta(seconds=5)).isoformat(), + conclusion="failure", + ) + failed = deepcopy(published_record) + failed.update(id="b" * 32, run_url=newer["run_url"], started_at=newer["started_at"]) + failed["tests"][0]["outcome"] = "failed" + incoming = incoming_report(tmp_path / "incoming", failed, include_result=evidence == "failed") + readme.ingest({"action": "publish", "attempt": newer}, ROOT, incoming, tmp_path, REPOSITORY) + view = readme.snapshot(tmp_path, registry, REPOSITORY, datetime.now(timezone.utc)) + row = selected_row(view, published_record) + expected = ("Working", "Not tested") if evidence == "missing" else ("Failing", "Failing") + assert (row["state"], row["latest_attempt_state"]) == expected + assert row["run_url"] == newer["run_url"] and view["latest_workflow"]["run_id"] == 43 + assert f"pymongo: {expected[1]}" in readme.badge_svg(view, "pymongo") + + +def test_failure_before_a_report_exists_is_visible(tmp_path, registry, attempt): + attempt["conclusion"] = "failure" + attempt["profiles"] = [] + readme.ingest( + {"action": "publish", "attempt": attempt}, + ROOT, + tmp_path / "missing", + tmp_path / "data", + REPOSITORY, + ) + view = readme.snapshot(tmp_path / "data", registry, REPOSITORY, datetime.now(timezone.utc)) + assert view["latest_workflow"]["errors"] + assert all(row["state"] == "Not tested" for row in view["integrations"]) + assert "missing or rejected evidence" in readme.svg(view) + + +def test_unknown_failed_selection_does_not_leave_an_earlier_badge_green( + tmp_path, registry, published_record, attempt +): + append_result(tmp_path / "results", published_record) + attempt.update( + run_id=43, + run_url=readme.run_url(REPOSITORY, 43, 1), + started_at=published_record["finished_at"], + profiles=[], + conclusion="failure", + ) + readme.ingest( + {"action": "publish", "attempt": attempt}, + ROOT, + tmp_path / "missing", + tmp_path, + REPOSITORY, + ) + view = readme.snapshot(tmp_path, registry, REPOSITORY, datetime.now(timezone.utc)) + assert selected_row(view, published_record)["state"] == "Working" + assert "pymongo: Not tested" in readme.badge_svg(view, "pymongo") + + +def test_badge_does_not_hide_another_versions_failure( + tmp_path, registry, published_record, other_version +): + append_result(tmp_path / "results", published_record) + failing = deepcopy(published_record) + failing["id"] = "b" * 32 + failing["upstream"]["version"] = other_version + failing["upstream"]["actual_version"] = other_version + failing["tests"][0]["outcome"] = "failed" + append_result(tmp_path / "results", failing) + view = readme.snapshot(tmp_path, registry, REPOSITORY, datetime.now(timezone.utc)) + assert selected_row(view, published_record)["state"] == "Working" + badge = ElementTree.fromstring(readme.badge_svg(view, "pymongo")) + assert badge.find("{http://www.w3.org/2000/svg}title").text == "pymongo: Failing" + assert readme.COLORS["Failing"] in [ + node.get("fill") for node in badge.iter("{http://www.w3.org/2000/svg}rect") + ] + + +def test_republication_can_recover_missing_artifacts_without_rewriting_run_identity( + tmp_path, registry, published_record, attempt +): + incoming = incoming_report(tmp_path / "incoming", published_record, include_result=False) + data = tmp_path / "data" + plan = {"action": "publish", "attempt": attempt} + readme.ingest(plan, ROOT, incoming, data, REPOSITORY) + before = readme.snapshot(data, registry, REPOSITORY, datetime.now(timezone.utc)) + append_result(incoming / "results", published_record) + readme.ingest(plan, ROOT, incoming, data, REPOSITORY) + after = readme.snapshot(data, registry, REPOSITORY, datetime.now(timezone.utc)) + assert selected_row(before, published_record)["latest_attempt_state"] == "Not tested" + assert selected_row(after, published_record)["state"] == "Working" + assert before["latest_workflow"]["started_at"] == after["latest_workflow"]["started_at"] + assert not after["latest_workflow"]["errors"] + changed = {**attempt, "head_sha": "b" * 40} + with pytest.raises(ValueError, match="identity"): + readme.save_attempt(data, changed, REPOSITORY) + + +def test_refresh_ages_evidence_without_inventing_a_new_execution( + tmp_path, registry, published_record, attempt +): + append_result(tmp_path / "results", published_record) + readme.save_attempt(tmp_path, attempt, REPOSITORY) + original = (tmp_path / f"results/{published_record['id']}.json").read_bytes() + first = readme.snapshot(tmp_path, registry, REPOSITORY, datetime.now(timezone.utc)) + days = registry["integrations"][published_record["integration"]]["freshness_days"] + later = readme.snapshot( + tmp_path, + registry, + REPOSITORY, + timestamp(published_record["finished_at"]) + timedelta(days=days, seconds=1), + ) + assert selected_row(first, published_record)["state"] == "Working" + assert selected_row(later, published_record)["state"] == "Stale" + assert "pymongo: Stale" in readme.badge_svg(later, "pymongo") + assert first["latest_workflow"] == later["latest_workflow"] + assert selected_row(first, published_record)["last_attempt"] == ( + selected_row(later, published_record)["last_attempt"] + ) + assert (tmp_path / f"results/{published_record['id']}.json").read_bytes() == original + + +def test_demonstrations_do_not_change_normal_readme_state( + tmp_path, registry, published_record, attempt +): + append_result(tmp_path / "results", published_record) + readme.save_attempt(tmp_path, attempt, REPOSITORY) + original = readme.snapshot(tmp_path, registry, REPOSITORY, datetime.now(timezone.utc)) + demo = deepcopy(published_record) + demo["id"] = "b" * 32 + demo["demonstration"] = True + demo["expected_tests"].append("test_failure_demonstration") + demo["tests"].append( + {"id": "test_failure_demonstration", "outcome": "failed", "message": "Deliberate failure"} + ) + incoming = incoming_report(tmp_path / "incoming", demo) + readme.ingest({"action": "publish", "attempt": attempt}, ROOT, incoming, tmp_path, REPOSITORY) + assert readme.snapshot(tmp_path, registry, REPOSITORY, datetime.now(timezone.utc)) == original + assert not (tmp_path / f"results/{demo['id']}.json").exists() + + +def test_svg_and_markdown_keep_metadata_as_text(tmp_path, registry): + view = readme.snapshot(tmp_path, registry, REPOSITORY, datetime.now(timezone.utc)) + view["integrations"][0]["profile"] = '' + view["integrations"][0]["integration"] = "[unsafe](javascript:alert(1))|bad" + svg = ElementTree.fromstring(readme.svg(view)) + assert not list(svg.iter("{http://www.w3.org/2000/svg}script")) + assert "