From c60fe3c060255e5c522bded45e4ee0064b233395 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Sat, 21 Nov 2026 20:36:27 +0100 Subject: [PATCH 1/3] ci: run benchmarks locally and publish retrieval results --- .github/INTEGRATION-TEST.md | 7 +- .github/RELEASE.md | 6 +- .github/scripts/release_gate.py | 1 - .github/workflows/ci.yml | 5 +- .github/workflows/product-quality.yml | 30 -- .github/workflows/release.yml | 5 +- AGENT-EXECUTION-PIPELINE.md | 9 + AGENTS.md | 6 +- CONTRIBUTING.md | 51 +- README.md | 17 +- docs/benchmarks/AGENTIC-BENCHMARK-DESIGN.md | 16 +- .../PUBLIC-BENCHMARK-METHODOLOGY.md | 5 + docs/benchmarks/SANDBOX-RUNBOOK.md | 3 + docs/benchmarks/results/v0.5.0/retrieval.json | 473 ++++++++++++++++++ docs/benchmarks/results/v0.5.0/run.txt | 5 + tests/test_ci_workflows.py | 16 + tests/test_release_gate.py | 4 + 17 files changed, 599 insertions(+), 60 deletions(-) create mode 100644 docs/benchmarks/results/v0.5.0/retrieval.json create mode 100644 docs/benchmarks/results/v0.5.0/run.txt diff --git a/.github/INTEGRATION-TEST.md b/.github/INTEGRATION-TEST.md index 8ff7277f..84fc327b 100644 --- a/.github/INTEGRATION-TEST.md +++ b/.github/INTEGRATION-TEST.md @@ -166,9 +166,10 @@ the documentation versions; do not infer named-client compatibility. returned `next_start_index`. Check no gaps/duplicate anchors and bounded response bodies. Retrieve individual sections via `get_docs(slug="whatsnew/3.15", version="3.15", anchor=...)`. -7. Preserve the original 3.11–3.13 frozen regression index and run - `uv run --locked python -m benchmarks.regression --index --output regression-results.json`. - The new separate 3.15 fixtures do not replace that gate. +7. Preserve the original 3.11–3.13 frozen regression index and follow the + [local benchmark workflow](../CONTRIBUTING.md#local-benchmark-workflow), + selecting that retained index with `--index`. The separate 3.15 fixtures + do not replace the local baseline comparison. ## Evidence log diff --git a/.github/RELEASE.md b/.github/RELEASE.md index 4e06f3e0..e98a177c 100644 --- a/.github/RELEASE.md +++ b/.github/RELEASE.md @@ -8,8 +8,10 @@ or disable checks. 1. Merge the version/changelog PR after independent current-head verification and all required CI. `pyproject.toml`, `uv.lock`, `server.json` and its package - entry must agree. CI covers Python 3.12–3.14 on Ubuntu and macOS, the real - benchmark corpus, offline full-index regression, and installed-wheel stdio. + entry must agree. CI covers ordinary product tests on Python 3.12–3.14 on + Ubuntu and macOS, static analysis, security checks and installed-wheel stdio. + Full-index installation E2E remains required. Benchmarks run locally and do + not gate releases. See the [local benchmark workflow](../CONTRIBUTING.md#local-benchmark-workflow). If an update from `main` changed the head, carry verification forward only under the amendment's rule: a conflict-free update, green required checks, a new record for the new head, and either (a) a rebase whose diff --git a/.github/scripts/release_gate.py b/.github/scripts/release_gate.py index b51d5f93..9d0e9448 100644 --- a/.github/scripts/release_gate.py +++ b/.github/scripts/release_gate.py @@ -19,7 +19,6 @@ "Dependency audit", "Analyze", "Installed package smoke", - "Product regression", } # First line of the owner's PR comment that records an independent verification. RECORD = re.compile(r"Independent verification: (PASS|FAIL)") diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6c3f2760..d03eaddd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -45,11 +45,8 @@ jobs: - name: Run type checker run: uv run --locked pyright src/ benchmarks/ - - name: Validate frozen benchmark corpus - run: uv run --locked python -m benchmarks validate-corpus --corpus docs/benchmarks/corpus.yml --schema docs/benchmarks/corpus.schema.json - - name: Run tests - run: uv run --locked pytest --tb=short -q + run: uv run --locked pytest --ignore=tests/benchmarks --tb=short -q - name: Verify wheel contents run: | diff --git a/.github/workflows/product-quality.yml b/.github/workflows/product-quality.yml index 78a9104d..600a8221 100644 --- a/.github/workflows/product-quality.yml +++ b/.github/workflows/product-quality.yml @@ -31,33 +31,3 @@ jobs: cp tests/test_stdio_smoke.py "${RUNNER_TEMP}/test_stdio_smoke.py" cd "${RUNNER_TEMP}" installed/bin/python -m pytest --import-mode=importlib test_stdio_smoke.py -q - - regression: - name: Product regression - runs-on: ubuntu-latest - timeout-minutes: 60 - env: - UV_PYTHON: '3.13' - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - persist-credentials: false - - uses: astral-sh/setup-uv@1c37ad07a6a961277cf70c0d37d6f313000f5884 # v10.3.0 - - run: echo "XDG_CACHE_HOME=${RUNNER_TEMP}/docs-cache" >> "$GITHUB_ENV" - - run: uv sync --locked --dev - - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - id: index - with: - path: ${{ runner.temp }}/docs-cache/mcp-python-docs/index.db - key: docs-regression-v1-${{ runner.os }}-${{ hashFiles('src/mcp_server_python_docs/ingestion/**', 'src/mcp_server_python_docs/storage/**', 'src/mcp_server_python_docs/__main__.py', 'uv.lock') }} - - name: Build full reference index - if: steps.index.outputs.cache-hit != 'true' - run: uv run --locked python-docs-mcp-server build-index --versions 3.11,3.12,3.13 - - name: Enforce offline retrieval baseline - run: uv run --locked python -m benchmarks.regression --output regression-results.json - - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 - if: always() - with: - name: product-regression-results - path: regression-results.json - if-no-files-found: error diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 5027fb90..2590f09c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -90,10 +90,7 @@ jobs: env: UV_BUILD_CONSTRAINT: .github/build-constraints.txt UV_REQUIRE_HASHES: "1" - run: uv run --no-sync pytest --tb=short -q - - - name: Validate frozen benchmark corpus - run: uv run --no-sync python -m benchmarks validate-corpus --corpus docs/benchmarks/corpus.yml --schema docs/benchmarks/corpus.schema.json + run: uv run --no-sync pytest --ignore=tests/benchmarks --tb=short -q - name: Validate MCP manifest before publication run: | diff --git a/AGENT-EXECUTION-PIPELINE.md b/AGENT-EXECUTION-PIPELINE.md index e57f7b25..de0161f4 100644 --- a/AGENT-EXECUTION-PIPELINE.md +++ b/AGENT-EXECUTION-PIPELINE.md @@ -10,6 +10,15 @@ **Current authority:** For v0.5.0 read the [2026-11-07 handback to Codex](#amendment-2026-11-07--v050-owner-handback-to-codex), the [2026-11-07 handover](#amendment-2026-11-07--v050-owner-handover-to-claude-code) and the [2026-11-04 delegation](#amendment-2026-11-04--v050-owner-delegation) together with [Amendment 2026-10-30](#amendment-2026-10-30--ownership-transferred-to-the-claude-code-owner) first. Together they supersede conflicting historical restrictions and earlier amendments below. +**Local benchmarking policy (2026-11-21):** All benchmarks run locally. +This supersedes earlier benchmark-in-CI requirements and the `Product regression` +merge/release check below. The owner handles removal of that ruleset status. +Other checks and independent review requirements still apply. Dated records remain +historical. [Owner authorization](https://github.com/ayhammouda/python-docs-mcp-server/issues/63#issuecomment-7068010392). + +For commands and reviewed results, follow the +[local benchmark workflow](CONTRIBUTING.md#local-benchmark-workflow). + --- ## 1. Operating Principles diff --git a/AGENTS.md b/AGENTS.md index b8d34813..99231c53 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -59,7 +59,7 @@ uv sync --locked --dev If `uv` is not on your `PATH` after installation, reopen the shell or use `python -m uv ...` as a fallback. -Core verification commands: +Core local verification commands (the default pytest run includes benchmark tests): ```bash uv run --locked ruff check src/ tests/ benchmarks/ ops/ .github/scripts/ @@ -67,12 +67,14 @@ uv run --locked pyright src/ benchmarks/ uv run --locked pytest --tb=short -q ``` +All benchmarks run locally. CI and release exclude `tests/benchmarks`. +For measured results, follow the [local benchmark workflow](CONTRIBUTING.md#local-benchmark-workflow). + Build and inspect a local docs index: ```bash uv run --locked python-docs-mcp-server build-index --versions 3.12,3.13 uv run --locked python-docs-mcp-server doctor -uv run --locked python -m benchmarks validate-corpus --corpus docs/benchmarks/corpus.yml --schema docs/benchmarks/corpus.schema.json ``` Package smoke check: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4c32d14e..f0743c65 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -14,7 +14,7 @@ python -m pip install uv Then bootstrap the repo: ```bash -uv sync --dev +uv sync --locked --dev ``` If `uv` is not on your `PATH` after installation, reopen the shell or use @@ -22,14 +22,20 @@ If `uv` is not on your `PATH` after installation, reopen the shell or use ## 2. Run the standard checks -Use the same commands the CI workflow runs: +Run the local checks (default pytest discovery includes `tests/benchmarks`): ```bash -uv run ruff check src/ tests/ -uv run pyright src/ -uv run pytest --tb=short -q +uv run --locked ruff check src/ tests/ benchmarks/ ops/ .github/scripts/ +uv run --locked pyright src/ benchmarks/ +uv run --locked pytest --tb=short -q ``` +CI and release run ordinary product tests with `pytest --ignore=tests/benchmarks`. +All benchmarks, including scripted development tests, run locally. Static +analysis of benchmark code and dependency security scanning remain in CI, +alongside product correctness, package/stdio smoke and full-index installation +E2E checks. See the [local benchmark workflow](#local-benchmark-workflow) below. + If you are working on retrieval behavior specifically, the curated regression suite is: @@ -76,6 +82,41 @@ the assembled grading probe suite (`docs/benchmarks/grading/probes.yml`). For release workflow details, PyPI trusted publishing setup, and the full release checklist, see [`.github/RELEASE.md`](.github/RELEASE.md). +## Local benchmark workflow + +Run from a clean checkout at the repository root. Each run gets a new directory. +Keep prior results. The ignored `.cache/benchmarks` directory holds the index. +For benchmark suite development, run `uv run --locked pytest tests/benchmarks -q` separately. + +```bash +uv sync --locked --dev +BENCHMARK_RUN="$(date -u +%Y-%m-%dT%H%M%SZ)-$(git rev-parse --short=12 HEAD)" +BENCHMARK_OUTPUT="docs/benchmarks/results/$BENCHMARK_RUN" +BENCHMARK_CACHE="$PWD/.cache/benchmarks" +git switch -c "benchmarks/$BENCHMARK_RUN" +mkdir -p docs/benchmarks/results +mkdir "$BENCHMARK_OUTPUT" +git rev-parse HEAD > "$BENCHMARK_OUTPUT/run.txt" +uv run --locked python -c 'import platform; print(platform.platform(), platform.machine(), platform.python_implementation(), platform.python_version())' >> "$BENCHMARK_OUTPUT/run.txt" +XDG_CACHE_HOME="$BENCHMARK_CACHE" uv run --locked python-docs-mcp-server build-index --versions 3.10,3.11,3.12,3.13,3.14 +uv run --locked python -m benchmarks.regression --index "$BENCHMARK_CACHE/mcp-python-docs/index.db" --output "$BENCHMARK_OUTPUT/retrieval.json" +``` + +The build downloads full documentation. To reuse a retained index, skip the build +and pass its path to `--index`. It must include Python 3.11–3.13 with content. +The offline evaluator validates the frozen corpus and compares against the baseline. +Review failures. Baseline changes require independent review. +Review the result and provenance before publishing. Exclude credentials, private raw +runs and transcripts. Open a PR after pushing the reviewed files: + +```bash +git add -- "$BENCHMARK_OUTPUT/retrieval.json" "$BENCHMARK_OUTPUT/run.txt" +git diff --cached --check +git diff --cached +git commit -m "docs: publish local retrieval measurements $BENCHMARK_RUN" +git push -u origin "benchmarks/$BENCHMARK_RUN" +``` + ## Project conventions - Keep the MCP tool surface small and read-only unless a change is explicitly diff --git a/README.md b/README.md index 5bb03d7d..d03299f1 100644 --- a/README.md +++ b/README.md @@ -233,8 +233,8 @@ args = ["python-docs-mcp-server"] ## Quality checks -- CI runs `ruff`, `pyright`, and `pytest` on macOS and Linux for Python 3.12 - and 3.13 +- CI runs `ruff`, `pyright`, and ordinary product tests on macOS and Linux + for Python 3.12–3.14 - subprocess-based stdio and smoke tests cover the MCP protocol pipe - packaging tests check the wheel contents and CLI entry points - retrieval regression tests cover exact symbol hits, version behavior, @@ -246,6 +246,19 @@ args = ["python-docs-mcp-server"] Contributor commands and validation steps live in [`CONTRIBUTING.md`](CONTRIBUTING.md). +## Local benchmarks + +The local v0.5.0 retrieval benchmark covers 50 questions across Python 3.11–3.13 +in 65 version-specific cases. Its five-version index contains 2,684 documents +for Python 3.10–3.14. Top-five search found an expected canonical page or anchor +in **35/65 cases (53.8%)**. Direct reads returned content for **69/69 known +citations**. These measure search retrieval and content availability. +[View the measured results](docs/benchmarks/results/v0.5.0/retrieval.json). + +Benchmarks run locally. Contributors can build an index, compare results against +the frozen baseline and submit a new result for review. +[Run and publish a local benchmark](CONTRIBUTING.md#local-benchmark-workflow). + ## Tools The server currently exposes seven MCP tools: diff --git a/docs/benchmarks/AGENTIC-BENCHMARK-DESIGN.md b/docs/benchmarks/AGENTIC-BENCHMARK-DESIGN.md index 5b2b2345..1e75efb7 100644 --- a/docs/benchmarks/AGENTIC-BENCHMARK-DESIGN.md +++ b/docs/benchmarks/AGENTIC-BENCHMARK-DESIGN.md @@ -90,8 +90,9 @@ Each claim has a pass/fail rule fixed before any data is seen (**Call**). (**Decided**), each behind the terms gate recorded in the competitor template. - The fixed-retrieval "mode A" benchmark as a public result. The agentic run - replaces it (**Call**). The CI retrieval regression in `benchmarks/regression.py` - is unaffected because it calls the services directly. + replaces it (**Call**). The local retrieval regression in `benchmarks/regression.py` + remains a separate measurement because it calls the services directly. + See the [contributor workflow](../../CONTRIBUTING.md#local-benchmark-workflow). - Provider-hosted MCP connectors (they cannot reach a local stdio server). - CLI-agent comparisons (Claude Code vs Codex CLI vs Gemini CLI). - A Python 3.15 post-cutoff slice, a contamination canary, new corpus questions. @@ -580,7 +581,7 @@ in the `dev` dependency group, pinned in `uv.lock`, so CI's existing change. - Replace the live-provider stubs with real implementations behind the existing - `require_live_environment` guard. Keep deterministic mocks so CI runs the + `require_live_environment` guard. Keep deterministic mocks so local tests run the whole agentic pipeline end to end with no network and no keys. - One generic MCP bridge (stdio or Streamable HTTP) serves every system, including `docs-fetch`, and replaces the five fixed-flow adapters. Once it @@ -768,7 +769,7 @@ The pilot decides whether k = 3 is enough (if the C2 interval cannot exclude 2027-01-01 if possible (Gemini price change). Suggested PR order (the builder may re-slice): (1) SDK v2 (done, #162); (2) methodology -amendment, model matrix, this document; (3) harness with mocked end-to-end CI +amendment, model matrix, this document; (3) harness with mocked end-to-end local test; (4) sandbox, proxy, run script, air-gapped runbook; (5) criteria file, probe suite, judge panel, reference grader, `scoring.py` provenance, post-hoc token counting, report; then G1, the maintainer-run pilot, review, full run, @@ -777,7 +778,8 @@ grading, and the report PR. ## 13. Constraints - Canonical gate from `AGENTS.md` (ruff, pyright on `src/` and `benchmarks/`, - pytest) passes on every PR. + local pytest) passes on every PR. All scripted benchmark tests run locally. + See the [contributor workflow](../../CONTRIBUTING.md#local-benchmark-workflow). - No paid call can happen in CI or tests; the live-phase guard stays. - Live runs need maintainer-supplied keys: `ANTHROPIC_API_KEY`, `OPENAI_API_KEY` and `GOOGLE_API_KEY` (the name @@ -791,8 +793,8 @@ grading, and the report PR. ## 14. Risks -- **Retrieval quality may cap correctness.** The CI retrieval baseline shows - 8 of 65 exact canonical hits in the top five. Agentic models can recover by +- **Retrieval quality may cap correctness.** The baseline observed during this + study showed 8 of 65 exact canonical hits in the top five. Agentic models can recover by calling `get_docs` with better arguments, at a token cost. The report publishes whatever happens. - **`docs-fetch` may be competitive on C2.** With 5,000-character windows and diff --git a/docs/benchmarks/PUBLIC-BENCHMARK-METHODOLOGY.md b/docs/benchmarks/PUBLIC-BENCHMARK-METHODOLOGY.md index 4602772e..37fe6a6b 100644 --- a/docs/benchmarks/PUBLIC-BENCHMARK-METHODOLOGY.md +++ b/docs/benchmarks/PUBLIC-BENCHMARK-METHODOLOGY.md @@ -1,6 +1,11 @@ # Public Benchmark Methodology **Status:** Accepted (blessed 2026-07-08; see PLAN-2026-07-08-benchmark-plumbing.md Amendment 1) + +**Execution policy (2026-11-21):** All benchmarks run locally. This supersedes +historical plans for benchmark execution in CI. For retrieval measurements and +publication, follow the [local benchmark workflow](../../CONTRIBUTING.md#local-benchmark-workflow). + Do not publish comparative claims until the harness has produced reproducible data from this methodology. diff --git a/docs/benchmarks/SANDBOX-RUNBOOK.md b/docs/benchmarks/SANDBOX-RUNBOOK.md index ccb941f4..382c0146 100644 --- a/docs/benchmarks/SANDBOX-RUNBOOK.md +++ b/docs/benchmarks/SANDBOX-RUNBOOK.md @@ -1,5 +1,8 @@ # Agentic benchmark sandbox: operator runbook +All benchmarks run locally under the 2026-11-21 policy. For ordinary retrieval +measurements, follow the [local benchmark workflow](../../CONTRIBUTING.md#local-benchmark-workflow). + How the maintainer runs the agentic benchmark in its sandbox (design §§7.2–7.4, §12, §14). Every live call in this runbook is the maintainer's, after PR 4 merges. An implementer never runs one. Every `run.sh` command names its models with `--models`. diff --git a/docs/benchmarks/results/v0.5.0/retrieval.json b/docs/benchmarks/results/v0.5.0/retrieval.json new file mode 100644 index 00000000..dd36b287 --- /dev/null +++ b/docs/benchmarks/results/v0.5.0/retrieval.json @@ -0,0 +1,473 @@ +{ + "schema_version": 1, + "corpus_sha256": "79ac86b444a8a2487fe342223af372bbed8ff6f98bd5faba302ad618da67caa6", + "index_versions": [ + "3.10", + "3.11", + "3.12", + "3.13", + "3.14" + ], + "index_documents": 2684, + "cases": { + "EX-001/3.13": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.13/library/itertools.html#itertools.accumulate" + ], + "seconds": 0.073811 + }, + "EX-002/3.13": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.13/library/itertools.html#itertools.pairwise" + ], + "seconds": 0.023909 + }, + "EX-003/3.13": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.13/library/itertools.html#itertools.groupby" + ], + "seconds": 0.023529 + }, + "EX-004/3.13": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.13/library/functools.html#functools.cache" + ], + "seconds": 0.443841 + }, + "EX-005/3.13": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.13/library/functools.html#functools.cached_property" + ], + "seconds": 0.021837 + }, + "EX-006/3.13": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.13/library/functools.html#functools.singledispatch" + ], + "seconds": 0.029584 + }, + "EX-007/3.13": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.13/library/pathlib.html#pathlib.Path.glob" + ], + "seconds": 0.032119 + }, + "EX-008/3.13": { + "retrieval_hit_at_5": false, + "resolved_citations": [ + "https://docs.python.org/3.13/library/pathlib.html#pathlib.Path.read_text" + ], + "seconds": 0.090921 + }, + "EX-009/3.13": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.13/library/pathlib.html#pathlib.PurePath.is_relative_to" + ], + "seconds": 0.020825 + }, + "EX-010/3.13": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.13/library/collections.html#collections.Counter.total" + ], + "seconds": 0.017866 + }, + "EX-011/3.13": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.13/library/collections.html#collections.deque.rotate" + ], + "seconds": 0.021753 + }, + "EX-012/3.13": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.13/library/statistics.html#statistics.fmean" + ], + "seconds": 0.02787 + }, + "EX-013/3.13": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.13/library/statistics.html#statistics.NormalDist.inv_cdf" + ], + "seconds": 0.021084 + }, + "EX-014/3.13": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.13/library/contextlib.html#contextlib.ExitStack" + ], + "seconds": 0.020716 + }, + "EX-015/3.13": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.13/library/tempfile.html#tempfile.TemporaryDirectory" + ], + "seconds": 0.027951 + }, + "CO-001/3.13": { + "retrieval_hit_at_5": false, + "resolved_citations": [ + "https://docs.python.org/3.13/library/pathlib.html#concrete-paths", + "https://docs.python.org/3.13/library/pathlib.html#pure-paths" + ], + "seconds": 0.018768 + }, + "CO-002/3.13": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.13/library/contextlib.html#contextlib.suppress" + ], + "seconds": 0.024699 + }, + "CO-003/3.13": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.13/library/decimal.html#decimal.localcontext" + ], + "seconds": 0.018851 + }, + "CO-004/3.13": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.13/library/asyncio-task.html#asyncio.TaskGroup" + ], + "seconds": 0.024273 + }, + "CO-005/3.13": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.13/library/concurrent.futures.html#concurrent.futures.as_completed" + ], + "seconds": 0.019491 + }, + "CO-006/3.13": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.13/library/csv.html#csv.DictReader" + ], + "seconds": 0.018374 + }, + "CO-007/3.13": { + "retrieval_hit_at_5": false, + "resolved_citations": [ + "https://docs.python.org/3.13/library/json.html#json.load" + ], + "seconds": 0.024549 + }, + "CO-008/3.13": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.13/library/shutil.html#shutil.copy2" + ], + "seconds": 0.023278 + }, + "CO-009/3.13": { + "retrieval_hit_at_5": false, + "resolved_citations": [ + "https://docs.python.org/3.13/library/sqlite3.html#how-to-use-placeholders-to-bind-values-in-sql-queries" + ], + "seconds": 0.008681 + }, + "CO-010/3.13": { + "retrieval_hit_at_5": false, + "resolved_citations": [ + "https://docs.python.org/3.13/library/logging.html#logging.Logger.propagate" + ], + "seconds": 0.077111 + }, + "XV-001/3.12": { + "retrieval_hit_at_5": false, + "resolved_citations": [ + "https://docs.python.org/3.12/library/base64.html" + ], + "seconds": 0.011739 + }, + "XV-001/3.13": { + "retrieval_hit_at_5": false, + "resolved_citations": [ + "https://docs.python.org/3.13/whatsnew/3.13.html#base64" + ], + "seconds": 0.008539 + }, + "XV-002/3.12": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.12/library/copy.html" + ], + "seconds": 0.131983 + }, + "XV-002/3.13": { + "retrieval_hit_at_5": false, + "resolved_citations": [ + "https://docs.python.org/3.13/whatsnew/3.13.html#copy" + ], + "seconds": 0.111082 + }, + "XV-003/3.12": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.12/library/dbm.html" + ], + "seconds": 0.092723 + }, + "XV-003/3.13": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.13/whatsnew/3.13.html#dbm" + ], + "seconds": 0.086209 + }, + "XV-004/3.12": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.12/library/argparse.html" + ], + "seconds": 0.079606 + }, + "XV-004/3.13": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.13/whatsnew/3.13.html#argparse" + ], + "seconds": 0.072125 + }, + "XV-005/3.12": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.12/library/ssl.html" + ], + "seconds": 0.020324 + }, + "XV-005/3.13": { + "retrieval_hit_at_5": false, + "resolved_citations": [ + "https://docs.python.org/3.13/whatsnew/3.13.html#ssl" + ], + "seconds": 0.01915 + }, + "XV-006/3.12": { + "retrieval_hit_at_5": false, + "resolved_citations": [ + "https://docs.python.org/3.12/library/random.html" + ], + "seconds": 0.106015 + }, + "XV-006/3.13": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.13/whatsnew/3.13.html#random" + ], + "seconds": 0.102378 + }, + "XV-007/3.12": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.12/library/itertools.html#itertools.batched" + ], + "seconds": 0.020152 + }, + "XV-007/3.13": { + "retrieval_hit_at_5": false, + "resolved_citations": [ + "https://docs.python.org/3.13/whatsnew/3.13.html#itertools" + ], + "seconds": 0.019477 + }, + "XV-008/3.12": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.12/library/queue.html" + ], + "seconds": 0.01858 + }, + "XV-008/3.13": { + "retrieval_hit_at_5": false, + "resolved_citations": [ + "https://docs.python.org/3.13/whatsnew/3.13.html#queue" + ], + "seconds": 0.017611 + }, + "XV-009/3.11": { + "retrieval_hit_at_5": false, + "resolved_citations": [ + "https://docs.python.org/3.11/library/distutils.html" + ], + "seconds": 0.00807 + }, + "XV-009/3.12": { + "retrieval_hit_at_5": false, + "resolved_citations": [ + "https://docs.python.org/3.12/whatsnew/3.12.html#summary-release-highlights" + ], + "seconds": 0.00754 + }, + "XV-010/3.11": { + "retrieval_hit_at_5": false, + "resolved_citations": [ + "https://docs.python.org/3.11/library/venv.html" + ], + "seconds": 0.010332 + }, + "XV-010/3.12": { + "retrieval_hit_at_5": false, + "resolved_citations": [ + "https://docs.python.org/3.12/whatsnew/3.12.html#summary-release-highlights" + ], + "seconds": 0.008142 + }, + "XV-011/3.11": { + "retrieval_hit_at_5": false, + "resolved_citations": [ + "https://docs.python.org/3.11/library/sqlite3.html" + ], + "seconds": 0.008825 + }, + "XV-011/3.12": { + "retrieval_hit_at_5": false, + "resolved_citations": [ + "https://docs.python.org/3.12/whatsnew/3.12.html#sqlite3" + ], + "seconds": 0.007478 + }, + "XV-012/3.11": { + "retrieval_hit_at_5": false, + "resolved_citations": [ + "https://docs.python.org/3.11/library/uuid.html" + ], + "seconds": 0.094377 + }, + "XV-012/3.12": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.12/whatsnew/3.12.html#uuid" + ], + "seconds": 0.097576 + }, + "XV-013/3.11": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.11/library/pathlib.html" + ], + "seconds": 0.019143 + }, + "XV-013/3.12": { + "retrieval_hit_at_5": false, + "resolved_citations": [ + "https://docs.python.org/3.12/whatsnew/3.12.html#pathlib" + ], + "seconds": 0.016829 + }, + "XV-014/3.11": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.11/library/shutil.html#shutil.rmtree" + ], + "seconds": 0.02007 + }, + "XV-014/3.12": { + "retrieval_hit_at_5": false, + "resolved_citations": [ + "https://docs.python.org/3.12/whatsnew/3.12.html#shutil" + ], + "seconds": 0.018507 + }, + "XV-015/3.11": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.11/library/tempfile.html#tempfile.NamedTemporaryFile" + ], + "seconds": 0.018774 + }, + "XV-015/3.12": { + "retrieval_hit_at_5": false, + "resolved_citations": [ + "https://docs.python.org/3.12/whatsnew/3.12.html#tempfile" + ], + "seconds": 0.019134 + }, + "PE-001/3.13": { + "retrieval_hit_at_5": false, + "resolved_citations": [ + "https://docs.python.org/3.13/whatsnew/3.13.html#free-threaded-cpython" + ], + "seconds": 0.013844 + }, + "PE-002/3.13": { + "retrieval_hit_at_5": false, + "resolved_citations": [ + "https://docs.python.org/3.13/library/typing.html#typing.TypeVar", + "https://docs.python.org/3.13/whatsnew/3.13.html#summary-release-highlights" + ], + "seconds": 0.013177 + }, + "PE-003/3.13": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.13/library/warnings.html#warnings.deprecated", + "https://docs.python.org/3.13/whatsnew/3.13.html#warnings" + ], + "seconds": 0.019404 + }, + "PE-004/3.13": { + "retrieval_hit_at_5": true, + "resolved_citations": [ + "https://docs.python.org/3.13/library/typing.html#typing.ReadOnly" + ], + "seconds": 0.021128 + }, + "PE-005/3.13": { + "retrieval_hit_at_5": false, + "resolved_citations": [ + "https://docs.python.org/3.13/library/typing.html#typing.TypeIs" + ], + "seconds": 0.012996 + }, + "AP-001/3.13": { + "retrieval_hit_at_5": false, + "resolved_citations": [ + "https://docs.python.org/3.13/library/secrets.html#secrets.token_urlsafe" + ], + "seconds": 0.015432 + }, + "AP-002/3.13": { + "retrieval_hit_at_5": false, + "resolved_citations": [ + "https://docs.python.org/3.13/library/contextlib.html#contextlib.closing" + ], + "seconds": 0.016644 + }, + "AP-003/3.13": { + "retrieval_hit_at_5": false, + "resolved_citations": [ + "https://docs.python.org/3.13/library/functions.html#open", + "https://docs.python.org/3.13/library/pathlib.html#pathlib.Path.open" + ], + "seconds": 0.134021 + }, + "AP-004/3.13": { + "retrieval_hit_at_5": false, + "resolved_citations": [ + "https://docs.python.org/3.13/library/argparse.html#argparse.ArgumentParser" + ], + "seconds": 0.087211 + }, + "AP-005/3.13": { + "retrieval_hit_at_5": false, + "resolved_citations": [ + "https://docs.python.org/3.13/library/hashlib.html#hashlib.file_digest" + ], + "seconds": 0.015245 + } + } +} diff --git a/docs/benchmarks/results/v0.5.0/run.txt b/docs/benchmarks/results/v0.5.0/run.txt new file mode 100644 index 00000000..e4f7933d --- /dev/null +++ b/docs/benchmarks/results/v0.5.0/run.txt @@ -0,0 +1,5 @@ +Measured: November 21, 2026 +Source: v0.5.0 at 3a48f832404a11fb18de7d56c27c8e84ba57c2cc +Environment: local macOS ARM64, CPython 3.13.10 +Index SHA256: 69537a695ce0cc3a79e251d1885583e8c121aa0e9ae854bebf012f3ab2550481 +Index hash independently checked on the host. diff --git a/tests/test_ci_workflows.py b/tests/test_ci_workflows.py index a8a95137..f3782d72 100644 --- a/tests/test_ci_workflows.py +++ b/tests/test_ci_workflows.py @@ -16,6 +16,22 @@ SUPPORTED_VERSION_ARGS = "3.10,3.11,3.12,3.13,3.14" +@pytest.mark.parametrize(("filename", "job"), [("ci.yml", "test"), ("release.yml", "build")]) +def test_ci_excludes_local_benchmark_suite(filename: str, job: str) -> None: + workflow = PROJECT_ROOT / ".github" / "workflows" / filename + steps = yaml.safe_load(workflow.read_text())["jobs"][job]["steps"] + commands = [s["run"] for s in steps if "pytest" in s.get("run", "")] + assert commands + assert all(re.search(r"--ignore(?:=|\s+)tests/benchmarks\b", c) for c in commands) + + +def test_full_index_benchmark_runner_is_absent_from_product_quality() -> None: + workflow = PROJECT_ROOT / ".github" / "workflows" / "product-quality.yml" + jobs = yaml.safe_load(workflow.read_text())["jobs"] + assert all("benchmarks.regression" not in s.get("run", "") + for job in jobs.values() for s in job.get("steps", [])) + + def test_slow_e2e_workflow_runs_installed_build_index() -> None: """Slow E2E workflow should validate installed-package build-index behavior.""" workflow = PROJECT_ROOT / ".github" / "workflows" / "e2e.yml" diff --git a/tests/test_release_gate.py b/tests/test_release_gate.py index 64366b7e..b80ce7e5 100644 --- a/tests/test_release_gate.py +++ b/tests/test_release_gate.py @@ -56,6 +56,10 @@ def make_state(*pages): } +def test_release_does_not_require_retired_benchmark_status(): + assert "Product regression" not in GATE["REQUIRED"] + + def test_release_eligibility_rejects_incomplete_or_wrong_identity_evidence(): state = make_state([note(RECORD)]) checks = state[f"commits/{SHA}/check-runs?per_page=100"]["check_runs"] From 720b3fe553ce4e66ad3fc0c25a28f90644a23384 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Sat, 21 Nov 2026 21:43:13 +0100 Subject: [PATCH 2/3] fix(release): test the installed wheel and recover the original v0.5.0 tag --- .github/RELEASE.md | 52 +++++++++++++++++++--- .github/scripts/release_gate.py | 51 +++++++++++++++++++-- .github/workflows/release.yml | 67 ++++++++++++++++++---------- tests/test_ci_workflows.py | 50 ++++++++++++++++++++- tests/test_packaging.py | 39 ++++++++++++++++ tests/test_release_gate.py | 79 +++++++++++++++++++++++++++++++++ 6 files changed, 305 insertions(+), 33 deletions(-) diff --git a/.github/RELEASE.md b/.github/RELEASE.md index e98a177c..13d01690 100644 --- a/.github/RELEASE.md +++ b/.github/RELEASE.md @@ -58,11 +58,16 @@ That file pins `hatchling` and every dependency with SHA-256 hashes, and the bui runs `uv build --build-constraint .github/build-constraints.txt --require-hashes`. Every project build in the build job uses that file. The job syncs dependencies with `uv sync --locked --dev --no-install-project --no-build`, which builds neither the -project nor any source distribution. It installs the built wheel with -`uv pip install --no-deps dist/*.whl` and runs every later command with -`uv run --no-sync`, so nothing re-syncs and rebuilds the project. The tests run -against that installed wheel, and the test suite's own wheel build gets the same -constraints through `UV_BUILD_CONSTRAINT` and `UV_REQUIRE_HASHES`. +project nor any source distribution, in a fresh `UV_PROJECT_ENVIRONMENT` under +`RUNNER_TEMP`. It installs the built wheel with +`uv pip install --python "$UV_PROJECT_ENVIRONMENT/bin/python" --no-deps dist/*.whl` +and runs later commands with `uv run --no-sync`. Product tests also inherit +`UV_NO_SYNC=1`, protecting the installation from nested `uv run` calls. Before +tests, the job requires imports from that environment's site-packages, compares +installed `schema.sql` and `synonyms.yaml` bytes with the wheel, and bootstraps an +in-memory database including FTS5. No source-tree resource fallback is used. +The test suite's own wheel build gets the same constraints through +`UV_BUILD_CONSTRAINT` and `UV_REQUIRE_HASHES`. Benchmark tests remain excluded. To update it, run `echo hatchling | uv pip compile --generate-hashes --universal --python-version 3.12 --upgrade - -o .github/build-constraints.txt`, then @@ -78,3 +83,40 @@ unchanged, with no bypass actors. No routine human reviewer is required. If publication partially fails, record which registries succeeded and diagnose the failure; never overwrite a published version, move a tag, or claim a release complete from a partial result. + +## One-time v0.5.0 recovery + +The failed v0.5.0 release spent its tag. It must continue to peel to +`3a48f832404a11fb18de7d56c27c8e84ba57c2cc`. The original wheel contains +`storage/schema.sql`: a local reproduction of the benchmark sandbox's nested +`uv run --locked` replaced the installed wheel with an editable install while +the parent test process retained its old site-packages imports. The next database +bootstrap then failed to read the removed schema. Running the same nested command +with the inherited no-sync guard preserved the wheel and allowed the bootstrap to +succeed. The sandbox test itself filters its subprocess environment, so excluding +benchmark tests remains necessary. This repairs the test environment; it does +not change the v0.5.0 package source. + +After independent review, merge of this repair, and green required checks on its +exact main commit, the owner may create **only** `v0.5.0-recovery.1` on that commit. +The existing `v*` creation restrictions, immutable-tag rules (no update/delete or +bypass actors), and `pypi` tag environment must cover this control tag as well as +`v0.5.0`. Keep those protections; do not move either tag. This implementation does +not create tags or change repository settings. + +Only the exact protected `refs/tags/v0.5.0-recovery.1` push selects recovery. The +eligibility job checks that its tag still names the event commit and applies the +normal main ancestry, merged-PR, CodeQL, owner-record and main-check gates. It +also peels the original tag to the pinned SHA and rechecks that commit's evidence +under its original frozen gate, including the historical `Product regression` +success. A missing, changed or failing record/check aborts recovery. Other tag +pushes retain the ordinary release path; no arbitrary ref or manual artifact +input is accepted. + +The repaired workflow builds and validates the manifest from the **original** +pinned source commit. Its verified target tag is `v0.5.0`, including the explicit +GitHub Release `tag_name` and package/manifest version checks. The existing +full-index E2E, artifact-ID/checksum checks, attestations, Trusted Publishing job, +`pypi` environment, MCP Registry publication and GitHub Release job remain in the +path. Provenance identifies the recovery workflow run; the gate identifies the +original source commit. Confirm all publication results using step 5 above. diff --git a/.github/scripts/release_gate.py b/.github/scripts/release_gate.py index 9d0e9448..996795b7 100644 --- a/.github/scripts/release_gate.py +++ b/.github/scripts/release_gate.py @@ -8,6 +8,11 @@ import os import re import urllib.request +from pathlib import Path + +RECOVERY_TAG = "v0.5.0-recovery.1" +RECOVERY_TARGET = "v0.5.0" +RECOVERY_SHA = "3a48f832404a11fb18de7d56c27c8e84ba57c2cc" REQUIRED = { "Test (Python 3.12, ubuntu-latest)", @@ -41,7 +46,7 @@ def verdict(comment, owner: str, head: str, merged_at: str) -> str | None: return match[1] if match else None -def require_eligible(api, sha: str, owner: str) -> None: +def require_eligible(api, sha: str, owner: str, *, required=None) -> None: if not re.fullmatch(r"[0-9a-f]{40}", sha) or not owner: raise ValueError("Exact commit and repository owner are required") if api(f"compare/{sha}...main")["status"] not in {"ahead", "identical"}: @@ -79,12 +84,50 @@ def require_eligible(api, sha: str, owner: str) -> None: if check["app"]["id"] == 15368: latest[check["name"]] = check failed = sorted( - name for name in REQUIRED if latest.get(name, {}).get("conclusion") != "success" + name for name in (REQUIRED if required is None else required) + if latest.get(name, {}).get("conclusion") != "success" ) if failed: raise ValueError(f"Missing or failing main checks: {', '.join(failed)}") +def tag_commit(api, tag: str) -> str: + """Peel lightweight or annotated tags, failing closed on malformed chains.""" + obj = api(f"git/ref/tags/{tag}")["object"] + for _ in range(10): + if not re.fullmatch(r"[0-9a-f]{40}", obj["sha"]): + break + if obj["type"] == "commit": + return obj["sha"] + if obj["type"] != "tag": + break + obj = api(f"git/tags/{obj['sha']}")["object"] + raise ValueError("Tag does not peel to an exact commit") + + +def release_target(api, env) -> tuple[str, str]: + """Only the named immutable recovery event may build a different commit.""" + sha, tag = env["GITHUB_SHA"], env["GITHUB_REF_NAME"] + owner = env.get("GITHUB_REPOSITORY_OWNER", "") + require_eligible(api, sha, owner) + if tag == RECOVERY_TAG: + if ( + env.get("GITHUB_EVENT_NAME") != "push" + or env.get("GITHUB_REF") != f"refs/tags/{RECOVERY_TAG}" + or env.get("GITHUB_REF_PROTECTED") != "true" + ): + raise ValueError("Recovery requires the exact protected tag push") + if tag_commit(api, RECOVERY_TAG) != sha: + raise ValueError("Recovery tag no longer names the event commit") + if tag_commit(api, RECOVERY_TARGET) != RECOVERY_SHA: + raise ValueError("Original v0.5.0 tag moved") + # Recheck the original frozen gate, including its then-required benchmark + # status. This does not restore a benchmark gate for new releases. + require_eligible(api, RECOVERY_SHA, owner, required=REQUIRED | {"Product regression"}) + return RECOVERY_SHA, RECOVERY_TARGET + return sha, tag + + def main() -> None: repo = os.environ["GITHUB_REPOSITORY"] token = os.environ["GH_TOKEN"] @@ -101,7 +144,9 @@ def api(path): with urllib.request.urlopen(request, timeout=30) as response: return json.load(response) - require_eligible(api, os.environ["GITHUB_SHA"], os.environ.get("GITHUB_REPOSITORY_OWNER", "")) + sha, tag = release_target(api, os.environ) + with Path(os.environ["GITHUB_OUTPUT"]).open("a") as output: + output.write(f"build-sha={sha}\ntarget-tag={tag}\n") print("Verified main commit, owner verification record and required main checks.") diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2590f09c..9dbb0c1a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -17,6 +17,9 @@ jobs: name: Release eligibility runs-on: ubuntu-latest timeout-minutes: 5 + outputs: + build-sha: ${{ steps.gate.outputs.build-sha }} + target-tag: ${{ steps.gate.outputs.target-tag }} permissions: contents: read checks: read @@ -27,6 +30,7 @@ jobs: with: persist-credentials: false - name: Require verified main commit + id: gate env: GH_TOKEN: ${{ github.token }} run: python .github/scripts/release_gate.py @@ -36,6 +40,8 @@ jobs: runs-on: ubuntu-latest name: Build & Test timeout-minutes: 180 + env: + RELEASE_TAG: ${{ needs.eligibility.outputs.target-tag }} outputs: dist-id: ${{ steps.upload-dist.outputs.artifact-id }} dist-sha256: ${{ steps.dist-sha256.outputs.dist-sha256 }} @@ -44,32 +50,35 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false + ref: ${{ needs.eligibility.outputs.build-sha }} - name: Install uv uses: astral-sh/setup-uv@1c37ad07a6a961277cf70c0d37d6f313000f5884 # v10.3.0 - name: Set up Python 3.13 - run: uv python install 3.13 + run: | + uv python install 3.13 + echo "UV_PROJECT_ENVIRONMENT=$RUNNER_TEMP/release-product-venv" >> "$GITHUB_ENV" - name: Install dependencies run: uv sync --locked --dev --no-install-project --no-build - name: Verify tag matches package version run: | - TAG_VERSION="${GITHUB_REF_NAME#v}" + TAG_VERSION="${RELEASE_TAG#v}" PKG_VERSION=$(uv run --no-sync python -c "import tomllib; print(tomllib.load(open('pyproject.toml','rb'))['project']['version'])") if [ "$TAG_VERSION" != "$PKG_VERSION" ]; then - echo "::error::Tag ${GITHUB_REF_NAME} does not match pyproject.toml version ${PKG_VERSION}" + echo "::error::Tag ${RELEASE_TAG} does not match pyproject.toml version ${PKG_VERSION}" exit 1 fi SERVER_VERSION=$(uv run --no-sync python -c "import json; print(json.load(open('server.json'))['version'])") PACKAGE_VERSION=$(uv run --no-sync python -c "import json; print(json.load(open('server.json'))['packages'][0]['version'])") if [ "$TAG_VERSION" != "$SERVER_VERSION" ]; then - echo "::error::Tag ${GITHUB_REF_NAME} does not match server.json version ${SERVER_VERSION}" + echo "::error::Tag ${RELEASE_TAG} does not match server.json version ${SERVER_VERSION}" exit 1 fi if [ "$TAG_VERSION" != "$PACKAGE_VERSION" ]; then - echo "::error::Tag ${GITHUB_REF_NAME} does not match server.json package version ${PACKAGE_VERSION}" + echo "::error::Tag ${RELEASE_TAG} does not match server.json package version ${PACKAGE_VERSION}" exit 1 fi echo "Version check passed: ${PKG_VERSION}" @@ -78,7 +87,30 @@ jobs: run: uv build --build-constraint .github/build-constraints.txt --require-hashes - name: Install the built wheel - run: uv pip install --no-deps dist/*.whl + run: uv pip install --python "$UV_PROJECT_ENVIRONMENT/bin/python" --no-deps dist/*.whl + + - name: Verify wheel contents and installed database bootstrap + run: | + uv run --no-sync python - <<'PY' + import sqlite3 + import sysconfig + import zipfile + from pathlib import Path + from mcp_server_python_docs.storage import db + + wheel, = Path("dist").glob("*.whl") + installed = Path(db.__file__).resolve().parents[1] + assert installed.is_relative_to(Path(sysconfig.get_path("purelib")).resolve()), installed + with zipfile.ZipFile(wheel) as archive: + for resource in ("storage/schema.sql", "data/synonyms.yaml"): + expected = archive.read(f"mcp_server_python_docs/{resource}") + assert expected and (installed / resource).read_bytes() == expected, resource + with sqlite3.connect(":memory:") as conn: + db.bootstrap_schema(conn) + assert conn.execute("PRAGMA user_version").fetchone()[0] == db.INDEX_FORMAT_VERSION + conn.execute("SELECT * FROM sections_fts LIMIT 0") + print(f"Verified wheel resources and installed database bootstrap: {installed}") + PY - name: Run linter run: uv run --no-sync ruff check src/ tests/ benchmarks/ ops/ .github/scripts/ @@ -90,6 +122,8 @@ jobs: env: UV_BUILD_CONSTRAINT: .github/build-constraints.txt UV_REQUIRE_HASHES: "1" + # Inherit into nested uv run calls; the CLI flag alone is not inherited. + UV_NO_SYNC: "1" run: uv run --no-sync pytest --ignore=tests/benchmarks --tb=short -q - name: Validate MCP manifest before publication @@ -97,22 +131,6 @@ jobs: bash .github/scripts/install_publisher.sh "${RUNNER_TEMP}/mcp-publisher" validate server.json - - name: Verify wheel contents - run: | - uv run --no-sync python -c " - import zipfile, glob, sys - wheels = glob.glob('dist/*.whl') - if not wheels: - print('No wheel found') - sys.exit(1) - with zipfile.ZipFile(wheels[0]) as zf: - names = zf.namelist() - if not any('synonyms.yaml' in n for n in names): - print('synonyms.yaml not found in wheel') - sys.exit(1) - print('Wheel contents OK') - " - - name: Record dist checksums id: dist-sha256 run: | @@ -177,7 +195,7 @@ jobs: uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # release/v1 publish-mcp-registry: - needs: publish + needs: [eligibility, publish] runs-on: ubuntu-latest name: Publish to MCP Registry timeout-minutes: 10 @@ -189,6 +207,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false + ref: ${{ needs.eligibility.outputs.build-sha }} - name: Install verified MCP publisher run: bash .github/scripts/install_publisher.sh @@ -201,6 +220,7 @@ jobs: github-release: needs: + - eligibility - build - publish - publish-mcp-registry @@ -233,5 +253,6 @@ jobs: - name: Create GitHub Release uses: softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3 with: + tag_name: ${{ needs.eligibility.outputs.target-tag }} files: dist/* generate_release_notes: true diff --git a/tests/test_ci_workflows.py b/tests/test_ci_workflows.py index f3782d72..56a6f3a6 100644 --- a/tests/test_ci_workflows.py +++ b/tests/test_ci_workflows.py @@ -216,19 +216,22 @@ def test_release_build_job_never_builds_the_project_with_an_unpinned_backend() - assert [c for c in commands if builders.search(c)] == [ "uv sync --locked --dev --no-install-project --no-build", "uv build --build-constraint .github/build-constraints.txt --require-hashes", - "uv pip install --no-deps dist/*.whl", + 'uv pip install --python "$UV_PROJECT_ENVIRONMENT/bin/python" --no-deps dist/*.whl', ] uv_runs = [c for c in commands if "uv run" in c] # a syncing `uv run` rebuilds the project editable with an unpinned backend assert uv_runs and all(c.count("uv run") == c.count("uv run --no-sync") for c in uv_runs) build = names.index("Build package") - assert steps[build + 1]["run"] == "uv pip install --no-deps dist/*.whl" + assert steps[build + 1]["run"] == ( + 'uv pip install --python "$UV_PROJECT_ENVIRONMENT/bin/python" --no-deps dist/*.whl' + ) tests = names.index("Run tests") assert build < tests # tests/test_packaging.py builds a wheel too; pin its backend the same way assert steps[tests]["env"] == { "UV_BUILD_CONSTRAINT": ".github/build-constraints.txt", "UV_REQUIRE_HASHES": "1", + "UV_NO_SYNC": "1", } @@ -238,3 +241,46 @@ def test_security_audit_covers_the_sandbox_fetch_requirements() -> None: (step,) = [s for s in job["steps"] if s.get("name") == "Audit dependencies"] assert "--requirement requirements-audit.txt" in step["run"] assert "--requirement benchmarks/sandbox/fetch-requirements.txt" in step["run"] + + +def test_release_uses_eligible_source_and_explicit_target_tag() -> None: + jobs = release_jobs() + source = "${{ needs.eligibility.outputs.build-sha }}" + tag = "${{ needs.eligibility.outputs.target-tag }}" + assert jobs["eligibility"]["outputs"] == { + "build-sha": "${{ steps.gate.outputs.build-sha }}", + "target-tag": "${{ steps.gate.outputs.target-tag }}", + } + for name in ("build", "publish-mcp-registry"): + job = jobs[name] + assert "eligibility" in job["needs"] + checkout, = [s for s in job["steps"] if s.get("uses", "").startswith("actions/checkout@")] + assert checkout["with"]["ref"] == source + assert jobs["build"]["env"]["RELEASE_TAG"] == tag + version = next(s for s in jobs["build"]["steps"] if s.get("name", "").startswith("Verify tag")) + assert '${RELEASE_TAG#v}' in version["run"] + assert 'GITHUB_REF_NAME' not in version["run"] + release = jobs["github-release"] + assert "eligibility" in release["needs"] + assert release["steps"][-1]["with"]["tag_name"] == tag + + +def test_release_bootstraps_installed_wheel_before_product_tests() -> None: + build = release_jobs()["build"] + assert "UV_PROJECT_ENVIRONMENT" not in build["env"] + steps = build["steps"] + setup = next(i for i, s in enumerate(steps) if s.get("name") == "Set up Python 3.13") + sync = next(i for i, s in enumerate(steps) if "uv sync" in s.get("run", "")) + assert setup < sync + assert steps[setup]["run"].splitlines() == [ + "uv python install 3.13", + 'echo "UV_PROJECT_ENVIRONMENT=$RUNNER_TEMP/release-product-venv" >> "$GITHUB_ENV"', + ] + smoke = next(i for i, s in enumerate(steps) if "db.bootstrap_schema" in s.get("run", "")) + tests = next(i for i, s in enumerate(steps) if s.get("name") == "Run tests") + assert smoke < tests + assert "storage/schema.sql" in steps[smoke]["run"] + assert 'sqlite3.connect(":memory:")' in steps[smoke]["run"] + assert 'sysconfig.get_path("purelib")' in steps[smoke]["run"] + assert "archive.read" in steps[smoke]["run"] + assert "--ignore=tests/benchmarks" in steps[tests]["run"] diff --git a/tests/test_packaging.py b/tests/test_packaging.py index 6efa45b5..142ee780 100644 --- a/tests/test_packaging.py +++ b/tests/test_packaging.py @@ -14,6 +14,7 @@ from pathlib import Path import pytest +import yaml PROJECT_ROOT = Path(__file__).parent.parent DIST_NAME = "python-docs-mcp-server" @@ -68,6 +69,44 @@ def test_schema_sql_in_wheel(self, built_wheel): + "\n".join(sorted(names)) ) + def test_installed_schema_survives_nested_uv_run(self, built_wheel, tmp_path): + """A nested uv run must not replace the wheel beneath imported modules.""" + env = {**os.environ, "UV_PROJECT_ENVIRONMENT": str(tmp_path / "installed")} + env.pop("VIRTUAL_ENV", None) + env.pop("UV_NO_SYNC", None) + # Like the workflow, apply test-only flags after installing our built wheel. + env.pop("UV_REQUIRE_HASHES", None) + uv = _uv_command() + executable = "Scripts/python.exe" if os.name == "nt" else "bin/python" + python = tmp_path / "installed" / executable + for args in ( + ["sync", "--locked", "--dev", "--no-install-project", "--no-build"], + ["pip", "install", "--python", str(python), "--no-deps", str(built_wheel)], + ): + result = subprocess.run( + uv + args, cwd=PROJECT_ROOT, env=env, capture_output=True, text=True, + ) + assert result.returncode == 0, result.stderr + workflow = yaml.safe_load((PROJECT_ROOT / ".github/workflows/release.yml").read_text()) + tests = next(s for s in workflow["jobs"]["build"]["steps"] if s.get("name") == "Run tests") + env.update(tests["env"]) + result = subprocess.run( + [str(python), "-c", """ +import sqlite3, subprocess, sys, sysconfig +from pathlib import Path +from mcp_server_python_docs.storage import db +schema = Path(db.__file__).with_name("schema.sql") +assert schema.is_relative_to(Path(sysconfig.get_path("purelib"))) +before = schema.read_bytes() +db.bootstrap_schema(sqlite3.connect(":memory:")) +subprocess.run([*sys.argv[1:], "run", "--locked", "python", "-c", "pass"], check=True) +assert schema.read_bytes() == before +db.bootstrap_schema(sqlite3.connect(":memory:")) +""", *uv], + cwd=PROJECT_ROOT, env=env, capture_output=True, text=True, + ) + assert result.returncode == 0, result.stderr + def test_wheel_metadata_uses_public_distribution_name(self, built_wheel): """Wheel metadata must publish under the repo-aligned distribution name.""" with zipfile.ZipFile(built_wheel) as zf: diff --git a/tests/test_release_gate.py b/tests/test_release_gate.py index b80ce7e5..5f5b9484 100644 --- a/tests/test_release_gate.py +++ b/tests/test_release_gate.py @@ -183,3 +183,82 @@ def test_release_eligibility_ignores_an_edited_record_for_another_head(): def test_release_eligibility_accepts_when_a_newer_pass_follows_a_fail(): state = make_state([note(FAILED), note(RECORD, created_at=LATER)]) GATE["require_eligible"](state.__getitem__, SHA, OWNER) + + +def recovery_state(): + import json + + state = make_state([note(RECORD)]) + original = json.loads(json.dumps(make_state([note(RECORD)])) + .replace(SHA, GATE["RECOVERY_SHA"]) + .replace(HEAD, "e" * 40) + .replace("issues/7/", "issues/8/")) + original[f"commits/{GATE['RECOVERY_SHA']}/pulls?per_page=100"][0]["number"] = 8 + original[f"commits/{GATE['RECOVERY_SHA']}/check-runs?per_page=100"]["check_runs"].append( + {"id": 100, "name": "Product regression", "app": {"id": 15368}, "conclusion": "success"} + ) + state.update(original) + state["git/ref/tags/v0.5.0-recovery.1"] = {"object": {"type": "commit", "sha": SHA}} + state["git/ref/tags/v0.5.0"] = {"object": {"type": "tag", "sha": "f" * 40}} + state[f"git/tags/{'f' * 40}"] = { + "object": {"type": "commit", "sha": GATE["RECOVERY_SHA"]} + } + env = { + "GITHUB_SHA": SHA, "GITHUB_REF_NAME": "v0.5.0-recovery.1", + "GITHUB_REPOSITORY_OWNER": OWNER, "GITHUB_EVENT_NAME": "push", + "GITHUB_REF": "refs/tags/v0.5.0-recovery.1", "GITHUB_REF_PROTECTED": "true", + } + return state, env + + +def test_only_exact_recovery_event_selects_original_release(): + state, env = recovery_state() + target = GATE["release_target"] + assert target(state.__getitem__, env) == (GATE["RECOVERY_SHA"], "v0.5.0") + for tag in ("v0.5.1", "v0.5.0-recovery.2", "v0.5.0-recovery.1-extra"): + assert target(state.__getitem__, {**env, "GITHUB_REF_NAME": tag}) == (SHA, tag) + + +@pytest.mark.parametrize(("key", "value"), [ + ("GITHUB_EVENT_NAME", "workflow_dispatch"), + ("GITHUB_REF", "refs/heads/v0.5.0-recovery.1"), + ("GITHUB_REF_PROTECTED", "false"), +]) +def test_recovery_requires_protected_tag_push(key, value): + state, env = recovery_state() + with pytest.raises(ValueError, match="protected tag push"): + GATE["release_target"](state.__getitem__, {**env, key: value}) + + +@pytest.mark.parametrize("tag", ["v0.5.0", "v0.5.0-recovery.1"]) +def test_recovery_rejects_moved_tags(tag): + state, env = recovery_state() + state[f"git/ref/tags/{tag}"] = {"object": {"type": "commit", "sha": "d" * 40}} + with pytest.raises(ValueError, match="tag"): + GATE["release_target"](state.__getitem__, env) + + +@pytest.mark.parametrize("original", [False, True]) +@pytest.mark.parametrize("failure", ["main", "checks", "record", "codeql"]) +def test_recovery_rechecks_both_commits(original, failure): + state, env = recovery_state() + sha, head, pr = (GATE["RECOVERY_SHA"], "e" * 40, 8) if original else (SHA, HEAD, 7) + if failure == "main": + state[f"compare/{sha}...main"]["status"] = "diverged" + elif failure == "checks": + # For the original this also exercises its frozen Product regression gate. + state[f"commits/{sha}/check-runs?per_page=100"]["check_runs"].pop() + elif failure == "record": + state[f"issues/{pr}/comments?per_page=100&page=1"][0]["body"] = FAILED.replace(HEAD, head) + else: + state[f"commits/{head}/check-runs?per_page=100"]["check_runs"][0]["conclusion"] = "failure" + with pytest.raises(ValueError): + GATE["release_target"](state.__getitem__, env) + + +@pytest.mark.parametrize("kind", ["blob", "tree", "tag"]) +def test_tag_peeling_rejects_non_commit_or_cyclic_objects(kind): + state = {"git/ref/tags/v0.5.0": {"object": {"type": kind, "sha": SHA}}} + state[f"git/tags/{SHA}"] = state["git/ref/tags/v0.5.0"] + with pytest.raises(ValueError, match="exact commit"): + GATE["tag_commit"](state.__getitem__, "v0.5.0") From 312af92cfa31483ae6840ab27a8af4a824e9ab28 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Sat, 21 Nov 2026 22:12:51 +0100 Subject: [PATCH 3/3] test: verify nested uv preserves the wheel without network access --- tests/test_packaging.py | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/tests/test_packaging.py b/tests/test_packaging.py index 142ee780..f71b90f6 100644 --- a/tests/test_packaging.py +++ b/tests/test_packaging.py @@ -71,7 +71,11 @@ def test_schema_sql_in_wheel(self, built_wheel): def test_installed_schema_survives_nested_uv_run(self, built_wheel, tmp_path): """A nested uv run must not replace the wheel beneath imported modules.""" - env = {**os.environ, "UV_PROJECT_ENVIRONMENT": str(tmp_path / "installed")} + env = { + **os.environ, + "UV_PROJECT_ENVIRONMENT": str(tmp_path / "installed"), + "UV_OFFLINE": "1", + } env.pop("VIRTUAL_ENV", None) env.pop("UV_NO_SYNC", None) # Like the workflow, apply test-only flags after installing our built wheel. @@ -80,7 +84,7 @@ def test_installed_schema_survives_nested_uv_run(self, built_wheel, tmp_path): executable = "Scripts/python.exe" if os.name == "nt" else "bin/python" python = tmp_path / "installed" / executable for args in ( - ["sync", "--locked", "--dev", "--no-install-project", "--no-build"], + ["venv", "--python", sys.executable, str(tmp_path / "installed")], ["pip", "install", "--python", str(python), "--no-deps", str(built_wheel)], ): result = subprocess.run( @@ -92,16 +96,15 @@ def test_installed_schema_survives_nested_uv_run(self, built_wheel, tmp_path): env.update(tests["env"]) result = subprocess.run( [str(python), "-c", """ -import sqlite3, subprocess, sys, sysconfig +import subprocess, sys, sysconfig +from importlib.resources import files from pathlib import Path -from mcp_server_python_docs.storage import db -schema = Path(db.__file__).with_name("schema.sql") -assert schema.is_relative_to(Path(sysconfig.get_path("purelib"))) +schema = Path(files("mcp_server_python_docs.storage").joinpath("schema.sql")).resolve() +assert schema.is_relative_to(Path(sysconfig.get_path("purelib")).resolve()) before = schema.read_bytes() -db.bootstrap_schema(sqlite3.connect(":memory:")) subprocess.run([*sys.argv[1:], "run", "--locked", "python", "-c", "pass"], check=True) +assert Path(files("mcp_server_python_docs.storage").joinpath("schema.sql")).resolve() == schema assert schema.read_bytes() == before -db.bootstrap_schema(sqlite3.connect(":memory:")) """, *uv], cwd=PROJECT_ROOT, env=env, capture_output=True, text=True, )