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..9293f54 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 JavaScript reporting and dashboard freshness + run: | + image=$(sed -n 's/^FROM //p' compatibility/integrations/nodejs/Dockerfile) + 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 compatibility/unit/test_nodejs.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..fd31730 --- /dev/null +++ b/.github/workflows/compatibility.yml @@ -0,0 +1,169 @@ +name: Ecosystem compatibility +run-name: ${{ inputs.demonstration && 'Ecosystem compatibility (demonstration)' || 'Ecosystem compatibility' }} + +on: + workflow_dispatch: + inputs: + integration: + description: Integration, or all enabled registry entries + type: choice + options: + - all + - pymongo + - nodejs + - mongoose + 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 + demonstration: + description: Add a separately labeled, intentionally failing assertion + type: boolean + default: 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 }} + DEMONSTRATION: ${{ inputs.demonstration }} + 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 [ "$DEMONSTRATION" = "true" ]; then args+=(--demonstration); 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 }} + DEMONSTRATION: ${{ matrix.demonstration }} + 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" + ) + if [ "$DEMONSTRATION" = "true" ]; then args+=(--demonstration); fi + 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 }} + DEMONSTRATION: ${{ inputs.demonstration }} + 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 [ "$DEMONSTRATION" = "true" ]; then args+=(--demonstration); fi + if [ -n "$TRIGGER" ]; then args+=(--trigger "$TRIGGER"); fi + python -m compatibility.workflow report "${args[@]}" + - name: Retain the combined summary and dashboard preview + 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/README.md b/README.md index b9f808c..2542b19 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,8 @@ playground's README states what it needs. ## Compatibility status [![PyMongo compatibility](/../compatibility-data/site/badges/pymongo.svg)](/../compatibility-data/site/README.md#pymongo) +[![Node.js compatibility](/../compatibility-data/site/badges/nodejs.svg)](/../compatibility-data/site/README.md#nodejs) +[![Mongoose compatibility](/../compatibility-data/site/badges/mongoose.svg)](/../compatibility-data/site/README.md#mongoose) [Run details and accessible results](/../compatibility-data/site/README.md) show tested versions, actual execution timestamps, and the latest attempt diff --git a/compatibility/README.md b/compatibility/README.md index bdf208c..1cd4ab5 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 @@ -29,10 +34,27 @@ 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. +For Node.js, every npm archive must match the SHA-512 integrity in the reviewed +`package-lock.json`. Installation is offline with lifecycle scripts and optional +packages disabled. The client verifies installed dependency versions and records +their SHA-256 hashes. Shared JavaScript execution and reporting live in +`compatibility/client.cjs` and `compatibility/report.cjs`, separate from adapters. + +The Node.js and Mongoose profiles accept only their reviewed locked versions. +To select another, update the manifest in `compatibility/integrations/nodejs` or +`compatibility/integrations/mongoose`, regenerate that adapter's lockfile using Node 24 and +`npm install --package-lock-only --ignore-scripts --engine-strict --omit=optional`, +and update the registry default and version policy. Review dependency changes and +rerun both the normal and demonstration profiles. +Mongoose's transitive MongoDB driver is independently locked and recorded as a +dependency, never substituted for the Mongoose package version. + ## 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: +The PyMongo and native Node.js profiles exercise synchronous Python and +asynchronous JavaScript driver APIs, respectively. Each profile's required +scenarios are declared in the registry's `expected_tests` list and cover the +following behavior: | Area | Behavior | | --- | --- | @@ -46,7 +68,33 @@ declared in the registry's `expected_tests` list and cover the following behavio 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. +for Python async APIs, transactions, vector search, or other unlisted features. + +The Node.js profile uses the corresponding camel-case APIs (`insertOne`, `findOne`, +`findOneAndUpdate`, and others), promises, and `for await` cursor iteration. It +checks native driver return shapes and BSON representations rather than replaying +raw commands through another client. Python async APIs, optional native Node.js +modules, transactions, vector search, and unlisted APIs remain out of scope. + +### Mongoose model coverage + +The Mongoose profile's `expected_tests` list names its required model and document +scenarios. They exercise ODM behavior rather than bypassing it through raw driver +collections: + +| Area | Behavior checked | +| --- | --- | +| Connection | Authenticated administrative ping through the model connection | +| Creation | `Model.create`, `insertMany`, identifiers, casting, defaults, timestamps, hydration, and exact readback | +| Reads and cursors | `findById` with string-ID casting, missing documents, filters, projection, sorting, counts, and observed `getMore` | +| Writes | Document `save` and dirty tracking, `updateOne`, `findOneAndUpdate`, deletes, result objects, and persisted effects | +| Aggregation and indexes | Exact aggregation output, schema-driven indexes, index listing, and duplicate-key rejection | +| Validation and BSON | Required/minimum validators on inserts and updates, ObjectId, BigInt, Decimal128, dates, buffers, arrays, booleans, and nested documents | + +Each scenario uses a fresh connection and database with automatic index and +collection creation and command buffering disabled. Every declared scenario must +pass; there are no known-failure exemptions. Transactions, population, +plugins, middleware, vector search, and unlisted model APIs are outside this profile. ## Run locally @@ -61,6 +109,10 @@ 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 +python -m compatibility.runner --integration nodejs \ + --output compatibility/.test-results/nodejs-001/result.json +python -m compatibility.runner --integration mongoose \ + --output compatibility/.test-results/mongoose-001/result.json ``` Each invocation requires a fresh output path and creates fresh credentials, @@ -73,6 +125,12 @@ verified wheels. `--wheelhouse /path/to/wheels` reuses downloaded wheels, but Py metadata verification still requires network access. Do not disable TLS verification for package downloads. +For Node.js profiles, `--package-cache /path/to/cache` reuses archives named +`.tgz`. Every cached archive is verified +against the reviewed lockfile; a complete cache needs no registry access. +`--wheelhouse` is Python-only and `--package-cache` is Node-only. Node.js is needed +only inside the pinned client container, not on the controller host. + 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. @@ -83,6 +141,10 @@ To verify the nonpassing path: ```bash python -m compatibility.runner --integration pymongo --demonstration \ --output compatibility/.test-results/pymongo-demo-001/result.json +python -m compatibility.runner --integration nodejs --demonstration \ + --output compatibility/.test-results/nodejs-demo-001/result.json +python -m compatibility.runner --integration mongoose --demonstration \ + --output compatibility/.test-results/mongoose-demo-001/result.json ``` This runs the normal scenarios plus one labeled intentional assertion failure @@ -105,6 +167,155 @@ 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 preview + +Append locally produced normal and demonstration 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 --preview +python -m compatibility.publish \ + --result compatibility/.test-results/pymongo-demo-001/result.json \ + --store compatibility/.test-results/history \ + --site compatibility/.test-results/site --preview +``` + +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. Demonstrations remain separate from normal +compatibility evidence. 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 `--preview` option labels review prototypes and hides public issue links. +Without it, 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. Keep the failure demonstration disabled for real results. + +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, override versions, or enable the +failure demonstration. + +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 preview in `site/`. +Only selected profiles and versions appear, including explicit overrides and +labeled demonstrations. 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, demonstration, 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`, using `--preview` +for review prototypes. 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 +373,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 +384,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 compatibility/unit/test_nodejs.cjs ``` +Run the JavaScript reporting and 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/client.cjs b/compatibility/client.cjs new file mode 100644 index 0000000..03d1e6a --- /dev/null +++ b/compatibility/client.cjs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. +// SPDX-License-Identifier: MIT + +"use strict"; + +const fs = require("node:fs"); +const path = require("node:path"); +const { run } = require("node:test"); +const { collect, junit } = require("./report.cjs"); + +async function main() { + const report = JSON.parse(fs.readFileSync("/install-report.json", "utf8")); + const dependencies = report.install.map(entry => { + const installed = JSON.parse(fs.readFileSync(path.join(entry.path, "package.json"), "utf8")); + if (installed.name !== entry.name || installed.version !== entry.version) { + throw new Error("Installed dependency does not match the verified archive"); + } + return { name: installed.name, version: installed.version, sha256: entry.sha256 }; + }); + const installed = dependencies.find(entry => entry.name === process.env.COMPATIBILITY_PACKAGE); + if (!installed) throw new Error("Selected integration is missing from the installation report"); + const files = [process.env.COMPATIBILITY_TEST_FILE]; + const integration = path.basename(path.dirname(files[0])); + if (process.env.COMPATIBILITY_DEMONSTRATION === "1") { + files.push(process.env.COMPATIBILITY_DEMONSTRATION_FILE); + } + const tests = await collect(run({ files, concurrency: 1, isolation: "none" })); + const exitCode = tests.some(test => ["failed", "error"].includes(test.outcome)) ? 1 : 0; + process.stdout.write(JSON.stringify({ + version: installed.version, + runtime: { name: "nodejs", version: process.versions.node }, + artifact_sha256: installed.sha256, + dependencies, + exit_code: exitCode, + tests, + junit: junit(tests, integration), + }) + "\n"); + process.exitCode = exitCode; +} + +main().catch(error => { + process.stderr.write(`${error.stack || error}\n`); + process.exitCode = 2; +}); diff --git a/compatibility/contracts.py b/compatibility/contracts.py index cd19158..6798d24 100644 --- a/compatibility/contracts.py +++ b/compatibility/contracts.py @@ -175,12 +175,15 @@ def suite_files(integration: str, root: Path = ROOT) -> list[Path]: root / "compatibility" / "client.py", root / "compatibility" / "contracts.py", root / "compatibility" / "runner.py", + root / "compatibility" / "npm.py", root / "compatibility" / "schemas" / "registry.json", root / "compatibility" / "schemas" / "result.json", adapter / "Dockerfile", ] - for pattern in ("*.py", "requirements.txt"): + for pattern in ("*.py", "*.cjs", "package*.json", "requirements.txt"): files.extend(adapter.glob(pattern)) + if any(path.suffix == ".cjs" for path in files): + files.extend([root / "compatibility" / name for name in ("client.cjs", "report.cjs")]) for path in files: if path.is_symlink(): raise ValueError("Suite files must not be symbolic links") 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..e2a8cca --- /dev/null +++ b/compatibility/dashboard/index.html @@ -0,0 +1,85 @@ + + + + + + DocumentDB ecosystem compatibility + + + + +

DocumentDB ecosystem compatibility

+ {% if preview %} +

Review prototype. This is a fork-hosted demo, + not an official compatibility support matrix. Issue reporting is not enabled + for this preview.

+ {% endif %} +

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.

+ {% for demonstration in [false, true] %} +

{{ "Failure demonstrations" if demonstration else "Compatibility results" }}

+ {% if demonstration %} +

Synthetic assertion failures are diagnostic demonstrations. + They never change a real integration's compatibility status.

+ {% endif %} + + + + + {% for row in rows if row.demonstration == demonstration %} + + + + + + + + {% endfor %} + +
IntegrationVersions and coverageStatusLast successful / attemptedEvidence
{{ row.integration }}Review route: {{ row.owner }}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 %} +
+
+ {% endfor %} + + diff --git a/compatibility/integrations/mongoose/Dockerfile b/compatibility/integrations/mongoose/Dockerfile new file mode 100644 index 0000000..1305960 --- /dev/null +++ b/compatibility/integrations/mongoose/Dockerfile @@ -0,0 +1,16 @@ +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: MIT + +FROM node:24.21.0-bookworm-slim@sha256:5cbc7caba8c2c0f0bca675d1b61b9f2857e1cf1853c6164ee9dd409501a936e7 + +WORKDIR /app +COPY npm-packages /npm-packages +COPY package.json package-lock.json ./ +RUN for package in /npm-packages/*.tgz; do npm cache add --offline --ignore-scripts "$package"; done \ + && npm ci --offline --ignore-scripts --engine-strict --omit=optional --no-audit --no-fund \ + && npm cache clean --force +COPY install-report.json /install-report.json +COPY compatibility /app/compatibility +USER node +ENV COMPATIBILITY_ACTIVE=1 +ENTRYPOINT ["node", "compatibility/client.cjs"] diff --git a/compatibility/integrations/mongoose/package-lock.json b/compatibility/integrations/mongoose/package-lock.json new file mode 100644 index 0000000..2aaf007 --- /dev/null +++ b/compatibility/integrations/mongoose/package-lock.json @@ -0,0 +1,236 @@ +{ + "name": "documentdb-mongoose-compatibility", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "documentdb-mongoose-compatibility", + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "mongoose": "9.11.0" + }, + "engines": { + "node": ">=24 <25" + } + }, + "node_modules/@mongodb-js/saslprep": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.6.0.tgz", + "integrity": "sha512-19jGXfpctLDJUELLUZGJ5BllcLT7rHdF+gTTaN2jzqu0bGkUhpdcYtgK2Vux+g3zuBAa0TM/W666QMIjYhYujw==", + "license": "MIT", + "dependencies": { + "sparse-bitfield": "^3.0.3" + } + }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "license": "MIT" + }, + "node_modules/@types/webidl-conversions": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.3.tgz", + "integrity": "sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==", + "license": "MIT" + }, + "node_modules/@types/whatwg-url": { + "version": "13.0.0", + "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-13.0.0.tgz", + "integrity": "sha512-N8WXpbE6Wgri7KUSvrmQcqrMllKZ9uxkYWMt+mCSGwNc0Hsw9VQTW7ApqI4XNrx6/SaM2QQJCzMPDEXE058s+Q==", + "license": "MIT", + "dependencies": { + "@types/webidl-conversions": "*" + } + }, + "node_modules/bson": { + "version": "7.3.3", + "resolved": "https://registry.npmjs.org/bson/-/bson-7.3.3.tgz", + "integrity": "sha512-oz3LwE3qGEhTCSyhzQRLY3Bj1NLOsjFMf6tcmY5J8M+3R7EVcmoBfSHWvjUK3yXCLDUsGpIuB3aQL4nDZ1EV/g==", + "license": "Apache-2.0", + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/kareem": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/kareem/-/kareem-3.4.0.tgz", + "integrity": "sha512-JAKhnR4S027v/8949QXNInRskgETCg9rFUMi1VjhGbjX+XltCAAEFcXykkSocNkom1kc66EMJfjWvhj87BDQKg==", + "license": "Apache-2.0", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/memory-pager": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", + "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==", + "license": "MIT" + }, + "node_modules/mongodb": { + "version": "7.7.0", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-7.7.0.tgz", + "integrity": "sha512-XG1xXEqyouAV8GCb3PuRaujofeXKpAJAPvXYWZgHl6Dz4QHSJ1nRLl0+GpqaLTwKvC0RFE9truOur34RNFY1nw==", + "license": "Apache-2.0", + "dependencies": { + "@mongodb-js/saslprep": "^1.5.0", + "bson": "^7.3.2", + "mongodb-connection-string-url": "^7.0.2" + }, + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@aws-sdk/credential-providers": "^3.806.0", + "@mongodb-js/zstd": "^7.0.0", + "gcp-metadata": "^7.0.1", + "kerberos": "^7.0.0", + "mongodb-client-encryption": "^7.2.0", + "snappy": "^7.3.2", + "socks": "^2.8.6" + }, + "peerDependenciesMeta": { + "@aws-sdk/credential-providers": { + "optional": true + }, + "@mongodb-js/zstd": { + "optional": true + }, + "gcp-metadata": { + "optional": true + }, + "kerberos": { + "optional": true + }, + "mongodb-client-encryption": { + "optional": true + }, + "snappy": { + "optional": true + }, + "socks": { + "optional": true + } + } + }, + "node_modules/mongodb-connection-string-url": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-7.0.2.tgz", + "integrity": "sha512-ZoS07RoFqpKYQwAk59qmrx8+jJHNHU30UjlU96QktiGn1ltvDr+vCznLX5DiUBLEpMAHatHNWV1nM/74ul66kA==", + "license": "Apache-2.0", + "dependencies": { + "@types/whatwg-url": "^13.0.0", + "whatwg-url": "^14.1.0" + }, + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/mongoose": { + "version": "9.11.0", + "resolved": "https://registry.npmjs.org/mongoose/-/mongoose-9.11.0.tgz", + "integrity": "sha512-dclC0gx/AfasCMX0VChpv4FQ69ylEf3Crve0zKhmYM3VVBK8b0FU8VODx50Th7evM60JxVal8V/1XZQiwLHjwA==", + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.1.0", + "kareem": "3.4.0", + "mongodb": "~7.7", + "mpath": "0.9.0", + "mquery": "6.0.0", + "ms": "2.1.3", + "sift": "17.1.3" + }, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mongoose" + } + }, + "node_modules/mpath": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/mpath/-/mpath-0.9.0.tgz", + "integrity": "sha512-ikJRQTk8hw5DEoFVxHG1Gn9T/xcjtdnOKIU1JTmGjZZlg9LST2mBLmcX3/ICIbgJydT2GOc15RnNy5mHmzfSew==", + "license": "MIT", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/mquery": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/mquery/-/mquery-6.0.0.tgz", + "integrity": "sha512-b2KQNsmgtkscfeDgkYMcWGn9vZI9YoXh802VDEwE6qc50zxBFQ0Oo8ROkawbPAsXCY1/Z1yp0MagqsZStPWJjw==", + "license": "MIT", + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/sift": { + "version": "17.1.3", + "resolved": "https://registry.npmjs.org/sift/-/sift-17.1.3.tgz", + "integrity": "sha512-Rtlj66/b0ICeFzYTuNvX/EF1igRbbnGSvEyT79McoZa/DeGhMyC5pWKOEsZKnpkqtSeovd5FL/bjHWC3CIIvCQ==", + "license": "MIT" + }, + "node_modules/sparse-bitfield": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", + "integrity": "sha512-kvzhi7vqKTfkh0PZU+2D2PIllw2ymqJKujUcyPMd9Y75Nv4nPbGJZXNhxsgdQab2BmlDct1YnfQCguEvHr7VsQ==", + "license": "MIT", + "dependencies": { + "memory-pager": "^1.0.2" + } + }, + "node_modules/tr46": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz", + "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==", + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-url": { + "version": "14.2.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz", + "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==", + "license": "MIT", + "dependencies": { + "tr46": "^5.1.0", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + } + } +} diff --git a/compatibility/integrations/mongoose/package.json b/compatibility/integrations/mongoose/package.json new file mode 100644 index 0000000..7a7352c --- /dev/null +++ b/compatibility/integrations/mongoose/package.json @@ -0,0 +1,12 @@ +{ + "name": "documentdb-mongoose-compatibility", + "version": "1.0.0", + "private": true, + "license": "MIT", + "engines": { + "node": ">=24 <25" + }, + "dependencies": { + "mongoose": "9.11.0" + } +} diff --git a/compatibility/integrations/mongoose/profile.cjs b/compatibility/integrations/mongoose/profile.cjs new file mode 100644 index 0000000..7f932c2 --- /dev/null +++ b/compatibility/integrations/mongoose/profile.cjs @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. +// SPDX-License-Identifier: MIT + +"use strict"; + +const { randomUUID } = require("node:crypto"); +const mongoose = require("mongoose"); + +async function createFixture() { + const connection = mongoose.createConnection(); + try { + await connection.openUri("mongodb://db:10260", { + auth: { username: process.env.USERNAME, password: process.env.PASSWORD }, + authSource: "admin", + dbName: `compat_${randomUUID().replaceAll("-", "")}`, + directConnection: true, + tls: true, + tlsAllowInvalidCertificates: true, + serverSelectionTimeoutMS: 15000, + connectTimeoutMS: 10000, + socketTimeoutMS: 15000, + monitorCommands: true, + autoCreate: false, + autoIndex: false, + bufferCommands: false, + appName: "documentdb-mongoose-compatibility", + }); + const commands = []; + connection.getClient().on("commandStarted", event => commands.push(event.commandName)); + const schema = new mongoose.Schema({ + sku: String, + name: { type: String, required: true }, + price: { type: Number, min: 0 }, + tags: { type: [String], default: [] }, + active: { type: Boolean, default: true }, + big: mongoose.Schema.Types.BigInt, + decimal: mongoose.Schema.Types.Decimal128, + date: Date, + binary: Buffer, + nested: { label: String, value: Number }, + }, { timestamps: true, autoCreate: false, autoIndex: false, bufferCommands: false }); + schema.index({ sku: 1 }, { name: "sku_unique", unique: true }); + schema.index({ name: 1, price: -1 }, { name: "name_price" }); + const model = connection.model("Item", schema, "items"); + return { + connection, model, commands, + async close() { + try { + await connection.dropDatabase(); + } finally { + await connection.destroy(); + } + }, + }; + } catch (error) { + try { + await connection.destroy(); + } catch (cleanupError) { + throw new AggregateError([error, cleanupError], "Mongoose setup and cleanup failed"); + } + throw error; + } +} + +module.exports = { createFixture }; diff --git a/compatibility/integrations/mongoose/test_demonstration.cjs b/compatibility/integrations/mongoose/test_demonstration.cjs new file mode 100644 index 0000000..ca8849e --- /dev/null +++ b/compatibility/integrations/mongoose/test_demonstration.cjs @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. +// SPDX-License-Identifier: MIT + +"use strict"; + +const assert = require("node:assert/strict"); +const { register } = require("../../report.cjs"); +const { createFixture } = require("./profile.cjs"); + +async function test_failure_demonstration({ model }) { + await model.create({ name: "Item" }); + assert.equal(await model.countDocuments({}), 0, + "Intentional failure demonstration; not a compatibility regression"); +} + +register({ test_failure_demonstration }, createFixture, true); diff --git a/compatibility/integrations/mongoose/test_mongoose.cjs b/compatibility/integrations/mongoose/test_mongoose.cjs new file mode 100644 index 0000000..628be35 --- /dev/null +++ b/compatibility/integrations/mongoose/test_mongoose.cjs @@ -0,0 +1,229 @@ +// Copyright (c) Microsoft Corporation. +// SPDX-License-Identifier: MIT + +"use strict"; + +const assert = require("node:assert/strict"); +const mongoose = require("mongoose"); +const { register } = require("../../report.cjs"); +const { createFixture } = require("./profile.cjs"); + +async function test_authenticated_ping({ connection }) { + assert.equal((await connection.getClient().db("admin").command({ ping: 1 })).ok, 1); +} + +async function test_model_create({ model }) { + const created = await model.create({ sku: "one", name: "Item", price: "3.5" }); + assert.ok(created instanceof model); + assert.ok(created._id instanceof mongoose.Types.ObjectId); + assert.equal(created.isNew, false); + assert.equal(created.price, 3.5); + assert.equal(created.active, true); + assert.ok(created.createdAt instanceof Date); + assert.ok(created.updatedAt instanceof Date); + const actual = await model.findById(created._id); + assert.ok(actual instanceof model); + assert.deepEqual(actual.toObject(), created.toObject()); +} + +async function test_insert_many({ model }) { + const inserted = await model.insertMany([ + { sku: "one", name: "First", price: 3 }, + { sku: "two", name: "Second", price: 7 }, + ]); + assert.equal(inserted.length, 2); + assert.ok(inserted.every(document => document instanceof model && !document.isNew)); + assert.deepEqual( + await model.find().sort({ sku: 1 }).select({ _id: 0, sku: 1, price: 1 }).lean(), + [{ sku: "one", price: 3 }, { sku: "two", price: 7 }], + ); +} + +async function test_find_by_id({ model }) { + const created = await model.create({ name: "Item", price: 3 }); + const actual = await model.findById(created._id.toString()); + assert.ok(actual instanceof model); + assert.equal(actual.name, "Item"); + assert.ok(actual._id.equals(created._id)); + assert.equal(await model.findById(new mongoose.Types.ObjectId()), null); +} + +async function test_find_filter_projection_sort_limit({ model }) { + await model.insertMany([ + { name: "First", price: 3 }, { name: "Second", price: 7 }, { name: "Third", price: 11 }, + ]); + const documents = await model.find({ price: { $gte: "5" } }) + .select({ _id: 0, price: 1 }).sort({ price: -1 }).limit(1).lean(); + assert.deepEqual(documents, [{ price: 11 }]); +} + +async function test_cursor_batches({ model, commands }) { + await model.insertMany(Array.from({ length: 7 }, (_, price) => ({ name: "Item", price }))); + commands.length = 0; + const cursor = model.find().sort({ price: 1 }).cursor({ batchSize: 2 }); + const prices = []; + try { + for await (const document of cursor) { + assert.ok(document instanceof model); + prices.push(document.price); + } + } finally { + await cursor.close(); + } + assert.deepEqual(prices, [0, 1, 2, 3, 4, 5, 6]); + assert.ok(commands.includes("find")); + assert.ok(commands.includes("getMore")); +} + +async function test_count_documents({ model }) { + await model.insertMany([{ name: "First", price: 3 }, { name: "Second", price: 7 }]); + assert.equal(await model.countDocuments({}), 2); + assert.equal(await model.countDocuments({ price: { $gte: 5 } }), 1); + assert.equal(await model.countDocuments({ price: 99 }), 0); +} + +async function test_document_save({ model }) { + const document = new model({ name: "Original", price: 3 }); + await document.save(); + document.name = "Updated"; + assert.equal(document.isModified("name"), true); + await document.save(); + assert.equal(document.isModified("name"), false); + const actual = await model.findById(document._id); + assert.equal(actual.name, "Updated"); + assert.equal(actual.price, 3); + assert.ok(actual.updatedAt >= actual.createdAt); + assert.equal(await model.countDocuments({}), 1); +} + +async function test_update_one({ model }) { + await model.create({ sku: "one", name: "Item", price: 3 }); + const result = await model.updateOne({ sku: "one" }, { $set: { price: 7 } }); + assert.equal(result.acknowledged, true); + assert.deepEqual([result.matchedCount, result.modifiedCount, result.upsertedId], [1, 1, null]); + assert.equal((await model.findOne({ sku: "one" })).price, 7); +} + +async function test_find_one_and_update({ model }) { + await model.create({ sku: "one", name: "Item", tags: ["alpha"] }); + const document = await model.findOneAndUpdate( + { sku: "one" }, { $push: { tags: "beta" } }, { returnDocument: "after" }, + ); + assert.ok(document instanceof model); + assert.deepEqual(Array.from(document.tags), ["alpha", "beta"]); + assert.deepEqual((await model.findOne({ sku: "one" })).toObject(), document.toObject()); +} + +async function test_delete_one({ model }) { + await model.insertMany([{ sku: "one", name: "First" }, { sku: "two", name: "Second" }]); + const result = await model.deleteOne({ sku: "one" }); + assert.equal(result.acknowledged, true); + assert.equal(result.deletedCount, 1); + assert.deepEqual(await model.find().select({ _id: 0, sku: 1 }).lean(), [{ sku: "two" }]); +} + +async function test_delete_many({ model }) { + await model.insertMany([ + { name: "First", price: 0 }, { name: "Second", price: 1 }, { name: "Third", price: 2 }, + ]); + const result = await model.deleteMany({ price: { $lt: 2 } }); + assert.equal(result.acknowledged, true); + assert.equal(result.deletedCount, 2); + assert.deepEqual(await model.find().select({ _id: 0, price: 1 }).lean(), [{ price: 2 }]); +} + +async function test_aggregate({ model }) { + await model.insertMany([ + { name: "First", tags: ["alpha", "beta"] }, { name: "Second", tags: ["beta"] }, + ]); + const documents = await model.aggregate([ + { $unwind: "$tags" }, + { $group: { _id: "$tags", count: { $sum: 1 } } }, + { $sort: { _id: 1 } }, + ]); + assert.deepEqual(documents, [{ _id: "alpha", count: 1 }, { _id: "beta", count: 2 }]); +} + +async function test_schema_indexes({ model }) { + await model.createCollection(); + await model.syncIndexes(); + const indexes = Object.fromEntries((await model.listIndexes()).map(index => [index.name, index])); + assert.deepEqual(Object.keys(indexes).sort(), ["_id_", "name_price", "sku_unique"]); + assert.deepEqual(indexes.sku_unique.key, { sku: 1 }); + assert.equal(indexes.sku_unique.unique, true); + assert.deepEqual(indexes.name_price.key, { name: 1, price: -1 }); +} + +async function test_duplicate_key_error({ model }) { + await model.createCollection(); + await model.createIndexes(); + await model.create({ sku: "one", name: "Original" }); + await assert.rejects( + model.create({ sku: "one", name: "Duplicate" }), + { name: "MongoServerError", code: 11000 }, + ); + assert.deepEqual( + await model.find().select({ _id: 0, sku: 1, name: 1 }).lean(), + [{ sku: "one", name: "Original" }], + ); +} + +async function test_schema_validation({ model }) { + await assert.rejects(model.create({ price: -1 }), error => { + assert.ok(error instanceof mongoose.Error.ValidationError); + assert.equal(error.errors.name?.kind, "required"); + assert.equal(error.errors.price?.kind, "min"); + return true; + }); + assert.equal(await model.countDocuments({}), 0); + await model.create({ sku: "one", name: "Valid", price: 3 }); + await assert.rejects( + model.updateOne({ sku: "one" }, { $set: { price: -1 } }, { runValidators: true }), + error => { + assert.ok(error instanceof mongoose.Error.ValidationError); + assert.equal(error.errors.price?.kind, "min"); + return true; + }, + ); + assert.equal((await model.findOne({ sku: "one" })).price, 3); + assert.equal(await model.countDocuments({}), 1); +} + +async function test_bson_round_trip({ model }) { + const document = { + _id: new mongoose.Types.ObjectId(), + name: "Typed", + price: 2.5, + big: (2n ** 60n) + 7n, + decimal: mongoose.Types.Decimal128.fromString("3.14"), + date: new Date("2024-01-01T00:00:00.000Z"), + binary: Buffer.from([0, 255]), + tags: ["one", "two"], + active: false, + nested: { label: "Child", value: 7 }, + }; + await model.create(document); + const actual = await model.findById(document._id); + assert.ok(actual instanceof model); + assert.ok(actual._id instanceof mongoose.Types.ObjectId); + assert.ok(actual._id.equals(document._id)); + assert.equal(actual.price, document.price); + assert.equal(actual.big, document.big); + assert.ok(actual.decimal instanceof mongoose.Types.Decimal128); + assert.equal(actual.decimal.toString(), "3.14"); + assert.ok(actual.date instanceof Date); + assert.equal(actual.date.toISOString(), document.date.toISOString()); + assert.ok(Buffer.isBuffer(actual.binary)); + assert.deepEqual(Buffer.from(actual.binary), document.binary); + assert.deepEqual(Array.from(actual.tags), document.tags); + assert.equal(actual.active, false); + assert.deepEqual(actual.toObject().nested, document.nested); +} + +register({ + test_authenticated_ping, test_model_create, test_insert_many, test_find_by_id, + test_find_filter_projection_sort_limit, test_cursor_batches, test_count_documents, + test_document_save, test_update_one, test_find_one_and_update, test_delete_one, + test_delete_many, test_aggregate, test_schema_indexes, test_duplicate_key_error, + test_schema_validation, test_bson_round_trip, +}, createFixture); diff --git a/compatibility/integrations/nodejs/Dockerfile b/compatibility/integrations/nodejs/Dockerfile new file mode 100644 index 0000000..1305960 --- /dev/null +++ b/compatibility/integrations/nodejs/Dockerfile @@ -0,0 +1,16 @@ +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: MIT + +FROM node:24.21.0-bookworm-slim@sha256:5cbc7caba8c2c0f0bca675d1b61b9f2857e1cf1853c6164ee9dd409501a936e7 + +WORKDIR /app +COPY npm-packages /npm-packages +COPY package.json package-lock.json ./ +RUN for package in /npm-packages/*.tgz; do npm cache add --offline --ignore-scripts "$package"; done \ + && npm ci --offline --ignore-scripts --engine-strict --omit=optional --no-audit --no-fund \ + && npm cache clean --force +COPY install-report.json /install-report.json +COPY compatibility /app/compatibility +USER node +ENV COMPATIBILITY_ACTIVE=1 +ENTRYPOINT ["node", "compatibility/client.cjs"] diff --git a/compatibility/integrations/nodejs/package-lock.json b/compatibility/integrations/nodejs/package-lock.json new file mode 100644 index 0000000..6a2b933 --- /dev/null +++ b/compatibility/integrations/nodejs/package-lock.json @@ -0,0 +1,169 @@ +{ + "name": "documentdb-nodejs-compatibility", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "documentdb-nodejs-compatibility", + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "mongodb": "7.7.0" + }, + "engines": { + "node": ">=24 <25" + } + }, + "node_modules/@mongodb-js/saslprep": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.5.4.tgz", + "integrity": "sha512-05UC0jQsjKAOuXQ0H9Ud9vUTJpZIg+n/FinpR30tI5I8pY2inTfPOZ5OF/cg3Ce/N9MoD1xhRCeOsJtuTbFYlw==", + "license": "MIT", + "dependencies": { + "sparse-bitfield": "^3.0.3" + } + }, + "node_modules/@types/webidl-conversions": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.3.tgz", + "integrity": "sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==", + "license": "MIT" + }, + "node_modules/@types/whatwg-url": { + "version": "13.0.0", + "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-13.0.0.tgz", + "integrity": "sha512-N8WXpbE6Wgri7KUSvrmQcqrMllKZ9uxkYWMt+mCSGwNc0Hsw9VQTW7ApqI4XNrx6/SaM2QQJCzMPDEXE058s+Q==", + "license": "MIT", + "dependencies": { + "@types/webidl-conversions": "*" + } + }, + "node_modules/bson": { + "version": "7.3.3", + "resolved": "https://registry.npmjs.org/bson/-/bson-7.3.3.tgz", + "integrity": "sha512-oz3LwE3qGEhTCSyhzQRLY3Bj1NLOsjFMf6tcmY5J8M+3R7EVcmoBfSHWvjUK3yXCLDUsGpIuB3aQL4nDZ1EV/g==", + "license": "Apache-2.0", + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/memory-pager": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", + "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==", + "license": "MIT" + }, + "node_modules/mongodb": { + "version": "7.7.0", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-7.7.0.tgz", + "integrity": "sha512-XG1xXEqyouAV8GCb3PuRaujofeXKpAJAPvXYWZgHl6Dz4QHSJ1nRLl0+GpqaLTwKvC0RFE9truOur34RNFY1nw==", + "license": "Apache-2.0", + "dependencies": { + "@mongodb-js/saslprep": "^1.5.0", + "bson": "^7.3.2", + "mongodb-connection-string-url": "^7.0.2" + }, + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@aws-sdk/credential-providers": "^3.806.0", + "@mongodb-js/zstd": "^7.0.0", + "gcp-metadata": "^7.0.1", + "kerberos": "^7.0.0", + "mongodb-client-encryption": "^7.2.0", + "snappy": "^7.3.2", + "socks": "^2.8.6" + }, + "peerDependenciesMeta": { + "@aws-sdk/credential-providers": { + "optional": true + }, + "@mongodb-js/zstd": { + "optional": true + }, + "gcp-metadata": { + "optional": true + }, + "kerberos": { + "optional": true + }, + "mongodb-client-encryption": { + "optional": true + }, + "snappy": { + "optional": true + }, + "socks": { + "optional": true + } + } + }, + "node_modules/mongodb-connection-string-url": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-7.0.2.tgz", + "integrity": "sha512-ZoS07RoFqpKYQwAk59qmrx8+jJHNHU30UjlU96QktiGn1ltvDr+vCznLX5DiUBLEpMAHatHNWV1nM/74ul66kA==", + "license": "Apache-2.0", + "dependencies": { + "@types/whatwg-url": "^13.0.0", + "whatwg-url": "^14.1.0" + }, + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/sparse-bitfield": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", + "integrity": "sha512-kvzhi7vqKTfkh0PZU+2D2PIllw2ymqJKujUcyPMd9Y75Nv4nPbGJZXNhxsgdQab2BmlDct1YnfQCguEvHr7VsQ==", + "license": "MIT", + "dependencies": { + "memory-pager": "^1.0.2" + } + }, + "node_modules/tr46": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz", + "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==", + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-url": { + "version": "14.2.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz", + "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==", + "license": "MIT", + "dependencies": { + "tr46": "^5.1.0", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + } + } +} diff --git a/compatibility/integrations/nodejs/package.json b/compatibility/integrations/nodejs/package.json new file mode 100644 index 0000000..b1c2718 --- /dev/null +++ b/compatibility/integrations/nodejs/package.json @@ -0,0 +1,12 @@ +{ + "name": "documentdb-nodejs-compatibility", + "version": "1.0.0", + "private": true, + "license": "MIT", + "engines": { + "node": ">=24 <25" + }, + "dependencies": { + "mongodb": "7.7.0" + } +} diff --git a/compatibility/integrations/nodejs/profile.cjs b/compatibility/integrations/nodejs/profile.cjs new file mode 100644 index 0000000..d75144f --- /dev/null +++ b/compatibility/integrations/nodejs/profile.cjs @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. +// SPDX-License-Identifier: MIT + +"use strict"; + +const { randomUUID } = require("node:crypto"); + +function createFixture() { + const { MongoClient } = require("mongodb"); + const client = new MongoClient("mongodb://db:10260", { + auth: { username: process.env.USERNAME, password: process.env.PASSWORD }, + authSource: "admin", + directConnection: true, + tls: true, + tlsAllowInvalidCertificates: true, + serverSelectionTimeoutMS: 15000, + connectTimeoutMS: 10000, + socketTimeoutMS: 15000, + monitorCommands: true, + appName: "documentdb-nodejs-compatibility", + }); + const commands = []; + client.on("commandStarted", event => commands.push(event.commandName)); + const database = client.db(`compat_${randomUUID().replaceAll("-", "")}`); + return { + client, database, collection: database.collection("items"), commands, + async close() { + try { + await database.dropDatabase(); + } finally { + await client.close(); + } + }, + }; +} + +module.exports = { createFixture }; diff --git a/compatibility/integrations/nodejs/test_demonstration.cjs b/compatibility/integrations/nodejs/test_demonstration.cjs new file mode 100644 index 0000000..10b98ff --- /dev/null +++ b/compatibility/integrations/nodejs/test_demonstration.cjs @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. +// SPDX-License-Identifier: MIT + +"use strict"; + +const assert = require("node:assert/strict"); +const { register } = require("../../report.cjs"); +const { createFixture } = require("./profile.cjs"); + +async function test_failure_demonstration({ collection }) { + await collection.insertOne({ _id: 1 }); + assert.equal(await collection.countDocuments({}), 0, + "Intentional failure demonstration; not a compatibility regression"); +} + +register({ test_failure_demonstration }, createFixture, true); diff --git a/compatibility/integrations/nodejs/test_nodejs.cjs b/compatibility/integrations/nodejs/test_nodejs.cjs new file mode 100644 index 0000000..7aff3ad --- /dev/null +++ b/compatibility/integrations/nodejs/test_nodejs.cjs @@ -0,0 +1,179 @@ +// Copyright (c) Microsoft Corporation. +// SPDX-License-Identifier: MIT + +"use strict"; + +const assert = require("node:assert/strict"); +const { Decimal128, Long, ObjectId } = require("mongodb"); +const { register } = require("../../report.cjs"); +const { createFixture } = require("./profile.cjs"); + +async function test_authenticated_ping({ client }) { + assert.equal((await client.db("admin").command({ ping: 1 })).ok, 1); +} + +async function test_insert_one({ collection }) { + const document = { value: 3 }; + const result = await collection.insertOne(document); + assert.equal(result.acknowledged, true); + assert.ok(result.insertedId instanceof ObjectId); + assert.deepEqual(await collection.findOne({ _id: result.insertedId }), document); +} + +async function test_insert_many({ collection }) { + const documents = [{ _id: 1, value: 3 }, { _id: 2, value: 7 }]; + const result = await collection.insertMany(documents); + assert.equal(result.acknowledged, true); + assert.deepEqual(Object.values(result.insertedIds), [1, 2]); + assert.deepEqual(await collection.find().sort({ _id: 1 }).toArray(), documents); +} + +async function test_find_one({ collection }) { + const document = { _id: 1, value: 3 }; + await collection.insertOne(document); + assert.deepEqual(await collection.findOne({ _id: 1 }), document); + assert.equal(await collection.findOne({ _id: 2 }), null); +} + +async function test_find_filter_projection_sort_limit({ collection }) { + await collection.insertMany([{ _id: 1, price: 3 }, { _id: 2, price: 7 }, { _id: 3, price: 11 }]); + const documents = await collection.find({ price: { $gte: 5 } }, { projection: { _id: 0, price: 1 } }) + .sort({ price: -1 }).limit(1).toArray(); + assert.deepEqual(documents, [{ price: 11 }]); +} + +async function test_cursor_batches({ collection, commands }) { + const documents = Array.from({ length: 7 }, (_, _id) => ({ _id })); + await collection.insertMany(documents); + commands.length = 0; + const cursor = collection.find().sort({ _id: 1 }).batchSize(2); + const actual = []; + try { + for await (const document of cursor) actual.push(document); + } finally { + await cursor.close(); + } + assert.deepEqual(actual, documents); + assert.ok(commands.includes("find")); + assert.ok(commands.includes("getMore")); +} + +async function test_count_documents({ collection }) { + await collection.insertMany([{ _id: 1, value: 3 }, { _id: 2, value: 7 }]); + assert.equal(await collection.countDocuments({}), 2); + assert.equal(await collection.countDocuments({ value: { $gte: 5 } }), 1); + assert.equal(await collection.countDocuments({ value: 99 }), 0); +} + +async function test_update_one({ collection }) { + await collection.insertOne({ _id: 1, value: 3 }); + const result = await collection.updateOne({ _id: 1 }, { $set: { value: 7 } }); + assert.equal(result.acknowledged, true); + assert.deepEqual([result.matchedCount, result.modifiedCount, result.upsertedId], [1, 1, null]); + assert.deepEqual(await collection.findOne({ _id: 1 }), { _id: 1, value: 7 }); +} + +async function test_find_one_and_update({ collection }) { + await collection.insertOne({ _id: 1, tags: ["alpha"] }); + const document = await collection.findOneAndUpdate( + { _id: 1 }, { $push: { tags: "beta" } }, + { returnDocument: "after", includeResultMetadata: false }, + ); + assert.deepEqual(document, { _id: 1, tags: ["alpha", "beta"] }); + assert.deepEqual(await collection.findOne({ _id: 1 }), document); +} + +async function test_delete_one({ collection }) { + await collection.insertMany([{ _id: 1 }, { _id: 2 }]); + const result = await collection.deleteOne({ _id: 1 }); + assert.equal(result.acknowledged, true); + assert.equal(result.deletedCount, 1); + assert.deepEqual(await collection.find().toArray(), [{ _id: 2 }]); +} + +async function test_delete_many({ collection }) { + await collection.insertMany([{ _id: 0 }, { _id: 1 }, { _id: 2 }]); + const result = await collection.deleteMany({ _id: { $lt: 2 } }); + assert.equal(result.acknowledged, true); + assert.equal(result.deletedCount, 2); + assert.deepEqual(await collection.find().toArray(), [{ _id: 2 }]); +} + +async function test_aggregate({ collection }) { + await collection.insertMany([{ _id: 1, tags: ["alpha", "beta"] }, { _id: 2, tags: ["beta"] }]); + const documents = await collection.aggregate([ + { $unwind: "$tags" }, + { $group: { _id: "$tags", count: { $sum: 1 } } }, + { $sort: { _id: 1 } }, + ]).toArray(); + assert.deepEqual(documents, [{ _id: "alpha", count: 1 }, { _id: "beta", count: 2 }]); +} + +async function test_create_indexes({ collection }) { + const names = await collection.createIndexes([ + { key: { sku: 1 }, name: "sku_unique", unique: true }, + { key: { name: 1, price: -1 }, name: "name_price" }, + ]); + assert.deepEqual(names, ["sku_unique", "name_price"]); + const indexes = Object.fromEntries((await collection.indexes()).map(index => [index.name, index])); + assert.deepEqual(indexes.sku_unique.key, { sku: 1 }); + assert.equal(indexes.sku_unique.unique, true); + assert.deepEqual(indexes.name_price.key, { name: 1, price: -1 }); +} + +async function test_list_indexes({ collection }) { + await collection.insertOne({ _id: 1, value: 3 }); + await collection.createIndex({ value: 1 }, { name: "value_1" }); + const indexes = Object.fromEntries((await collection.listIndexes().toArray()).map(index => [index.name, index])); + assert.deepEqual(Object.keys(indexes).sort(), ["_id_", "value_1"]); + assert.deepEqual(indexes.value_1.key, { value: 1 }); +} + +async function test_drop_index({ collection }) { + await collection.insertOne({ _id: 1, value: 3 }); + await collection.createIndex({ value: 1 }, { name: "value_1" }); + await collection.dropIndex("value_1"); + assert.deepEqual((await collection.listIndexes().toArray()).map(index => index.name), ["_id_"]); +} + +async function test_duplicate_key_error({ collection }) { + await collection.createIndex({ sku: 1 }, { unique: true }); + await collection.insertOne({ _id: 1, sku: "one" }); + await assert.rejects( + collection.insertOne({ _id: 2, sku: "one" }), + { name: "MongoServerError", code: 11000 }, + ); + assert.deepEqual(await collection.find().toArray(), [{ _id: 1, sku: "one" }]); +} + +async function test_bson_round_trip({ collection }) { + const document = { + _id: new ObjectId(), + integer: 7, + long: Long.fromBigInt(2n ** 40n), + double: 2.5, + decimal: Decimal128.fromString("3.14"), + date: new Date("2024-01-01T00:00:00.000Z"), + binary: Buffer.from([0, 255]), + array: [1, "two", null], + boolean: true, + }; + await collection.insertOne(document); + const actual = await collection.findOne( + { _id: document._id }, { promoteLongs: false, promoteBuffers: true }, + ); + assert.deepEqual(actual, document); + assert.ok(actual._id instanceof ObjectId); + assert.ok(actual.long instanceof Long); + assert.ok(actual.decimal instanceof Decimal128); + assert.ok(actual.date instanceof Date); + assert.ok(Buffer.isBuffer(actual.binary)); +} + +register({ + 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, +}, createFixture); diff --git a/compatibility/npm.py b/compatibility/npm.py new file mode 100644 index 0000000..e85d2fd --- /dev/null +++ b/compatibility/npm.py @@ -0,0 +1,140 @@ +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: MIT + +"""Prepare verified npm archives without executing package code in the controller.""" + +from __future__ import annotations + +import base64 +import hashlib +import json +import os +import re +import shutil +import tempfile +import urllib.parse +import urllib.request +from pathlib import Path +from typing import Any + +from compatibility.contracts import ROOT, suite_files + +REGISTRY = "https://registry.npmjs.org" +MAX_PACKAGE_BYTES = 32 * 1024 * 1024 +PACKAGE_NAME = r"(?:@[a-z0-9][a-z0-9_.-]*/)?[a-z0-9][a-z0-9_.-]*" +PACKAGE_PATH = rf"node_modules/{PACKAGE_NAME}(?:/node_modules/{PACKAGE_NAME})*" + + +def registry_bytes(url: str, limit: int) -> bytes: + """Keep metadata and package downloads bounded and on the public registry.""" + validate_registry_url(url) + with urllib.request.urlopen(url, timeout=30) as response: + if response.geturl() != url: + raise ValueError("Unexpected npm registry redirect") + content: bytes = response.read(limit + 1) + if len(content) > limit: + raise ValueError("npm registry response exceeded its size limit") + return content + + +def validate_registry_url(url: str) -> None: + parsed = urllib.parse.urlsplit(url) + if parsed.scheme != "https" or parsed.netloc != "registry.npmjs.org": + raise ValueError("Package URL is outside the reviewed npm registry") + + +def verify_integrity(content: bytes, integrity: str) -> str: + """Check npm's published SHA-512 integrity before recording the archive SHA-256.""" + if not integrity.startswith("sha512-"): + raise ValueError("npm archive requires SHA-512 integrity") + expected = base64.b64decode(integrity.removeprefix("sha512-"), validate=True) + if hashlib.sha512(content).digest() != expected: + raise ValueError("npm archive does not match its published integrity") + return hashlib.sha256(content).hexdigest() + + +def prepare_node_client( + context: Path, + spec: dict[str, Any], + version: str, + package_cache: Path | None = None, +) -> str: + """Verify every archive against the reviewed lockfile before an offline installation.""" + integration = Path(spec["test_file"]).parent.name + for source in suite_files(integration): + destination = context / source.relative_to(ROOT) + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, destination) + adapter = context / Path(spec["test_file"]).parent + manifest = json.loads((adapter / "package.json").read_text()) + lock = json.loads((adapter / "package-lock.json").read_text()) + if ( + manifest["dependencies"] != {spec["package"]: version} + or lock.get("lockfileVersion") != 3 + or not isinstance(lock.get("packages"), dict) + or not 2 <= len(lock["packages"]) <= 101 + or lock["packages"].get("", {}).get("dependencies") != {spec["package"]: version} + ): + raise ValueError("npm lockfile does not match the selected integration") + packages = context / "npm-packages" + packages.mkdir() + if package_cache is not None: + if package_cache.is_symlink(): + raise ValueError("npm package cache must not be a symbolic link") + package_cache.mkdir(parents=True, exist_ok=True) + installed = [] + verified: dict[tuple[str, str], tuple[str, str, str]] = {} + selected = None + for path, entry in lock["packages"].items(): + if path == "" or entry.get("optional"): + continue + if not re.fullmatch(PACKAGE_PATH, path) or entry.get("link"): + raise ValueError("npm lockfile contains an unsupported package location") + name = path.rsplit("node_modules/", 1)[1] + package_version = entry["version"] + if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+(?:[-+][a-zA-Z0-9.-]+)?", package_version): + raise ValueError("npm lockfile contains an invalid package version") + identity = (name, package_version) + if identity not in verified: + archive_url = entry["resolved"] + validate_registry_url(archive_url) + integrity = entry["integrity"] + cache_name = hashlib.sha256(integrity.encode()).hexdigest() + ".tgz" + cached = package_cache / cache_name if package_cache is not None else None + if cached is not None and (cached.exists() or cached.is_symlink()): + if ( + cached.is_symlink() + or not cached.is_file() + or cached.stat().st_size > MAX_PACKAGE_BYTES + ): + raise ValueError("npm package cache entry must be a bounded regular file") + with cached.open("rb") as file: + content = file.read(MAX_PACKAGE_BYTES + 1) + if len(content) > MAX_PACKAGE_BYTES: + raise ValueError("npm package cache entry exceeded its size limit") + else: + content = registry_bytes(archive_url, MAX_PACKAGE_BYTES) + digest = verify_integrity(content, integrity) + if cached is not None and not cached.exists(): + with tempfile.NamedTemporaryFile(dir=package_cache, delete=False) as temporary: + temporary.write(content) + try: + os.replace(temporary.name, cached) + finally: + Path(temporary.name).unlink(missing_ok=True) + (packages / f"{digest}.tgz").write_bytes(content) + verified[identity] = (archive_url, integrity, digest) + archive_url, integrity, digest = verified[identity] + if entry["resolved"] != archive_url or entry["integrity"] != integrity: + raise ValueError("Conflicting npm artifacts for the same package version") + installed.append({"path": path, "name": name, "version": package_version, "sha256": digest}) + if path == f"node_modules/{spec['package']}": + if package_version != version: + raise ValueError("Locked driver version does not match the request") + selected = digest + if selected is None: + raise ValueError("npm lockfile is missing the selected driver") + (context / "package.json").write_text(json.dumps(manifest)) + (context / "package-lock.json").write_text(json.dumps(lock)) + (context / "install-report.json").write_text(json.dumps({"install": installed})) + return selected 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..b110a3b --- /dev/null +++ b/compatibility/publish.py @@ -0,0 +1,133 @@ +# 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", + preview: bool = False, + 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"))] + rows = dashboard_rows(results, registry, now, issue_repository, expected_runs=expected_runs) + if preview: + for row in rows: + row["issue_url"] = None + 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, preview=preview + ) + (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") + parser.add_argument( + "--preview", action="store_true", help="Label a demo site; hide issue links" + ) + 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) + 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, + preview=args.preview, + ) + print(f"Dashboard rendered at {args.site / 'index.html'}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/compatibility/registry.yaml b/compatibility/registry.yaml index 6c878b4..4d19f35 100644 --- a/compatibility/registry.yaml +++ b/compatibility/registry.yaml @@ -36,3 +36,65 @@ integrations: - test_drop_index - test_duplicate_key_error - test_bson_round_trip + mongoose: + repository: https://github.com/Automattic/mongoose + owner: "@documentdb/documentdb-maintainers" + enabled: true + runtime: nodejs + package: mongoose + default_version: "9.11.0" + version_pattern: '^9\.11\.0$' + profile: node24-linux-x64-mongoose + test_file: compatibility/integrations/mongoose/test_mongoose.cjs + demonstration_file: compatibility/integrations/mongoose/test_demonstration.cjs + timeout_seconds: 300 + freshness_days: 7 + expected_tests: + - test_authenticated_ping + - test_model_create + - test_insert_many + - test_find_by_id + - test_find_filter_projection_sort_limit + - test_cursor_batches + - test_count_documents + - test_document_save + - test_update_one + - test_find_one_and_update + - test_delete_one + - test_delete_many + - test_aggregate + - test_schema_indexes + - test_duplicate_key_error + - test_schema_validation + - test_bson_round_trip + nodejs: + repository: https://github.com/mongodb/node-mongodb-native + owner: "@documentdb/documentdb-maintainers" + enabled: true + runtime: nodejs + package: mongodb + default_version: "7.7.0" + version_pattern: '^7\.7\.0$' + profile: node24-linux-x64-async + test_file: compatibility/integrations/nodejs/test_nodejs.cjs + demonstration_file: compatibility/integrations/nodejs/test_demonstration.cjs + 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/report.cjs b/compatibility/report.cjs new file mode 100644 index 0000000..cf37740 --- /dev/null +++ b/compatibility/report.cjs @@ -0,0 +1,112 @@ +// Copyright (c) Microsoft Corporation. +// SPDX-License-Identifier: MIT + +"use strict"; + +const { test } = require("node:test"); + +function classify(error) { + if (error?.code === "ERR_TEST_FAILURE") { + if (error.failureType !== "testCodeFailure") return "error"; + return classify(error.cause); + } + if (error?.code === "ERR_ASSERTION" || error?.name === "AssertionError") return "failed"; + if (["ValidationError", "CastError", "VersionError", "DocumentNotFoundError"].includes(error?.name)) { + return "failed"; + } + if (["MongoServerError", "MongoBulkWriteError", "MongoUnexpectedServerResponseError"].includes(error?.name)) { + return [50, 262].includes(error.code) ? "error" : "failed"; + } + return "error"; +} + +async function runScenario(createFixture, body) { + let fixture; + try { + fixture = await createFixture(); + } catch (error) { + throw new Error(`Fixture setup failed: ${error}`, { cause: error }); + } + let failure; + let failed = false; + try { + await body(fixture); + } catch (error) { + failed = true; + failure = error; + } + try { + await fixture.close(); + } catch (error) { + if (failed && classify(failure) === "failed") { + process.stderr.write(`Fixture cleanup also failed: ${error}\n`); + } else { + failure = new Error(`Fixture cleanup failed: ${error}`, { cause: error }); + failed = true; + } + } + if (failed) throw failure; +} + +function register(scenarios, createFixture, demonstration = false) { + const skip = process.env.COMPATIBILITY_ACTIVE !== "1" + || (demonstration && process.env.COMPATIBILITY_DEMONSTRATION !== "1"); + for (const [name, body] of Object.entries(scenarios)) { + test(name, { skip }, () => runScenario(createFixture, body)); + } +} + +function message(error) { + return [error?.stack || String(error), error?.cause?.stack || ""].filter(Boolean).join("\n").slice(0, 2000); +} + +async function collect(events) { + const tests = new Map(); + let successful = false; + for await (const { type, data } of events) { + if (type === "test:stderr" || type === "test:stdout") { + process.stderr.write(data.message); + } + if (type === "test:diagnostic") process.stderr.write(`${data.message}\n`); + if (type === "test:summary") successful = data.success === true; + if (type !== "test:pass" && type !== "test:fail") continue; + if (!/^test_[a-z0-9_]+$/.test(data.name)) { + if (type === "test:fail" && data.details.error?.failureType !== "subtestsFailed") { + throw data.details.error; + } + continue; + } + if (tests.has(data.name)) throw new Error("Duplicate scenario names are not supported"); + const outcome = data.skip || data.todo ? "skipped" + : type === "test:pass" ? "passed" : classify(data.details.error); + tests.set(data.name, { + id: data.name, + outcome, + message: outcome === "passed" ? "" : data.skip || data.todo + ? String(data.skip || data.todo) : message(data.details.error), + }); + } + const results = [...tests.values()]; + if (!successful && !results.some(test => ["failed", "error"].includes(test.outcome))) { + throw new Error("Test execution did not complete successfully"); + } + return results; +} + +function xml(value) { + return String(value).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g, "") + .replace(/[&<>"']/g, character => ({ + "&": "&", "<": "<", ">": ">", "\"": """, "'": "'", + })[character]); +} + +function junit(tests, integration) { + const count = outcome => tests.filter(test => test.outcome === outcome).length; + const cases = tests.map(test => { + const tag = { failed: "failure", error: "error", skipped: "skipped" }[test.outcome]; + return `${tag ? `<${tag}>${xml(test.message)}` : ""}`; + }).join(""); + return `${cases}`; +} + +module.exports = { classify, collect, junit, register, runScenario }; 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/runner.py b/compatibility/runner.py index db76969..eb02520 100644 --- a/compatibility/runner.py +++ b/compatibility/runner.py @@ -38,6 +38,7 @@ validate_client_report, validate_result, ) +from compatibility.npm import prepare_node_client LABEL = "org.documentdb.compatibility.run" MAX_COMMAND_OUTPUT = 4 * 1024 * 1024 @@ -204,6 +205,7 @@ def execute( output: Path, *, wheelhouse: Path | None = None, + package_cache: Path | None = None, demonstration: bool = False, run_url: str | None = None, trigger: str = "manual", @@ -217,8 +219,10 @@ def execute( 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 wheelhouse is not None and spec["runtime"] != "python": + raise ValueError("--wheelhouse is only supported by Python integrations") + if package_cache is not None and spec["runtime"] != "nodejs": + raise ValueError("--package-cache is only supported by Node integrations") if output.suffix != ".json": raise ValueError("Result output must use a .json extension") if any( @@ -267,7 +271,10 @@ def execute( with tempfile.TemporaryDirectory(prefix="docdb-compat-") as directory: context = Path(directory) / "context" context.mkdir() - digest = prepare_client(context, spec, version, wheelhouse) + if spec["runtime"] == "python": + digest = prepare_client(context, spec, version, wheelhouse) + else: + digest = prepare_node_client(context, spec, version, package_cache) result["upstream"]["artifact_sha256"] = digest result["suite_digest"] = suite_digest(integration, spec, root=context) candidate_image = f"docdb-compat-{run_id}" @@ -454,6 +461,7 @@ def main() -> int: ) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--wheelhouse", type=Path) + parser.add_argument("--package-cache", type=Path, help="Reuse integrity-checked npm archives") parser.add_argument("--run-url") parser.add_argument( "--trigger", @@ -472,6 +480,7 @@ def main() -> int: args.documentdb_version or default_documentdb_version(registry), args.output, wheelhouse=args.wheelhouse, + package_cache=args.package_cache, demonstration=args.demonstration, run_url=args.run_url, trigger=args.trigger, diff --git a/compatibility/unit/test_contracts.py b/compatibility/unit/test_contracts.py index f558c7e..a165c7f 100644 --- a/compatibility/unit/test_contracts.py +++ b/compatibility/unit/test_contracts.py @@ -187,6 +187,29 @@ def test_legacy_python_records_remain_unchanged_and_readable(record, registry): assert record == original +@pytest.mark.parametrize("integration", ["nodejs", "mongoose"]) +def test_node_result_and_scoped_dependency_names_are_valid(record, registry, integration): + spec = registry["integrations"][integration] + record.update( + integration=integration, **{key: spec[key] for key in ("repository", "owner", "profile")} + ) + record["expected_tests"] = list(spec["expected_tests"]) + record["tests"] = [ + {"id": name, "outcome": "passed", "message": ""} for name in spec["expected_tests"] + ] + record["upstream"].update( + version=spec["default_version"], + actual_version=spec["default_version"], + runtime={"name": "nodejs", "version": "24.0.0"}, + ) + record["upstream"]["dependencies"] = [ + {"name": spec["package"], "version": spec["default_version"], "sha256": "b" * 64}, + {"name": "@example/dependency", "version": "1.0.0", "sha256": "d" * 64}, + ] + validate_result(record, spec) + assert compatibility_state(record) == "Working" + + @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} @@ -219,6 +242,7 @@ def test_prepared_build_context_preserves_the_reviewed_suite(prepared_context, r "compatibility/pyproject.toml", "compatibility/schemas/result.json", "compatibility/runner.py", + "compatibility/npm.py", "compatibility/integrations/pymongo/Dockerfile", "compatibility/integrations/pymongo/requirements.txt", ], 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_nodejs.cjs b/compatibility/unit/test_nodejs.cjs new file mode 100644 index 0000000..3ee3c8b --- /dev/null +++ b/compatibility/unit/test_nodejs.cjs @@ -0,0 +1,177 @@ +// Copyright (c) Microsoft Corporation. +// SPDX-License-Identifier: MIT + +"use strict"; + +const assert = require("node:assert/strict"); +const { spawnSync } = require("node:child_process"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); +const { test } = require("node:test"); +const { classify, collect, junit, runScenario } = require("../report.cjs"); +const reporter = path.resolve(__dirname, "../report.cjs"); + +function execute(source) { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "compat-node-unit-")); + const profile = path.join(directory, "profile.cjs"); + fs.writeFileSync(profile, source); + const environment = { ...process.env }; + delete environment.NODE_TEST_CONTEXT; + try { + return spawnSync(process.execPath, ["-e", ` + const { run } = require("node:test"); + const { collect } = require(${JSON.stringify(reporter)}); + collect(run({ files: [process.argv[1]], concurrency: 1, isolation: "none" })) + .then(tests => { + process.stdout.write(JSON.stringify(tests)); + process.exitCode = tests.some(test => ["failed", "error"].includes(test.outcome)) ? 1 : 0; + }) + .catch(error => { console.error(error); process.exitCode = 2; }); + `, profile], { encoding: "utf8", timeout: 10000, env: environment }); + } finally { + fs.rmSync(directory, { recursive: true }); + } +} + +for (const [name, body, outcome] of [ + ["pass", "", "passed"], + ["assertion", "require('node:assert/strict').fail('Mismatch')", "failed"], + ["missing-exception", "await require('node:assert/strict').rejects(Promise.resolve())", "failed"], + ["operation", "throw Object.assign(new Error('Unsupported'), {name:'MongoServerError', code:115})", "failed"], + ["model-validation", "throw Object.assign(new Error('Unexpected validation'), {name:'ValidationError'})", "failed"], + ["model-cast", "throw Object.assign(new Error('Unexpected cast'), {name:'CastError'})", "failed"], + ["model-version", "throw Object.assign(new Error('Version conflict'), {name:'VersionError'})", "failed"], + ["model-missing-document", "throw Object.assign(new Error('Missing document'), {name:'DocumentNotFoundError'})", "failed"], + ["timeout", "throw Object.assign(new Error('Timed out'), {name:'MongoServerError', code:50})", "error"], + ["network", "throw Object.assign(new Error('Unavailable'), {name:'MongoNetworkError'})", "error"], + ["runtime", "throw new TypeError('Invalid execution')", "error"], +]) { + test(`production reporter classifies ${name}`, () => { + const result = execute(`require("node:test").test("test_profile", async () => { ${body}; });`); + assert.equal(result.status, outcome === "passed" ? 0 : 1, result.stderr); + const records = JSON.parse(result.stdout); + assert.equal(records.length, 1); + assert.equal(records[0].id, "test_profile"); + assert.equal(records[0].outcome, outcome); + }); +} + +for (const option of ["skip", "todo"]) { + test(`${option} is not a passing scenario`, () => { + const result = execute(`require("node:test").test("test_profile", {${option}:true}, () => {});`); + assert.equal(result.status, 0, result.stderr); + assert.equal(JSON.parse(result.stdout)[0].outcome, "skipped"); + }); +} + +for (const [active, demonstration, demoScenario, outcome] of [ + [false, false, false, "skipped"], + [true, false, false, "passed"], + [true, false, true, "skipped"], + [true, true, true, "passed"], +]) { + test(`shared registration gates active=${active} demonstration=${demonstration} scenario=${demoScenario}`, () => { + const result = execute(` + process.env.COMPATIBILITY_ACTIVE = ${JSON.stringify(active ? "1" : "0")}; + process.env.COMPATIBILITY_DEMONSTRATION = ${JSON.stringify(demonstration ? "1" : "0")}; + const {register} = require(${JSON.stringify(reporter)}); + register({ test_profile() {} }, () => ({ close() {} }), ${demoScenario}); + `); + assert.equal(result.status, 0, result.stderr); + assert.equal(JSON.parse(result.stdout)[0].outcome, outcome); + }); +} + +test("duplicate scenario names are rejected", () => { + const result = execute(` + const {test} = require("node:test"); + test("test_profile", () => {}); + test("test_profile", () => {}); + `); + assert.equal(result.status, 2); + assert.match(result.stderr, /Duplicate scenario/); +}); + +test("collection errors cannot pass", () => { + const result = execute("throw new Error('Collection failed');"); + assert.equal(result.status, 2); + assert.match(result.stderr, /Collection failed/); +}); + +for (const body of [ + "throw new Error('Late asynchronous failure')", + "Promise.reject(new Error('Late asynchronous failure'))", +]) { + test(`late asynchronous errors cannot pass: ${body}`, () => { + const result = execute(` + require("node:test").test("test_profile", () => { + setImmediate(() => { ${body}; }); + }); + `); + assert.equal(result.status, 2, result.stdout + result.stderr); + assert.match(result.stderr, /Late asynchronous failure/); + }); +} + +test("assertions survive a later asynchronous error", () => { + const result = execute(` + require("node:test").test("test_profile", () => { + setImmediate(() => { throw new Error("Late asynchronous failure"); }); + require("node:assert/strict").fail("Assertion mismatch"); + }); + `); + assert.equal(result.status, 1, result.stderr); + assert.equal(JSON.parse(result.stdout)[0].outcome, "failed"); + assert.match(result.stderr, /Late asynchronous failure/); +}); + +test("missing runner summary cannot pass", async () => { + await assert.rejects(collect([ + { type: "test:pass", data: { name: "test_profile", details: {} } }, + ]), /did not complete successfully/); +}); + +test("fixture setup errors do not become compatibility failures", async () => { + await assert.rejects(runScenario( + () => { throw Object.assign(new Error("Setup failed"), { name: "MongoServerError" }); }, + () => {}, + ), error => classify(error) === "error"); +}); + +test("fixture cleanup errors do not become compatibility failures", async () => { + await assert.rejects(runScenario( + () => ({ close() { throw new Error("Cleanup failed"); } }), + () => {}, + ), error => classify(error) === "error"); +}); + +test("assertions survive a subsequent fixture cleanup failure", async () => { + await assert.rejects(runScenario( + () => ({ close() { throw new Error("Cleanup failed"); } }), + () => assert.fail("Assertion mismatch"), + ), error => classify(error) === "failed" && /Assertion mismatch/.test(error.message)); +}); + +test("falsy scenario exceptions cannot become passes", async () => { + for (const value of [null, undefined, false, 0, ""]) { + await assert.rejects(runScenario( + () => ({ close() {} }), + () => { throw value; }, + )); + } +}); + +test("JUnit preserves outcomes and escapes diagnostics", () => { + const output = junit([ + { id: "test_pass", outcome: "passed", message: "" }, + { id: "test_failure", outcome: "failed", message: " & \"value\"" }, + { id: "test_error", outcome: "error", message: "Unavailable" }, + { id: "test_skip", outcome: "skipped", message: "Skipped" }, + ], "driver & integration"); + assert.match(output, /name="driver & integration"/); + assert.match(output, /tests="4" failures="1" errors="1" skipped="1"/); + assert.match(output, /<mismatch> & "value"/); + assert.match(output, /Unavailable<\/error>/); + assert.match(output, /Skipped<\/skipped>/); +}); diff --git a/compatibility/unit/test_npm.py b/compatibility/unit/test_npm.py new file mode 100644 index 0000000..7876258 --- /dev/null +++ b/compatibility/unit/test_npm.py @@ -0,0 +1,186 @@ +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: MIT + +"""Lockfile provenance and offline npm preparation without executing package code.""" + +import base64 +import hashlib +import json +import shutil +from pathlib import Path + +import pytest + +from compatibility import npm +from compatibility.contracts import ROOT, read_registry, suite_digest, suite_files + +pytestmark = pytest.mark.unit + + +@pytest.fixture +def npm_fixture(tmp_path, monkeypatch, registry): + spec = registry["integrations"]["nodejs"] + version = spec["default_version"] + source = tmp_path / "source" + adapter = source / Path(spec["test_file"]).parent + adapter.mkdir(parents=True) + content = b"synthetic archive for verification only" + integrity = "sha512-" + base64.b64encode(hashlib.sha512(content).digest()).decode() + url = f"{npm.REGISTRY}/{spec['package']}/-/driver-{version}.tgz" + manifest = {"dependencies": {spec["package"]: version}} + lock = { + "lockfileVersion": 3, + "packages": { + "": manifest, + f"node_modules/{spec['package']}": { + "version": version, + "resolved": url, + "integrity": integrity, + }, + }, + } + (adapter / "package.json").write_text(json.dumps(manifest)) + (adapter / "package-lock.json").write_text(json.dumps(lock)) + monkeypatch.setattr(npm, "ROOT", source) + monkeypatch.setattr(npm, "suite_files", lambda integration: list(adapter.glob("*.json"))) + monkeypatch.setattr(npm, "registry_bytes", lambda address, limit: content) + return spec, version, content, integrity, lock, adapter + + +def prepare(tmp_path, fixture, cache=None): + spec, version, _, _, _, _ = fixture + context = tmp_path / "context" + context.mkdir() + return context, npm.prepare_node_client(context, spec, version, cache) + + +def test_locked_archive_is_verified_and_recorded(tmp_path, npm_fixture): + context, digest = prepare(tmp_path, npm_fixture) + spec, version, content, _, _, _ = npm_fixture + assert digest == hashlib.sha256(content).hexdigest() + assert json.loads((context / "install-report.json").read_text())["install"] == [ + { + "path": f"node_modules/{spec['package']}", + "name": spec["package"], + "version": version, + "sha256": digest, + } + ] + assert (context / "npm-packages" / f"{digest}.tgz").read_bytes() == content + + +def test_verified_cache_can_be_used_without_network(tmp_path, npm_fixture, monkeypatch): + _, _, content, integrity, _, _ = npm_fixture + cache = tmp_path / "cache" + cache.mkdir() + (cache / (hashlib.sha256(integrity.encode()).hexdigest() + ".tgz")).write_bytes(content) + + def unexpected(*args): + pytest.fail("A complete reviewed cache must not use the network") + + monkeypatch.setattr(npm, "registry_bytes", unexpected) + _, digest = prepare(tmp_path, npm_fixture, cache) + assert digest == hashlib.sha256(content).hexdigest() + + +def test_corrupt_cached_archive_is_rejected(tmp_path, npm_fixture): + _, _, _, integrity, _, _ = npm_fixture + cache = tmp_path / "cache" + cache.mkdir() + (cache / (hashlib.sha256(integrity.encode()).hexdigest() + ".tgz")).write_bytes(b"corrupted") + with pytest.raises(ValueError, match="integrity"): + prepare(tmp_path, npm_fixture, cache) + + +def test_downloaded_archive_is_verified_before_caching(tmp_path, npm_fixture, monkeypatch): + monkeypatch.setattr(npm, "registry_bytes", lambda *args: b"corrupted") + cache = tmp_path / "cache" + with pytest.raises(ValueError, match="integrity"): + prepare(tmp_path, npm_fixture, cache) + assert not list(cache.iterdir()) + + +def test_cache_population_is_reusable(tmp_path, npm_fixture): + _, _, content, integrity, _, _ = npm_fixture + cache = tmp_path / "cache" + prepare(tmp_path, npm_fixture, cache) + assert list(cache.iterdir()) == [ + cache / (hashlib.sha256(integrity.encode()).hexdigest() + ".tgz") + ] + assert next(cache.iterdir()).read_bytes() == content + + +def test_cache_symlinks_are_rejected(tmp_path, npm_fixture): + _, _, content, integrity, _, _ = npm_fixture + original = tmp_path / "archive" + original.write_bytes(content) + cache = tmp_path / "cache" + cache.mkdir() + (cache / (hashlib.sha256(integrity.encode()).hexdigest() + ".tgz")).symlink_to(original) + with pytest.raises(ValueError, match="regular file"): + prepare(tmp_path, npm_fixture, cache) + + +@pytest.mark.parametrize( + "url", ["http://registry.npmjs.org/driver.tgz", "https://example.test/driver.tgz"] +) +def test_lockfile_cannot_fetch_from_an_unreviewed_source(tmp_path, npm_fixture, url): + spec, _, _, _, lock, adapter = npm_fixture + lock["packages"][f"node_modules/{spec['package']}"]["resolved"] = url + (adapter / "package-lock.json").write_text(json.dumps(lock)) + with pytest.raises(ValueError, match="registry"): + prepare(tmp_path, npm_fixture) + + +def test_dependency_locations_cannot_escape_node_modules(tmp_path, npm_fixture): + spec, _, _, _, lock, adapter = npm_fixture + lock["packages"]["node_modules/../../outside"] = lock["packages"].pop( + f"node_modules/{spec['package']}" + ) + (adapter / "package-lock.json").write_text(json.dumps(lock)) + with pytest.raises(ValueError, match="location"): + prepare(tmp_path, npm_fixture) + + +def test_unreviewed_driver_version_is_rejected(tmp_path, npm_fixture): + spec, version, _, _, _, _ = npm_fixture + context = tmp_path / "context" + context.mkdir() + major, minor, patch = version.split(".") + with pytest.raises(ValueError, match="lockfile"): + npm.prepare_node_client(context, spec, f"{major}.{minor}.{int(patch) + 1}") + + +def test_weaker_or_malformed_integrity_is_rejected(): + for integrity in ("sha1-invalid", "sha512-***", "sha512-YWJj"): + with pytest.raises(ValueError): + npm.verify_integrity(b"archive", integrity) + + +@pytest.mark.parametrize("integration", ["nodejs", "mongoose"]) +def test_reviewed_node_manifest_and_lock_match_the_registry(integration): + spec = read_registry()["integrations"][integration] + adapter = ROOT / Path(spec["test_file"]).parent + manifest = json.loads((adapter / "package.json").read_text()) + lock = json.loads((adapter / "package-lock.json").read_text()) + assert manifest["dependencies"] == {spec["package"]: spec["default_version"]} + assert lock["packages"][""]["dependencies"] == manifest["dependencies"] + assert lock["packages"][f"node_modules/{spec['package']}"]["version"] == spec["default_version"] + + +@pytest.mark.parametrize("integration", ["nodejs", "mongoose"]) +@pytest.mark.parametrize("filename", ["package-lock.json", "client.cjs", "report.cjs"]) +def test_node_source_and_lock_are_part_of_provenance(tmp_path, integration, filename): + spec = read_registry()["integrations"][integration] + for source in suite_files(integration): + destination = tmp_path / source.relative_to(ROOT) + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, destination) + original = suite_digest(integration, spec, tmp_path) + assert original == suite_digest(integration, spec) + directory = ( + Path(spec["test_file"]).parent if filename == "package-lock.json" else Path("compatibility") + ) + source = tmp_path / directory / filename + source.write_text(source.read_text() + "\n") + assert suite_digest(integration, spec, tmp_path) != original diff --git a/compatibility/unit/test_orchestration.py b/compatibility/unit/test_orchestration.py new file mode 100644 index 0000000..9422f78 --- /dev/null +++ b/compatibility/unit/test_orchestration.py @@ -0,0 +1,616 @@ +# 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"], True) + 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"] and run["demonstration"] + 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"], + "demonstration": False, + "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", "demonstration", "error"), + [ + ("scheduled", "all", None, None, False, "every reviewed DocumentDB release"), + ("scheduled", "all", None, "selected", False, "every reviewed DocumentDB release"), + ("documentdb_release", "all", None, None, False, "one reviewed release"), + ("documentdb_release", "all", None, "all", False, "one reviewed release"), + ("scheduled", "selected", None, "all", False, "every enabled integration"), + ("documentdb_release", "all", "selected", "selected", False, "every enabled integration"), + ("documentdb_release", "all", None, "selected", True, "every enabled integration"), + ("push", "all", None, "selected", False, "Unknown execution trigger"), + ], +) +def test_automatic_runs_cannot_narrow_the_reviewed_selection( + registry, selection, trigger, integration, version, database, demonstration, 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, + demonstration, + 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 and row["issue_url"] is None + 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")) + + +@pytest.mark.parametrize("missing", [False, True]) +def test_demonstrations_have_separate_rows_and_complete_expected_coverage( + tmp_path, registry, selection, records, missing +): + runs = workflow.select_runs(registry, "all", None, selection["documentdb_version"], True) + for integration, record in records.items(): + record["demonstration"] = True + record["expected_tests"] = expected_tests(registry["integrations"][integration], True) + record["tests"].append( + { + "id": record["expected_tests"][-1], + "outcome": "failed", + "message": "Deliberate mismatch", + } + ) + incoming = tmp_path / "incoming" + if not missing: + write_records(incoming, records) + output = tmp_path / "report" + assert not workflow.collect_report(incoming, output, registry, runs) + _, rows, history = read_report(output) + assert set(rows) == set(records) + for integration, row in rows.items(): + assert row["demonstration"] + assert row["scenarios"] == expected_tests(registry["integrations"][integration], True) + assert row["expected"] == len(row["scenarios"]) + assert row["state"] == ("Not tested" if missing else "Failing") + assert all(record["demonstration"] for record in history) + assert "Demonstration" in (output / "summary.md").read_text() + + +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, "demonstration": False, "trigger": "manual"}, + {**selection, "integration": "additional", "demonstration": False, "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 "