~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(ci): execute encrypted upgrade compatibility probe (#6958)
LearningCircuit3c34c4853c93
diff --git a/.github/SECURITY_SCORECARD.md b/.github/SECURITY_SCORECARD.mdindex fbd6f55027..1034f7cfff 100644--- a/.github/SECURITY_SCORECARD.md+++ b/.github/SECURITY_SCORECARD.md@@ -79,14 +79,13 @@ The remaining pip commands use exact version pinning.| semgrep.yml | 50 | `python -m pip install semgrep==1.177.0` | Version-pinned || update-precommit-hooks.yml | 35-38 | `pip install pip==25.0` `pip install pre-commit-update==0.6.1` | **Hash-pinned** || validate-image-pinning.yml | 67 | `pip install pyyaml==6.0.2` | Version-pinned |-| backwards-compatibility.yml | 66-68 | `pip install --upgrade pip` `pip install pytest` `pip install -e .` | Intentionally unpinned |-| backwards-compatibility.yml | 106-107 | `pip install --upgrade pip` `pip install pytest` | Intentionally unpinned |-| backwards-compatibility.yml | 154-155 | `pip install --upgrade pip` `pip install "local-deep-research==..."` | Intentionally unpinned |-| backwards-compatibility.yml | 169 | `pip install -e .` | Local package |-> **Note:** `backwards-compatibility.yml` intentionally uses unpinned pip commands-> because it tests compatibility with prior PyPI releases of local-deep-research.-> Pinning these commands would defeat the purpose of the compatibility tests.+> **Note:** `backwards-compatibility.yml` installs its tooling with `pdm install --dev`+> and runs no pip command itself. Its probe+> (`tests/performance/database/test_backwards_compatibility.py`) runs+> `pip install "local-deep-research==<predecessor>"` in a throwaway venv: the+> package version is exact, but the predecessor's own dependencies are resolved+> unpinned on purpose, because the probe tests what users installing that release get.> **Note:** `semgrep.yml` pins the Semgrep engine, but the `p/security-audit` and> `p/secrets` registry rulesets are fetched live and unpinned. The scan runs with@@ -241,7 +240,7 @@ is a safe operation on localhost data.We have automated verification for our pinning strategy:- `.github/workflows/validate-image-pinning.yml` - Validates Docker image digests- Pre-commit hooks verify action SHA pinning-- All pip install commands use explicit version specifiers (except `backwards-compatibility.yml` which intentionally tests with unpinned versions)+- All pip install commands use explicit version specifiers (except the dependencies of the published predecessor that the backwards-compatibility probe installs, which are intentionally unpinned)### Review Cadencediff --git a/.github/workflows/backwards-compatibility.yml b/.github/workflows/backwards-compatibility.ymlindex 9724855ad5..976a0d8026 100644--- a/.github/workflows/backwards-compatibility.yml+++ b/.github/workflows/backwards-compatibility.yml@@ -2,6 +2,14 @@ name: Backwards Compatibilityon:workflow_call: # Allows this workflow to be called by other workflows+ inputs:+ caller:+ # release.yml runs this workflow twice in one run (compat-test-gate+ # and release-gate's backwards-compatibility). Artifact names must be+ # unique per run, so each caller passes a distinct id.+ description: 'Unique id of the calling job, used in artifact names'+ required: true+ type: stringpull_request:types: [opened, synchronize, reopened]branches: [main]@@ -26,6 +34,8 @@ on:- 'src/local_deep_research/database/alembic_runner.py'- 'src/local_deep_research/database/migrations/**'# Test files (ensure tests themselves are valid)+ - '.github/workflows/backwards-compatibility.yml'+ - 'tests/ci/test_pypi_compatibility_probe.py'- 'tests/performance/database/test_backwards_compatibility.py'- 'tests/database/test_encryption_constants.py'- 'tests/database/test_alembic_migrations.py'@@ -45,7 +55,7 @@ on:# No concurrency group — intentionally omitted.# This workflow triggers on both pull_request and workflow_call (from-# ci-gate.yml / release-gate.yml). A shared concurrency key would cause+# release.yml / release-gate.yml). A shared concurrency key would cause# direct PR runs and workflow_call runs to cancel each other mid-flight.# See #3554 (reverted in #3599) for context.@@ -126,95 +136,53 @@ jobs:sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache/CodeQLsudo docker image prune --all --force- - name: Install test dependencies- run: |- python -m pip install --upgrade pip- pip install pytest-- - name: Get previous PyPI version- id: prev-version- run: |- # Get list of available versions from PyPI- VERSIONS_OUTPUT=$(pip index versions local-deep-research 2>&1) || true-- if echo "$VERSIONS_OUTPUT" | grep -q "Available versions:"; then- VERSIONS=$(echo "$VERSIONS_OUTPUT" | grep "Available versions:" | cut -d: -f2 | tr ',' '\n' | tr -d ' ')- else- echo "::warning::Could not fetch versions from PyPI: ${VERSIONS_OUTPUT}"- echo "skip=true" >> "$GITHUB_OUTPUT"- exit 0- fi-- if [ -z "$VERSIONS" ]; then- echo "::warning::No versions found on PyPI"- echo "skip=true" >> "$GITHUB_OUTPUT"- exit 0- fi-- # Get current and previous versions- CURRENT=$(echo "$VERSIONS" | head -1)- PREVIOUS=$(echo "$VERSIONS" | head -2 | tail -1)-- if [ "$CURRENT" = "$PREVIOUS" ] || [ -z "$PREVIOUS" ]; then- echo "No previous version available"- echo "skip=true" >> "$GITHUB_OUTPUT"- exit 0- fi-- {- echo "current=$CURRENT"- echo "previous=$PREVIOUS"- echo "skip=false"- } >> "$GITHUB_OUTPUT"- echo "Previous version: $PREVIOUS, Current: $CURRENT"-- - name: Create database with previous version- id: create-db- if: steps.prev-version.outputs.skip != 'true'- run: |- # Create isolated venv for previous version- python -m venv prev_venv- source prev_venv/bin/activate-- # Install previous version — may fail if the published package- # has broken dependency metadata (e.g. requests version conflict).- # Upgrade pip for reliable dependency resolution in fresh venvs.- python -m pip install --upgrade pip- if ! pip install "local-deep-research==${{ steps.prev-version.outputs.previous }}" 2>&1; then- echo "::warning::Previous version ${{ steps.prev-version.outputs.previous }} has unresolvable dependencies — skipping compat test"- echo "install_failed=true" >> "$GITHUB_OUTPUT"- deactivate- exit 0- fi- echo "install_failed=false" >> "$GITHUB_OUTPUT"-- # Create test database- mkdir -p test_db- python tests/performance/database/scripts/create_compat_db.py test_db compat_user "TestPass123!"-- deactivate-- echo "Database created with version ${{ steps.prev-version.outputs.previous }}"- ls -la test_db/-- name: Install current version- if: steps.prev-version.outputs.skip != 'true' && steps.create-db.outputs.install_failed != 'true'run: pdm install --dev- - name: Test opening database with current version- if: steps.prev-version.outputs.skip != 'true' && steps.create-db.outputs.install_failed != 'true'+ - name: Test opening database from the latest published version+ id: compatibility-test+ env:+ RUN_SLOW_TESTS: 'true'+ shell: bashrun: |- # Run the backwards compatibility test with RUN_SLOW_TESTS enabled- RUN_SLOW_TESTS=true pdm run pytest tests/performance/database/test_backwards_compatibility.py -v --tb=short-- - name: Report skipped- if: steps.prev-version.outputs.skip == 'true' || steps.create-db.outputs.install_failed == 'true'+ mkdir -p test-results+ pdm run pytest tests/performance/database/test_backwards_compatibility.py \+ -v -ra -s --tb=short -p no:cov \+ --junitxml=test-results/pypi-compatibility.xml \+ 2>&1 | tee test-results/pypi-compatibility.log++ - name: Require the database compatibility probe to pass+ id: validate-results+ if: always()+ shell: bashrun: |- if [ "${{ steps.create-db.outputs.install_failed }}" = "true" ]; then- echo "::notice::Backwards compatibility test skipped - previous version has unresolvable dependency conflicts"- else- echo "::notice::Backwards compatibility test skipped - no previous PyPI version available"- fi+ python - <<'PYTHON'+ from pathlib import Path+ from xml.etree import ElementTree++ report = Path("test-results/pypi-compatibility.xml")+ if not report.is_file():+ raise SystemExit("Missing PyPI compatibility test report")+ cases = list(ElementTree.parse(report).getroot().iter("testcase"))+ if (+ len(cases) != 1+ or cases[0].get("name") != "test_open_database_from_previous_version"+ or any(child.tag in {"skipped", "failure", "error"} for child in cases[0])+ ):+ raise SystemExit("PyPI compatibility probe did not execute and pass")+ print("PyPI compatibility probe executed and passed")+ PYTHON++ - name: Upload PyPI compatibility diagnostics+ if: always()+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ # Unique per caller and per attempt: upload-artifact fails on a+ # name that already exists in the run (overwrite defaults to false).+ name: pypi-compatibility-results-${{ inputs.caller || 'standalone' }}-${{ github.run_attempt }}+ path: test-results/pypi-compatibility.*+ if-no-files-found: error+ retention-days: 14# Database migration tests - validates Alembic migration infrastructure.# Runs on any trigger — including PRs that touch migration-relevant pathsdiff --git a/.github/workflows/release-gate.yml b/.github/workflows/release-gate.ymlindex e5ebd74310..a575e342e5 100644--- a/.github/workflows/release-gate.yml+++ b/.github/workflows/release-gate.yml@@ -295,6 +295,8 @@ jobs:# ============================================backwards-compatibility:uses: $/.github/workflows/backwards-compatibility.yml+ with:+ caller: release-gatepermissions:contents: readdiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 40f0c1132d..152de21b64 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -209,6 +209,8 @@ jobs:if: needs.version-check.outputs.should_release == 'true'# Runs in parallel with release-gate (no dependency besides version-check)uses: $/.github/workflows/backwards-compatibility.yml+ with:+ caller: release-compat-test-gatepermissions:contents: readdiff --git a/tests/ci/test_pypi_compatibility_probe.py b/tests/ci/test_pypi_compatibility_probe.pynew file mode 100644index 0000000000..cd404088bb--- /dev/null+++ b/tests/ci/test_pypi_compatibility_probe.py@@ -0,0 +1,304 @@+"""An opted-in compatibility run must execute against a published predecessor."""++# allow: no-sut-import — exercises the real compatibility probe and workflow commands.++import importlib.util+import io+import json+import os+from contextlib import contextmanager+from pathlib import Path+import subprocess+import sys+from xml.etree import ElementTree++import pytest+import yaml+++ROOT = Path(__file__).resolve().parents[2]+++@contextmanager+def _setup_must_fail(message):+ # An uncaught pytest.skip would also skip this regression test. Convert it+ # to a failure so restoring the old behavior cannot make the test green.+ try:+ with pytest.raises(pytest.fail.Exception, match=message):+ yield+ except pytest.skip.Exception as exc:+ pytest.fail(f"Opted-in compatibility probe skipped: {exc}")+++def probe_module():+ spec = importlib.util.spec_from_file_location(+ "pypi_compatibility_probe",+ ROOT / "tests/performance/database/test_backwards_compatibility.py",+ )+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def test_predecessor_is_latest_non_yanked_stable_release_without_pip(+ probe_module, monkeypatch+):+ payload = {+ "releases": {+ "1.10.6": [{"yanked": False}],+ "1.9.99": [{"yanked": False}],+ "1.10.7": [{"yanked": True}, {"yanked": False}],+ "1.10.8": [{"yanked": True}],+ "2.0.0rc1": [{"yanked": False}],+ "3.0.0.dev1": [{"yanked": False}],+ "9.0.0": [],+ }+ }++ def request(url, *, timeout):+ assert url == "https://pypi.org/pypi/local-deep-research/json"+ assert 0 < timeout <= 30+ return io.BytesIO(json.dumps(payload).encode())++ def no_pip(*args, **kwargs):+ pytest.fail("Version discovery must work without pip in the PDM venv")++ monkeypatch.setattr(probe_module, "urlopen", request)+ monkeypatch.setattr(probe_module.subprocess, "run", no_pip)+ assert (+ probe_module.TestBackwardsCompatibility().get_previous_version()+ == "1.10.7"+ )+++def _serve(probe_module, monkeypatch, releases):+ monkeypatch.setattr(+ probe_module,+ "urlopen",+ lambda *a, **kw: io.BytesIO(+ json.dumps({"releases": releases}).encode()+ ),+ )+++def test_known_uninstallable_release_is_replaced_by_next_predecessor(+ probe_module, monkeypatch+):+ # 1.4.0's published metadata cannot be resolved (#3331). It must not+ # block the gate, and the probe must still run against a real release.+ _serve(+ probe_module,+ monkeypatch,+ {+ "1.3.9": [{"yanked": False}],+ "1.4.0": [{"yanked": False}],+ },+ )+ assert "1.4.0" in probe_module.KNOWN_UNINSTALLABLE_RELEASES+ assert (+ probe_module.TestBackwardsCompatibility().get_previous_version()+ == "1.3.9"+ )+++def test_uninstallable_allowance_is_exact_and_documented(probe_module):+ from packaging.version import Version++ allowed = probe_module.KNOWN_UNINSTALLABLE_RELEASES+ # A narrow, pinned list: exact stable versions with a reason, never a+ # range or a blanket switch.+ assert allowed == {+ "1.4.0": "requests>=2.33 conflicts with arxiv~=2.4 (requests~=2.32.0)"+ }+ for version, reason in allowed.items():+ assert str(Version(version)) == version+ assert reason.strip()+++def test_allowance_does_not_exclude_neighbouring_releases(+ probe_module, monkeypatch+):+ # Only the listed version is excluded: a neighbouring release (1.4.1) is+ # still chosen, so its install failure fails the probe.+ _serve(+ probe_module,+ monkeypatch,+ {"1.4.0": [{"yanked": False}], "1.4.1": [{"yanked": False}]},+ )+ assert (+ probe_module.TestBackwardsCompatibility().get_previous_version()+ == "1.4.1"+ )+++def test_only_uninstallable_releases_is_an_error(probe_module, monkeypatch):+ _serve(probe_module, monkeypatch, {"1.4.0": [{"yanked": False}]})+ with pytest.raises(ValueError, match="KNOWN_UNINSTALLABLE_RELEASES"):+ probe_module.TestBackwardsCompatibility().get_previous_version()+++def test_no_published_predecessor_is_an_error(probe_module, monkeypatch):+ monkeypatch.setattr(+ probe_module,+ "urlopen",+ lambda *a, **kw: io.BytesIO(b'{"releases": {}}'),+ )+ with pytest.raises(ValueError, match="no non-yanked stable release"):+ probe_module.TestBackwardsCompatibility().get_previous_version()+++def test_version_discovery_failure_cannot_skip(+ probe_module, monkeypatch, tmp_path+):+ def unavailable(*args, **kwargs):+ raise OSError("PyPI unavailable")++ monkeypatch.setattr(probe_module, "urlopen", unavailable)+ with _setup_must_fail("PyPI unavailable"):+ probe_module.TestBackwardsCompatibility().test_open_database_from_previous_version(+ tmp_path, monkeypatch+ )+++ ("failing_call", "message"),+ [+ (1, "Could not create venv"),+ (2, "Could not install previous version"),+ (3, "Could not create database with previous version"),+ ],+)+def test_predecessor_setup_failures_cannot_skip_or_import_checkout(+ probe_module, monkeypatch, tmp_path, failing_call, message+):+ probe = probe_module.TestBackwardsCompatibility()+ monkeypatch.setattr(probe, "get_previous_version", lambda: "1.10.7")+ monkeypatch.setenv("PYTHONPATH", str(ROOT / "src"))+ calls = []++ def run(args, **kwargs):+ calls.append(args)+ assert kwargs["cwd"] == tmp_path+ assert "PYTHONPATH" not in kwargs["env"]+ assert 0 < kwargs["timeout"] <= 600+ return subprocess.CompletedProcess(+ args,+ int(len(calls) == failing_call),+ stdout="",+ stderr="setup failed",+ )++ monkeypatch.setattr(probe_module.subprocess, "run", run)+ with _setup_must_fail(message):+ probe.test_open_database_from_previous_version(tmp_path, monkeypatch)+ assert len(calls) == failing_call+ if failing_call >= 2:+ assert "local-deep-research==1.10.7" in calls[1]+ assert str(tmp_path / "prev_venv") in calls[1][0]+ if failing_call == 3:+ assert Path(calls[2][1]).parent == tmp_path++[email protected](scope="module")+def compatibility_job():+ return yaml.safe_load(+ (ROOT / ".github/workflows/backwards-compatibility.yml").read_text()+ )["jobs"]["pypi-compatibility"]+++def _step(job, step_id):+ return next(s for s in job["steps"] if s.get("id") == step_id)+++def _execute(script, directory, extra_env=None):+ return subprocess.run(+ ["bash", "-e", "-o", "pipefail", "-c", script],+ cwd=directory,+ env={+ **os.environ,+ "PATH": f"{Path(sys.executable).parent}:{os.environ.get('PATH', '')}",+ **(extra_env or {}),+ },+ capture_output=True,+ text=True,+ timeout=20,+ check=False,+ )+++def test_workflow_opts_in_and_retains_diagnostics(compatibility_job):+ test = _step(compatibility_job, "compatibility-test")+ assert test["env"]["RUN_SLOW_TESTS"] == "true"+ assert test["shell"] == "bash"+ assert "if" not in test and not test.get("continue-on-error")+ assert "--junitxml=test-results/pypi-compatibility.xml" in test["run"]+ validator = _step(compatibility_job, "validate-results")+ assert validator["if"] == "always()"+ assert not validator.get("continue-on-error")+ upload = next(+ s+ for s in compatibility_job["steps"]+ if s.get("uses", "").startswith("actions/upload-artifact@")+ )+ assert upload["if"] == "always()"+ assert upload["with"]["path"] == "test-results/pypi-compatibility.*"+++ "outcome",+ [+ "passed",+ "skipped",+ "failure",+ "error",+ "wrong-test",+ "empty",+ "missing",+ "malformed",+ ],+)+def test_real_workflow_rejects_unexecuted_probe(+ compatibility_job, tmp_path, outcome+):+ report = tmp_path / "test-results/pypi-compatibility.xml"+ if outcome != "missing":+ report.parent.mkdir()+ if outcome == "malformed":+ report.write_text("<testsuites>")+ else:+ suite = ElementTree.Element("testsuite")+ if outcome != "empty":+ case = ElementTree.SubElement(+ suite,+ "testcase",+ name="unrelated_test"+ if outcome == "wrong-test"+ else "test_open_database_from_previous_version",+ )+ if outcome in {"skipped", "failure", "error"}:+ ElementTree.SubElement(case, outcome)+ ElementTree.ElementTree(suite).write(report)+ result = _execute(+ _step(compatibility_job, "validate-results")["run"], tmp_path+ )+ assert (result.returncode == 0) is (outcome == "passed"), (+ result.stdout + result.stderr+ )++[email protected]("pytest_status", [0, 1, 5])+def test_pytest_status_survives_log_pipeline(+ compatibility_job, tmp_path, pytest_status+):+ binary = tmp_path / "bin"+ binary.mkdir()+ pdm = binary / "pdm"+ pdm.write_text(f"#!/bin/sh\nexit {pytest_status}\n")+ pdm.chmod(0o755)+ result = _execute(+ _step(compatibility_job, "compatibility-test")["run"],+ tmp_path,+ {"PATH": f"{binary}:{os.environ.get('PATH', '')}"},+ )+ assert result.returncode == pytest_status, result.stdout + result.stderrdiff --git a/tests/ci/test_workflow_artifact_names.py b/tests/ci/test_workflow_artifact_names.pynew file mode 100644index 0000000000..21f2fc56a5--- /dev/null+++ b/tests/ci/test_workflow_artifact_names.py@@ -0,0 +1,201 @@+"""Artifact names must be unique within every workflow run, across call paths.++actions/upload-artifact fails when an artifact with the same name already+exists in the run (``overwrite`` defaults to false). A reusable workflow that+one run reaches twice -- release.yml calls backwards-compatibility.yml+directly and again through release-gate.yml -- therefore uploads twice under+the same name unless each call path renders a distinct name.+"""++# allow: no-sut-import — parses the real GitHub workflow files.++import re+from collections import Counter+from pathlib import Path++import pytest+import yaml+++WORKFLOWS = Path(__file__).resolve().parents[2] / ".github" / "workflows"+_LOCAL_CALL = re.compile(r"\.github/workflows/([^/@]+\.ya?ml)$")+_EXPRESSION = re.compile(r"\$\{\{\s*(.*?)\s*\}\}")+_LITERAL = re.compile(r"^'((?:[^']|'')*)'$")+++def _load(directory):+ return {+ path.name: yaml.safe_load(path.read_text())+ for path in sorted(directory.glob("*.y*ml"))+ }+++def _triggers(doc):+ # PyYAML parses the bare key `on` as the boolean True.+ return doc.get("on", doc.get(True)) or {}+++def _input_defaults(doc):+ call = _triggers(doc)+ call = call.get("workflow_call") if isinstance(call, dict) else None+ inputs = (call or {}).get("inputs") or {}+ return {+ name: str(spec.get("default", ""))+ for name, spec in inputs.items()+ if isinstance(spec, dict)+ }+++def _render(template, inputs):+ """Render the parts of a name that differ between call paths.++ ``inputs.*`` take the caller's ``with:`` value (or the declared default)+ and ``a || b`` picks the first non-empty operand. Anything else, such as+ ``github.run_attempt`` or ``matrix.*``, is identical for every call path+ of one run attempt, so it is kept verbatim.+ """++ def operand(text):+ text = text.strip()+ literal = _LITERAL.match(text)+ if literal:+ return literal.group(1).replace("''", "'")+ if text.startswith("inputs."):+ return inputs.get(text[len("inputs.") :], "")+ return "${{ " + text + " }}"++ def expression(match):+ for part in match.group(1).split("||"):+ value = operand(part)+ if value:+ return value+ return ""++ return _EXPRESSION.sub(expression, str(template))+++def artifact_names_per_run(docs, entry):+ """Every artifact name one run of ``entry`` uploads, one per call path."""+ names = []++ def visit(workflow, inputs, path):+ for job_id, job in (docs[workflow].get("jobs") or {}).items():+ uses = job.get("uses")+ target = _LOCAL_CALL.search(uses) if isinstance(uses, str) else None+ if target:+ called = target.group(1)+ assert called not in path, f"call cycle via {called}"+ passed = {+ **_input_defaults(docs[called]),+ **{+ key: _render(value, inputs)+ for key, value in (job.get("with") or {}).items()+ },+ }+ visit(called, passed, (*path, f"{workflow}:{job_id}"))+ continue+ for step in job.get("steps") or []:+ if "actions/upload-artifact@" not in str(step.get("uses", "")):+ continue+ name = (step.get("with") or {}).get("name", "artifact")+ names.append(+ (+ _render(name, inputs),+ " -> ".join((*path, f"{workflow}:{job_id}")),+ )+ )++ visit(entry, _input_defaults(docs[entry]), ())+ return names+++def _duplicates(docs, entry):+ names = artifact_names_per_run(docs, entry)+ counts = Counter(name for name, _ in names)+ return {+ name: [where for n, where in names if n == name]+ for name, count in counts.items()+ if count > 1+ }+++REAL_DOCS = _load(WORKFLOWS)++[email protected]("entry", sorted(REAL_DOCS))+def test_artifact_names_are_unique_within_each_run(entry):+ assert _duplicates(REAL_DOCS, entry) == {}+++def test_release_run_uploads_both_compatibility_results_distinctly():+ names = [+ name+ for name, _ in artifact_names_per_run(REAL_DOCS, "release.yml")+ if name.startswith("pypi-compatibility-results")+ ]+ # Reached directly (compat-test-gate) and via release-gate.+ assert len(names) == 2+ assert len(set(names)) == 2+ assert all("${{ github.run_attempt }}" in name for name in names)+++def test_checker_detects_a_shared_name_reached_twice(tmp_path):+ reusable = {+ "on": {"workflow_call": {}},+ "jobs": {+ "probe": {+ "steps": [+ {+ "uses": "actions/upload-artifact@x",+ "with": {"name": "results"},+ }+ ]+ }+ },+ }+ gate = {+ "on": {"workflow_call": {}},+ "jobs": {"compat": {"uses": "./.github/workflows/reusable.yml"}},+ }+ release = {+ "on": {"push": {}},+ "jobs": {+ "gate": {"uses": "./.github/workflows/gate.yml"},+ "compat": {"uses": "./.github/workflows/reusable.yml"},+ },+ }+ for name, doc in {+ "reusable.yml": reusable,+ "gate.yml": gate,+ "release.yml": release,+ }.items():+ (tmp_path / name).write_text(yaml.safe_dump(doc))+ docs = _load(tmp_path)+ assert list(_duplicates(docs, "release.yml")) == ["results"]++ # A caller-supplied input in the name resolves the collision.+ reusable["on"]["workflow_call"]["inputs"] = {+ "caller": {"required": True, "type": "string"}+ }+ reusable["jobs"]["probe"]["steps"][0]["with"]["name"] = (+ "results-${{ inputs.caller || 'standalone' }}"+ )+ gate["jobs"]["compat"]["with"] = {"caller": "gate"}+ release["jobs"]["compat"]["with"] = {"caller": "direct"}+ for name, doc in {+ "reusable.yml": reusable,+ "gate.yml": gate,+ "release.yml": release,+ }.items():+ (tmp_path / name).write_text(yaml.safe_dump(doc))+ docs = _load(tmp_path)+ assert _duplicates(docs, "release.yml") == {}+ assert sorted(+ n for n, _ in artifact_names_per_run(docs, "release.yml")+ ) == [+ "results-direct",+ "results-gate",+ ]+ assert [n for n, _ in artifact_names_per_run(docs, "reusable.yml")] == [+ "results-standalone"+ ]diff --git a/tests/performance/database/scripts/create_compat_db.py b/tests/performance/database/scripts/create_compat_db.pyindex e9334b9294..985bca9092 100644--- a/tests/performance/database/scripts/create_compat_db.py+++ b/tests/performance/database/scripts/create_compat_db.py@@ -11,6 +11,7 @@ Usage:"""import sys+from importlib.metadata import versionfrom pathlib import Path# Set up paths@@ -28,6 +29,7 @@ from local_deep_research.database.encrypted_db import DatabaseManager # noqa: E# Create a fresh manager with patched pathmanager = DatabaseManager()+assert manager.has_encryption, "Predecessor SQLCipher support is unavailable"manager.data_dir = db_dir / "encrypted_databases"manager.data_dir.mkdir(parents=True, exist_ok=True)@@ -40,7 +42,11 @@ from local_deep_research.database.models import UserSettings # noqa: E402setting = UserSettings(key="test.backwards_compat",- value={"version": "previous", "test": True},+ value={+ "version": "previous",+ "test": True,+ "package_version": version("local-deep-research"),+ },category="test",)session.add(setting)@@ -48,4 +54,9 @@ session.commit()session.close()manager.close_user_database(username)-print("Database created successfully")+with manager._get_user_db_path(username).open("rb") as database_file:+ header = database_file.read(16)+assert len(header) == 16 and header != b"SQLite format 3\x00", (+ "The predecessor fixture must be an encrypted database"+)+print("Encrypted database created successfully")diff --git a/tests/performance/database/test_backwards_compatibility.py b/tests/performance/database/test_backwards_compatibility.pyindex 8b4b1f711a..46cf8dea58 100644--- a/tests/performance/database/test_backwards_compatibility.py+++ b/tests/performance/database/test_backwards_compatibility.py@@ -6,23 +6,42 @@ This test ensures that databases created with previous versions can stillbe opened with the current version. This prevents breaking changes likesalt modifications from going undetected.-The key tests are:-1. TestSaltStability - Fast tests that verify encryption constants haven't changed-2. TestBackwardsCompatibility - Slow test that actually installs previous PyPI version--The salt stability tests run in CI and catch 99% of breaking changes.-The full backwards compatibility test can be run manually with:- pytest tests/performance/database/test_backwards_compatibility.py -m slow --run-slow+The full probe installs the latest published version, creates an encrypted+database outside the checkout, and opens it with the candidate. Once explicitly+enabled, setup failures must fail the probe rather than report a skipped success.++The only exception is KNOWN_UNINSTALLABLE_RELEASES: exact published versions+whose dependency metadata pip cannot resolve. A published package cannot be+fixed, so such a version is never chosen as the predecessor; the probe still+runs against the newest stable release that is not listed. Any other install+failure fails the probe (and the release gate that requires it). If a newly+published release turns out to be uninstallable, either yank it on PyPI (yanked+files are ignored) or add its exact version here, with the reason, in a+reviewed commit.+Run it manually with:+ RUN_SLOW_TESTS=true pytest tests/performance/database/test_backwards_compatibility.py"""+import jsonimport osimport subprocessimport sysimport tempfilefrom pathlib import Path+from urllib.request import urlopenimport pytest+from packaging.version import Version++# Exact published versions that can never be installed, mapped to the reason.+# Keep this narrow: list a version only after confirming its metadata is+# unresolvable, and never use it to hide a database compatibility failure.+KNOWN_UNINSTALLABLE_RELEASES = {+ # #3331: the PDM override requests>=2.33 leaked into the published+ # metadata and conflicts with arxiv~=2.4's requests~=2.32.0 pin.+ "1.4.0": "requests>=2.33 conflicts with arxiv~=2.4 (requests~=2.32.0)",+}# Path to the script that creates a database using the installed package# This is in a separate file for better IDE support (syntax highlighting, linting)@@ -41,42 +60,37 @@ class TestBackwardsCompatibility:yield Path(tmpdir)def get_previous_version(self) -> str:- """Get the previous version number from PyPI."""- result = subprocess.run(- [- sys.executable,- "-m",- "pip",- "index",- "versions",- "local-deep-research",- ],- capture_output=True,- text=True,- )+ """Resolve the latest installable stable release without requiring pip.- if result.returncode != 0:- # Fallback: try to get from pip show- result = subprocess.run(- [sys.executable, "-m", "pip", "show", "local-deep-research"],- capture_output=True,- text=True,+ Yanked releases and the exact versions in KNOWN_UNINSTALLABLE_RELEASES+ are not candidates; everything else is.+ """+ with urlopen(+ "https://pypi.org/pypi/local-deep-research/json", timeout=30+ ) as response:+ payload = json.load(response)+ # The candidate is unreleased: the newest published stable package is+ # its predecessor, not the second entry returned by `pip index`.+ versions = [+ Version(version)+ for version, files in payload["releases"].items()+ if files and any(not file.get("yanked", False) for file in files)+ ]+ excluded = {Version(v) for v in KNOWN_UNINSTALLABLE_RELEASES}+ stable = [+ v+ for v in versions+ if not v.is_prerelease and not v.is_devrelease and v not in excluded+ ]+ if not stable:+ raise ValueError(+ "PyPI has no non-yanked stable release outside "+ "KNOWN_UNINSTALLABLE_RELEASES")- # Can't determine previous version- pytest.skip("Could not determine previous version from PyPI")-- # Parse versions from output- # Output format: "local-deep-research (1.3.21)\nAvailable versions: 1.3.21, 1.3.20, ..."- for line in result.stdout.split("\n"):- if "Available versions:" in line:- versions = line.split(":")[1].strip().split(", ")- if len(versions) >= 2:- return versions[1] # Second version is the previous one-- pytest.skip("Could not find previous version")+ return str(max(stable))@pytest.mark.slow- @pytest.mark.timeout(600) # 10 minutes - installing PyPI package takes time+ @pytest.mark.timeout(900) # Includes installation and real database checks.@pytest.mark.skipif(os.environ.get("RUN_SLOW_TESTS") != "true",reason="Slow test - set RUN_SLOW_TESTS=true to run",@@ -94,7 +108,14 @@ class TestBackwardsCompatibility:try:previous_version = self.get_previous_version()except Exception as e:- pytest.skip(f"Could not get previous version: {e}")+ pytest.fail(f"Could not get previous version: {e}")++ print(+ f"Testing encrypted database upgrade from PyPI {previous_version}"+ )+ # Do not let a checkout's PYTHONPATH replace the installed predecessor.+ child_env = os.environ.copy()+ child_env.pop("PYTHONPATH", None)# Create isolated venv for previous versionvenv_dir = temp_dir / "prev_venv"@@ -106,9 +127,12 @@ class TestBackwardsCompatibility:[sys.executable, "-m", "venv", str(venv_dir)],capture_output=True,text=True,+ cwd=temp_dir,+ env=child_env,+ timeout=60,)if result.returncode != 0:- pytest.skip(f"Could not create venv: {result.stderr}")+ pytest.fail(f"Could not create venv: {result.stderr}")# Get venv pythonif sys.platform == "win32":@@ -129,10 +153,12 @@ class TestBackwardsCompatibility:],capture_output=True,text=True,+ cwd=temp_dir,+ env=child_env,timeout=600, # 10 minute timeout - package has many dependencies)if result.returncode != 0:- pytest.skip(f"Could not install previous version: {result.stderr}")+ pytest.fail(f"Could not install previous version: {result.stderr}")# Create database with previous versionusername = "compat_test_user"@@ -152,6 +178,8 @@ class TestBackwardsCompatibility:],capture_output=True,text=True,+ cwd=temp_dir,+ env=child_env,timeout=60,)if result.returncode != 0:@@ -171,6 +199,9 @@ class TestBackwardsCompatibility:from local_deep_research.database.models import UserSettingsmanager = DatabaseManager()+ assert manager.has_encryption, (+ "Candidate SQLCipher support is unavailable"+ )manager.data_dir = db_dir / "encrypted_databases"# Try to open the database@@ -181,21 +212,22 @@ class TestBackwardsCompatibility:)# Verify we can read the data- session = manager.get_session(username)- setting = (- session.query(UserSettings)- .filter_by(key="test.backwards_compat")- .first()- )-- assert setting is not None, (- "Could not read data from previous version database"- )- assert setting.value["version"] == "previous"- assert setting.value["test"] is True-- session.close()- manager.close_user_database(username)+ try:+ with manager.get_session(username) as session:+ setting = (+ session.query(UserSettings)+ .filter_by(key="test.backwards_compat")+ .first()+ )++ assert setting is not None, (+ "Could not read data from previous version database"+ )+ assert setting.value["version"] == "previous"+ assert setting.value["test"] is True+ assert setting.value["package_version"] == previous_version+ finally:+ manager.close_user_database(username)# Note: Salt stability tests have been moved to test_encryption_constants.py