diff --git a/.github/ISSUE_TEMPLATE/compatibility-report.yml b/.github/ISSUE_TEMPLATE/compatibility-report.yml new file mode 100644 index 0000000..418d176 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/compatibility-report.yml @@ -0,0 +1,48 @@ +name: Integration compatibility problem +description: Report behavior that disagrees with a tested compatibility result. +title: "[Compatibility] " +body: + - type: markdown + attributes: + value: | + Include a minimal reproduction with synthetic data. Do not include credentials, + connection strings containing secrets, or customer data. A passing dashboard + result covers only its listed scenarios and version pair. + - type: input + id: integration + attributes: + label: Integration + validations: + required: true + - type: input + id: documentdb_version + attributes: + label: DocumentDB version + validations: + required: true + - type: input + id: upstream_version + attributes: + label: Integration version + validations: + required: true + - type: textarea + id: environment + attributes: + label: Actual environment + description: Include operating system, runtime, topology, and relevant non-secret settings. + validations: + required: true + - type: textarea + id: reproduction + attributes: + label: Reproduction and expected versus actual behavior + validations: + required: true + - type: textarea + id: dashboard_run + attributes: + label: Dashboard and pipeline run + description: Include the dashboard entry or run that led you to expect this scenario to work. + validations: + required: true diff --git a/.github/workflows/compatibility-ci.yml b/.github/workflows/compatibility-ci.yml index dc764dd..3c8dc3e 100644 --- a/.github/workflows/compatibility-ci.yml +++ b/.github/workflows/compatibility-ci.yml @@ -9,12 +9,14 @@ on: - "compatibility/**" - ".github/workflows/compatibility*" - ".github/aw/actions-lock.json" + - ".github/ISSUE_TEMPLATE/compatibility-report.yml" pull_request: types: [opened, reopened, synchronize, ready_for_review] paths: - "compatibility/**" - ".github/workflows/compatibility*" - ".github/aw/actions-lock.json" + - ".github/ISSUE_TEMPLATE/compatibility-report.yml" concurrency: group: compatibility-infrastructure-${{ github.event.pull_request.number || github.ref }} @@ -43,5 +45,15 @@ jobs: 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 trusted Git history publisher + run: shellcheck compatibility/persist.sh - name: Check the README dashboard publisher run: shellcheck compatibility/publish-readme.sh + - name: Check dashboard freshness + run: | + image=node:24.21.0-bookworm-slim@sha256:5cbc7caba8c2c0f0bca675d1b61b9f2857e1cf1853c6164ee9dd409501a936e7 + docker run --rm --read-only --network none --user 1000:1000 \ + --tmpfs /tmp:size=64m --cap-drop=ALL --security-opt=no-new-privileges \ + --mount "type=bind,source=$PWD,target=/workspace,readonly" \ + --workdir /workspace "$image" \ + node --test compatibility/unit/test_freshness.cjs diff --git a/.github/workflows/compatibility-documentdb-release.yml b/.github/workflows/compatibility-documentdb-release.yml new file mode 100644 index 0000000..4f76cf4 --- /dev/null +++ b/.github/workflows/compatibility-documentdb-release.yml @@ -0,0 +1,46 @@ +name: Compatibility DocumentDB releases + +on: + push: + branches: [main] + paths: + - compatibility/registry.yaml + +permissions: + contents: read + +jobs: + dispatch: + name: Test added or re-pinned DocumentDB releases + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + actions: write + contents: read + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + fetch-depth: 0 + persist-credentials: false + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: "3.12" + - name: Install trusted orchestration dependencies + run: python -m pip install -r compatibility/requirements.txt + - name: Dispatch the compatibility workflow for each changed release + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + BEFORE: ${{ github.event.before }} + run: | + previous="$RUNNER_TEMP/previous-registry.yaml" + if ! git show "$BEFORE:compatibility/registry.yaml" > "$previous"; then + echo "The previous registry is unavailable, so every reviewed release is dispatched." + : > "$previous" + fi + releases=$(python -m compatibility.workflow changed-releases --previous "$previous") + for release in $releases; do + printf 'Dispatching compatibility runs for DocumentDB %s\n' "$release" + gh workflow run compatibility.yml --ref "$GITHUB_REF_NAME" \ + -f integration=all -f documentdb_version="$release" -f trigger=documentdb_release + done diff --git a/.github/workflows/compatibility.yml b/.github/workflows/compatibility.yml new file mode 100644 index 0000000..072ee0c --- /dev/null +++ b/.github/workflows/compatibility.yml @@ -0,0 +1,156 @@ +name: Ecosystem compatibility + +on: + workflow_dispatch: + inputs: + integration: + description: Integration, or all enabled registry entries + type: choice + options: + - all + - pymongo + default: all + required: true + version: + description: Upstream version override (single integration only; blank uses registry defaults) + type: string + required: false + documentdb_version: + description: Reviewed DocumentDB release from compatibility/registry.yaml, or all (blank uses the newest) + type: string + required: false + trigger: + description: Execution trigger recorded with the results + type: choice + options: + - manual + - documentdb_release + default: manual + required: true + schedule: + - cron: "41 5 * * *" + +permissions: + contents: read + +jobs: + plan: + name: Select integrations + runs-on: ubuntu-24.04 + timeout-minutes: 5 + outputs: + matrix: ${{ steps.select.outputs.matrix }} + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + persist-credentials: false + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: "3.12" + - name: Install trusted orchestration dependencies + run: python -m pip install -r compatibility/requirements.txt + - name: Resolve the reviewed integration matrix + id: select + env: + INTEGRATION: ${{ inputs.integration }} + VERSION: ${{ inputs.version }} + DOCUMENTDB_VERSION: ${{ github.event_name == 'schedule' && 'all' || inputs.documentdb_version }} + TRIGGER: ${{ github.event_name == 'schedule' && 'scheduled' || inputs.trigger }} + run: | + args=() + if [ -n "$INTEGRATION" ]; then args+=(--integration "$INTEGRATION"); fi + if [ -n "$DOCUMENTDB_VERSION" ]; then args+=(--documentdb-version "$DOCUMENTDB_VERSION"); fi + if [ -n "$VERSION" ]; then args+=(--version "$VERSION"); fi + if [ -n "$TRIGGER" ]; then args+=(--trigger "$TRIGGER"); fi + matrix=$(python -m compatibility.workflow matrix "${args[@]}") + printf 'matrix=%s\n' "$matrix" >> "$GITHUB_OUTPUT" + test: + name: ${{ matrix.integration }} ${{ matrix.version }} on DocumentDB ${{ matrix.documentdb_version }} + needs: plan + strategy: + fail-fast: false + matrix: ${{ fromJSON(needs.plan.outputs.matrix) }} + runs-on: ubuntu-24.04 + timeout-minutes: 30 + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + persist-credentials: false + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: "3.12" + - name: Install trusted orchestration dependencies + run: python -m pip install -r compatibility/requirements.txt + - name: Run the isolated integration profile + id: suite + env: + INTEGRATION: ${{ matrix.integration }} + VERSION: ${{ matrix.version }} + DOCUMENTDB_VERSION: ${{ matrix.documentdb_version }} + TRIGGER: ${{ matrix.trigger }} + run: | + args=( + --integration "$INTEGRATION" + --version "$VERSION" + --documentdb-version "$DOCUMENTDB_VERSION" + --output "results/$INTEGRATION/$DOCUMENTDB_VERSION/result.json" + --run-url "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID/attempts/$GITHUB_RUN_ATTEMPT" + --trigger "$TRIGGER" + ) + python -m compatibility.runner "${args[@]}" + - name: Retain integration results and sanitized diagnostics + if: always() + uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6 + with: + name: compatibility-results-${{ matrix.integration }}-${{ matrix.documentdb_version }}-${{ github.run_attempt }} + path: results/ + if-no-files-found: error + retention-days: 30 + report: + name: Combined compatibility report + needs: [plan, test] + if: always() && needs.plan.result == 'success' + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + persist-credentials: false + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: "3.12" + - name: Install trusted reporting dependencies + run: python -m pip install -r compatibility/requirements.txt + - name: Collect this attempt's integration artifacts + uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7 + with: + pattern: compatibility-results-*-${{ github.run_attempt }} + path: incoming + merge-multiple: true + - name: Render combined results, including missing or failed integrations + if: always() + env: + INTEGRATION: ${{ inputs.integration }} + VERSION: ${{ inputs.version }} + DOCUMENTDB_VERSION: ${{ github.event_name == 'schedule' && 'all' || inputs.documentdb_version }} + TRIGGER: ${{ github.event_name == 'schedule' && 'scheduled' || inputs.trigger }} + run: | + args=( + --input incoming + --output report + --summary "$GITHUB_STEP_SUMMARY" + --expected-run-url "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID/attempts/$GITHUB_RUN_ATTEMPT" + ) + if [ -n "$INTEGRATION" ]; then args+=(--integration "$INTEGRATION"); fi + if [ -n "$DOCUMENTDB_VERSION" ]; then args+=(--documentdb-version "$DOCUMENTDB_VERSION"); fi + if [ -n "$VERSION" ]; then args+=(--version "$VERSION"); fi + if [ -n "$TRIGGER" ]; then args+=(--trigger "$TRIGGER"); fi + python -m compatibility.workflow report "${args[@]}" + - name: Retain the combined summary and dashboard + if: always() + uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6 + with: + name: compatibility-report-${{ github.run_attempt }} + path: report/ + if-no-files-found: error + retention-days: 30 diff --git a/compatibility/README.md b/compatibility/README.md index bdf208c..31ce2eb 100644 --- a/compatibility/README.md +++ b/compatibility/README.md @@ -4,6 +4,11 @@ This registry-driven runner tests ecosystem integration profiles against reviewe DocumentDB releases. Execution, artifact verification, and result contracts are shared; each integration adapter implements its own scenario suite. +The GitHub Actions workflow runs on demand, daily, and for newly reviewed +DocumentDB releases. It selects enabled profiles and combines validated results as +Markdown, HTML, and JSON. A trusted publisher can append results to Git history +with the persistence helper. + ## Profiles and reviewed artifacts [`registry.yaml`](registry.yaml) defines profiles, enablement, default package @@ -105,6 +110,149 @@ 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. +## Results and dashboard + +Append locally produced records to an immutable store: + +```bash +python -m compatibility.publish \ + --result compatibility/.test-results/pymongo-001/result.json \ + --store compatibility/.test-results/history \ + --site compatibility/.test-results/site +``` + +Open `compatibility/.test-results/site/index.html`. The same validated history +produces HTML, `current.json`, and `history.json`. Conflicting run IDs are rejected; +identical replays are idempotent. Failure demonstrations are rejected and never +rendered. Local runs have no fabricated pipeline URL. + +| State | Meaning | +| --- | --- | +| Working | All required scenarios passed with verified artifacts | +| Failing | A conclusive assertion or non-timeout operation/protocol failure | +| Not tested | Missing or skipped coverage, timeouts, setup errors, or other incomplete execution | +| Stale | The last conclusive result is older than the profile's freshness policy or no longer matches its execution inputs/artifacts | + +If a newer attempt cannot execute, retain the previous conclusive result while +exposing the new attempt's failure separately. Keep version pairs and profiles +distinct. Browser-side freshness also ages previously rendered results. + +The renderer provides prefilled links to this repository's +[compatibility issue form](../.github/ISSUE_TEMPLATE/compatibility-report.yml). +Use `--issue-repository` to select a different reporting destination with the +same form field IDs. A report should include the actual version pair, +runtime/profile, relevant run, and a minimal synthetic reproduction, never +credentials or customer data. + +This renderer does not push Git history, deploy a site, create issues, or change +repository settings. Public hosting and durable publication require a separately +approved destination, publisher, operational owner, and reporting route. + +## GitHub Actions workflow + +Manual dispatch requires the workflow on the repository's default branch. +Select **Ecosystem compatibility** in the Actions tab, then choose the branch +and, optionally, a reviewed database release. A blank release uses the newest +reviewed release in the registry, and `all` selects every reviewed release. The +integration defaults to `all`: a planning job expands every enabled registry entry +using its own reviewed default version. Select one integration for a focused run +or version override. A version override with `all`, a disabled integration, a +version outside its registry policy, or an unknown database release is rejected +before test jobs start. + +The workflow also runs daily on the default branch. Scheduled runs test every +enabled integration at its default version against every reviewed DocumentDB +release. + +Each push to `main` that changes `registry.yaml` starts **Compatibility DocumentDB +releases**. It compares the registry with the version before the push and +dispatches this workflow once for each added or re-pinned release, with every +enabled integration at its default version and the `documentdb_release` trigger. +If the earlier registry is unavailable, every reviewed release is dispatched. The +`trigger` input defaults to `manual`; a `documentdb_release` run requires one +reviewed release and cannot narrow integrations or override versions. + +Each matrix job runs its complete scenario suite against its own disposable +database. Matrix fail-fast is disabled. JSON and available JUnit/logs are retained +in `compatibility-results---` artifacts +even when the job fails. Results record the trigger (`manual`, `scheduled`, or +`documentdb_release`) and exact workflow-attempt URL. + +After the matrix finishes, reporting validates each selected result's identity, +trigger, coverage, artifacts, suite digest, and workflow-attempt URL. The summary +includes every selected integration and database release. Missing or rejected +results are **Not tested**, with a diagnostic, not fabricated envelopes or an +earlier attempt's pass. Compatibility failures remain **Failing**, and failed or +incomplete reports exit nonzero without suppressing matrix failures. + +The `compatibility-report-` artifact contains `summary.md`, machine-readable +`summary.json`, accepted envelopes in `results/`, and a combined dashboard in `site/`. +Only selected profiles and versions appear, including explicit overrides. All +artifacts have 30-day retention. + +Use **Re-run all jobs** for a complete matrix rerun. Reporting deliberately +collects only the current attempt's artifacts, so rerunning only failed jobs can +leave other integrations or releases without current-attempt evidence. Re-running +an older workflow retains its original commit; dispatch a fresh run to test new +code. + +All compatibility jobs have read-only repository permissions. The release +dispatcher additionally receives `actions: write` only to start this workflow. +Neither workflow publishes Git history, deploys a site, creates issues, or changes +repository settings. +Normal default-branch completions notify the separate README dashboard publisher. +That publisher retains its own write permission; integration execution and report +generation never receive publication credentials. + +To inspect selection, combine locally produced records, or list the releases a +registry change would dispatch: + +```bash +python -m compatibility.workflow matrix --integration all +python -m compatibility.workflow matrix --documentdb-version all --trigger scheduled +python -m compatibility.workflow report --integration all \ + --input compatibility/.test-results/incoming \ + --output compatibility/.test-results/combined-001 +python -m compatibility.workflow changed-releases --previous /path/to/previous-registry.yaml +``` + +Place each record under `incoming///result.json`. +Use the same integration, version, database, and trigger selection +as the producing runs, and a fresh output directory. `--expected-run-url` binds a +combined report to one workflow attempt; omit it for local results. `--summary` +appends the Markdown report to a GitHub step-summary file. + +## Durable Git history + +The generic history helper is available for an explicitly configured trusted +publisher, not for integration clients: + +```bash +bash compatibility/persist.sh /path/to/result.json "$EXPECTED_RUN_URL" +``` + +Run it from the trusted source checkout with write access to the intended +`origin`. Set `EXPECTED_RUN_URL` to the originating test attempt, not a later +publication retry. The helper verifies that URL, declared coverage, database +artifact, and execution-input digest, then appends `results/.json` to +`compatibility-data`. + +The helper uses non-force pushes with bounded conflict retries and initializes +an orphan branch containing only result data. Identical replays are idempotent; +conflicting run IDs fail rather than overwrite history. Concurrent writers' +records survive retry, and temporary worktrees are removed. Retain the data +branch independently of artifact expiration. + +Keep write credentials separate from integration execution. A publisher must +retain failed attempts and serialize deployment only after results are durably +stored. Render complete history with `compatibility.publish`. Deployment retries +must not delete or rewrite history. +Cancellation before persistence is not a compatibility verdict. + +Invoke this helper explicitly from the trusted publisher; the compatibility +workflow does not call it. It does not configure hosting, GitHub Pages, +credentials, repository permissions, or a release-watcher ledger. + ## README dashboard The repository README embeds compact integration badges from the `compatibility-data` @@ -162,6 +310,7 @@ 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. +Expose it in the workflow's integration selector as well as the registry. Run infrastructure checks in a prepared Python 3.12 tooling container: @@ -172,8 +321,13 @@ python -m isort --check-only --settings-path compatibility/pyproject.toml compat 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 +shellcheck compatibility/persist.sh +node --test compatibility/unit/test_freshness.cjs ``` +Run the JavaScript freshness checks with Node 24 in a tooling container. They do +not require a database or installed integration packages. + 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 diff --git a/compatibility/dashboard/freshness.js b/compatibility/dashboard/freshness.js new file mode 100644 index 0000000..4619796 --- /dev/null +++ b/compatibility/dashboard/freshness.js @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. +// SPDX-License-Identifier: MIT + +"use strict"; + +function updateFreshness(now) { + for (const element of document.querySelectorAll("[data-compatibility-status]")) { + const tested = Date.parse(element.dataset.conclusiveAt); + const maximumAge = Number(element.dataset.freshnessDays) * 86400000; + if (Number.isFinite(tested) && now - tested > maximumAge) { + element.textContent = `Stale (last: ${element.dataset.previousState})`; + element.className = "Stale"; + } + } +} + +updateFreshness(Date.now()); +setInterval(() => updateFreshness(Date.now()), 60000); diff --git a/compatibility/dashboard/index.html b/compatibility/dashboard/index.html new file mode 100644 index 0000000..2c97937 --- /dev/null +++ b/compatibility/dashboard/index.html @@ -0,0 +1,73 @@ + + + + + + DocumentDB ecosystem compatibility + + + + +

DocumentDB ecosystem compatibility

+

Results cover only the listed version pairs, runtime profiles, and executed scenarios. + They do not certify every feature, deployment, or client API.

+

Generated . + Machine-readable current results and + complete history.

+

Compatibility results

+ + + + + {% for row in rows %} + + + + + + + + {% endfor %} + +
IntegrationVersions and coverageStatusLast successful / attemptedEvidence
{{ row.integration }}DocumentDB {{ row.documentdb_version }}
+ Upstream {{ row.upstream_version }}{{ row.profile }} +

{{ row.passed }} / {{ row.expected }} scenarios passed in the displayed result.

+
Coverage
    + {% for scenario in row.scenarios %}
  • {{ scenario }}
  • {% endfor %} +
+
+ {{ row.state }} + {% if row.state == "Stale" %}Last known outcome: {{ row.previous_state }}{% endif %} + Latest attempt: {{ row.latest_attempt_state }} + {% if row.error %}
{{ row.error }}
{% endif %} +
Success: {{ row.last_success or "Never" }}
Attempt: {{ row.last_attempt or "Never" }} + Trigger: {{ row.trigger or "None" }}
+ {% if row.run_url %}Latest pipeline run + {% elif row.last_attempt %}Local run (not published){% else %}No run{% endif %} + {% if row.issue_url %} +

Report a compatibility problem

+ {% endif %} +
History ({{ row.history | length }})
    + {% for record in row.history %} +
  • {{ record.finished_at }}: {{ record.tests | length }} scenario records + {% if record.run_url %}run{% endif %} + {% if record.execution_error %}
    {{ record.execution_error }}
    {% endif %} +
      {% for test in record.tests %}
    • {{ test.id }}: {{ test.outcome }} + {% if test.message %}
      {{ test.message }}
      {% endif %} +
    • {% endfor %}
    +
  • + {% endfor %} +
+
+ + diff --git a/compatibility/persist.sh b/compatibility/persist.sh new file mode 100644 index 0000000..cec296c --- /dev/null +++ b/compatibility/persist.sh @@ -0,0 +1,74 @@ +#!/usr/bin/env bash +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: MIT + +set -euo pipefail + +if [[ $# -ne 2 ]]; then + printf 'Usage: bash compatibility/persist.sh RESULT_JSON EXPECTED_RUN_URL\n' >&2 + exit 2 +fi + +result=$(realpath --no-symlinks "$1") +run_url=$2 +repo_root=$(git rev-parse --show-toplevel) +cd "$repo_root" +worktree="" +scratch="" + +cleanup() { + if [[ -n "$worktree" ]]; then + git worktree remove --force "$worktree" + worktree="" + scratch="" + elif [[ -n "$scratch" ]]; then + rmdir "$scratch" + scratch="" + fi +} +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 result history 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-history.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 + git -C "$worktree" switch --orphan "history-$(basename "$worktree")" + fi + + python -m compatibility.publish --result "$result" \ + --store "$worktree/results" --expected-run-url "$run_url" + git -C "$worktree" add -- results + if git -C "$worktree" diff --cached --quiet; then + printf 'Identical result is already persisted.\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 "Record compatibility result from $run_url" + revision=$(git -C "$worktree" rev-parse HEAD) + if git push origin "$revision:refs/heads/compatibility-data"; then + exit 0 + fi + cleanup + printf 'History push failed; retrying from the current remote history (%s/5).\n' "$attempt" >&2 + sleep "$attempt" +done + +printf 'Could not append the result after five conflict-safe attempts.\n' >&2 +exit 1 diff --git a/compatibility/publish.py b/compatibility/publish.py new file mode 100644 index 0000000..d8c79cf --- /dev/null +++ b/compatibility/publish.py @@ -0,0 +1,126 @@ +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: MIT + +"""Append immutable results and render a credential-free static compatibility dashboard.""" + +from __future__ import annotations + +import argparse +import json +import re +from datetime import datetime, timezone +from pathlib import Path +from typing import Any +from urllib.parse import urlencode + +from jinja2 import Environment, FileSystemLoader, StrictUndefined + +from compatibility.contracts import ROOT, read_registry +from compatibility.results import ( + RunKey, + append_result, +) +from compatibility.results import dashboard_rows as result_rows +from compatibility.results import read_result, validate_incoming_result + + +def reporting_link(repository: str, row: dict[str, Any]) -> str: + """Use the issue form's stable field IDs and encode every prefilled value.""" + if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*/[A-Za-z0-9][A-Za-z0-9_.-]*", repository): + raise ValueError("Invalid issue repository") + query = urlencode( + { + "template": "compatibility-report.yml", + "title": f"[Compatibility] {row['integration']} {row['upstream_version']}", + "integration": row["integration"], + "documentdb_version": row["documentdb_version"], + "upstream_version": row["upstream_version"], + "environment": row["profile"], + "dashboard_run": row["run_url"] or "No published run; include your dashboard/run link", + } + ) + return f"https://github.com/{repository}/issues/new?{query}" + + +def dashboard_rows( + results: list[dict[str, Any]], + registry: dict[str, Any], + now: datetime, + issue_repository: str, + *, + expected_runs: dict[RunKey, str | None] | None = None, +) -> list[dict[str, Any]]: + """Add issue-report routes to the shared compatibility evidence projection.""" + rows = result_rows(results, registry, now, expected_runs=expected_runs) + for row in rows: + row["issue_url"] = reporting_link(issue_repository, row) + return rows + + +def render( + store: Path, + site: Path, + registry: dict[str, Any], + *, + issue_repository: str = "documentdb/documentdb-playground", + now: datetime | None = None, + expected_runs: dict[RunKey, str | None] | None = None, +) -> list[dict[str, Any]]: + """Publish static HTML and JSON from the same validated history.""" + now = now or datetime.now(timezone.utc) + if store.is_symlink(): + raise ValueError("The result store must not be a symbolic link") + results = [read_result(path) for path in sorted(store.glob("*.json"))] + results = [result for result in results if not result["demonstration"]] + rows = dashboard_rows(results, registry, now, issue_repository, expected_runs=expected_runs) + site.mkdir(parents=True, exist_ok=True) + environment = Environment( + loader=FileSystemLoader(ROOT / "compatibility" / "dashboard"), + autoescape=True, + undefined=StrictUndefined, + ) + generated = now.isoformat() + page = environment.get_template("index.html").render(rows=rows, generated_at=generated) + (site / "index.html").write_text(page) + (site / "freshness.js").write_text( + (ROOT / "compatibility" / "dashboard" / "freshness.js").read_text() + ) + (site / "history.json").write_text(json.dumps(results, indent=2, allow_nan=False) + "\n") + current = [{key: value for key, value in row.items() if key != "history"} for row in rows] + (site / "current.json").write_text( + json.dumps({"generated_at": generated, "integrations": current}, indent=2, allow_nan=False) + + "\n" + ) + return rows + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--result", type=Path) + parser.add_argument("--store", type=Path, required=True) + parser.add_argument("--site", type=Path) + parser.add_argument("--issue-repository", default="documentdb/documentdb-playground") + parser.add_argument("--expected-run-url") + args = parser.parse_args() + if args.result is None and args.site is None: + parser.error("Provide a result to append or a site to render") + registry = read_registry() + if args.result: + result = read_result(args.result) + if result["demonstration"]: + parser.error("Failure demonstrations are not published") + validate_incoming_result(result, registry, args.expected_run_url) + append_result(args.store, result) + if args.site: + render( + args.store, + args.site, + registry, + issue_repository=args.issue_repository, + ) + print(f"Dashboard rendered at {args.site / 'index.html'}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/compatibility/requirements.txt b/compatibility/requirements.txt index c80ef4b..fbdbbdd 100644 --- a/compatibility/requirements.txt +++ b/compatibility/requirements.txt @@ -1,3 +1,4 @@ PyYAML>=6.0,<7 jsonschema>=4.18,<5 +Jinja2>=3.1.2,<4 packaging>=24.2,<27 diff --git a/compatibility/unit/test_freshness.cjs b/compatibility/unit/test_freshness.cjs new file mode 100644 index 0000000..04334c1 --- /dev/null +++ b/compatibility/unit/test_freshness.cjs @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. +// SPDX-License-Identifier: MIT + +"use strict"; + +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); +const test = require("node:test"); +const vm = require("node:vm"); + +const source = fs.readFileSync(path.join(__dirname, "../dashboard/freshness.js"), "utf8"); +const day = 86400000; +const tested = Date.UTC(2024, 0, 1); + +function status(state, conclusiveAt = new Date(tested).toISOString(), freshnessDays = 7) { + return { + dataset: { conclusiveAt, freshnessDays: String(freshnessDays), previousState: state }, + textContent: state, + className: state, + }; +} + +function load(elements, now) { + let clock = now; + let interval; + vm.runInNewContext(source, { + document: { + querySelectorAll(selector) { + assert.equal(selector, "[data-compatibility-status]"); + return elements; + }, + }, + Date: { parse: Date.parse, now: () => clock }, + setInterval(callback, delay) { + assert.ok(Number.isFinite(delay) && delay > 0); + interval = callback; + }, + }); + return (next) => { + clock = next; + interval(); + }; +} + +for (const freshnessDays of [1, 7, 30]) { + test(`the ${freshnessDays}-day boundary stays fresh until a later timer tick`, () => { + const element = status("Working", new Date(tested).toISOString(), freshnessDays); + const boundary = tested + freshnessDays * day; + const tick = load([element], boundary); + assert.equal(element.textContent, "Working"); + tick(boundary + 1); + assert.equal(element.textContent, "Stale (last: Working)"); + assert.equal(element.className, "Stale"); + }); +} + +test("failed results age without becoming a fabricated passing result", () => { + const element = status("Failing"); + load([element], tested + 8 * day); + assert.equal(element.textContent, "Stale (last: Failing)"); +}); + +test("an untested entry has no conclusive timestamp to refresh", () => { + const element = status("Not tested", ""); + load([element], tested + 8 * day); + assert.equal(element.textContent, "Not tested"); +}); + +test("fresh timestamps cannot undo server-side stale classification", () => { + const element = status("Working"); + element.textContent = element.className = "Stale"; + load([element], tested + day); + assert.equal(element.textContent, "Stale"); +}); diff --git a/compatibility/unit/test_orchestration.py b/compatibility/unit/test_orchestration.py new file mode 100644 index 0000000..2de52f4 --- /dev/null +++ b/compatibility/unit/test_orchestration.py @@ -0,0 +1,582 @@ +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: MIT + +"""Registry-driven fan-out and combined reports with incomplete or conflicting evidence.""" + +import json +import sys +from copy import deepcopy +from datetime import timedelta + +import pytest +import yaml +from packaging.version import Version + +from compatibility import workflow +from compatibility.contracts import RUNTIME_PREFIXES, expected_tests, suite_digest, timestamp + +pytestmark = pytest.mark.unit +RUN_URL = "https://github.com/example/project/actions/runs/42/attempts/3" + + +@pytest.fixture +def runs(registry, selection): + return workflow.select_runs(registry, "all", None, selection["documentdb_version"]) + + +@pytest.fixture +def records(registry, record, runs): + results = {} + for index, run in enumerate(runs): + integration = run["integration"] + spec = registry["integrations"][integration] + result = deepcopy(record) + result.update( + id=f"{index + 1:032x}", + integration=integration, + suite_digest=suite_digest(integration, spec), + **{key: spec[key] for key in ("repository", "owner", "profile")}, + ) + result["expected_tests"] = expected_tests(spec, False) + result["tests"] = [ + {"id": name, "outcome": "passed", "message": ""} for name in result["expected_tests"] + ] + runtime = spec["runtime"] + parts = RUNTIME_PREFIXES[runtime].rstrip(".").split(".") + result["upstream"].update( + version=run["version"], + actual_version=run["version"], + runtime={"name": runtime, "version": ".".join(parts + ["0"] * (3 - len(parts)))}, + dependencies=[{"name": spec["package"], "version": run["version"], "sha256": "b" * 64}], + ) + results[integration] = result + return results + + +def write_records(path, records, release=None): + for integration, result in records.items(): + directory = path / integration / (release or result["documentdb"]["version"]) + directory.mkdir(parents=True, exist_ok=True) + (directory / "result.json").write_text(json.dumps(result)) + return path + + +def read_report(output): + report = json.loads((output / "summary.json").read_text()) + history = json.loads((output / "site/history.json").read_text()) + return report, {row["integration"]: row for row in report["integrations"]}, history + + +def test_all_uses_each_enabled_default_and_accepts_new_registry_entries(registry, selection): + extra = deepcopy(registry["integrations"][selection["integration"]]) + extra.update(default_version="99.1.2", version_pattern=r"^99\.1\.2$") + registry["integrations"]["additional"] = extra + registry["integrations"][selection["integration"]]["enabled"] = False + runs = workflow.select_runs(registry, "all", None, selection["documentdb_version"]) + assert {run["integration"]: run["version"] for run in runs} == { + name: spec["default_version"] + for name, spec in registry["integrations"].items() + if spec["enabled"] + } + assert all(run["documentdb_version"] == selection["documentdb_version"] for run in runs) + + +@pytest.mark.parametrize("override", [False, True]) +def test_single_integration_default_and_override(registry, selection, other_version, override): + version = other_version if override else None + runs = workflow.select_runs( + registry, selection["integration"], version, selection["documentdb_version"] + ) + assert runs == [ + { + **selection, + "version": version or selection["version"], + "trigger": "manual", + } + ] + + +def test_newest_release_is_the_default_and_all_selects_every_release(registry, selection): + reviewed = registry["documentdb"][selection["documentdb_version"]] + for release in ("0.9.0", "999.0.0"): + registry["documentdb"][release] = deepcopy(reviewed) + enabled = sorted(name for name, spec in registry["integrations"].items() if spec["enabled"]) + newest = workflow.select_runs(registry, selection["integration"], None, None) + assert [run["documentdb_version"] for run in newest] == ["999.0.0"] + every = workflow.select_runs(registry, "all", None, "all", trigger="scheduled") + assert [(run["integration"], run["documentdb_version"]) for run in every] == [ + (name, release) + for name in enabled + for release in sorted(registry["documentdb"], key=Version) + ] + assert all(run["trigger"] == "scheduled" for run in every) + release = workflow.select_runs(registry, "all", None, "0.9.0", trigger="documentdb_release") + assert [(run["integration"], run["documentdb_version"], run["trigger"]) for run in release] == [ + (name, "0.9.0", "documentdb_release") for name in enabled + ] + + +@pytest.mark.parametrize( + ("trigger", "integration", "version", "database", "error"), + [ + ("scheduled", "all", None, None, "every reviewed DocumentDB release"), + ("scheduled", "all", None, "selected", "every reviewed DocumentDB release"), + ("documentdb_release", "all", None, None, "one reviewed release"), + ("documentdb_release", "all", None, "all", "one reviewed release"), + ("scheduled", "selected", None, "all", "every enabled integration"), + ("documentdb_release", "all", "selected", "selected", "every enabled integration"), + ("push", "all", None, "selected", "Unknown execution trigger"), + ], +) +def test_automatic_runs_cannot_narrow_the_reviewed_selection( + registry, selection, trigger, integration, version, database, error +): + with pytest.raises(ValueError, match=error): + workflow.select_runs( + registry, + selection["integration"] if integration == "selected" else integration, + selection["version"] if version == "selected" else version, + selection["documentdb_version"] if database == "selected" else database, + trigger=trigger, + ) + + +def test_changed_releases_are_added_or_re_pinned_entries(tmp_path, registry, selection): + release = selection["documentdb_version"] + previous = deepcopy(registry) + for added in ("999.0.0", "0.9.0"): + registry["documentdb"][added] = deepcopy(registry["documentdb"][release]) + source = tmp_path / "previous.yaml" + source.write_text(yaml.safe_dump(previous)) + assert workflow.changed_releases(registry, source) == ["0.9.0", "999.0.0"] + image = previous["documentdb"][release]["image"] + previous["documentdb"][release]["image"] = image[:-1] + ("1" if image[-1] == "0" else "0") + source.write_text(yaml.safe_dump(previous)) + assert workflow.changed_releases(registry, source) == ["0.9.0", release, "999.0.0"] + previous["documentdb"] = deepcopy(registry["documentdb"]) + previous["integrations"][selection["integration"]]["default_version"] = "0.0.0" + source.write_text(yaml.safe_dump(previous)) + assert workflow.changed_releases(registry, source) == [] + + +@pytest.mark.parametrize( + "contents", [None, "", "{", "- documentdb\n", "schema_version: 1\n", "documentdb: []\n"] +) +def test_unreadable_previous_registry_selects_every_release(tmp_path, registry, contents): + source = tmp_path / "previous.yaml" + if contents is not None: + source.write_text(contents) + assert workflow.changed_releases(registry, source) == sorted( + registry["documentdb"], key=Version + ) + + +@pytest.mark.parametrize( + ("integration", "version", "database", "error"), + [ + ("all", "1.2.3", None, "single integration"), + ("unknown", None, None, "Unknown or disabled"), + (None, "not-a-version; echo unsafe", None, "outside the policy"), + ("all", None, "99.99.99", "Unknown DocumentDB"), + ], +) +def test_invalid_selection_is_rejected(registry, selection, integration, version, database, error): + with pytest.raises(ValueError, match=error): + workflow.select_runs( + registry, + integration or selection["integration"], + version, + database or selection["documentdb_version"], + ) + + +def test_disabled_or_empty_selection_is_rejected(registry, selection): + for spec in registry["integrations"].values(): + spec["enabled"] = False + with pytest.raises(ValueError, match="disabled"): + workflow.select_runs( + registry, selection["integration"], None, selection["documentdb_version"] + ) + with pytest.raises(ValueError, match="No enabled"): + workflow.select_runs(registry, "all", None, selection["documentdb_version"]) + + +def test_matrix_cli_serializes_the_selected_runs(monkeypatch, capsys, selection, runs): + monkeypatch.setattr( + sys, "argv", ["workflow", "matrix", "--documentdb-version", selection["documentdb_version"]] + ) + assert workflow.main() == 0 + assert json.loads(capsys.readouterr().out) == {"include": runs} + + +def test_matrix_cli_does_not_emit_a_plan_for_invalid_input(monkeypatch, capsys): + monkeypatch.setattr(sys, "argv", ["workflow", "matrix", "--version", "1.2.3"]) + assert workflow.main() == 2 + captured = capsys.readouterr() + assert not captured.out and "single integration" in captured.err + + +def test_combined_passes_preserve_envelopes_and_share_dashboard_data( + tmp_path, registry, runs, records +): + for record in records.values(): + record["run_url"] = RUN_URL + incoming = write_records(tmp_path / "incoming", records) + output = tmp_path / "report" + summary = tmp_path / "step-summary" + summary.write_text("Earlier step\n") + assert workflow.collect_report( + incoming, output, registry, runs, expected_run_url=RUN_URL, summary=summary + ) + report, rows, history = read_report(output) + assert report["schema_version"] == 1 and report["success"] and report["errors"] == [] + assert set(rows) == set(records) + assert {record["integration"]: record for record in history} == records + assert {path.stem for path in (output / "results").glob("*.json")} == { + record["id"] for record in records.values() + } + for integration, row in rows.items(): + assert row["state"] == "Working" + assert row["passed"] == row["expected"] == len(records[integration]["expected_tests"]) + assert row["run_url"] == RUN_URL + assert row["issue_url"].startswith( + "https://github.com/documentdb/documentdb-playground/issues/new?" + ) + assert ( + json.loads((output / "site/current.json").read_text())["integrations"] + == report["integrations"] + ) + assert summary.read_text() == "Earlier step\n" + (output / "summary.md").read_text() + assert "All selected profiles passed." in summary.read_text() + + +@pytest.mark.parametrize("outcome", ["failed", "error", "skipped", "infrastructure", "incomplete"]) +def test_one_nonpassing_profile_does_not_erase_other_results( + tmp_path, registry, selection, runs, records, outcome +): + integration = selection["integration"] + record = records[integration] + if outcome == "infrastructure": + record["tests"] = [] + record["execution_error"] = "Fixture unavailable" + elif outcome == "incomplete": + record["tests"].pop() + else: + record["tests"][0].update(outcome=outcome, message="Scenario diagnostic") + incoming = write_records(tmp_path / "incoming", records) + output = tmp_path / "report" + assert not workflow.collect_report(incoming, output, registry, runs) + report, rows, history = read_report(output) + assert not report["success"] + assert rows[integration]["state"] == ("Failing" if outcome == "failed" else "Not tested") + assert all(row["state"] == "Working" for name, row in rows.items() if name != integration) + assert {record["integration"]: record for record in history} == records + + +@pytest.mark.parametrize( + ("field", "value", "diagnostic"), + [ + (("integration",), "other", "selected integration"), + (("upstream", "version"), "99.1.2", "selected integration"), + (("documentdb", "version"), "99.1.2", "selected integration"), + (("profile",), "other-profile", "selected integration"), + (("demonstration",), True, "selected integration"), + (("trigger",), "scheduled", "selected integration"), + (("repository",), "https://github.com/example/other", "repository"), + (("owner",), "@example/other", "owner"), + (("suite_digest",), "0" * 64, "suite revision"), + (("documentdb", "actual_extension_version"), "99.1-2", "installed extension"), + ( + ("documentdb", "image"), + "ghcr.io/documentdb/documentdb/documentdb-local@sha256:" + "0" * 64, + "reviewed database artifact", + ), + (("upstream", "runtime", "name"), "nodejs", "runtime"), + (("expected_tests",), ["test_other"], "undeclared scenario"), + ], +) +def test_unmatched_or_unreviewed_evidence_is_rejected_independently( + tmp_path, registry, selection, runs, records, field, value, diagnostic +): + integration = selection["integration"] + target = records[integration] + for part in field[:-1]: + target = target[part] + target[field[-1]] = value + incoming = write_records(tmp_path / "incoming", records, selection["documentdb_version"]) + output = tmp_path / "report" + assert not workflow.collect_report(incoming, output, registry, runs) + _, rows, history = read_report(output) + assert rows[integration]["state"] == "Not tested" + assert diagnostic in rows[integration]["error"] + assert rows[integration]["passed"] == 0 and rows[integration]["last_attempt"] is None + assert all(row["state"] == "Working" for name, row in rows.items() if name != integration) + assert {record["integration"] for record in history} == set(records) - {integration} + + +@pytest.mark.parametrize( + "origin", + [ + None, + "https://github.com/example/project/actions/runs/42", + "https://github.com/example/project/actions/runs/42/attempts/2", + "https://github.com/example/other/actions/runs/42/attempts/3", + "https://github.com/example/project/actions/runs/43/attempts/3", + ], +) +def test_other_runs_and_attempts_never_fill_current_evidence( + tmp_path, registry, selection, runs, records, origin +): + for record in records.values(): + record["run_url"] = RUN_URL + records[selection["integration"]]["run_url"] = origin + incoming = write_records(tmp_path / "incoming", records) + output = tmp_path / "report" + assert not workflow.collect_report(incoming, output, registry, runs, expected_run_url=RUN_URL) + _, rows, history = read_report(output) + assert rows[selection["integration"]]["state"] == "Not tested" + assert "workflow run" in rows[selection["integration"]]["error"] + assert {record["integration"] for record in history} == set(records) - { + selection["integration"] + } + + +@pytest.mark.parametrize( + "kind", + [ + "absent", + "json", + "schema", + "encoding", + "oversized", + "directory", + "file-link", + "directory-link", + "integration-link", + ], +) +def test_missing_or_malformed_artifacts_still_produce_a_combined_report( + tmp_path, registry, selection, runs, records, kind +): + integration = selection["integration"] + incoming = write_records(tmp_path / "incoming", records) + path = incoming / integration / selection["documentdb_version"] / "result.json" + path.unlink() + if kind == "json": + path.write_text("{") + elif kind == "schema": + path.write_text("{}") + elif kind == "encoding": + path.write_bytes(b"\xff") + elif kind == "oversized": + path.write_bytes(b" " * (1024 * 1024 + 1)) + elif kind == "directory": + path.mkdir() + elif kind == "file-link": + path.symlink_to(tmp_path / "absent.json") + elif kind == "directory-link": + path.parent.rmdir() + path.parent.symlink_to(tmp_path / "absent-directory", target_is_directory=True) + elif kind == "integration-link": + # A valid record behind a linked integration directory is still rejected. + target = tmp_path / "linked-integration" + path.parent.parent.rename(target) + (target / path.parent.name / "result.json").write_text(json.dumps(records[integration])) + path.parent.parent.symlink_to(target, target_is_directory=True) + output = tmp_path / "report" + assert not workflow.collect_report(incoming, output, registry, runs) + report, rows, history = read_report(output) + assert not report["success"] and rows[integration]["state"] == "Not tested" + assert rows[integration]["error"].startswith("Result unavailable:") + assert all(row["state"] == "Working" for name, row in rows.items() if name != integration) + assert {record["integration"] for record in history} == set(records) - {integration} + assert "Result unavailable:" in (output / "summary.md").read_text() + + +@pytest.mark.parametrize("missing", [False, True]) +def test_override_has_only_the_selected_integration_and_version( + tmp_path, registry, selection, other_version, records, missing +): + runs = workflow.select_runs( + registry, selection["integration"], other_version, selection["documentdb_version"] + ) + incoming = tmp_path / "incoming" + record = records[selection["integration"]] + record["upstream"].update(version=other_version, actual_version=other_version) + record["upstream"]["dependencies"][0]["version"] = other_version + if not missing: + write_records(incoming, {selection["integration"]: record}) + output = tmp_path / "report" + assert workflow.collect_report(incoming, output, registry, runs) is not missing + _, rows, history = read_report(output) + assert set(rows) == {selection["integration"]} + assert history == ([] if missing else [record]) + row = rows[selection["integration"]] + assert (row["upstream_version"], row["state"], row["passed"]) == ( + other_version, + "Not tested" if missing else "Working", + 0 if missing else len(record["expected_tests"]), + ) + if missing: + assert not list((output / "results").glob("*.json")) + + +def test_conflicting_ids_do_not_overwrite_other_integration_evidence( + tmp_path, registry, selection, record, monkeypatch +): + first = deepcopy(record) + second = {**deepcopy(record), "integration": "additional"} + registry["integrations"]["additional"] = deepcopy( + registry["integrations"][first["integration"]] + ) + # Exercise cross-integration collisions without requiring a second real adapter. + monkeypatch.setattr("compatibility.results.suite_digest", lambda *_: first["suite_digest"]) + runs = [ + {**selection, "trigger": "manual"}, + {**selection, "integration": "additional", "trigger": "manual"}, + ] + records = {first["integration"]: first, second["integration"]: second} + incoming = write_records(tmp_path / "incoming", records) + output = tmp_path / "report" + assert not workflow.collect_report(incoming, output, registry, runs) + _, rows, history = read_report(output) + assert rows[first["integration"]]["state"] == "Working" + assert rows[second["integration"]]["state"] == "Not tested" + assert "same run ID" in rows[second["integration"]]["error"] + assert first in history and second not in history + + +@pytest.mark.parametrize("level", ["integration", "release"]) +def test_unexpected_artifacts_are_reported_without_erasing_valid_results( + tmp_path, registry, selection, runs, records, level +): + incoming = write_records(tmp_path / "incoming", records) + parent = incoming if level == "integration" else incoming / selection["integration"] + (parent / "unexpected").mkdir() + output = tmp_path / "report" + assert not workflow.collect_report(incoming, output, registry, runs) + report, rows, history = read_report(output) + assert report["errors"] and not report["success"] + assert all(row["state"] == "Working" for row in rows.values()) + assert {record["integration"]: record for record in history} == records + assert "Reporting errors" in (output / "summary.md").read_text() + + +@pytest.mark.parametrize("missing", [False, True]) +def test_scheduled_reports_keep_each_release_independent( + tmp_path, registry, selection, records, missing +): + release = selection["documentdb_version"] + registry["documentdb"]["999.0.0"] = deepcopy(registry["documentdb"][release]) + runs = workflow.select_runs(registry, "all", None, "all", trigger="scheduled") + incoming = tmp_path / "incoming" + expected = [] + for index, database in enumerate(sorted(registry["documentdb"], key=Version)): + current = deepcopy(records) + for offset, record in enumerate(current.values()): + record.update(id=f"{index + 1:016x}{offset + 1:016x}", trigger="scheduled") + record["documentdb"]["version"] = database + expected.append(record) + if not (missing and database == "999.0.0"): + write_records(incoming, current) + output = tmp_path / "report" + assert workflow.collect_report(incoming, output, registry, runs) is not missing + report, _, history = read_report(output) + states = { + (row["integration"], row["documentdb_version"]): row["state"] + for row in report["integrations"] + } + assert states == { + (run["integration"], run["documentdb_version"]): ( + "Not tested" if missing and run["documentdb_version"] == "999.0.0" else "Working" + ) + for run in runs + } + assert sorted(history, key=lambda record: record["id"]) == [ + record + for record in expected + if not (missing and record["documentdb"]["version"] == "999.0.0") + ] + + +def test_nested_report_is_not_mistaken_for_an_incoming_artifact(tmp_path, registry, runs, records): + incoming = write_records(tmp_path / "incoming", records) + output = incoming / "report" + assert workflow.collect_report(incoming, output, registry, runs) + report, _, history = read_report(output) + assert report["errors"] == [] + assert {record["integration"]: record for record in history} == records + + +def test_existing_report_and_symbolic_input_root_are_rejected(tmp_path, registry, runs, records): + incoming = write_records(tmp_path / "incoming", records) + output = tmp_path / "report" + output.mkdir() + sentinel = output / "preserved" + sentinel.write_text("Original report") + with pytest.raises(ValueError, match="overwrite"): + workflow.collect_report(incoming, output, registry, runs) + assert sentinel.read_text() == "Original report" + link = tmp_path / "linked" + link.symlink_to(incoming, target_is_directory=True) + with pytest.raises(ValueError, match="symbolic link"): + workflow.collect_report(link, tmp_path / "another-report", registry, runs) + + +def test_expired_success_is_not_reported_as_a_current_pass( + tmp_path, registry, selection, runs, records +): + record = records[selection["integration"]] + age = timedelta(days=registry["integrations"][selection["integration"]]["freshness_days"] + 1) + for key in ("started_at", "finished_at"): + record[key] = (timestamp(record[key]) - age).isoformat() + incoming = write_records(tmp_path / "incoming", records) + output = tmp_path / "report" + assert not workflow.collect_report(incoming, output, registry, runs) + _, rows, _ = read_report(output) + assert rows[selection["integration"]]["state"] == "Stale" + + +def test_summary_diagnostics_cannot_inject_markup_or_extra_rows( + tmp_path, registry, selection, runs, records +): + records[selection["integration"]]["tests"][0].update( + outcome="failed", message="\n| Working | [click](https://example.com)\r" + ) + incoming = write_records(tmp_path / "incoming", records) + output = tmp_path / "report" + assert not workflow.collect_report(incoming, output, registry, runs) + summary = (output / "summary.md").read_text() + assert "") + append_result(tmp_path / "data", record) + render(tmp_path / "data", tmp_path / "site", registry) + html = (tmp_path / "site" / "index.html").read_text() + history = json.loads((tmp_path / "site" / "history.json").read_text()) + assert "