Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 15 additions & 12 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
# Replace every <placeholder> before running. No secrets or real resources belong in Git.
# Use a text-embedding-3-small deployment with 1536 dimensions for these sample inputs.
DOCUMENTDB_CLUSTER_NAME=<your-cluster-name>
AZURE_OPENAI_EMBEDDING_ENDPOINT=https://<your-openai-resource>.openai.azure.com/
AZURE_OPENAI_EMBEDDING_MODEL=<embedding-deployment-name>
AZURE_OPENAI_EMBEDDING_API_VERSION=2023-05-15
AZURE_DOCUMENTDB_DATABASENAME=Hotels
# Documentation only: process environment is read; this file is never auto-loaded.
MONGO_AUTH_MODE=oidc
MONGO_HOST=<cluster>.global.mongocluster.cosmos.azure.com
MONGO_DATABASE=vectorsearch_disposable_my_run
MONGO_COLLECTION_PREFIX=oidc
# Optional registered OIDC principal username:
# MONGO_OIDC_USERNAME=<principal>
# Native mode instead: set MONGO_AUTH_MODE=connection-string, unset MONGO_HOST and
# MONGO_OIDC_USERNAME, and inject MONGO_CONNECTION_STRING securely (never commit it).
DATA_FILE_WITH_VECTORS=data/Hotels_Vector.json
EMBEDDED_FIELD=DescriptionVector
EMBEDDING_DIMENSIONS=1536
LOAD_SIZE_BATCH=100
QUERY_TEXT=luxury hotel near the beach
TOP_K=5
QUERY_VECTOR_FILE=data/query-vector.json
EMBEDDING_MODE=offline
VECTOR_SEARCH_ALLOW_WRITES=false
VECTOR_SEARCH_TIMEOUT_SECONDS=600
VECTOR_SEARCH_CASE_TIMEOUT_SECONDS=120
# Explicit real tests additionally require VECTOR_SEARCH_LIVE_TEST=1.
35 changes: 35 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
name: Python checks
on:
push:
pull_request:
permissions:
contents: read
jobs:
offline:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
persist-credentials: false
- uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6
with:
python-version: '3.12.13'
- name: Hash-locked dependencies
run: python -m pip install --require-hashes -r requirements-dev.txt
- name: Dependency compatibility
run: python -m pip check
- name: Compile
run: python -m compileall -q src tests tests_live
- name: Offline contracts (no Azure calls)
run: python -m pytest -q
- name: Current vulnerability advisories
run: python -m pip_audit -r requirements-dev.txt --no-deps --disable-pip --vulnerability-service osv
- name: Explicit real gate rejects missing authorization
shell: bash
run: |
if VECTOR_SEARCH_LIVE_TEST= python -m pytest tests_live -q > live-gate.log 2>&1; then
echo 'Explicit real gate unexpectedly accepted missing opt-in'
exit 1
fi
grep -q 'requires VECTOR_SEARCH_LIVE_TEST=1; no network calls made' live-gate.log
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,7 @@ __pycache__/
bin/
obj/
target/

.pytest_cache/
.coverage
*.egg-info/
127 changes: 85 additions & 42 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,74 +1,117 @@
# select-algorithm-python

**Python**. Compare IVF, HNSW, and DiskANN against cosine, L2, and inner-product metrics: nine combinations with sequential index creation, search, and removal.
A standalone Python 3.12 sample for **IVF, HNSW and DiskANN vector search on Azure DocumentDB**. The primary path uses 50 public hotel records with precomputed 1536-dimensional vectors and a JSON query vector. **No Azure OpenAI resource, model configuration or model call is needed.**

Standalone extraction of [the upstream sample](https://github.com/Azure-Samples/documentdb-samples/tree/f5a2675bbf349737234d0391e3ebee24b260e06f/ai/select-algorithm-python). See [UPSTREAM.md](UPSTREAM.md) for attribution, exact revision, changes, and maintenance policy.
All nine combinations of **IVF/HNSW/DiskANN × COS/L2/IP** use separate `<prefix>_<algorithm>_<metric-lowercase>` collections. The runner checks each real vector index, insert-only fixture loading, top-5 known fixture membership and an independent metric-specific ranking oracle. COS and IP maximize similarity/dot product; L2 minimizes squared distance. Raw scores are never compared across metrics; ties use a 1e-6 tolerance. This tiny fixture is a functional contract, **not a performance or semantic-relevance benchmark**. See [TESTED.md](TESTED.md) for proof boundaries and [UPSTREAM.md](UPSTREAM.md) for the pinned Microsoft source and downstream changes.

## Before you run
## Prerequisites and costs

Use **Python 3.11 (the upstream CI version)**, Git, and Azure CLI or another supported Azure Identity sign-in mechanism.
Use an existing, explicitly approved disposable Azure DocumentDB environment and an Azure OpenAI embedding deployment compatible with `text-embedding-3-small` and 1536-dimensional vectors.
Your identity needs appropriate model access and a registered DocumentDB database identity with permissions for the sample operations. Network access must be configured deliberately; signing in alone does not grant database access.
- Patched **Python 3.12** (tested on 3.12.13), Git, and network access to an approved disposable Azure DocumentDB cluster in public Azure.
- A tier/region supporting the requested algorithms. **S0 is not eligible for this full vector gate.** Do not infer DiskANN eligibility from successful authentication. Check current service requirements before provisioning; the sample neither deploys nor upgrades resources.
- Either native database SCRAM credentials, or an Azure CLI sign-in whose Entra principal has been registered/authorized in the database. Azure RBAC/sign-in alone does not grant data-plane access. For OIDC use `az login` outside the sample and verify the intended account/resource.
- Database calls and provisioned resources can incur charges even though embedding inference is absent. Use least-privilege database access and deliberate firewall rules. No China-cloud, arbitrary MongoDB endpoint, local insecure-TLS mode, deployment automation or production-use claim is included.

**These are cloud-mutating samples, not production services or read-only demos.** They can create/drop indexes, replace/drop collections, and invoke billable models. Some programs hardcode `Hotels` or collection names; an environment-variable change alone is not a universal isolation guarantee.
## 1. Install reproducibly

Upstream documentation differs on minimum DiskANN tiers and model/API versions. Confirm current service requirements for your selected region and tier; the shared provisioning template currently chooses M40. Do not infer live readiness from source code, saved output, or syntax/build CI.
POSIX shell, from the repository root:

## Setup
```sh
python3.12 -m venv .venv
.venv/bin/python -m pip install --require-hashes -r requirements.txt
```

PowerShell: use `py -3.12 -m venv .venv` and `.\.venv\Scripts\python.exe` in place of `.venv/bin/python`. Dependency locks include all transitive runtime dependencies and hashes; development/security dependencies are separately locked in `requirements-dev.txt`.

Commands below use PowerShell and run from this repository root. They are instructions for a separately approved run; no live run is claimed by this extraction.
## 2. Retrieve the pinned public fixture

```sh
.venv/bin/python src/fixture.py download
.venv/bin/python src/fixture.py extract
```

### 1. Retrieve the pinned sample data
These are explicit operations, not install side effects. The downloader accepts only the pinned public GitHub URL, validates SHA-256 and 50x1536 schema, has a 30-second network timeout/8 MiB bound, and rejects redirects. The extractor writes the first hotel's vector to `data/query-vector.json`. Both refuse to overwrite existing files or symlinks. If the fixture already exists, skip `download`; choose a new `--output` for repeated extraction. No environment or credentials are written. See [data/README.md](data/README.md) for dataset provenance/terms; a checksum is not a separate data-rights grant.

Follow [data/README.md](data/README.md). It provides explicit downloads, source links, and SHA-256 checks. No data download or model call happens automatically on clone or install.
## 3. Explicit configuration and authentication

### 2. Configure the sample
Only the **process environment** is read. `.env` is **not** loaded or executed automatically. `.env.example` documents placeholders; never commit credentials. Do not paste connection strings into tracked files, commands saved in shell history, CI, or reports. Supply `MONGO_CONNECTION_STRING` privately through your normal secret manager/process launcher.

Copy the placeholder-only example, then edit `.env` with your approved resource configuration. Do not commit `.env`.
Common settings (POSIX; in PowerShell use `$env:NAME='value'`):

```powershell
if (Test-Path -LiteralPath .env) { throw '.env already exists; edit it instead of overwriting it.' }
Copy-Item -LiteralPath .env.example -Destination .env
```sh
export MONGO_DATABASE=vectorsearch_disposable_my_run
export MONGO_COLLECTION_PREFIX=native
export DATA_FILE_WITH_VECTORS=data/Hotels_Vector.json
export QUERY_VECTOR_FILE=data/query-vector.json
export EMBEDDING_MODE=offline
export VECTOR_SEARCH_ALLOW_WRITES=true
```

After replacing every `<placeholder>`, import these plain `KEY=value` lines into this PowerShell process. Keep values unquoted and put comments on separate lines; this reads data without executing the file:
`MONGO_DATABASE` must begin exactly `vectorsearch_disposable`, optionally followed by `_lowercase_run_id`, maximum 63 characters. Prefixes are simple lowercase identifiers, maximum 40 characters. There are **no default destinations**. Use distinct `native` and `oidc` collection prefixes when checking both auth modes.

```powershell
Get-Content -LiteralPath .env | ForEach-Object {
$line = $_.Trim()
if ($line.Length -eq 0 -or $line.StartsWith('#')) { return }
if ($line -notmatch '^([A-Z][A-Z0-9_]*)=(.*)$') { throw 'Invalid .env line; expected KEY=value or a comment.' }
[Environment]::SetEnvironmentVariable($Matches[1], $Matches[2], 'Process')
}
### Native SCRAM

Set `MONGO_AUTH_MODE=connection-string` and privately inject `MONGO_CONNECTION_STRING`. Unset `MONGO_HOST` and `MONGO_OIDC_USERNAME`. The URI must be:

```text
mongodb+srv://<percent-encoded-user>:<percent-encoded-password>@<cluster>.global.mongocluster.cosmos.azure.com/?tls=true&retryWrites=false&authMechanism=SCRAM-SHA-256
```

The explicit import also covers samples that do not load dotenv files themselves. Node scripts and Go/Python dotenv helpers may additionally read the same repository-local `.env`.
Non-global `<cluster>.mongocluster.cosmos.azure.com` is also allowed. No port, database path, fragment, alternative host, duplicate option or unknown URI option is accepted. Allowed URI options are `tls/ssl=true`, `retryWrites=false`, `authSource=admin`, `authMechanism=SCRAM-SHA-256`, and the three TLS-bypass options **only when false**. Remove harmless portal telemetry options such as `appName` when preparing the secret URI. The driver forces verified TLS, SCRAM-SHA-256, admin auth source, bounded networking and disabled retryable writes.

For an interactive passwordless run, sign in to the intended Azure identity with `az login`; confirm the resource permissions and database identity independently.
### Entra OIDC

```sh
unset MONGO_CONNECTION_STRING
export MONGO_AUTH_MODE=oidc
export MONGO_HOST='<cluster>.global.mongocluster.cosmos.azure.com'
export MONGO_COLLECTION_PREFIX=oidc
# Optional, when required by the configured database principal:
# export MONGO_OIDC_USERNAME='<registered principal username>'
```

### 3. Install/build when you are ready
OIDC deliberately uses **AzureCliCredential**, not a broad automatic credential chain. CLI token acquisition is limited to 10 seconds; no fallback to native auth or another credential source is performed. The fixed audience is `https://ossrdbms-aad.database.windows.net/.default`, never an audience supplied by a server. The actual PyMongo 4.18 callback returns `OIDCCallbackResult(access_token=..., expires_in_seconds=...)` after rejecting empty/expired/near-expiry tokens. The Azure CLI owns its existing sign-in cache; the sample stores no credentials. Clients and credentials close on success, failure and cancellation.

```powershell
python -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements.txt
## 4. Run

```sh
.venv/bin/python src/compare_all.py
```

### 4. Run only against the approved disposable environment
Every CLI error exits nonzero. `compare_all.py` records all nine case outcomes; any failed/unsupported case makes the aggregate exit nonzero. JSON reports contain controlled status/count fields, never raw server exceptions, document contents, URIs or tokens. Errors with a server code retain that numeric code, not sensitive error text. Global connection/input failures end before any cases. Ctrl-C/SIGTERM cancels and closes clients; data already inserted is preserved.

Timeout controls: `VECTOR_SEARCH_TIMEOUT_SECONDS` defaults to 600 (1–1800); `VECTOR_SEARCH_CASE_TIMEOUT_SECONDS` defaults to 120 (1–300). PyMongo client-side operation deadlines and bounded connect/select/socket waits are enabled. Only successful **empty** searches are retried while index visibility catches up. Authentication, tier, schema and ranking errors are never silently retried or downgraded to success.

### Write-safety and reruns

- Every write needs `VECTOR_SEARCH_ALLOW_WRITES=true` and the disposable namespace. Invalid inputs/destinations are rejected **before credential construction or network access**.
- Each case validates the **entire index catalog document before any mutation**, even if its collection is populated. Incompatible kind, dimensions, metric, algorithm parameters, partial/sparse/unique/hidden/TTL/collation or unknown semantics fail closed. No existing index is dropped or modified. Missing indexes are created and read back.
- Seed IDs are existing string `_id` values or deterministic `vectorsearch:<HotelId>`. Ordered `$setOnInsert` upserts only add missing IDs. Existing edits and unrelated records remain untouched. All input is validated before any writes; failures/partial batch acknowledgements are not swallowed. Retrying an interrupted run is insert-only and idempotent.
- Preserved edits/unrelated vectors can legitimately fail the known-fixture quality gate. Use a fresh approved collection prefix; **the sample will not delete or overwrite data to manufacture a pass**. Concurrent DDL/edits by another operator are outside this small sample's isolation guarantees.
- There are no reset/drop/DeleteMany commands or automatic cleanup. Inspect retained sample data and have the authorized resource owner delete only the intended disposable database/resource afterward. Billing continues until resources are stopped/deleted as appropriate.

```powershell
.\.venv\Scripts\python.exe .\src\compare_all.py
## Offline tests, security checks, and explicit real gate

```sh
.venv/bin/python -m pip install --require-hashes -r requirements-dev.txt
.venv/bin/python -m compileall -q src tests tests_live
.venv/bin/python -m pytest -q
.venv/bin/python -m pip_audit -r requirements-dev.txt --no-deps --disable-pip --vulnerability-service osv
```

This compares search behavior on a small fixture, not production-scale performance. All nine combinations are attempted; use a tier supporting all three algorithms. Precomputed document vectors do not eliminate the live query-embedding call.
Default tests are no-network failure-injection contracts, not fake Azure readiness. CI uses SHA-pinned actions, read-only permissions, exact Python 3.12.13, hash-locked installs, compile/tests and current advisory scanning; no Azure secrets/deployments.

After separately authorizing an eligible cluster and configuring it above:

## Shared provisioning
```sh
export VECTOR_SEARCH_LIVE_TEST=1
.venv/bin/python src/compare_all.py --live-check
.venv/bin/python -m pytest tests_live -q
```

Provisioning remains [upstream](https://github.com/Azure-Samples/documentdb-samples/tree/f5a2675bbf349737234d0391e3ebee24b260e06f/infra), not duplicated here. If you choose azd, use a separate checkout of the [upstream repository root](https://github.com/Azure-Samples/documentdb-samples/blob/f5a2675bbf349737234d0391e3ebee24b260e06f/README.md), not this sample directory.
Review and harden its broad firewall/admin defaults and fallback administrator password before any deployment. No infrastructure, cloud credentials, GitHub Actions workflows, or automatic deployments are included in this extraction.
The explicit gate **fails**, rather than skipping, if live opt-in is absent. It requires the checksum-pinned 50-record fixture and first-record self query, runs each case twice, checks top 5/exact metric ranking/self-match, and checks second-run zero inserts/all 50 existing. Repeat under **both auth modes with separate prefixes**. It never drops its data. A blocked tier/network/credential is a failed/unverified gate, not a mock pass.

## Maintenance and license
## Scope, maintenance and license

This is a standalone downstream snapshot, not a GitHub fork of the complete monorepo. Upstream fixes must be reviewed and ported manually; update the recorded revision in [UPSTREAM.md](UPSTREAM.md) when doing so.
Dependencies and sample algorithms are retained from the pinned source. Static extraction checks do not certify dependency compatibility, authentication, deployment, or model behavior.
The broken optional live embedding generator and index-inspection legacy entry points were removed, not left as an untested side path. Precomputed vectors are the only supported embedding mode. Supply a compatible JSON vector via `QUERY_VECTOR_FILE`; this repo does not generate embeddings. Missing OpenAI configuration is irrelevant.

Sample code is Copyright (c) Microsoft Corporation, under the preserved [MIT license](LICENSE.md). Dataset source/terms remain linked in the data guide.
Original Microsoft sample code/notice is preserved under [MIT](LICENSE.md). This is an independently maintained downstream snapshot, not an automatically synchronized fork. Review and port upstream fixes manually and record changes in [UPSTREAM.md](UPSTREAM.md). A passing small-fixture gate does not certify production scale, availability, custom datasets, model relevance or every service tier.
Loading
Loading