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..d40f1de 100644 --- a/.github/workflows/compatibility-ci.yml +++ b/.github/workflows/compatibility-ci.yml @@ -8,13 +8,13 @@ on: paths: - "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 +43,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-watcher.yml b/.github/workflows/compatibility-watcher.yml new file mode 100644 index 0000000..ac070f6 --- /dev/null +++ b/.github/workflows/compatibility-watcher.yml @@ -0,0 +1,57 @@ +name: Upstream compatibility watcher + +on: + schedule: + - cron: "23 8 * * *" + workflow_dispatch: + +permissions: {} + +concurrency: + group: compatibility-upstream-watcher + cancel-in-progress: false + +jobs: + discover: + name: Discover eligible upstream releases + if: ${{ vars.COMPATIBILITY_WATCHER_ENABLED == 'true' && github.ref_name == github.event.repository.default_branch }} + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: write + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + persist-credentials: false + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: "3.12" + - name: Install trusted watcher dependencies + run: python -m pip install -r compatibility/requirements.txt + - name: Discover and durably record eligible releases + env: + GITHUB_TOKEN: ${{ github.token }} + COMPATIBILITY_WATCHER_ENABLED: ${{ vars.COMPATIBILITY_WATCHER_ENABLED }} + run: python -m compatibility.watcher discover + dispatch: + name: Dispatch reviewed compatibility profiles + needs: discover + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: write + actions: write + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + persist-credentials: false + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: "3.12" + - name: Install trusted watcher dependencies + run: python -m pip install -r compatibility/requirements.txt + - name: Reconcile receipts and dispatch at most three reviewed version pairs + env: + GITHUB_TOKEN: ${{ github.token }} + COMPATIBILITY_WATCHER_ENABLED: ${{ vars.COMPATIBILITY_WATCHER_ENABLED }} + run: python -m compatibility.watcher dispatch diff --git a/.github/workflows/compatibility.yml b/.github/workflows/compatibility.yml new file mode 100644 index 0000000..83382e0 --- /dev/null +++ b/.github/workflows/compatibility.yml @@ -0,0 +1,199 @@ +name: Ecosystem compatibility +run-name: ${{ inputs.detection_id != '' && format('Ecosystem compatibility [watch:{0}:{1}]', inputs.detection_id, inputs.dispatch_id) || 'Ecosystem compatibility' }} + +on: + workflow_dispatch: + inputs: + integration: + description: Integration, or all enabled registry entries + type: choice + options: + - all + - pymongo + - mongodb-node + - mongoose + default: all + required: true + version: + description: Upstream version override (single integration only; blank uses registry defaults) + type: string + required: false + documentdb_version: + description: Version key from compatibility/registry.yaml (e.g. 1.2.0), or all (blank uses the newest) + type: string + required: false + trigger: + description: Execution trigger recorded with the results + type: choice + options: + - manual + - documentdb_release + default: manual + required: true + detection_id: + description: Recorded upstream detection ID (leave blank for a manual run) + type: string + required: false + dispatch_id: + description: Recorded dispatch nonce (required with detection_id) + type: string + required: false + schedule: + - cron: "41 5 * * *" + +permissions: + contents: read + +jobs: + plan: + name: Select integrations + runs-on: ubuntu-24.04 + timeout-minutes: 5 + outputs: + matrix: ${{ steps.select.outputs.matrix }} + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + persist-credentials: false + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: "3.12" + - name: Install trusted orchestration dependencies + run: python -m pip install -r compatibility/requirements.txt + - name: Resolve the reviewed integration matrix + id: select + env: + INTEGRATION: ${{ inputs.integration }} + VERSION: ${{ inputs.version }} + DOCUMENTDB_VERSION: ${{ github.event_name == 'schedule' && 'all' || inputs.documentdb_version }} + TRIGGER: ${{ github.event_name == 'schedule' && 'scheduled' || inputs.trigger }} + DETECTION_ID: ${{ inputs.detection_id }} + DISPATCH_ID: ${{ inputs.dispatch_id }} + GITHUB_TOKEN: ${{ github.token }} + COMPATIBILITY_WATCHER_ENABLED: ${{ vars.COMPATIBILITY_WATCHER_ENABLED }} + run: | + args=() + if [ -n "$INTEGRATION" ]; then args+=(--integration "$INTEGRATION"); fi + if [ -n "$DOCUMENTDB_VERSION" ]; then args+=(--documentdb-version "$DOCUMENTDB_VERSION"); fi + if [ -n "$VERSION" ]; then args+=(--version "$VERSION"); fi + if [ -n "$TRIGGER" ]; then args+=(--trigger "$TRIGGER"); fi + if [ -n "$DETECTION_ID" ] || [ -n "$DISPATCH_ID" ]; then + args+=(--detection-id "$DETECTION_ID" --dispatch-id "$DISPATCH_ID") + fi + matrix=$(python -m compatibility.workflow matrix "${args[@]}") + printf 'matrix=%s\n' "$matrix" >> "$GITHUB_OUTPUT" + test: + name: ${{ matrix.integration_label }} ${{ matrix.version }} on DocumentDB ${{ matrix.documentdb_release_tag }} + needs: plan + strategy: + fail-fast: false + matrix: ${{ fromJSON(needs.plan.outputs.matrix) }} + runs-on: ubuntu-24.04 + timeout-minutes: 30 + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + persist-credentials: false + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: "3.12" + - name: Install trusted orchestration dependencies + run: python -m pip install -r compatibility/requirements.txt + - name: Run the isolated integration profile + id: suite + env: + INTEGRATION: ${{ matrix.integration }} + VERSION: ${{ matrix.version }} + DOCUMENTDB_VERSION: ${{ matrix.documentdb_version }} + TRIGGER: ${{ matrix.trigger }} + DETECTION_ID: ${{ matrix.detection_id }} + EXPECTED_ARTIFACTS: ${{ join(matrix.artifact_sha256s || fromJSON('[]'), ',') }} + NPM_BUNDLE: ${{ matrix.npm_bundle }} + EXPECTED_NPM_BUNDLE_SHA256: ${{ matrix.npm_bundle_sha256 }} + 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 [ -n "$DETECTION_ID" ]; then + args+=(--detection-id "$DETECTION_ID") + IFS=, read -r -a artifacts <<< "$EXPECTED_ARTIFACTS" + for artifact in "${artifacts[@]}"; do args+=(--expected-artifact-sha256 "$artifact"); done + if [ -n "$NPM_BUNDLE" ]; then + printf '%s' "$NPM_BUNDLE" > "$RUNNER_TEMP/compatibility-npm-candidate.json" + args+=( + --npm-bundle "$RUNNER_TEMP/compatibility-npm-candidate.json" + --expected-npm-bundle-sha256 "$EXPECTED_NPM_BUNDLE_SHA256" + ) + fi + 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 }} + TRIGGER: ${{ github.event_name == 'schedule' && 'scheduled' || inputs.trigger }} + DETECTION_ID: ${{ inputs.detection_id }} + DISPATCH_ID: ${{ inputs.dispatch_id }} + EXPECTED_NPM_BUNDLE_SHA256: ${{ fromJSON(needs.plan.outputs.matrix).include[0].npm_bundle_sha256 }} + run: | + args=( + --input incoming + --output report + --summary "$GITHUB_STEP_SUMMARY" + --expected-run-url "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID/attempts/$GITHUB_RUN_ATTEMPT" + ) + if [ -n "$INTEGRATION" ]; then args+=(--integration "$INTEGRATION"); fi + if [ -n "$DOCUMENTDB_VERSION" ]; then args+=(--documentdb-version "$DOCUMENTDB_VERSION"); fi + if [ -n "$VERSION" ]; then args+=(--version "$VERSION"); fi + if [ -n "$TRIGGER" ]; then args+=(--trigger "$TRIGGER"); fi + if [ -n "$DETECTION_ID" ] || [ -n "$DISPATCH_ID" ]; then + args+=(--detection-id "$DETECTION_ID" --dispatch-id "$DISPATCH_ID") + fi + if [ -n "$EXPECTED_NPM_BUNDLE_SHA256" ]; then + args+=(--expected-npm-bundle-sha256 "$EXPECTED_NPM_BUNDLE_SHA256") + fi + python -m compatibility.workflow report "${args[@]}" + - name: Retain the combined summary and dashboard + if: always() + uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6 + with: + name: compatibility-report-${{ github.run_attempt }} + path: report/ + if-no-files-found: error + retention-days: 30 diff --git a/README.md b/README.md index b9f808c..0cf77b1 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) +[![mongodb-node compatibility](/../compatibility-data/site/badges/nodejs.svg)](/../compatibility-data/site/README.md#mongodb-node) +[![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..9d02e6f 100644 --- a/compatibility/README.md +++ b/compatibility/README.md @@ -4,6 +4,12 @@ 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. An opt-in release watcher requests compatibility +runs for upstream artifacts that pass its eligibility checks. + ## Profiles and reviewed artifacts [`registry.yaml`](registry.yaml) defines profiles, enablement, default package @@ -13,8 +19,10 @@ and scenario suites. These definitions identify the package, runtime, and databa combination for a run, not the newest upstream releases. Database and client base images are pinned by digest. -Runs target the newest reviewed DocumentDB release by default. -`--documentdb-version` selects another release listed in the registry. +Runs target the newest reviewed DocumentDB release by default. Workflow job +names and dashboards show the public OSS release tag (for example, `v1.2-0`). +To select that release with `--documentdb-version` or the workflow input, use +its numeric registry key (`1.2.0`). Version overrides must match the integration's registry policy and have eligible artifacts for its runtime. PyMongo versions use three numeric components, such as @@ -29,10 +37,30 @@ 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. + +Manual Node.js and Mongoose runs accept only their reviewed locked versions. +To change a manual baseline, 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. +Authorized upstream runs instead use a frozen candidate manifest and lockfile +recorded by the watcher. They do not modify the checked-in baselines or broaden +manual version overrides. + ## 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 +74,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 +115,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 mongodb-node \ + --output compatibility/.test-results/mongodb-node-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 +131,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 +147,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 mongodb-node --demonstration \ + --output compatibility/.test-results/mongodb-node-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 +173,292 @@ Never share credentials or customer data. Runs emit runtime-neutral schema version 2. Schema-version-1 Python records remain readable without rewriting their immutable provenance. +## Results and dashboard + +Append locally produced records to an immutable store: + +```bash +python -m compatibility.publish \ + --result compatibility/.test-results/pymongo-001/result.json \ + --store compatibility/.test-results/history \ + --site compatibility/.test-results/site +``` + +Open `compatibility/.test-results/site/index.html`. The same validated history +produces HTML, `current.json`, and `history.json`. Conflicting run IDs are rejected; +identical replays are idempotent. Failure demonstrations are rejected and never +rendered. Local runs have no fabricated pipeline URL. + +| State | Meaning | +| --- | --- | +| Working | All required scenarios passed with verified artifacts | +| Failing | A conclusive assertion or non-timeout operation/protocol failure | +| Not tested | Missing or skipped coverage, timeouts, setup errors, or other incomplete execution | +| Stale | The last conclusive result is older than the profile's freshness policy or no longer matches its execution inputs/artifacts | + +If a newer attempt cannot execute, retain the previous conclusive result while +exposing the new attempt's failure separately. Keep version pairs and profiles +distinct. Browser-side freshness also ages previously rendered results. + +The renderer provides prefilled links to this repository's +[compatibility issue form](../.github/ISSUE_TEMPLATE/compatibility-report.yml). +Use `--issue-repository` to select a different reporting destination with the +same form field IDs. A report should include the actual version pair, +runtime/profile, relevant run, and a minimal synthetic reproduction, never +credentials or customer data. + +This renderer does not push Git history, deploy a site, create issues, or change +repository settings. Public hosting and durable publication require a separately +approved destination, publisher, operational owner, and reporting route. + +## GitHub Actions workflow + +Manual dispatch requires the workflow on the repository's default branch. +Select **Ecosystem compatibility** in the Actions tab, then choose the branch +and, optionally, a reviewed database release. A blank release uses the newest +reviewed release in the registry, and `all` selects every reviewed release. The +integration defaults to `all`: a planning job expands every enabled registry entry +using its own reviewed default version. Select one integration for a focused run +or version override. A version override with `all`, a disabled integration, a +version outside its registry policy, or an unknown database release is rejected +before test jobs start. + +The workflow also runs daily on the default branch. Scheduled runs test every +enabled integration at its default version against every reviewed DocumentDB +release. + +Each push to `main` that changes `registry.yaml` starts **Compatibility DocumentDB +releases**. It compares the registry with the version before the push and +dispatches this workflow once for each added or re-pinned release, with every +enabled integration at its default version and the `documentdb_release` trigger. +If the earlier registry is unavailable, every reviewed release is dispatched. The +`trigger` input defaults to `manual`; a `documentdb_release` run requires one +reviewed release and cannot narrow integrations or override versions. + +Each matrix job runs its complete scenario suite against its own disposable +database. Matrix fail-fast is disabled. JSON and available JUnit/logs are retained +in `compatibility-results---` artifacts +even when the job fails. Results record the trigger (`manual`, `scheduled`, +`documentdb_release`, or the watcher's `upstream_release`) and exact +workflow-attempt URL. + +After the matrix finishes, reporting validates each selected result's identity, +trigger, coverage, artifacts, suite digest, and workflow-attempt URL. The summary +includes every selected integration and database release. Missing or rejected +results are **Not tested**, with a diagnostic, not fabricated envelopes or an +earlier attempt's pass. Compatibility failures remain **Failing**, and failed or +incomplete reports exit nonzero without suppressing matrix failures. + +The `compatibility-report-` artifact contains `summary.md`, machine-readable +`summary.json`, accepted envelopes in `results/`, and a combined dashboard in `site/`. +Only selected profiles and versions appear, including explicit overrides. All +artifacts have 30-day retention. + +Use **Re-run all jobs** for a complete matrix rerun. Reporting deliberately +collects only the current attempt's artifacts, so rerunning only failed jobs can +leave other integrations or releases without current-attempt evidence. Re-running +an older workflow retains its original commit; dispatch a fresh run to test new +code. + +All compatibility jobs have read-only repository permissions. The release +dispatcher additionally receives `actions: write` only to start this workflow. +Neither workflow publishes Git history, deploys a site, creates issues, or changes +repository settings. +Normal default-branch completions notify the separate README dashboard publisher. +That publisher retains its own write permission; integration execution and report +generation never receive publication credentials. + +To inspect selection, combine locally produced records, or list the releases a +registry change would dispatch: + +```bash +python -m compatibility.workflow matrix --integration all +python -m compatibility.workflow matrix --documentdb-version all --trigger scheduled +python -m compatibility.workflow report --integration all \ + --input compatibility/.test-results/incoming \ + --output compatibility/.test-results/combined-001 +python -m compatibility.workflow changed-releases --previous /path/to/previous-registry.yaml +``` + +Place each record under `incoming///result.json`. +Use the same integration, version, database, and trigger selection +as the producing runs, and a fresh output directory. `--expected-run-url` binds a +combined report to one workflow attempt; omit it for local results. `--summary` +appends the Markdown report to a GitHub step-summary file. +The Markdown summary labels each result's trigger. Upstream-triggered reports +select `upstream_release` with `--detection-id` and `--dispatch-id` instead of +`--trigger`, and carry the detection ID through JSON and the dashboard. + +## Opt-in upstream release watcher + +[compatibility-watcher.yml](../.github/workflows/compatibility-watcher.yml) +discovers eligible upstream releases and dispatches their complete profiles. +It is disabled unless the `COMPATIBILITY_WATCHER_ENABLED` repository or +organization variable is the literal string `true`. + +Before enabling it, maintainers must allow the workflow's GitHub token to write +the dedicated state branch and dispatch workflows. No PAT or new secret is +required. The workflow does not configure credentials, variables, branch rules, +or hosting. Its `discover` job holds only `contents: write`; only the `dispatch` +job also receives `actions: write`. + +The watcher and compatibility workflows must exist on the default branch. The watcher +accepts only scheduled or manual execution on that branch. It runs daily at +08:23 UTC and can also be started with **Run workflow**. Its invocations are +serialized. Disable the enablement variable to stop future work, and explicitly +cancel an in-flight run when immediate suspension is needed. + +Release discovery uses each enabled registry entry with a `watch_version_pattern`. +That optional field opts a profile into discovery and defines its automatic version +range independently of the manual `version_pattern`. The checked-in policies admit +stable releases at least as new as each baseline within its current major version. +Prereleases and new majors are not selected automatically. + +The watcher reads at most 30 releases from each registered upstream GitHub +repository, for at most ten watched integrations. It examines those feeds in +round-robin order rather than draining one integration's release backlog first. +GitHub release identities must match the registered repository. +Package names, versions, and artifacts are checked against the corresponding +official package registry. Unpublished metadata is recorded and reconsidered +on later scans. + +Python discovery requires eligible non-yanked wheels from PyPI. +The wheel tags match the runner's Python 3.12 Linux x64 download policy. +`Requires-Python` must admit **3.12.0**, a conservative floor: a release requiring +a newer 3.12 patch is not automatically selected even if a particular image +could run it. + +For npm, the package's registry repository must match the registered upstream, +and deprecated releases are excluded. A disposable container using the profile's +digest-pinned Node image resolves the exact candidate with lifecycle scripts, +optional installation, auditing, and funding requests disabled. Engine requirements +are enforced. The resolver has no credentials, checkout mount, or Docker socket; +only its temporary filesystem is writable. Resolution failures stop discovery +with an explicit ledger error, not an invented compatibility verdict. + +The resulting manifest, lockfile, and resolver image form a bundle capped at +64 KiB and 100 locked dependencies. Every non-optional archive must pass the +existing registry-origin and SHA-512 verification before the candidate is recorded. +The locked root archive must also match the independently fetched release metadata. +The complete bundle is stored in the Git-backed ledger, and its SHA-256 contributes +to the detection identity. Rediscovery and retries reuse that bundle instead of +resolving a newer transitive dependency tree. Changed execution inputs or published +root artifacts require a new detection. + +At most three new version pairs are recorded per invocation. Each detection +includes the upstream artifacts and hashes, DocumentDB image and version, +profile, execution-input digest, source revision, release evidence, and discovery +run. The key covers the execution identity, not just the latest version string. + +Every dispatch runs the complete affected profile. Before dispatch, the code +revalidates the reviewed execution inputs and official release artifacts. +An unexpected downloaded artifact is rejected before Docker build or execution. +Only the planning step reads watcher state. It passes the validated bundle and +its hash as bounded matrix data, not executable instructions. The runner checks +that identity before downloading archives or building a client and installs the +frozen dependency tree offline. Results retain the bundle and hash alongside the +actual installed dependencies; report collection checks the planned hash. +No GitHub token is passed to the isolated test client. + +Normal default-branch upstream runs use the same combined reports and README +publisher as manual and scheduled runs. Verified candidate results, including compatibility +failures and incomplete attempts, can therefore update the existing badges +without changing the default package versions. Discovering a release or +resolving its dependencies cannot make a badge green. + +### State, retries, and recovery + +The orphan `compatibility-watcher-state` branch contains a single `ledger.json`, +including the frozen npm inputs needed to reproduce its detections. +Non-force Git reference updates reject concurrent writers. Each reservation is +persisted before contacting the dispatch API, and the resulting workflow receipt +is saved afterward. Git history retains earlier scans and state transitions. +Allow the workflow's GitHub token to create and update this data branch; a denied +write stops the operation rather than falling back to ephemeral deduplication. + +There are at most three automatic dispatch requests per invocation and three +automatic attempts per detection. Only definite rate-limit rejections are +automatically retried on later invocations. Unknown outcomes are reconciled by +receipt or the exact detection/dispatch nonce in the workflow title, never +blindly resent. The bounded lookup covers up to seven days and 1,000 runs. +Incomplete lookups and duplicate nonces require attention. + +| Ledger status | Meaning | +| --- | --- | +| `pending` | Durable eligible work waiting for dispatch, possibly after a rate limit | +| `dispatching` | A reservation exists but its API outcome is not yet established | +| `dispatched` | A validated workflow receipt is recorded | +| `completed` | The associated workflow is terminal, not a compatibility pass | +| `blocked` | Automatic processing stopped and requires maintainer investigation | +| `superseded` | The reviewed execution inputs, policy, or upstream artifacts changed | + +For a known workflow receipt, use **Re-run all jobs** to repeat the full selected +profile. If dispatch was rejected or its outcome is unknown, first inspect the +recorded watcher run and search the compatibility workflow for the exact nonce. +If no run was accepted, manually dispatch **Ecosystem compatibility** on the +default branch with the recorded integration/version/database, `detection_id`, +and last attempt's `dispatch_id`. Do not create a new nonce. The consumer +validates these inputs against the ledger, and the next +watcher invocation can associate the manual run. After execution inputs change, +use a new discovery rather than overriding the identity checks. An ordinary +manual run with both IDs blank remains available independently of the watcher. + +Inspect compatibility artifacts and use the reporting guidance above for +conclusive scenario failures. `completed` or a successful dispatch does not +establish Working. Watcher failures remain visible as failed Actions jobs and +ledger errors; the watcher does not create issues. + +The ledger is bounded to 1,000 entries and 2 MiB. Exhaustion stops new writes +and requires a reviewed retention strategy preserving the audit and deduplication +identities. Do not delete the state branch or old detection IDs to retry work. +Watcher state is not the compatibility-result history or an automatically +published dashboard. + +Automatic dispatch uses the registry's reviewed DocumentDB releases; release +discovery does not select new database images. Compatibility results are retained +as workflow artifacts, not deployed to a public site. + +Adding a package ecosystem to discovery requires a metadata adapter and a +reviewed version-selection policy compatible with the runner's artifact checks. +Python and npm profiles share the existing metadata and preparation paths. Adding +an adapter for either runtime requires its registered official package/repository, +complete scenario contract, and an explicit `watch_version_pattern`; the reviewed +manual manifest and lockfile remain the default for npm profiles. + +Local unit tests simulate GitHub receipts, interruptions, and real Git conflicts +without production dispatches. + +## Durable Git history + +The generic history helper is available for an explicitly configured trusted +publisher, not for integration clients: + +```bash +bash compatibility/persist.sh /path/to/result.json "$EXPECTED_RUN_URL" +``` + +Run it from the trusted source checkout with write access to the intended +`origin`. Set `EXPECTED_RUN_URL` to the originating test attempt, not a later +publication retry. The helper verifies that URL, declared coverage, database +artifact, and execution-input digest, then appends `results/.json` to +`compatibility-data`. + +The helper uses non-force pushes with bounded conflict retries and initializes +an orphan branch containing only result data. Identical replays are idempotent; +conflicting run IDs fail rather than overwrite history. Concurrent writers' +records survive retry, and temporary worktrees are removed. Retain the data +branch independently of artifact expiration. + +Keep write credentials separate from integration execution. A publisher must +retain failed attempts and serialize deployment only after results are durably +stored. Render complete history with `compatibility.publish`. Deployment retries +must not delete or rewrite history. +Cancellation before persistence is not a compatibility verdict. + +Invoke this helper explicitly from the trusted publisher; the compatibility +workflow does not call it. It does not configure hosting, GitHub Pages, +credentials, repository permissions, or a release-watcher ledger. + ## README dashboard The repository README embeds compact integration badges from the `compatibility-data` @@ -154,14 +508,17 @@ to actual runs, never to rendering or refresh time. ## Extend and maintain When adding an integration, include its badge in the root README. Use -`/../compatibility-data/site/badges/.svg` for the image and -`/../compatibility-data/site/README.md#` for the details link. +the integration ID for the badge image path and its display label for the +details anchor. For example, `mongodb-node` uses `site/badges/nodejs.svg` and +`site/README.md#mongodb-node` on the `compatibility-data` branch because +results and watcher records retain the `nodejs` ID. Add a reviewed adapter directory, pinned image and package requirements, normal and deliberate-failure suites, and a registry entry naming every required scenario. Keep package preparation, runtime validation, and provenance support with any new runtime. Enable an integration only when its real adapter exists. A registry entry alone does not implement runtime support. +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 +529,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..1c59eb0 100644 --- a/compatibility/contracts.py +++ b/compatibility/contracts.py @@ -8,6 +8,7 @@ import hashlib import json import re +import urllib.request from datetime import datetime, timedelta, timezone from pathlib import Path from typing import Any @@ -19,6 +20,52 @@ ROOT = Path(__file__).resolve().parent.parent DEMONSTRATION_TEST = "test_failure_demonstration" RUNTIME_PREFIXES = {"python": "3.12.", "nodejs": "24."} +INTEGRATION_LABELS = {"nodejs": "mongodb-node"} +INTEGRATION_IDS = {label: identifier for identifier, label in INTEGRATION_LABELS.items()} +MAX_NPM_BUNDLE_BYTES = 64 * 1024 +PYTHON_PLATFORMS = ( + "manylinux_2_28_x86_64", + "manylinux_2_17_x86_64", + "manylinux2014_x86_64", + "manylinux1_x86_64", +) + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request( + self, req: Any, fp: Any, code: int, msg: str, headers: Any, newurl: str + ) -> None: + return None + + +def canonical_bytes(value: Any) -> bytes: + return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode() + + +def json_digest(value: Any) -> str: + return hashlib.sha256(canonical_bytes(value)).hexdigest() + + +def npm_bundle_digest(bundle: dict[str, Any]) -> str: + validate_schema(bundle, "npm-bundle") + contents = canonical_bytes(bundle) + if len(contents) > MAX_NPM_BUNDLE_BYTES: + raise ValueError("npm candidate bundle exceeded its size limit") + return hashlib.sha256(contents).hexdigest() + + +def version_allowed(spec: dict[str, Any], version: str, *, upstream: bool = False) -> bool: + pattern = ( + spec.get("watch_version_pattern", spec["version_pattern"]) + if upstream + else spec["version_pattern"] + ) + return bool( + len(version) <= 40 + and re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", version) + and re.fullmatch(pattern, version) + and (not upstream or Version(version) >= Version(spec["default_version"])) + ) def validate_schema(value: Any, name: str) -> None: @@ -40,6 +87,8 @@ def read_registry( for name, integration in registry["integrations"].items(): if not re.fullmatch(integration["version_pattern"], integration["default_version"]): raise ValueError(f"Default version is outside the policy for {name}") + if not version_allowed(integration, integration["default_version"], upstream=True): + raise ValueError(f"Default version is outside the watcher policy for {name}") for key in ("test_file", "demonstration_file"): test_file = (root / integration[key]).resolve() allowed = (root / "compatibility" / "integrations" / name).resolve() @@ -53,11 +102,25 @@ def read_registry( return dict(registry) +def integration_label(identifier: str) -> str: + return INTEGRATION_LABELS.get(identifier, identifier) + + +def integration_id(name: str) -> str: + return INTEGRATION_IDS.get(name, name) + + def default_documentdb_version(registry: dict[str, Any]) -> str: """Return the newest reviewed DocumentDB release using version ordering.""" return str(max(registry["documentdb"], key=Version)) +def documentdb_release_tag(version: str) -> str: + """Convert a validated DocumentDB version key to its public OSS release tag.""" + major, minor, patch = version.split(".") + return f"v{major}.{minor}-{patch}" + + def timestamp(value: str) -> datetime: """Parse an explicitly zoned timestamp into UTC.""" parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) @@ -74,6 +137,10 @@ def expected_tests(spec: dict[str, Any], demonstration: bool) -> list[str]: def validate_result(result: dict[str, Any], spec: dict[str, Any] | None = None) -> None: """Validate raw records before either persistence or rendering.""" validate_schema(result, "result") + if "detection_id" in result and ( + result["trigger"] != "upstream_release" or result["demonstration"] + ): + raise ValueError("Detection provenance requires a normal upstream-release result") if timestamp(result["finished_at"]) < timestamp(result["started_at"]): raise ValueError("Result finishes before it starts") if timestamp(result["finished_at"]) > datetime.now(timezone.utc) + timedelta(minutes=5): @@ -84,6 +151,20 @@ def validate_result(result: dict[str, Any], spec: dict[str, Any] | None = None) if not set(identifiers).issubset(result["expected_tests"]): raise ValueError("Result contains an undeclared scenario") runtime = result_runtime(result) + bundle = result["upstream"].get("npm_bundle") + bundle_sha256 = result["upstream"].get("npm_bundle_sha256") + npm_release = ( + runtime["name"] == "nodejs" + and result["trigger"] == "upstream_release" + and "detection_id" in result + ) + if bundle is not None or bundle_sha256 is not None: + if not npm_release: + raise ValueError("npm candidate provenance requires a recorded upstream release") + if bundle is not None and npm_bundle_digest(bundle) != bundle_sha256: + raise ValueError("npm candidate bundle does not match its recorded identity") + if npm_release and bundle_sha256 is None: + raise ValueError("npm upstream results require a candidate bundle identity") if runtime["version"] is not None and not runtime["version"].startswith( RUNTIME_PREFIXES[runtime["name"]] ): @@ -157,6 +238,11 @@ def compatibility_state(result: dict[str, Any]) -> str: or not result["upstream"]["client_image"] or not result_runtime(result)["version"] or not result["upstream"]["dependencies"] + or ( + result["trigger"] == "upstream_release" + and result_runtime(result)["name"] == "nodejs" + and not result["upstream"].get("npm_bundle") + ) ): return "Not tested" outcomes = {test["id"]: test["outcome"] for test in result["tests"]} @@ -175,12 +261,22 @@ 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")) + candidate_files = [root / "compatibility" / "schemas" / "npm-bundle.json"] + if any(path.suffix == ".cjs" for path in files): + candidate_files.append(root / "compatibility" / "resolve-npm.cjs") + # Historical source revisions predate candidate preparation. + files.extend( + path for path in candidate_files if root == ROOT or path.exists() or path.is_symlink() + ) 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..51aceda --- /dev/null +++ b/compatibility/dashboard/index.html @@ -0,0 +1,74 @@ + + + + + + DocumentDB ecosystem compatibility + + + + +

DocumentDB ecosystem compatibility

+

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

+

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

+

Compatibility results

+ + + + + {% for row in rows %} + + + + + + + + {% endfor %} + +
IntegrationVersions and coverageStatusLast successful / attemptedEvidence
{{ row.integration_label }}DocumentDB {{ row.documentdb_release_tag }}
+ 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.detection_id %}Detection: {{ row.detection_id }}{% endif %}
+ {% if row.run_url %}Latest pipeline run + {% elif row.last_attempt %}Local run (not published){% else %}No run{% endif %} + {% if row.issue_url %} +

Report a compatibility problem

+ {% endif %} +
History ({{ row.history | length }})
    + {% for record in row.history %} +
  • {{ record.finished_at }}: {{ record.tests | length }} scenario records + {% if record.run_url %}run{% endif %} + {% if record.execution_error %}
    {{ record.execution_error }}
    {% endif %} +
      {% for test in record.tests %}
    • {{ test.id }}: {{ test.outcome }} + {% if test.message %}
      {{ test.message }}
      {% endif %} +
    • {% endfor %}
    +
  • + {% endfor %} +
+
+ + diff --git a/compatibility/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..c32bc57 --- /dev/null +++ b/compatibility/npm.py @@ -0,0 +1,219 @@ +# 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 ( + MAX_NPM_BUNDLE_BYTES, + ROOT, + NoRedirect, + npm_bundle_digest, + 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.build_opener(NoRedirect()).open(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: + if not isinstance(url, str): + raise ValueError("Package URL must name a reviewed npm registry archive") + parsed = urllib.parse.urlsplit(url) + if ( + parsed.scheme != "https" + or parsed.netloc != "registry.npmjs.org" + or parsed.query + or parsed.fragment + ): + 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 node_image(spec: dict[str, Any], root: Path = ROOT) -> str: + recipe = root / Path(spec["test_file"]).parent / "Dockerfile" + images: list[str] = re.findall( + r"^FROM (node:24\.[0-9]+\.[0-9]+-[A-Za-z0-9_.-]+@sha256:[a-f0-9]{64})$", + recipe.read_text(), + re.M, + ) + if len(images) != 1: + raise ValueError("npm candidates require one digest-pinned Node 24 base image") + return images[0] + + +def validate_lock( + manifest: dict[str, Any], lock: dict[str, Any], spec: dict[str, Any], version: str +) -> None: + if ( + not isinstance(manifest, dict) + or not isinstance(lock, dict) + or manifest.get("dependencies") != {spec["package"]: version} + or lock.get("lockfileVersion") != 3 + or not isinstance(lock.get("packages"), dict) + or not 2 <= len(lock["packages"]) <= 101 + or not all(isinstance(entry, dict) for entry in lock["packages"].values()) + or lock["packages"].get("", {}).get("dependencies") != {spec["package"]: version} + ): + raise ValueError("npm lockfile does not match the selected integration") + for path, entry in lock["packages"].items(): + if path == "": + continue + if not re.fullmatch(PACKAGE_PATH, path) or entry.get("link"): + raise ValueError("npm lockfile contains an unsupported package location") + version_value = entry.get("version") + if not isinstance(version_value, str) or not re.fullmatch( + r"[0-9]+\.[0-9]+\.[0-9]+(?:[-+][a-zA-Z0-9.-]+)?", version_value + ): + raise ValueError("npm lockfile contains an invalid package version") + validate_registry_url(entry.get("resolved")) + integrity = entry.get("integrity") + if ( + not isinstance(integrity, str) + or not integrity.startswith("sha512-") + or len(base64.b64decode(integrity.removeprefix("sha512-"), validate=True)) != 64 + ): + raise ValueError("npm archive requires SHA-512 integrity") + selected = lock["packages"].get(f"node_modules/{spec['package']}", {}) + if selected.get("version") != version or selected.get("optional"): + raise ValueError("npm lockfile is missing the selected driver version") + + +def validate_npm_bundle( + bundle: dict[str, Any], spec: dict[str, Any], version: str, *, root: Path = ROOT +) -> str: + digest = npm_bundle_digest(bundle) + if spec["runtime"] != "nodejs" or bundle["resolver_image"] != node_image(spec, root): + raise ValueError("npm candidate resolver does not match the reviewed runtime image") + validate_lock(bundle["manifest"], bundle["lockfile"], spec, version) + return digest + + +def read_npm_bundle(path: Path) -> dict[str, Any]: + if path.is_symlink() or not path.is_file() or path.stat().st_size > MAX_NPM_BUNDLE_BYTES: + raise ValueError("npm candidate input must be a bounded regular JSON file") + with path.open("rb") as file: + contents = file.read(MAX_NPM_BUNDLE_BYTES + 1) + if len(contents) > MAX_NPM_BUNDLE_BYTES: + raise ValueError("npm candidate input exceeded its size limit") + bundle = json.loads(contents) + npm_bundle_digest(bundle) + return dict(bundle) + + +def prepare_node_client( + context: Path, + spec: dict[str, Any], + version: str, + package_cache: Path | None = None, + npm_bundle: dict[str, Any] | None = None, +) -> str: + """Verify the selected frozen dependency tree 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 + if npm_bundle is None: + manifest = json.loads((adapter / "package.json").read_text()) + lock = json.loads((adapter / "package-lock.json").read_text()) + validate_lock(manifest, lock, spec, version) + else: + validate_npm_bundle(npm_bundle, spec, version) + manifest = npm_bundle["manifest"] + lock = npm_bundle["lockfile"] + 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 + name = path.rsplit("node_modules/", 1)[1] + package_version = entry["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..10bd99a --- /dev/null +++ b/compatibility/publish.py @@ -0,0 +1,126 @@ +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: MIT + +"""Append immutable results and render a credential-free static compatibility dashboard.""" + +from __future__ import annotations + +import argparse +import json +import re +from datetime import datetime, timezone +from pathlib import Path +from typing import Any +from urllib.parse import urlencode + +from jinja2 import Environment, FileSystemLoader, StrictUndefined + +from compatibility.contracts import ROOT, read_registry +from compatibility.results import ( + RunKey, + append_result, +) +from compatibility.results import dashboard_rows as result_rows +from compatibility.results import read_result, validate_incoming_result + + +def reporting_link(repository: str, row: dict[str, Any]) -> str: + """Use the issue form's stable field IDs and encode every prefilled value.""" + if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*/[A-Za-z0-9][A-Za-z0-9_.-]*", repository): + raise ValueError("Invalid issue repository") + query = urlencode( + { + "template": "compatibility-report.yml", + "title": f"[Compatibility] {row['integration_label']} {row['upstream_version']}", + "integration": row["integration_label"], + "documentdb_version": row["documentdb_release_tag"], + "upstream_version": row["upstream_version"], + "environment": row["profile"], + "dashboard_run": row["run_url"] or "No published run; include your dashboard/run link", + } + ) + return f"https://github.com/{repository}/issues/new?{query}" + + +def dashboard_rows( + results: list[dict[str, Any]], + registry: dict[str, Any], + now: datetime, + issue_repository: str, + *, + expected_runs: dict[RunKey, str | None] | None = None, +) -> list[dict[str, Any]]: + """Add issue-report routes to the shared compatibility evidence projection.""" + rows = result_rows(results, registry, now, expected_runs=expected_runs) + for row in rows: + row["issue_url"] = reporting_link(issue_repository, row) + return rows + + +def render( + store: Path, + site: Path, + registry: dict[str, Any], + *, + issue_repository: str = "documentdb/documentdb-playground", + now: datetime | None = None, + expected_runs: dict[RunKey, str | None] | None = None, +) -> list[dict[str, Any]]: + """Publish static HTML and JSON from the same validated history.""" + now = now or datetime.now(timezone.utc) + if store.is_symlink(): + raise ValueError("The result store must not be a symbolic link") + results = [read_result(path) for path in sorted(store.glob("*.json"))] + results = [result for result in results if not result["demonstration"]] + rows = dashboard_rows(results, registry, now, issue_repository, expected_runs=expected_runs) + site.mkdir(parents=True, exist_ok=True) + environment = Environment( + loader=FileSystemLoader(ROOT / "compatibility" / "dashboard"), + autoescape=True, + undefined=StrictUndefined, + ) + generated = now.isoformat() + page = environment.get_template("index.html").render(rows=rows, generated_at=generated) + (site / "index.html").write_text(page) + (site / "freshness.js").write_text( + (ROOT / "compatibility" / "dashboard" / "freshness.js").read_text() + ) + (site / "history.json").write_text(json.dumps(results, indent=2, allow_nan=False) + "\n") + current = [{key: value for key, value in row.items() if key != "history"} for row in rows] + (site / "current.json").write_text( + json.dumps({"generated_at": generated, "integrations": current}, indent=2, allow_nan=False) + + "\n" + ) + return rows + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--result", type=Path) + parser.add_argument("--store", type=Path, required=True) + parser.add_argument("--site", type=Path) + parser.add_argument("--issue-repository", default="documentdb/documentdb-playground") + parser.add_argument("--expected-run-url") + args = parser.parse_args() + if args.result is None and args.site is None: + parser.error("Provide a result to append or a site to render") + registry = read_registry() + if args.result: + result = read_result(args.result) + if result["demonstration"]: + parser.error("Failure demonstrations are not published") + validate_incoming_result(result, registry, args.expected_run_url) + append_result(args.store, result) + if args.site: + render( + args.store, + args.site, + registry, + issue_repository=args.issue_repository, + ) + print(f"Dashboard rendered at {args.site / 'index.html'}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/compatibility/readme.py b/compatibility/readme.py index bb6aab5..6df426b 100644 --- a/compatibility/readme.py +++ b/compatibility/readme.py @@ -18,7 +18,13 @@ from typing import Any from xml.etree import ElementTree -from compatibility.contracts import read_registry, timestamp, validate_schema +from compatibility.contracts import ( + integration_label, + read_registry, + timestamp, + validate_schema, + version_allowed, +) from compatibility.results import ( RunKey, append_result, @@ -188,6 +194,12 @@ def selected_profiles( or not 0 < len(summary["integrations"]) <= 100 ): raise ValueError("Invalid combined report envelope") + trigger = summary.get("trigger", "manual") + if trigger not in {"manual", "scheduled", "documentdb_release", "upstream_release"} or ( + trigger == "upstream_release" + and not re.fullmatch(r"[a-f0-9]{64}", summary.get("detection_id") or "") + ): + raise ValueError("Invalid combined report trigger provenance") profiles = [] modes = set() for row in summary["integrations"]: @@ -198,7 +210,9 @@ def selected_profiles( if ( profile["profile"] != spec["profile"] or profile["documentdb_version"] not in registry["documentdb"] - or not re.fullmatch(spec["version_pattern"], profile["upstream_version"]) + or not version_allowed( + spec, profile["upstream_version"], upstream=trigger == "upstream_release" + ) or profile in profiles ): raise ValueError("Combined report does not match the reviewed selection") @@ -243,10 +257,13 @@ def ingest( raise ValueError("Publication directories must not be symbolic links") errors = [] profiles: list[dict[str, Any]] = [] + expected_detection = None + expected_bundle = None try: - profiles, demonstration = selected_profiles( - read_object(incoming / "summary.json"), registry - ) + summary = read_object(incoming / "summary.json") + profiles, demonstration = selected_profiles(summary, registry) + expected_detection = summary.get("detection_id") + expected_bundle = summary.get("npm_bundle_sha256") if demonstration: print("Demonstration report ignored; normal compatibility evidence is unchanged.") return @@ -268,6 +285,14 @@ def ingest( if path.stem != result["id"] or result["demonstration"]: raise ValueError("Result identity or mode does not match publication") validate_incoming_result(result, registry, attempt["run_url"], root=source_root) + if ( + expected_detection is not None + and result.get("detection_id") != expected_detection + ) or ( + expected_bundle is not None + and result["upstream"].get("npm_bundle_sha256") != expected_bundle + ): + raise ValueError("Result does not match the report's recorded candidate") profile = profile_from_result(result) if profiles and profile not in profiles: raise ValueError("Result is outside the selected profile set") @@ -285,7 +310,9 @@ def ingest( available = {result_key(result) for result in results} for profile in profiles: if profile_key(profile) not in available: - errors.append(f"Missing validated result for {profile['integration']}") + errors.append( + f"Missing validated result for {integration_label(profile['integration'])}" + ) attempt["profiles"] = profiles attempt["errors"] = [message[:1000] for message in errors] save_attempt(data, attempt, repository) @@ -401,8 +428,11 @@ def markdown(view: dict[str, Any]) -> str: else: lines += ["**No completed compatibility workflow has been published.**", ""] for integration, rows in groupby(view["integrations"], key=lambda row: row["integration"]): + label = integration_label(integration) + if label != integration: + lines += [f'', ""] lines += [ - f"## {markdown_cell(integration)}", + f"## {markdown_cell(label)}", "", "| Client / DocumentDB | Profile | Evidence | Verified cases | Last conclusive | " "Latest attempt | Attempted at | Details |", @@ -410,7 +440,7 @@ def markdown(view: dict[str, Any]) -> str: ] for row in rows: fields = [ - f"{row['upstream_version']} / {row['documentdb_version']}", + f"{row['upstream_version']} / {row['documentdb_release_tag']}", row["profile"], row["state"], f"{row['passed']}/{row['expected']}", @@ -517,10 +547,10 @@ def text(x: int, y: int, value: str, size: int = 14, color: str = "#182230") -> "fill": "#f2f4f7" if index % 2 == 0 else "#ffffff", }, ) - text(24, top + 25, row["integration"], 18) + text(24, top + 25, row["integration_label"], 18) text(24, top + 49, row["profile"], 11, "#475467") text(255, top + 25, row["upstream_version"]) - text(350, top + 25, row["documentdb_version"]) + text(350, top + 25, row["documentdb_release_tag"]) text(470, top + 25, row["state"], 17, COLORS[row["state"]]) text(470, top + 49, "Conclusive:", 10, "#475467") text(470, top + 66, utc(row["conclusive_at"]), 10, "#475467") @@ -540,6 +570,7 @@ def text(x: int, y: int, value: str, size: int = 14, color: str = "#182230") -> def badge_svg(view: dict[str, Any], integration: str) -> str: rows = [row for row in view["integrations"] if row["integration"] == integration] + label = integration_label(integration) states = {row["state"] for row in rows} latest = view["latest_workflow"] unknown_selection = latest and latest["errors"] and not latest["profiles"] @@ -552,7 +583,7 @@ def badge_svg(view: dict[str, Any], integration: str) -> str: state = next( value for value in ("Failing", "Not tested", "Stale", "Working") if value in states ) - left_width = 20 + 7 * len(integration) + left_width = 20 + 7 * len(label) right_width = 20 + 7 * len(state) width = left_width + right_width root = ElementTree.Element( @@ -566,9 +597,9 @@ def badge_svg(view: dict[str, Any], integration: str) -> str: "aria-labelledby": "title description", }, ) - ElementTree.SubElement(root, "title", {"id": "title"}).text = f"{integration}: {state}" + ElementTree.SubElement(root, "title", {"id": "title"}).text = f"{label}: {state}" details = [ - f"Client {row['upstream_version']}, DocumentDB {row['documentdb_version']}, " + f"Client {row['upstream_version']}, DocumentDB {row['documentdb_release_tag']}, " f"profile {row['profile']}: {row['state']}. " f"Latest attempt: {row['latest_attempt_state']} at {utc(row['last_attempt'])}." for row in rows @@ -592,7 +623,7 @@ def badge_svg(view: dict[str, Any], integration: str) -> str: {"x": str(left_width), "width": str(right_width), "height": "24", "fill": COLORS[state]}, ) for x, value in ( - (left_width / 2, integration), + (left_width / 2, label), (left_width + right_width / 2, state), ): ElementTree.SubElement( diff --git a/compatibility/registry.yaml b/compatibility/registry.yaml index 6c878b4..6ec1eca 100644 --- a/compatibility/registry.yaml +++ b/compatibility/registry.yaml @@ -4,6 +4,10 @@ documentdb: image: ghcr.io/documentdb/documentdb/documentdb-local@sha256:d972e7145da660ad4892ce6f5c22039086ff5148dce7225f20b76af959cd2ce0 postgres_major: 17 extension_version: "0.117-0" + "1.2.0": + image: ghcr.io/documentdb/documentdb/documentdb-local@sha256:1d40546ccf53a0229f98a0848b7c3d6d74dc35a9fa535a1d1c8f70e3bed10d23 + postgres_major: 17 + extension_version: "1.2-0" integrations: pymongo: repository: https://github.com/mongodb/mongo-python-driver @@ -13,6 +17,7 @@ integrations: package: pymongo default_version: "4.18.0" version_pattern: '^4\.(9|[1-9][0-9]+)\.[0-9]+$' + watch_version_pattern: '^4\.[0-9]+\.[0-9]+$' profile: python312-linux-x64-sync test_file: compatibility/integrations/pymongo/test_pymongo.py demonstration_file: compatibility/integrations/pymongo/test_demonstration.py @@ -36,3 +41,67 @@ 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$' + watch_version_pattern: '^9\.[0-9]+\.[0-9]+$' + 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$' + watch_version_pattern: '^7\.[0-9]+\.[0-9]+$' + 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/resolve-npm.cjs b/compatibility/resolve-npm.cjs new file mode 100644 index 0000000..253a7ae --- /dev/null +++ b/compatibility/resolve-npm.cjs @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. +// SPDX-License-Identifier: MIT + +"use strict"; + +const fs = require("node:fs"); +const { spawnSync } = require("node:child_process"); + +const [name, version] = process.argv.slice(1); +if (!/^[a-z][a-z0-9_-]{0,39}$/.test(name) || !/^[0-9]+\.[0-9]+\.[0-9]+$/.test(version)) { + throw new Error("Invalid npm candidate identity"); +} +const directory = fs.mkdtempSync("/tmp/compatibility-npm-"); +const manifest = { + name: "documentdb-compatibility-candidate", + version: "1.0.0", + private: true, + dependencies: { [name]: version }, +}; +fs.writeFileSync(`${directory}/package.json`, JSON.stringify(manifest)); +const result = spawnSync( + "npm", + [ + "install", "--package-lock-only", "--ignore-scripts", "--save-exact", + "--engine-strict", "--omit=optional", "--no-audit", "--no-fund", + "--registry=https://registry.npmjs.org", "--cache=/tmp/npm-cache", + "--userconfig=/dev/null", + ], + { cwd: directory, encoding: "utf8", timeout: 120000, maxBuffer: 1024 * 1024 }, +); +if (result.error || result.status !== 0) { + console.error(result.error?.message || (result.stderr || result.stdout).slice(-4000)); + process.exit(1); +} +const contents = fs.readFileSync(`${directory}/package-lock.json`); +if (contents.length > 64 * 1024) { + throw new Error("npm candidate lockfile exceeded its size limit"); +} +process.stdout.write(JSON.stringify({ manifest, lockfile: JSON.parse(contents) })); diff --git a/compatibility/results.py b/compatibility/results.py index 47cd258..ad13c42 100644 --- a/compatibility/results.py +++ b/compatibility/results.py @@ -7,7 +7,6 @@ import json import os -import re import tempfile from collections import defaultdict from collections.abc import Callable @@ -19,11 +18,15 @@ ROOT, artifact_sha256, compatibility_state, + documentdb_release_tag, expected_tests, + integration_label, suite_digest, timestamp, validate_result, + version_allowed, ) +from compatibility.npm import validate_npm_bundle RunKey = tuple[str, str, str, str, bool] @@ -60,8 +63,14 @@ def validate_incoming_result( raise ValueError("Result does not belong to the publishing workflow run") spec = registry["integrations"][result["integration"]] validate_result(result, spec) - if not re.fullmatch(spec["version_pattern"], result["upstream"]["version"]): + if not version_allowed( + spec, result["upstream"]["version"], upstream=result["trigger"] == "upstream_release" + ): raise ValueError("Incoming result is outside the reviewed version policy") + if "npm_bundle" in result["upstream"]: + validate_npm_bundle( + result["upstream"]["npm_bundle"], spec, result["upstream"]["version"], root=root + ) database = registry["documentdb"][result["documentdb"]["version"]] if result["documentdb"]["image"] != database["image"]: raise ValueError("Incoming result does not reference the reviewed database artifact") @@ -146,6 +155,11 @@ def dashboard_rows( and artifact_sha256(latest) and artifact_sha256(latest) != artifact_sha256(current) ) + or ( + latest is not None + and latest["upstream"].get("npm_bundle_sha256") + != current["upstream"].get("npm_bundle_sha256") + ) ): state = "Stale" coverage_source = current or latest @@ -158,9 +172,11 @@ def dashboard_rows( rows.append( { "integration": integration, + "integration_label": integration_label(integration), "repository": spec["repository"], "owner": spec["owner"], "documentdb_version": database_version, + "documentdb_release_tag": documentdb_release_tag(database_version), "upstream_version": upstream_version, "profile": profile, "demonstration": demonstration, diff --git a/compatibility/runner.py b/compatibility/runner.py index db76969..c68a5fd 100644 --- a/compatibility/runner.py +++ b/compatibility/runner.py @@ -28,16 +28,20 @@ from packaging.version import Version from compatibility.contracts import ( + PYTHON_PLATFORMS, ROOT, compatibility_state, default_documentdb_version, expected_tests, + integration_id, read_registry, suite_digest, suite_files, validate_client_report, validate_result, + version_allowed, ) +from compatibility.npm import prepare_node_client, read_npm_bundle, validate_npm_bundle LABEL = "org.documentdb.compatibility.run" MAX_COMMAND_OUTPUT = 4 * 1024 * 1024 @@ -125,14 +129,11 @@ def prepare_client( "cp", "--abi", "cp312", - "--platform", - "manylinux_2_28_x86_64", - "--platform", - "manylinux_2_17_x86_64", - "--platform", - "manylinux2014_x86_64", - "--platform", - "manylinux1_x86_64", + *( + argument + for platform in PYTHON_PLATFORMS + for argument in ("--platform", platform) + ), "--dest", str(wheels), "-r", @@ -204,21 +205,47 @@ def execute( output: Path, *, wheelhouse: Path | None = None, + package_cache: Path | None = None, demonstration: bool = False, run_url: str | None = None, trigger: str = "manual", + detection_id: str | None = None, + expected_artifact_sha256s: list[str] | None = None, + npm_bundle: Path | None = None, + expected_npm_bundle_sha256: str | None = None, ) -> dict[str, Any]: """Emit a validated result even when setup, execution, or teardown fails.""" spec = registry["integrations"][integration] database = registry["documentdb"][documentdb_version] - if ( - not spec["enabled"] - or len(version) > 40 - or not re.fullmatch(spec["version_pattern"], version) + if not spec["enabled"] or not version_allowed( + spec, version, upstream=trigger == "upstream_release" ): 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 trigger == "upstream_release": + if ( + not detection_id + or not re.fullmatch(r"[a-f0-9]{64}", detection_id) + or not expected_artifact_sha256s + or len(expected_artifact_sha256s) > 10 + or any(not re.fullmatch(r"[a-f0-9]{64}", value) for value in expected_artifact_sha256s) + or demonstration + ): + raise ValueError( + "Upstream execution requires a detection ID and reviewed artifact hashes" + ) + elif detection_id is not None or expected_artifact_sha256s is not None: + raise ValueError("Watcher provenance is only supported for upstream-release execution") + if trigger == "upstream_release" and spec["runtime"] == "nodejs": + if npm_bundle is None or not re.fullmatch( + r"[a-f0-9]{64}", expected_npm_bundle_sha256 or "" + ): + raise ValueError("npm upstream execution requires its frozen bundle and recorded hash") + elif npm_bundle is not None or expected_npm_bundle_sha256 is not None: + raise ValueError("npm candidate bundles are only supported for recorded npm releases") + 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( @@ -259,6 +286,10 @@ def execute( "demonstration": demonstration, "execution_error": None, } + if detection_id is not None: + result["detection_id"] = detection_id + if expected_npm_bundle_sha256 is not None: + result["upstream"]["npm_bundle_sha256"] = expected_npm_bundle_sha256 validate_result(result, spec) password = secrets.token_urlsafe(24) + "Aa1!" image = "" @@ -267,8 +298,21 @@ 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: + bundle = None + if npm_bundle is not None: + bundle = read_npm_bundle(npm_bundle) + if validate_npm_bundle(bundle, spec, version) != expected_npm_bundle_sha256: + raise ValueError("npm candidate bundle differs from the recorded inputs") + result["upstream"]["npm_bundle"] = bundle + digest = prepare_node_client(context, spec, version, package_cache, bundle) result["upstream"]["artifact_sha256"] = digest + if expected_artifact_sha256s is not None and digest not in expected_artifact_sha256s: + raise ValueError( + "Selected package differs from the durably recorded upstream artifacts" + ) result["suite_digest"] = suite_digest(integration, spec, root=context) candidate_image = f"docdb-compat-{run_id}" command( @@ -454,27 +498,42 @@ 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", - choices=("manual", "push", "scheduled", "documentdb_release"), + choices=("manual", "push", "scheduled", "documentdb_release", "upstream_release"), default="manual", ) + parser.add_argument("--detection-id") + parser.add_argument( + "--expected-artifact-sha256", dest="expected_artifact_sha256s", action="append" + ) + parser.add_argument( + "--npm-bundle", type=Path, help="Frozen inputs from an authorized detection" + ) + parser.add_argument("--expected-npm-bundle-sha256") parser.add_argument("--demonstration", action="store_true") args = parser.parse_args() try: registry = read_registry() - version = args.version or registry["integrations"][args.integration]["default_version"] + integration = integration_id(args.integration) + version = args.version or registry["integrations"][integration]["default_version"] result = execute( registry, - args.integration, + integration, version, 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, + detection_id=args.detection_id, + expected_artifact_sha256s=args.expected_artifact_sha256s, + npm_bundle=args.npm_bundle, + expected_npm_bundle_sha256=args.expected_npm_bundle_sha256, ) except KeyError: print("Unknown integration or DocumentDB release", file=sys.stderr) diff --git a/compatibility/schemas/npm-bundle.json b/compatibility/schemas/npm-bundle.json new file mode 100644 index 0000000..1c59926 --- /dev/null +++ b/compatibility/schemas/npm-bundle.json @@ -0,0 +1,42 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "additionalProperties": false, + "required": ["resolver_image", "manifest", "lockfile"], + "properties": { + "resolver_image": { + "type": "string", + "pattern": "^node:24\\.[0-9]+\\.[0-9]+-[A-Za-z0-9_.-]+@sha256:[a-f0-9]{64}$" + }, + "manifest": { + "type": "object", + "additionalProperties": false, + "required": ["name", "version", "private", "dependencies"], + "properties": { + "name": {"const": "documentdb-compatibility-candidate"}, + "version": {"const": "1.0.0"}, + "private": {"const": true}, + "dependencies": { + "type": "object", + "minProperties": 1, + "maxProperties": 1, + "propertyNames": {"pattern": "^[a-z][a-z0-9_-]{0,39}$"}, + "additionalProperties": {"type": "string", "pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+$"} + } + } + }, + "lockfile": { + "type": "object", + "required": ["lockfileVersion", "packages"], + "properties": { + "lockfileVersion": {"const": 3}, + "packages": { + "type": "object", + "minProperties": 2, + "maxProperties": 101, + "additionalProperties": {"type": "object"} + } + } + } + } +} diff --git a/compatibility/schemas/registry.json b/compatibility/schemas/registry.json index 23e587a..839d753 100644 --- a/compatibility/schemas/registry.json +++ b/compatibility/schemas/registry.json @@ -36,6 +36,7 @@ "package": {"type": "string", "pattern": "^[a-z][a-z0-9_-]{0,39}$"}, "default_version": {"type": "string", "pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+$"}, "version_pattern": {"type": "string", "minLength": 1, "maxLength": 100}, + "watch_version_pattern": {"type": "string", "minLength": 1, "maxLength": 100}, "profile": {"type": "string", "pattern": "^[a-z0-9_-]{1,80}$"}, "test_file": {"type": "string", "pattern": "^compatibility/integrations/[a-z0-9_]+/test_[a-z0-9_]+\\.(?:py|cjs)$"}, "demonstration_file": {"type": "string", "pattern": "^compatibility/integrations/[a-z0-9_]+/test_[a-z0-9_]+\\.(?:py|cjs)$"}, diff --git a/compatibility/schemas/result.json b/compatibility/schemas/result.json index bb58bf4..b1b1e16 100644 --- a/compatibility/schemas/result.json +++ b/compatibility/schemas/result.json @@ -56,6 +56,8 @@ "actual_version": {"type": ["string", "null"], "pattern": "^[0-9]+\\.[0-9]+(?:\\.[0-9]+)?$"}, "wheel_sha256": {"type": ["string", "null"], "pattern": "^[a-f0-9]{64}$"}, "artifact_sha256": {"type": ["string", "null"], "pattern": "^[a-f0-9]{64}$"}, + "npm_bundle_sha256": {"type": "string", "pattern": "^[a-f0-9]{64}$"}, + "npm_bundle": {"type": "object"}, "runtime": {"$ref": "#/$defs/runtime"}, "client_image": {"type": ["string", "null"], "pattern": "^sha256:[a-f0-9]{64}$"}, "python_version": {"type": ["string", "null"], "pattern": "^3\\.12\\.[0-9]+$"}, @@ -92,6 +94,7 @@ "started_at": {"type": "string", "format": "date-time"}, "finished_at": {"type": "string", "format": "date-time"}, "trigger": {"enum": ["manual", "push", "documentdb_release", "upstream_release", "scheduled"]}, + "detection_id": {"type": "string", "pattern": "^[a-f0-9]{64}$"}, "run_url": {"type": ["string", "null"], "pattern": "^https://github\\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/actions/runs/[0-9]+(?:/attempts/[1-9][0-9]*)?$"}, "demonstration": {"type": "boolean"}, "execution_error": {"type": ["string", "null"], "maxLength": 2000} diff --git a/compatibility/schemas/watcher.json b/compatibility/schemas/watcher.json new file mode 100644 index 0000000..3004906 --- /dev/null +++ b/compatibility/schemas/watcher.json @@ -0,0 +1,95 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", "additionalProperties": false, + "required": ["schema_version", "entries", "last_scan"], + "properties": { + "schema_version": {"const": 1}, + "entries": { + "type": "object", "maxProperties": 1000, + "propertyNames": {"pattern": "^[a-f0-9]{64}$"}, + "additionalProperties": {"$ref": "#/$defs/entry"} + }, + "last_scan": { + "type": ["object", "null"], "additionalProperties": false, + "required": ["run_url", "at", "observations", "error"], + "properties": { + "run_url": {"$ref": "#/$defs/run_url"}, + "at": {"type": "string", "format": "date-time"}, + "observations": { + "type": "array", "maxItems": 300, + "items": { + "type": "object", "additionalProperties": false, + "required": ["tag", "decision"], + "properties": { + "integration": {"type": "string", "pattern": "^[a-z][a-z0-9_]{0,39}$"}, + "tag": {"type": "string", "maxLength": 100}, + "decision": {"type": "string", "maxLength": 200} + } + } + }, + "error": {"type": ["string", "null"], "maxLength": 500} + } + } + }, + "$defs": { + "sha256": {"type": "string", "pattern": "^[a-f0-9]{64}$"}, + "run_url": {"type": "string", "pattern": "^https://github\\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/actions/runs/[0-9]+(?:/attempts/[1-9][0-9]*)?$"}, + "entry": { + "type": "object", "additionalProperties": false, + "required": ["integration", "version", "documentdb_version", "documentdb_image", "profile", "suite_digest", "artifacts", "release", "metadata_sha256", "detected_at", "source_sha", "detected_by", "status", "attempts", "error"], + "properties": { + "integration": {"type": "string", "pattern": "^[a-z][a-z0-9_]{0,39}$"}, + "version": {"type": "string", "pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+$"}, + "documentdb_version": {"type": "string", "pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+$"}, + "documentdb_image": {"type": "string", "pattern": "^ghcr\\.io/documentdb/documentdb/documentdb-local@sha256:[a-f0-9]{64}$"}, + "profile": {"type": "string", "pattern": "^[a-z0-9_-]{1,80}$"}, + "suite_digest": {"$ref": "#/$defs/sha256"}, + "npm_bundle": {"type": "object"}, + "artifacts": { + "type": "array", "minItems": 1, "maxItems": 10, + "items": { + "type": "object", "additionalProperties": false, + "required": ["filename", "sha256"], + "properties": { + "filename": {"type": "string", "pattern": "^[a-zA-Z0-9][A-Za-z0-9_.+-]*\\.(?:whl|tgz)$", "maxLength": 250}, + "sha256": {"$ref": "#/$defs/sha256"} + } + } + }, + "release": { + "type": "object", "additionalProperties": false, + "required": ["id", "tag", "url", "published_at"], + "properties": { + "id": {"type": "integer", "minimum": 1}, + "tag": {"type": "string", "maxLength": 100}, + "url": {"type": "string", "pattern": "^https://github\\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/releases/tag/v?[0-9]+\\.[0-9]+(?:\\.[0-9]+)?$"}, + "published_at": {"type": "string", "format": "date-time"} + } + }, + "metadata_sha256": {"$ref": "#/$defs/sha256"}, + "detected_at": {"type": "string", "format": "date-time"}, + "source_sha": {"type": "string", "pattern": "^[a-f0-9]{40}$"}, + "detected_by": {"$ref": "#/$defs/run_url"}, + "status": {"enum": ["pending", "dispatching", "dispatched", "completed", "blocked", "superseded"]}, + "attempts": { + "type": "array", "maxItems": 3, + "items": { + "type": "object", "additionalProperties": false, + "required": ["id", "watcher_run_url", "started_at", "state", "run_id", "run_url", "conclusion", "error"], + "properties": { + "id": {"type": "string", "pattern": "^[a-f0-9]{32}$"}, + "watcher_run_url": {"$ref": "#/$defs/run_url"}, + "started_at": {"type": "string", "format": "date-time"}, + "state": {"enum": ["dispatching", "dispatched", "rejected", "unknown", "reconciled"]}, + "run_id": {"type": ["integer", "null"], "minimum": 1}, + "run_url": {"type": ["string", "null"], "pattern": "^https://github\\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/actions/runs/[0-9]+$"}, + "conclusion": {"type": ["string", "null"], "maxLength": 100}, + "error": {"type": ["string", "null"], "maxLength": 500} + } + } + }, + "error": {"type": ["string", "null"], "maxLength": 500} + } + } + } +} diff --git a/compatibility/unit/conftest.py b/compatibility/unit/conftest.py index a602013..87f30a6 100644 --- a/compatibility/unit/conftest.py +++ b/compatibility/unit/conftest.py @@ -3,6 +3,7 @@ """Validated test records for compatibility infrastructure.""" +import base64 import hashlib import io import json @@ -17,6 +18,7 @@ from compatibility import runner from compatibility.contracts import ROOT, read_registry, suite_digest +from compatibility.npm import REGISTRY, node_image @pytest.fixture @@ -60,6 +62,45 @@ def registry(): return read_registry() +@pytest.fixture +def npm_archive(): + return b"synthetic npm archive for contract tests" + + +@pytest.fixture +def npm_bundle(registry, npm_archive): + def make(integration="nodejs", version=None): + spec = registry["integrations"][integration] + selected = version or spec["default_version"] + archive = f"{REGISTRY}/{spec['package']}/-/{spec['package']}-{selected}.tgz" + manifest = { + "name": "documentdb-compatibility-candidate", + "version": "1.0.0", + "private": True, + "dependencies": {spec["package"]: selected}, + } + return { + "resolver_image": node_image(spec), + "manifest": manifest, + "lockfile": { + "name": manifest["name"], + "version": manifest["version"], + "lockfileVersion": 3, + "packages": { + "": deepcopy(manifest), + f"node_modules/{spec['package']}": { + "version": selected, + "resolved": archive, + "integrity": "sha512-" + + base64.b64encode(hashlib.sha512(npm_archive).digest()).decode(), + }, + }, + }, + } + + return make + + @pytest.fixture def selection(registry): return { diff --git a/compatibility/unit/test_contracts.py b/compatibility/unit/test_contracts.py index f558c7e..84c9c5c 100644 --- a/compatibility/unit/test_contracts.py +++ b/compatibility/unit/test_contracts.py @@ -8,6 +8,7 @@ import pytest +from compatibility import contracts from compatibility.contracts import ( artifact_sha256, compatibility_state, @@ -18,6 +19,7 @@ validate_result, validate_schema, ) +from compatibility.results import validate_incoming_result pytestmark = pytest.mark.unit @@ -187,6 +189,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} @@ -212,6 +237,19 @@ def test_prepared_build_context_preserves_the_reviewed_suite(prepared_context, r assert suite_digest(integration, spec, prepared_context) == suite_digest(integration, spec) +def test_historical_source_without_candidate_files_can_still_be_validated( + prepared_context, registry, selection, record, monkeypatch +): + integration = selection["integration"] + spec = registry["integrations"][integration] + (prepared_context / "compatibility/schemas/npm-bundle.json").unlink() + record["suite_digest"] = suite_digest(integration, spec, prepared_context) + validate_incoming_result(record, registry, root=prepared_context) + monkeypatch.setattr(contracts, "ROOT", prepared_context) + with pytest.raises(FileNotFoundError): + suite_digest(integration, spec, prepared_context) + + @pytest.mark.parametrize( "filename", [ @@ -219,6 +257,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..61cf589 --- /dev/null +++ b/compatibility/unit/test_freshness.cjs @@ -0,0 +1,44 @@ +// 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(previousState, conclusiveAt = new Date(tested).toISOString(), textContent = previousState) { + return { dataset: { conclusiveAt, freshnessDays: "7", previousState }, textContent, className: textContent }; +} + +function load(element, now) { + let interval; + vm.runInNewContext(source, { + document: { querySelectorAll: selector => (selector === "[data-compatibility-status]" ? [element] : []) }, + Date: { parse: Date.parse, now: () => now }, + setInterval: callback => { interval = callback; }, + }); + return next => { now = next; interval(); }; +} + +test("the freshness boundary stays fresh until a later timer tick", () => { + const element = status("Working"); + const tick = load(element, tested + 7 * day); + assert.equal(element.textContent, "Working"); + tick(tested + 7 * day + 1); + assert.deepEqual([element.textContent, element.className], ["Stale (last: Working)", "Stale"]); +}); + +test("untested entries and server-side stale classifications are not refreshed", () => { + const untested = status("Not tested", ""); + const stale = status("Working", undefined, "Stale"); + load(untested, tested + 8 * day); + load(stale, tested + day); + assert.deepEqual([untested.textContent, stale.textContent], ["Not tested", "Stale"]); +}); diff --git a/compatibility/unit/test_nodejs.cjs b/compatibility/unit/test_nodejs.cjs new file mode 100644 index 0000000..e97534f --- /dev/null +++ b/compatibility/unit/test_nodejs.cjs @@ -0,0 +1,96 @@ +// 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); + 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: { ...process.env, NODE_TEST_CONTEXT: undefined } }); + } finally { + fs.rmSync(directory, { recursive: true }); + } +} + +test("registered scenarios are gated and classified by the production reporter", () => { + const result = execute(` + const { register } = require(${JSON.stringify(reporter)}); + const fixture = () => ({ close() {} }); + const server = code => Object.assign(new Error("Server"), { name: "MongoServerError", code }); + process.env.COMPATIBILITY_ACTIVE = "0"; + process.env.COMPATIBILITY_DEMONSTRATION = "0"; + register({ test_inactive() {} }, fixture); + process.env.COMPATIBILITY_ACTIVE = "1"; + register({ test_pass() {}, test_operation() { throw server(115); }, test_timeout() { throw server(50); } }, fixture); + register({ test_hidden_demonstration() {} }, fixture, true); + process.env.COMPATIBILITY_DEMONSTRATION = "1"; + register({ test_demonstration() {} }, fixture, true); + `); + assert.equal(result.status, 1, result.stderr); + assert.deepEqual(JSON.parse(result.stdout).map(record => [record.id, record.outcome]), [ + ["test_inactive", "skipped"], + ["test_pass", "passed"], + ["test_operation", "failed"], + ["test_timeout", "error"], + ["test_hidden_demonstration", "skipped"], + ["test_demonstration", "passed"], + ]); +}); + +for (const [name, source, message] of [ + ["duplicate scenario names", "const { test } = require('node:test'); test('test_a', () => {}); test('test_a', () => {});", /Duplicate scenario/], + ["collection errors", "throw new Error('Collection failed');", /Collection failed/], + ["late asynchronous errors", "require('node:test').test('test_a', () => { setImmediate(() => { throw new Error('Late failure'); }); });", /Late failure/], +]) { + test(`${name} cannot pass`, () => { + const result = execute(source); + assert.equal(result.status, 2, result.stdout + result.stderr); + assert.match(result.stderr, message); + }); +} + +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 errors cannot mask or become compatibility failures", async () => { + const setup = () => { throw Object.assign(new Error("Setup failed"), { name: "MongoServerError" }); }; + const cleanup = () => ({ close() { throw new Error("Cleanup failed"); } }); + await assert.rejects(runScenario(setup, () => {}), error => classify(error) === "error"); + await assert.rejects(runScenario(cleanup, () => {}), error => classify(error) === "error"); + await assert.rejects(runScenario(cleanup, () => assert.fail("Mismatch")), error => classify(error) === "failed"); + await assert.rejects(runScenario(() => ({ close() {} }), () => { throw undefined; })); +}); + +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" tests="4" failures="1" errors="1" skipped="1"/); + assert.match(output, /<mismatch> & "value"<\/failure>/); +}); diff --git a/compatibility/unit/test_npm.py b/compatibility/unit/test_npm.py new file mode 100644 index 0000000..6550687 --- /dev/null +++ b/compatibility/unit/test_npm.py @@ -0,0 +1,123 @@ +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: MIT + +"""Lockfile provenance and offline npm preparation without executing package code.""" + +import hashlib +import json +import shutil +from pathlib import Path + +import pytest + +from compatibility import npm +from compatibility.contracts import ROOT, suite_digest, suite_files + +pytestmark = pytest.mark.unit + + +@pytest.fixture +def reviewed(tmp_path, monkeypatch, registry, npm_bundle, npm_archive): + spec = registry["integrations"]["nodejs"] + bundle = npm_bundle() + adapter = tmp_path / "source" / Path(spec["test_file"]).parent + adapter.mkdir(parents=True) + (adapter / "package.json").write_text(json.dumps(bundle["manifest"])) + (adapter / "package-lock.json").write_text(json.dumps(bundle["lockfile"])) + monkeypatch.setattr(npm, "ROOT", tmp_path / "source") + monkeypatch.setattr(npm, "suite_files", lambda integration: list(adapter.glob("*.json"))) + monkeypatch.setattr(npm, "registry_bytes", lambda address, limit: npm_archive) + return spec + + +def prepare(tmp_path, spec, name="context", version=None, **options): + context = tmp_path / name + context.mkdir() + version = version or spec["default_version"] + return context, npm.prepare_node_client(context, spec, version, **options) + + +def test_locked_archive_is_verified_recorded_and_cached( + tmp_path, reviewed, npm_archive, monkeypatch +): + cache = tmp_path / "cache" + context, digest = prepare(tmp_path, reviewed, package_cache=cache) + assert digest == hashlib.sha256(npm_archive).hexdigest() + assert json.loads((context / "install-report.json").read_text())["install"] == [ + { + "path": f"node_modules/{reviewed['package']}", + "name": reviewed["package"], + "version": reviewed["default_version"], + "sha256": digest, + } + ] + assert (context / "npm-packages" / f"{digest}.tgz").read_bytes() == npm_archive + monkeypatch.setattr(npm, "registry_bytes", lambda *args: pytest.fail("Cache used the network")) + assert prepare(tmp_path, reviewed, "offline", package_cache=cache)[1] == digest + + +def test_downloaded_archive_is_verified_before_caching(tmp_path, reviewed, monkeypatch): + monkeypatch.setattr(npm, "registry_bytes", lambda *args: b"corrupted") + cache = tmp_path / "cache" + with pytest.raises(ValueError, match="integrity"): + prepare(tmp_path, reviewed, package_cache=cache) + assert not list(cache.iterdir()) + + +@pytest.mark.parametrize("integration", ["nodejs", "mongoose"]) +def test_reviewed_node_lockfiles_pin_the_registry_default(registry, integration): + spec = registry["integrations"][integration] + adapter = ROOT / Path(spec["test_file"]).parent + manifest, lock = ( + json.loads((adapter / name).read_text()) for name in ("package.json", "package-lock.json") + ) + npm.validate_lock(manifest, lock, spec, spec["default_version"]) + + +def test_node_lockfile_is_part_of_provenance(tmp_path, registry): + spec = registry["integrations"]["nodejs"] + for source in suite_files("nodejs"): + destination = tmp_path / source.relative_to(ROOT) + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, destination) + original = suite_digest("nodejs", spec, tmp_path) + lock = tmp_path / Path(spec["test_file"]).parent / "package-lock.json" + lock.write_text(lock.read_text() + "\n") + assert suite_digest("nodejs", spec, tmp_path) != original + + +def test_candidate_bundle_uses_its_exact_lock_and_preserves_reviewed_sources( + tmp_path, registry, monkeypatch, npm_bundle, npm_archive +): + spec = registry["integrations"]["nodejs"] + major, minor, _ = spec["default_version"].split(".") + version = f"{major}.{int(minor) + 1}.0" + bundle = npm_bundle("nodejs", version) + monkeypatch.setattr(npm, "registry_bytes", lambda *args: npm_archive) + context, digest = prepare(tmp_path, spec, version=version, npm_bundle=bundle) + assert digest == hashlib.sha256(npm_archive).hexdigest() + assert json.loads((context / "package-lock.json").read_text()) == bundle["lockfile"] + assert suite_digest("nodejs", spec, context) == suite_digest("nodejs", spec) + with pytest.raises(ValueError, match="lockfile"): + prepare(tmp_path, spec, "manual", version) + + +@pytest.mark.parametrize( + ("location", "field", "value", "message"), + [ + (None, "resolved", "https://example.test/driver.tgz", "registry"), + (None, "integrity", "sha1-unreviewed", "SHA-512"), + ("node_modules/../../outside", "optional", True, "location"), + ], +) +def test_candidate_lock_is_validated_before_any_archive_access( + tmp_path, registry, monkeypatch, npm_bundle, location, field, value, message +): + spec = registry["integrations"]["nodejs"] + bundle = npm_bundle() + packages = bundle["lockfile"]["packages"] + selected = f"node_modules/{spec['package']}" + packages[location or selected] = {**packages[selected], field: value} + monkeypatch.setattr(npm, "registry_bytes", lambda *args: pytest.fail("Fetched an archive")) + with pytest.raises(ValueError, match=message): + prepare(tmp_path, spec, npm_bundle=bundle) diff --git a/compatibility/unit/test_orchestration.py b/compatibility/unit/test_orchestration.py new file mode 100644 index 0000000..43796b7 --- /dev/null +++ b/compatibility/unit/test_orchestration.py @@ -0,0 +1,359 @@ +# 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 + +import pytest +import yaml +from packaging.version import Version + +from compatibility import workflow +from compatibility.contracts import ( + RUNTIME_PREFIXES, + expected_tests, + npm_bundle_digest, + suite_digest, +) + +pytestmark = pytest.mark.unit +RUN_URL = "https://github.com/example/project/actions/runs/42/attempts/3" +PROVENANCE = ["--detection-id", "a" * 64, "--dispatch-id", "b" * 32] + + +@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): + name, version = run["integration"], run["version"] + spec = registry["integrations"][name] + parts = RUNTIME_PREFIXES[spec["runtime"]].rstrip(".").split(".") + runtime = {"name": spec["runtime"], "version": ".".join(parts + ["0"] * (3 - len(parts)))} + result = deepcopy(record) + result.update( + id=f"{index + 1:032x}", + integration=name, + suite_digest=suite_digest(name, spec), + expected_tests=expected_tests(spec, False), + **{key: spec[key] for key in ("repository", "owner", "profile")}, + ) + result["tests"] = [ + {"id": test, "outcome": "passed", "message": ""} for test in result["expected_tests"] + ] + result["upstream"].update( + version=version, + actual_version=version, + runtime=runtime, + dependencies=[{"name": spec["package"], "version": version, "sha256": "b" * 64}], + ) + results[name] = result + return results + + +def write_records(path, records): + for integration, result in records.items(): + directory = path / integration / 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 run_cli(monkeypatch, *arguments): + monkeypatch.setattr(sys, "argv", ["workflow", *arguments]) + return workflow.main() + + +def test_single_integration_version_override(registry, selection, other_version): + runs = workflow.select_runs( + registry, selection["integration"], other_version, selection["documentdb_version"] + ) + assert runs == [{**selection, "version": other_version, "trigger": "manual"}] + + +def test_automatic_runs_select_each_enabled_default_and_reviewed_release(registry, selection): + registry["integrations"][selection["integration"]]["enabled"] = False + reviewed = registry["documentdb"][selection["documentdb_version"]] + for release in ("0.9.0", "999.0.0"): + registry["documentdb"][release] = deepcopy(reviewed) + releases = sorted(registry["documentdb"], key=Version) + enabled = sorted(name for name, spec in registry["integrations"].items() if spec["enabled"]) + every = workflow.select_runs(registry, "all", None, "all", trigger="scheduled") + assert [tuple(run.values()) for run in every] == [ + (name, registry["integrations"][name]["default_version"], release, "scheduled") + for name in enabled + for release in releases + ] + one = workflow.select_runs(registry, "all", None, "0.9.0", trigger="documentdb_release") + assert [(run["integration"], run["documentdb_version"]) for run in one] == [ + (name, "0.9.0") for name in enabled + ] + newest = workflow.select_runs(registry, enabled[-1], None, None) + assert newest == [{**every[-1], "trigger": "manual"}] + + +@pytest.mark.parametrize( + ("trigger", "integration", "version", "database", "error"), + [ + ("manual", "unknown", None, None, "Unknown or disabled"), + ("manual", None, "not-a-version; echo unsafe", None, "outside the policy"), + ("manual", "all", None, "99.99.99", "Unknown DocumentDB"), + ("scheduled", "all", None, None, "every reviewed DocumentDB release"), + ("documentdb_release", "all", None, "all", "one reviewed release"), + ("scheduled", None, None, "all", "every enabled integration"), + ("push", "all", None, "all", "Unknown execution trigger"), + ], +) +def test_invalid_or_narrowed_selection_is_rejected( + registry, selection, trigger, integration, version, database, error +): + with pytest.raises(ValueError, match=error): + workflow.select_runs( + registry, + integration or selection["integration"], + version, + database or selection["documentdb_version"], + trigger=trigger, + ) + + +def test_changed_releases_are_added_or_re_pinned_entries(tmp_path, registry, selection): + release = selection["documentdb_version"] + previous = deepcopy(registry) + registry["documentdb"]["999.0.0"] = deepcopy(registry["documentdb"][release]) + image = previous["documentdb"][release]["image"] + previous["documentdb"][release]["image"] = image[:-1] + ("1" if image[-1] == "0" else "0") + previous["integrations"][selection["integration"]]["default_version"] = "0.0.0" + source = tmp_path / "previous.yaml" + source.write_text(yaml.safe_dump(previous)) + assert workflow.changed_releases(registry, source) == [release, "999.0.0"] + for contents in ("{", "documentdb: []\n"): + source.write_text(contents) + assert workflow.changed_releases(registry, source) == sorted( + registry["documentdb"], key=Version + ) + + +@pytest.mark.parametrize(("release", "tag"), [("0.117.0", "v0.117-0"), ("1.2.0", "v1.2-0")]) +def test_matrix_cli_serializes_the_selected_runs(monkeypatch, capsys, registry, release, tag): + runs = workflow.select_runs(registry, "all", None, release) + assert run_cli(monkeypatch, "matrix", "--documentdb-version", release) == 0 + labels = {"mongoose": "mongoose", "nodejs": "mongodb-node", "pymongo": "pymongo"} + assert json.loads(capsys.readouterr().out) == { + "include": [ + {**run, "documentdb_release_tag": tag, "integration_label": labels[run["integration"]]} + for run in runs + ] + } + + +@pytest.mark.parametrize("name", ["mongodb-node", "nodejs"]) +def test_node_driver_selector_keeps_the_existing_result_identity(registry, name): + runs = workflow.select_runs(registry, name, None, None) + assert [run["integration"] for run in runs] == ["nodejs"] + + +@pytest.mark.parametrize( + ("arguments", "error"), + [ + (["--version", "1.2.3"], "single integration"), + (["--trigger", "scheduled", *PROVENANCE], "cannot be combined"), + ], +) +def test_matrix_cli_does_not_emit_a_plan_for_invalid_input(monkeypatch, capsys, arguments, error): + monkeypatch.setattr(workflow, "validate_dispatch", lambda *_: {}) + assert run_cli(monkeypatch, "matrix", *arguments) == 2 + captured = capsys.readouterr() + assert not captured.out and error in captured.err + + +@pytest.mark.parametrize("authorized", [False, True]) +def test_upstream_matrix_uses_only_ledger_authorized_artifacts( + monkeypatch, capsys, selection, authorized +): + def authorize(registry, runs, identifier, nonce): + assert runs == [{**selection, "trigger": "upstream_release"}] + assert identifier == "a" * 64 and nonce == "b" * 32 + if not authorized: + raise ValueError("Fixture ledger rejected this request") + return {"artifact_sha256s": ["c" * 64]} + + monkeypatch.setattr(workflow, "validate_dispatch", authorize) + arguments = [f"--{key.replace('_', '-')}={value}" for key, value in selection.items()] + assert run_cli(monkeypatch, "matrix", *arguments, *PROVENANCE) == (0 if authorized else 2) + captured = capsys.readouterr() + plan = { + **selection, + "trigger": "upstream_release", + "detection_id": "a" * 64, + "integration_label": "pymongo", + "documentdb_release_tag": "v0.117-0", + } + if authorized: + assert json.loads(captured.out)["include"] == [{**plan, "artifact_sha256s": ["c" * 64]}] + else: + assert not captured.out and "ledger rejected" 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["success"] and report["errors"] == [] + assert {record["integration"]: record for record in history} == records + for integration, row in rows.items(): + assert row["state"] == "Working" and row["run_url"] == RUN_URL + assert row["passed"] == row["expected"] == len(records[integration]["expected_tests"]) + assert summary.read_text() == "Earlier step\n" + (output / "summary.md").read_text() + assert "All selected profiles passed." in summary.read_text() + assert "| v0.117-0 |" in summary.read_text() + assert "| mongodb-node |" in summary.read_text() + page = (output / "site/index.html").read_text() + assert "DocumentDB v0.117-0" in page + assert ">mongodb-node" in page + assert "integration=mongodb-node" in rows["nodejs"]["issue_url"] + with pytest.raises(ValueError, match="overwrite"): + workflow.collect_report(incoming, output, registry, runs) + assert read_report(output)[0] == report + + +@pytest.mark.parametrize("bundle_matches", [True, False]) +def test_upstream_report_requires_the_planned_npm_bundle( + tmp_path, registry, selection, records, npm_bundle, bundle_matches +): + candidate = records["nodejs"] + major, minor, _ = candidate["upstream"]["version"].split(".") + version = f"{major}.{int(minor) + 1}.0" + database = selection["documentdb_version"] + with pytest.raises(ValueError, match="outside the policy"): + workflow.select_runs(registry, "nodejs", version, database) + runs = workflow.select_runs(registry, "nodejs", version, database, trigger="upstream_release") + bundle = npm_bundle("nodejs", version) + digest = npm_bundle_digest(bundle) + candidate.update(trigger="upstream_release", detection_id="a" * 64, run_url=RUN_URL) + candidate["upstream"].update( + version=version, actual_version=version, npm_bundle=bundle, npm_bundle_sha256=digest + ) + candidate["upstream"]["dependencies"][0]["version"] = version + incoming = write_records(tmp_path / "incoming", {"nodejs": candidate}) + output = tmp_path / "report" + success = workflow.collect_report( + incoming, + output, + registry, + runs, + expected_run_url=RUN_URL, + detection_id="a" * 64, + expected_npm_bundle_sha256=digest if bundle_matches else "f" * 64, + ) + assert success is bundle_matches + report, rows, history = read_report(output) + assert report["detection_id"] == "a" * 64 + assert rows["nodejs"]["state"] == ("Working" if bundle_matches else "Not tested") + assert history == ([candidate] if bundle_matches else []) + + +@pytest.mark.parametrize( + ("field", "value", "diagnostic"), + [ + (("upstream", "version"), "99.1.2", "selected integration"), + (("owner",), "@example/other", "owner"), + (("documentdb", "actual_extension_version"), "99.1-2", "installed extension"), + ( + ("documentdb", "image"), + "ghcr.io/documentdb/documentdb/documentdb-local@sha256:" + "0" * 64, + "reviewed database artifact", + ), + (("run_url",), RUN_URL[:-1] + "2", "workflow run"), + ], +) +def test_unmatched_or_unreviewed_evidence_is_rejected_independently( + tmp_path, registry, selection, runs, records, field, value, diagnostic +): + integration = selection["integration"] + for record in records.values(): + record["run_url"] = RUN_URL + target = records[integration] + for part in field[:-1]: + target = target[part] + target[field[-1]] = value + 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[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("linked", [False, True]) +def test_missing_linked_or_unexpected_artifacts_still_produce_a_combined_report( + tmp_path, registry, selection, runs, records, linked +): + integration = selection["integration"] + incoming = write_records(tmp_path / "incoming", records) + (incoming / "unexpected").mkdir() + path = incoming / integration / selection["documentdb_version"] / "result.json" + if linked: + # A valid record behind a linked integration directory is still rejected. + target = tmp_path / "linked-integration" + path.parent.parent.rename(target) + path.parent.parent.symlink_to(target, target_is_directory=True) + else: + path.unlink() + output = tmp_path / "report" + assert not workflow.collect_report(incoming, output, registry, runs) + report, rows, history = read_report(output) + assert report["errors"] 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 "Reporting errors" in (output / "summary.md").read_text() + + +def test_report_cli_fails_without_letting_diagnostics_inject_summary_rows( + tmp_path, monkeypatch, 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" + code = run_cli( + monkeypatch, + "report", + f"--input={incoming}", + f"--output={output}", + f"--documentdb-version={selection['documentdb_version']}", + ) + assert code == 1 + report, rows, _ = read_report(output) + assert not report["success"] and rows[selection["integration"]]["state"] == "Failing" + summary = (output / "summary.md").read_text() + assert "") + for result in (record, failed): + append_result(tmp_path / "data", result) + rows = render(tmp_path / "data", tmp_path / "site", registry) + row = next(row for row in rows if row["history"]) + html = (tmp_path / "site" / "index.html").read_text() + assert (row["state"], len(row["history"])) == ("Failing", 2) + assert "