diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..295f5ee --- /dev/null +++ b/.dockerignore @@ -0,0 +1,16 @@ +.git +.venv +venv +.mimir +**/__pycache__ +**/*.pyc +**/*.egg-info +dist +build +client +backstage-plugin +docs +tests +.github +.claude +.DS_Store diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 48b2461..b7b0142 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,21 +6,28 @@ on: push: branches: [main, develop] +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + jobs: test: - name: Tests + name: Tests (Python ${{ matrix.python-version }}) runs-on: ubuntu-latest strategy: + fail-fast: false matrix: python-version: ["3.11", "3.12", "3.13"] steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 + - uses: actions/checkout@v7 - - uses: actions/setup-python@v5 + - uses: actions/setup-python@v7 with: python-version: ${{ matrix.python-version }} + cache: pip - name: Install dependencies run: pip install -e ".[dev]" @@ -28,50 +35,27 @@ jobs: - name: Run tests run: pytest --tb=short -q - guardrails: - name: Architectural Guardrails + build: + name: Build verification runs-on: ubuntu-latest - if: github.event_name == 'pull_request' - permissions: - contents: read - pull-requests: write steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 with: - fetch-depth: 0 + fetch-depth: 0 # setuptools-scm derives the version from git tags - - uses: actions/setup-python@v5 + - uses: actions/setup-python@v7 with: python-version: "3.13" - - name: Install Mimir - run: pip install -e . + - name: Install build tools + run: pip install build twine - - name: Build code graph - run: mimir index + - name: Build server package + run: python -m build --outdir dist/ - - name: Run guardrail check - id: guardrails - run: | - EXIT_CODE=0 - git diff origin/${{ github.base_ref }}...${{ github.event.pull_request.head.sha }} | \ - mimir guardrail check --diff - \ - --rules mimir-rules.yaml \ - --base origin/${{ github.base_ref }} \ - --head ${{ github.event.pull_request.head.sha }} \ - --output github-pr-comment \ - --report-file guardrail-report.md \ - || EXIT_CODE=$? - echo "exit_code=$EXIT_CODE" >> $GITHUB_ENV - cat guardrail-report.md >> $GITHUB_STEP_SUMMARY - - - name: Comment on PR - if: always() && hashFiles('guardrail-report.md') != '' - uses: marocchino/sticky-pull-request-comment@v2 - with: - header: mimir-guardrails - path: guardrail-report.md + - name: Build client package + run: python -m build --outdir dist/ + working-directory: client - - name: Fail if violations - if: env.exit_code != '0' - run: exit 1 + - name: Check package metadata + run: twine check --strict dist/* client/dist/* diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index bb81d6a..031301c 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -6,24 +6,41 @@ on: - "v*" permissions: - contents: write - id-token: write + contents: read jobs: + test: + name: Tests + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + + - uses: actions/setup-python@v7 + with: + python-version: "3.13" + cache: pip + + - name: Install dependencies + run: pip install -e ".[dev]" + + - name: Run tests + run: pytest --tb=short -q + build: name: Build packages + needs: test runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 with: fetch-depth: 0 - - uses: actions/setup-python@v5 + - uses: actions/setup-python@v7 with: python-version: "3.13" - name: Install build tools - run: pip install build + run: pip install build twine - name: Build server package run: python -m build --outdir dist/ @@ -32,8 +49,11 @@ jobs: run: python -m build --outdir dist/ working-directory: client + - name: Check package metadata + run: twine check --strict dist/* client/dist/* + - name: Upload artifacts - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v7 with: name: dist path: | @@ -42,13 +62,15 @@ jobs: github-release: name: Create GitHub Release - needs: build + needs: [publish-server, publish-client] runs-on: ubuntu-latest + permissions: + contents: write steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 - name: Download artifacts - uses: actions/download-artifact@v4 + uses: actions/download-artifact@v8 with: name: dist path: artifacts @@ -63,7 +85,7 @@ jobs: run: echo "version=${GITHUB_REF_NAME#v}" >> "$GITHUB_OUTPUT" - name: Create GitHub Release - uses: softprops/action-gh-release@v2 + uses: softprops/action-gh-release@v3 with: tag_name: ${{ github.ref_name }} name: Mimir ${{ steps.version.outputs.version }} @@ -79,7 +101,7 @@ jobs: id-token: write steps: - name: Download artifacts - uses: actions/download-artifact@v4 + uses: actions/download-artifact@v8 with: name: dist path: artifacts @@ -101,7 +123,7 @@ jobs: id-token: write steps: - name: Download artifacts - uses: actions/download-artifact@v4 + uses: actions/download-artifact@v8 with: name: dist path: artifacts diff --git a/CLAUDE.md b/CLAUDE.md index 9ed9f04..2f1b5c3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -15,14 +15,18 @@ pip install -e ".[dev]" # Run tests (the venv lives at ./.venv — activate it or call it directly) .venv/bin/pytest # or: source .venv/bin/activate && pytest +.venv/bin/pytest tests/test_guardrail_service.py -k test_name # Single test/module + +# No linter or formatter is configured (no ruff/black/mypy). Tests are the only gate. +# pytest runs in asyncio_mode = "auto" — async tests need no @pytest.mark.asyncio. # CLI usage mimir init # Create mimir.toml config -mimir index # Build/update semantic code graph -mimir search "query" # Search and assemble context -mimir serve # Start MCP server (stdio) -mimir serve --http # Start shared HTTP server (port 8421) -mimir quality # Analyze graph connectivity gaps +mimir indexer run # Build and publish an index version +mimir query search "query" # Search the active published index +mimir query serve # Start MCP server (stdio) +mimir query serve --http # Start shared HTTP server (port 8421) +mimir query status # Show the active index version and graph counts # Guardrails mimir guardrail init # Generate example rules + agent policy @@ -48,10 +52,10 @@ Mimir-Approved-Reason: legal signoff ticket #4821 Workflow: -1. CI fails on a BLOCK violation. PR comment lists the failing rule ids. +1. `mimir guardrail check` (local run or pre-commit hook) fails on a BLOCK violation and lists the failing rule ids. 2. Someone runs `mimir guardrail approve --reason "..."` on the PR branch. This creates an empty commit with the trailer. -3. Push. CI re-runs, reads HEAD trailers, clears the matching BLOCKs. +3. Re-run the check; it reads HEAD trailers and clears the matching BLOCKs. (Repo CI does not run guardrails.) 4. Any subsequent commit without the trailer invalidates the approval because HEAD has moved. No `revoke` command is needed. @@ -73,18 +77,18 @@ Services (business logic: indexing, retrieval, temporal, quality, intent, sessio ↓ Domain (core models: CodeGraph, Node, Edge, Config, Session — all frozen dataclasses/enums) ↓ -Ports (protocol interfaces: Parser, Embedder, VectorStore, GraphStore, SessionStore, LLMClient) +Ports (protocol interfaces: Parser, Embedder, VectorStore, GraphStore, SessionStore) ↓ -Infra (concrete implementations: tree-sitter, sentence-transformers/jina, SQLite, ChromaDB, LiteLLM) +Infra (concrete implementations: tree-sitter, ONNX Runtime embeddings (local) / Jina API, SQLite, in-memory NumPy vector index) ``` ### Key Layers - **`mimir/domain/`** — Immutable core: `models.py` (NodeKind/EdgeKind enums, Node/Edge), `graph.py` (NetworkX-backed CodeGraph), `config.py` (TOML-mapped dataclasses), `guardrails.py` (Rule/Violation/ChangeSet/GuardrailResult) - **`mimir/ports/`** — Protocol interfaces for dependency injection boundaries -- **`mimir/services/`** — All business logic. Heaviest files: `indexing.py` (parse→graph→embed pipeline), `retrieval.py` (query→seed→expand→rank→budget-fit), `guardrail.py` (rule evaluation engine), `diff_analyzer.py` (git diff→ChangeSet), `agent_policy.py` (bounded autonomy) -- **`mimir/infra/`** — Pluggable implementations: `parsers/tree_sitter.py`, `embedders/local.py`+`jina.py`, `stores/sqlite_graph.py`, `vector_stores/numpy_store.py`+`chroma.py` -- **`mimir/adapters/`** — External interfaces: `cli.py` (Typer entry point), `mcp_server.py` (MCP stdio), `http_server.py` (REST API) +- **`mimir/services/`** — All business logic (19 modules). Core pipeline: `indexing.py` (parse→graph→embed), `retrieval.py` (query→seed→expand→rank→budget-fit), `summarizer.py`, `graph_linker.py` (cross-file reference resolution). Ranking signals: `intent.py` (query classification), `quality.py`, `temporal.py`. Guardrails: `guardrail.py` (rule engine), `guardrail_report.py`, `guardrail_trailers.py` (approval trailers), `diff_analyzer.py` (git diff→ChangeSet), `agent_policy.py` (bounded autonomy). Also `impact.py` (blast-radius reverse-tracing), `session.py` (dedup w/ exponential decay), `write_context.py` (write-path bundles), `catalog.py` (Backstage), `watcher.py` (live re-index) +- **`mimir/infra/`** — Pluggable implementations: `parsers/tree_sitter.py`, `embedders/local.py`+`jina.py`, `stores/sqlite_graph.py`+`sqlite_session.py`, `vector_stores/numpy_store.py` (in-memory, rebuilt from `graph.db` embeddings on startup) +- **`mimir/adapters/`** — External interfaces: `cli.py` (Typer entry point) + `cli_support/`, `mcp_server.py` (MCP stdio), `remote_mcp.py` (proxy to remote server), `http_server.py` (REST API), `web/server.py` (Web Inspector UI), plus `ci/` (GitHub Action) and `hooks/` (pre-commit) integration assets - **`mimir/container.py`** — Wires all layers together via DI ### Retrieval Pipeline @@ -95,9 +99,15 @@ Infra (concrete implementations: tree-sitter, sentence-transformers/jina, SQLite 1. Tree-sitter parse → 2. Build node/edge graph → 3. Cross-file reference resolution → 4. Heuristic summarization → 5. Embedding → 6. Persist to SQLite + vector store. Supports incremental indexing via git diff. +## CI + +`.github/workflows/ci.yml` runs on PRs and pushes to `main`/`develop` and does only two things: `pytest --tb=short -q` on Python 3.11/3.12/3.13, and build verification (`python -m build` for the server and `client/` packages + `twine check --strict`). Guardrail checks are not run in CI; use `mimir guardrail check` locally or via the pre-commit hook. + +`.github/workflows/publish.yml` releases on `v*` tag pushes only: tests → build → publish both packages to PyPI (trusted publishing, `pypi` environment) → GitHub Release with the dists attached. Versions come from the git tag via setuptools-scm. + ## Configuration -Primary config: `mimir.toml` (TOML). Key sections: `[[repos]]`, `[indexing]`, `[embeddings]`, `[retrieval]`, `[temporal]`, `[session]`, `[vector_db]`, `[llm]`. +Primary config: `mimir.toml` (TOML). Key sections: `[[repos]]`, `[indexing]`, `[embeddings]`, `[retrieval]`, `[temporal]`, `[session]`, `[watcher]`. `mimir.toml` indexes the Mimir source itself (used for both development and CI). @@ -108,9 +118,9 @@ Guardrails config: `mimir-rules.yaml` (architectural rules) and `mimir-agent-pol Default location: `.mimir/`, split into two subfolders: - **`.mimir/project/`** — tracked in git. Contains `graph.db` (the code graph). Committing this lets CI skip re-indexing and lets new developers get a working context engine on clone. -- **`.mimir/session/`** — ignored by git. Contains `sessions.db` (session state), `models/` (downloaded embedding weights), `chroma/` (derived vector store). Anything personal or re-derivable lives here. +- **`.mimir/session/`** — ignored by git. Contains `sessions.db` (session state), `models/` (downloaded ONNX embedding models). Anything personal or re-derivable lives here. -Run `mimir index` and commit `.mimir/project/graph.db` after significant code changes. +Run `mimir indexer run` and commit `.mimir/project/graph.db` after significant code changes. ## Docker diff --git a/Dockerfile b/Dockerfile index 7a07ae1..bc23f64 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,8 +1,10 @@ -FROM python:3.11-slim +# syntax=docker/dockerfile:1 +FROM python:3.13-slim -# Install system dependencies: git for repo operations, build-essential for native extensions +# git for repo operations (indexing, temporal signals, diffs). Every Python +# dependency ships wheels, so no compiler toolchain is needed. RUN apt-get update && \ - apt-get install -y --no-install-recommends git build-essential && \ + apt-get install -y --no-install-recommends git && \ rm -rf /var/lib/apt/lists/* # Fix for "dubious ownership" error in mounted volumes @@ -10,22 +12,29 @@ RUN git config --global --add safe.directory '*' WORKDIR /app -# Upgrade pip -RUN pip install --no-cache-dir --upgrade pip +ENV PIP_DISABLE_PIP_VERSION_CHECK=1 -# Copy project metadata and source code +# Third-party dependencies only, read from pyproject.toml. This layer (and the +# model download below) is reused across source-code changes. COPY pyproject.toml ./ -COPY mimir/ ./mimir/ +RUN --mount=type=cache,target=/root/.cache/pip \ + python -c "import tomllib; print('\n'.join(tomllib.load(open('pyproject.toml','rb'))['project']['dependencies']))" > /tmp/requirements.txt && \ + pip install -r /tmp/requirements.txt -# Install application and all dependencies -RUN pip install --no-cache-dir . +# Pre-download the standard embedding model (ONNX export) so the container +# runs 100% offline. File list matches _MODEL_FILES in mimir/infra/embedders/local.py. +RUN python -c "from huggingface_hub import snapshot_download; snapshot_download('sentence-transformers/all-mpnet-base-v2', allow_patterns=['onnx/model.onnx', 'onnx/model.onnx_data', 'tokenizer.json', 'config.json', 'modules.json', 'sentence_bert_config.json', '1_Pooling/config.json'])" -# Pre-download the standard embedding model -# This caches model weights into the Docker layer so the container runs 100% offline -RUN python -c "from sentence_transformers import SentenceTransformer; SentenceTransformer('all-mpnet-base-v2')" +# The build context has no .git, so setuptools-scm cannot derive the version. +# Pass it explicitly: docker build --build-arg MIMIR_VERSION=1.2.0 . +ARG MIMIR_VERSION=0.0.0 +ENV SETUPTOOLS_SCM_PRETEND_VERSION_FOR_MIMIR_CONTEXT_SERVER=${MIMIR_VERSION} -# Remove build tools to shrink final image -RUN apt-get purge -y build-essential && apt-get autoremove -y && rm -rf /var/lib/apt/lists/* +# Application code last — only this layer rebuilds on a code change +COPY README.md ./ +COPY mimir/ ./mimir/ +RUN --mount=type=cache,target=/root/.cache/pip \ + pip install --no-deps . # Offline hugging face mode ENV HF_HUB_OFFLINE=1 diff --git a/client/pyproject.toml b/client/pyproject.toml index dafe512..77e63bb 100644 --- a/client/pyproject.toml +++ b/client/pyproject.toml @@ -1,5 +1,5 @@ [build-system] -requires = ["setuptools>=68.0", "wheel>=0.46", "setuptools-scm>=8"] +requires = ["setuptools>=84.0", "wheel>=0.48", "setuptools-scm>=10.3"] build-backend = "setuptools.build_meta" [project] @@ -8,13 +8,12 @@ dynamic = ["version"] description = "Lightweight MCP proxy client for remote Mimir context servers — no repos, no models, no indexing needed" readme = "README.md" requires-python = ">=3.10" -license = {text = "MIT"} +license = "MIT" keywords = ["mcp", "context", "code", "llm", "proxy", "mimir"] classifiers = [ "Development Status :: 4 - Beta", "Environment :: Console", "Intended Audience :: Developers", - "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", @@ -25,8 +24,8 @@ classifiers = [ ] dependencies = [ - "aiohttp>=3.9", - "typer>=0.9", + "aiohttp>=3.14.3", + "typer>=0.27.2", ] [project.urls] diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh index 4be35f5..029e5bb 100755 --- a/docker-entrypoint.sh +++ b/docker-entrypoint.sh @@ -12,14 +12,14 @@ fi # Also triggered by "serve" with AUTO_INDEX=1 if [ "$1" = "auto" ] || [ "${AUTO_INDEX:-0}" = "1" ]; then echo "==> Indexing repositories from ${CONFIG} ..." - mimir index --config "$CONFIG" || { + mimir indexer run --config "$CONFIG" || { echo "WARNING: Indexing failed, starting server with whatever data exists" } fi # Start HTTP server echo "==> Starting Mimir HTTP server on ${MIMIR_HOST:-0.0.0.0}:${MIMIR_PORT:-8421}" -exec mimir serve \ +exec mimir query serve \ --http \ --http-host "${MIMIR_HOST:-0.0.0.0}" \ --http-port "${MIMIR_PORT:-8421}" \ diff --git a/docs/architecture.md b/docs/architecture.md index 9f19e55..73efa0a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -15,9 +15,9 @@ Services (business logic: indexing, retrieval, temporal, quality, intent, sessio ↓ Domain (core models: CodeGraph, Node, Edge, Config, Session — all frozen dataclasses/enums) ↓ -Ports (protocol interfaces: Parser, Embedder, VectorStore, GraphStore, SessionStore, LLMClient) +Ports (protocol interfaces: Parser, Embedder, VectorStore, GraphStore, SessionStore) ↓ -Infra (concrete implementations: tree-sitter, sentence-transformers/jina, SQLite, ChromaDB, LiteLLM) +Infra (concrete implementations: tree-sitter, ONNX Runtime embeddings (local) / Jina API, SQLite, in-memory NumPy vector index) ``` ## Project Structure @@ -27,7 +27,7 @@ Infra (concrete implementations: tree-sitter, sentence-transformers/jina, SQLite │ ├── domain/ # Core models, config, graph, catalog, guardrails, errors │ ├── ports/ # Interface definitions (embedder, parser, stores) │ ├── services/ # Business logic (indexing, retrieval, catalog, impact, guardrail, temporal, session, quality) -│ ├── infra/ # Implementations (tree-sitter, embedders, SQLite, ChromaDB) +│ ├── infra/ # Implementations (tree-sitter, embedders, SQLite, NumPy vector index) │ ├── adapters/ # External interfaces (CLI, MCP, HTTP, web UI) │ ├── runtime.py # IndexerRuntime and QueryRuntime composition │ └── container.py # Legacy local composition path @@ -62,7 +62,6 @@ Mimir stores all index data in a local directory (default `.mimir/`, configurabl ├── sessions.db # SQLite: session state for deduplication ├── feedback.db # retrieval feedback signals ├── models/ # downloaded embedding weights - ├── chroma/ # ChromaDB data (only if backend = "chroma") └── guardrail_audit.jsonl # Guardrail check audit log (if enabled) ``` diff --git a/docs/configuration.md b/docs/configuration.md index 4299c3f..3a732b5 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -25,9 +25,6 @@ concurrency = 10 model = "all-mpnet-base-v2" # local, offline, no API keys needed batch_size = 64 -[vector_db] -backend = "numpy" # numpy (in-process) | chroma (persistent) - [retrieval] default_beam_width = 3 default_token_budget = 8000 @@ -53,8 +50,7 @@ topic_tracking_alpha = 0.3 | `indexing` | `summary_mode` | `heuristic` | `none` = raw code only; `heuristic` = signatures, docstrings, and dependency info | | `indexing` | `max_file_size_kb` | `500` | Skip files larger than this | | `indexing` | `concurrency` | `10` | Parallel file parsing limit | -| `embeddings` | `model` | `jina-embeddings-v2-base-code` | Any sentence-transformers model or Jina API model | -| `vector_db` | `backend` | `numpy` | `numpy` for dev/small projects; `chroma` for persistent production use | +| `embeddings` | `model` | `jina-embeddings-v2-base-code` | Any sentence-transformers or Jina model that ships an ONNX export (run locally), or `api:` for the Jina API | | `retrieval` | `default_token_budget` | `8000` | Maximum tokens per context bundle | | `retrieval` | `expansion_hops` | `2` | How many graph hops to expand from seed nodes | | `retrieval` | `hybrid_alpha` | `0.7` | Weight between semantic (1.0) and BM25 keyword (0.0) search | diff --git a/docs/web-inspector.md b/docs/web-inspector.md index 07f7d78..eff9597 100644 --- a/docs/web-inspector.md +++ b/docs/web-inspector.md @@ -5,8 +5,8 @@ Mimir includes a browser-based graph visualization UI: ```bash -mimir ui # launches at http://localhost:8420 -mimir ui --port 9000 # custom port +mimir query ui # launches at http://localhost:8420 +mimir query ui --port 9000 # custom port ``` Explore nodes by kind and repo, inspect edges, view cross-repo links, and drill into individual symbols. diff --git a/mimir.toml b/mimir.toml index 71983bc..11f7de1 100644 --- a/mimir.toml +++ b/mimir.toml @@ -20,9 +20,6 @@ max_file_size_kb = 500 model = "all-mpnet-base-v2" batch_size = 64 -[vector_db] -backend = "chroma" - [retrieval] default_beam_width = 3 default_token_budget = 8000 diff --git a/mimir/adapters/cli_support/app.py b/mimir/adapters/cli_support/app.py index f98792a..53ada5c 100644 --- a/mimir/adapters/cli_support/app.py +++ b/mimir/adapters/cli_support/app.py @@ -49,9 +49,6 @@ def init( [embeddings] model = "local:all-MiniLM-L6-v2" -[vector_db] -backend = "chroma" - [retrieval] default_beam_width = 3 default_token_budget = 8000 diff --git a/mimir/container.py b/mimir/container.py index 3c6b385..4a7b9f0 100644 --- a/mimir/container.py +++ b/mimir/container.py @@ -9,7 +9,7 @@ import logging from typing import Optional -from mimir.domain.config import MimirConfig, VectorBackend +from mimir.domain.config import MimirConfig logger = logging.getLogger(__name__) @@ -50,9 +50,6 @@ def __init__(self, config: MimirConfig) -> None: smoothing=config.feedback.score_smoothing, ) - # LLM client (used by the `ask` CLI command for interactive Q&A) - self.llm_client = self._build_llm_client() - # Services ------------------------------------------------------ from mimir.services.indexing import IndexingService @@ -133,14 +130,14 @@ def _build_embedder(self): ) except Exception as exc: logger.warning("Jina API embedder init failed (%s), falling back to local", exc) - # Default: run locally via sentence-transformers + # Default: run locally via ONNX Runtime from mimir.infra.embedders.local import LocalEmbedder model_name = model.removeprefix("local:") if model.startswith("local:") else model cache_dir = self.config.embeddings.cache_dir or str(self.config.session_dir / "models") logger.info("Using local embedder: %s (cache: %s)", model_name, cache_dir) return LocalEmbedder(model_name=model_name, cache_dir=cache_dir) else: - # Default: run locally via sentence-transformers + # Default: run locally via ONNX Runtime from mimir.infra.embedders.local import LocalEmbedder model_name = model.removeprefix("local:") if model.startswith("local:") else model cache_dir = self.config.embeddings.cache_dir or str(self.config.session_dir / "models") @@ -148,24 +145,8 @@ def _build_embedder(self): return LocalEmbedder(model_name=model_name, cache_dir=cache_dir) def _build_vector_store(self): - backend = self.config.vector_db.backend - if backend is VectorBackend.CHROMA: - from mimir.infra.vector_stores.chroma import ChromaVectorStore - return ChromaVectorStore( - persist_directory=self.config.vector_db.persist_directory - or str(self.config.session_dir / "chroma"), - ) - else: - from mimir.infra.vector_stores.numpy_store import NumpyVectorStore - return NumpyVectorStore() - - def _build_llm_client(self): - from mimir.infra.llm.litellm_client import LiteLlmClient - return LiteLlmClient( - model=self.config.llm.model, - max_concurrent=self.config.indexing.concurrency, - api_base=self.config.llm.api_base, - ) + from mimir.infra.vector_stores.numpy_store import NumpyVectorStore + return NumpyVectorStore() def load_graph(self, *, force_reload: bool = False): """Load the persisted graph and hydrate the vector store.""" @@ -205,9 +186,6 @@ def clear_data(self, *, graph: bool = True, sessions: bool = True) -> dict: self._graph = None # invalidate in-memory cache cleared.append("graph") - # Reset the vector store through its live client so file handles stay valid. - # We must NOT use shutil.rmtree() here while the store's SQLite client is open, - # because deleting chroma files under an active handle puts SQLite into readonly mode. self.vector_store.reset() cleared.append("vector_store") diff --git a/mimir/domain/config.py b/mimir/domain/config.py index 5e37988..6bee28b 100644 --- a/mimir/domain/config.py +++ b/mimir/domain/config.py @@ -25,14 +25,6 @@ class SummaryMode(str, Enum): HEURISTIC = "heuristic" -@unique -class VectorBackend(str, Enum): - """Supported vector-store backends.""" - - CHROMA = "chroma" - NUMPY = "numpy" - - # --------------------------------------------------------------------------- # Sub-configs # --------------------------------------------------------------------------- @@ -102,13 +94,6 @@ def __post_init__(self) -> None: raise ConfigError("concurrency must be positive") -@dataclass(frozen=True) -class LlmConfig: - model: str = "claude-haiku-4-5-20251001" - api_key_env: Optional[str] = None - api_base: Optional[str] = None - - @dataclass(frozen=True) class EmbeddingConfig: model: str = "jina-embeddings-v2-base-code" @@ -124,19 +109,6 @@ def __post_init__(self) -> None: raise ConfigError("embedding max_concurrent_batches must be >= 1") -@dataclass(frozen=True) -class VectorDbConfig: - backend: VectorBackend = VectorBackend.CHROMA - persist_directory: Optional[str] = None - - def __post_init__(self) -> None: - if not isinstance(self.backend, VectorBackend): - try: - object.__setattr__(self, "backend", VectorBackend(self.backend)) - except ValueError as exc: - raise ConfigError(f"Invalid vector_db.backend: {self.backend!r}") from exc - - @dataclass(frozen=True) class RetrievalConfig: default_beam_width: int = 3 @@ -214,9 +186,7 @@ class MimirConfig: cross_repo: CrossRepoConfig = field(default_factory=CrossRepoConfig) indexing: IndexingConfig = field(default_factory=IndexingConfig) - llm: LlmConfig = field(default_factory=LlmConfig) embeddings: EmbeddingConfig = field(default_factory=EmbeddingConfig) - vector_db: VectorDbConfig = field(default_factory=VectorDbConfig) retrieval: RetrievalConfig = field(default_factory=RetrievalConfig) temporal: TemporalConfig = field(default_factory=TemporalConfig) session: SessionConfig = field(default_factory=SessionConfig) @@ -235,7 +205,7 @@ def __post_init__(self) -> None: # Layout: .mimir/ is split into two subfolders # project/ — shared data tracked in git (graph.db) # session/ — personal / derived data ignored by git - # (sessions.db, embedding model cache, chroma store) + # (sessions.db, embedding model cache) # ------------------------------------------------------------------ @property @@ -251,13 +221,13 @@ def session_dir(self) -> Path: @classmethod def load(cls, path: Path) -> MimirConfig: """Parse a ``mimir.toml`` file into a validated config.""" - import tomli + import tomllib if not path.is_file(): raise ConfigError(f"Config file not found: {path}") with open(path, "rb") as f: - raw = tomli.load(f) + raw = tomllib.load(f) try: repos = [ @@ -277,13 +247,6 @@ def load(cls, path: Path) -> MimirConfig: # Resolve relative paths in sub-configs against config file dir config_dir = path.parent - vector_db = _parse_section(VectorDbConfig, raw.get("vector_db", {})) - if vector_db.persist_directory and not Path(vector_db.persist_directory).is_absolute(): - object.__setattr__( - vector_db, "persist_directory", - str(config_dir.joinpath(vector_db.persist_directory).resolve()), - ) - embeddings = _parse_section(EmbeddingConfig, raw.get("embeddings", {})) if embeddings.cache_dir and not Path(embeddings.cache_dir).is_absolute(): object.__setattr__( @@ -303,9 +266,7 @@ def load(cls, path: Path) -> MimirConfig: data_dir=data_dir, cross_repo=_parse_section(CrossRepoConfig, raw.get("cross_repo", {})), indexing=_parse_section(IndexingConfig, raw.get("indexing", {})), - llm=_parse_section(LlmConfig, raw.get("llm", {})), embeddings=embeddings, - vector_db=vector_db, retrieval=_parse_section(RetrievalConfig, raw.get("retrieval", {})), temporal=_parse_section(TemporalConfig, raw.get("temporal", {})), session=_parse_section(SessionConfig, raw.get("session", {})), diff --git a/mimir/domain/errors.py b/mimir/domain/errors.py index d244968..08ab5b6 100644 --- a/mimir/domain/errors.py +++ b/mimir/domain/errors.py @@ -2,7 +2,7 @@ Every infrastructure adapter catches library-specific exceptions and re-raises as the appropriate Mimir error with context. The application layer never sees -``chromadb.errors.*`` or ``sqlite3.OperationalError``. +``sqlite3.OperationalError`` or library-specific errors. """ from __future__ import annotations @@ -33,7 +33,7 @@ class EmbeddingError(IndexingError): class StorageError(MimirError): - """Database read/write failure (SQLite, ChromaDB, etc.).""" + """Database read/write failure (SQLite, etc.).""" class RetrievalError(MimirError): diff --git a/mimir/domain/workspace.py b/mimir/domain/workspace.py index 751d5a9..e94a63f 100644 --- a/mimir/domain/workspace.py +++ b/mimir/domain/workspace.py @@ -32,9 +32,9 @@ def _load_raw(self) -> dict: """Load and return the raw TOML dict, or an empty dict if not found.""" if not self._path.exists(): return {} - import tomli + import tomllib with open(self._path, "rb") as f: - return tomli.load(f) + return tomllib.load(f) def list(self) -> dict[str, Path]: """Return all registered workspaces as {name: config_path}.""" diff --git a/mimir/infra/embedders/local.py b/mimir/infra/embedders/local.py index e54da6d..a44aaaa 100644 --- a/mimir/infra/embedders/local.py +++ b/mimir/infra/embedders/local.py @@ -1,84 +1,180 @@ -"""Local embedder using sentence-transformers (zero-cost, offline).""" +"""Local embedder running sentence-transformers models via ONNX Runtime (zero-cost, offline). + +Loads the ONNX export that sentence-transformers model repos ship under +``onnx/model.onnx`` and reproduces the sentence-transformers pipeline +(tokenize → transformer → pooling → optional normalize) from the repo's own +``modules.json`` / ``1_Pooling/config.json``. No torch required. +""" from __future__ import annotations import asyncio +import json import logging import os +from pathlib import Path from typing import Optional +import numpy as np + from mimir.domain.errors import EmbeddingError logger = logging.getLogger(__name__) os.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1") os.environ.setdefault("TOKENIZERS_PARALLELISM", "false") -os.environ.setdefault("TRANSFORMERS_VERBOSITY", "error") -# HF_HUB_OFFLINE is set dynamically in _ensure_model after first download -for _noisy in ( - "sentence_transformers", - "sentence_transformers.models.transformer", - "huggingface_hub", - "huggingface_hub.utils._http", - "transformers", - "transformers.utils.loading_report", - "httpx", -): +for _noisy in ("huggingface_hub", "huggingface_hub.utils._http", "httpx"): logging.getLogger(_noisy).setLevel(logging.ERROR) +_MODEL_FILES = [ + "onnx/model.onnx", + "onnx/model.onnx_data", + "tokenizer.json", + "config.json", + "modules.json", + "sentence_bert_config.json", + "1_Pooling/config.json", +] + +# Texts per ONNX forward pass. Texts are length-sorted first so each chunk +# pads to a similar length. +_CHUNK_SIZE = 32 + + +def _repo_id(model_name: str) -> str: + """Map short names (``all-MiniLM-L6-v2``, ``jina-embeddings-v2-base-code``) to repo ids.""" + if "/" in model_name: + return model_name + owner = "jinaai" if model_name.startswith("jina-") else "sentence-transformers" + return f"{owner}/{model_name}" + class LocalEmbedder: - """Embedder backed by sentence-transformers, runs fully offline. + """Embedder for sentence-transformers models, runs fully offline on CPU. - Default model: ``all-MiniLM-L6-v2`` (384 dimensions, ~80MB). + Default model: ``all-MiniLM-L6-v2`` (384 dimensions, ~90MB). """ def __init__(self, model_name: str = "all-MiniLM-L6-v2", cache_dir: Optional[str] = None) -> None: self._model_name = model_name self._cache_dir = cache_dir - self._model: Optional[object] = None + self._session = None + self._tokenizer = None + self._input_names: set[str] = set() + self._pooling = "mean" + self._normalize = False self._dim: Optional[int] = None + def _download(self) -> Path: + from huggingface_hub import snapshot_download + + repo = _repo_id(self._model_name) + # Prefer local copies: the configured cache, then the default HF cache + # (where the Docker image pre-bakes the model). Download only if neither has it. + for cache_dir in dict.fromkeys([self._cache_dir, None]): + try: + path = Path(snapshot_download( + repo, allow_patterns=_MODEL_FILES, cache_dir=cache_dir, local_files_only=True, + )) + if (path / "onnx" / "model.onnx").is_file(): + return path + except Exception: + continue + logger.info("Model '%s' not cached — downloading for the first time...", repo) + path = Path(snapshot_download(repo, allow_patterns=_MODEL_FILES, cache_dir=self._cache_dir)) + if not (path / "onnx" / "model.onnx").is_file(): + raise EmbeddingError(f"Model '{repo}' has no ONNX export (onnx/model.onnx)") + return path + def _ensure_model(self) -> None: - if self._model is not None: + if self._session is not None: return try: - from sentence_transformers import SentenceTransformer + import onnxruntime as ort + from tokenizers import Tokenizer - # Allow first download, then enforce offline mode for subsequent loads - try: - os.environ["HF_HUB_OFFLINE"] = "1" - self._model = SentenceTransformer(self._model_name, cache_folder=self._cache_dir) - except OSError: - logger.info("Model '%s' not cached — downloading for the first time...", self._model_name) - os.environ.pop("HF_HUB_OFFLINE", None) - self._model = SentenceTransformer(self._model_name, cache_folder=self._cache_dir) - os.environ["HF_HUB_OFFLINE"] = "1" - - # Probe dimension quietly - test = self._model.encode(["test"], show_progress_bar=False) - self._dim = len(test[0]) - logger.info("Loaded local embedding model: %s (dim=%d)", self._model_name, self._dim) - except ImportError: - raise EmbeddingError( - "sentence-transformers not installed. " - "Install with: pip install sentence-transformers" + path = self._download() + + def _read(name: str) -> dict: + f = path / name + return json.loads(f.read_text()) if f.is_file() else {} + + modules = _read("modules.json") + pooling_cfg = _read("1_Pooling/config.json") + max_len = _read("sentence_bert_config.json").get("max_seq_length") or 512 + max_len = min(max_len, _read("config.json").get("max_position_embeddings") or max_len) + + if pooling_cfg.get("pooling_mode_cls_token"): + self._pooling = "cls" + elif pooling_cfg.get("pooling_mode_max_tokens"): + self._pooling = "max" + else: + self._pooling = "mean" + self._normalize = any(m.get("type", "").endswith("Normalize") for m in modules) + + tokenizer = Tokenizer.from_file(str(path / "tokenizer.json")) + tokenizer.enable_truncation(max_length=max_len) + pad = tokenizer.padding or {} + tokenizer.enable_padding( + pad_id=pad.get("pad_id", 0), pad_token=pad.get("pad_token", "[PAD]"), ) + self._tokenizer = tokenizer + + opts = ort.SessionOptions() + opts.log_severity_level = 3 + self._session = ort.InferenceSession( + str(path / "onnx" / "model.onnx"), opts, providers=["CPUExecutionProvider"], + ) + self._input_names = {i.name for i in self._session.get_inputs()} + + self._dim = len(self._encode(["test"])[0]) + logger.info("Loaded local embedding model: %s (dim=%d)", self._model_name, self._dim) + except EmbeddingError: + raise except Exception as exc: + self._session = None raise EmbeddingError(f"Failed to load model '{self._model_name}': {exc}") from exc + def _encode(self, texts: list[str]) -> np.ndarray: + order = sorted(range(len(texts)), key=lambda i: len(texts[i])) + out = np.empty((len(texts), 0), dtype=np.float32) + for start in range(0, len(order), _CHUNK_SIZE): + idx = order[start:start + _CHUNK_SIZE] + encs = self._tokenizer.encode_batch([texts[i] for i in idx]) # type: ignore[union-attr] + mask = np.array([e.attention_mask for e in encs], dtype=np.int64) + feeds = { + "input_ids": np.array([e.ids for e in encs], dtype=np.int64), + "attention_mask": mask, + "token_type_ids": np.array([e.type_ids for e in encs], dtype=np.int64), + } + feeds = {k: v for k, v in feeds.items() if k in self._input_names} + tokens = self._session.run(None, feeds)[0] # type: ignore[union-attr] # (batch, seq, dim) + + if self._pooling == "cls": + pooled = tokens[:, 0] + elif self._pooling == "max": + pooled = np.where(mask[..., None] > 0, tokens, -1e9).max(axis=1) + else: + m = mask[..., None].astype(np.float32) + pooled = (tokens * m).sum(axis=1) / np.clip(m.sum(axis=1), 1e-9, None) + if self._normalize: + pooled = pooled / np.clip(np.linalg.norm(pooled, axis=1, keepdims=True), 1e-12, None) + + if out.shape[1] == 0: + out = np.empty((len(texts), pooled.shape[1]), dtype=np.float32) + out[idx] = pooled + return out + async def embed_batch(self, texts: list[str]) -> list[list[float]]: self._ensure_model() + if not texts: + return [] try: - # sentence-transformers' encode() is synchronous and CPU/GPU bound. - # Offload to a worker thread so callers (HTTP/MCP handlers running - # on the same loop) stay responsive during indexing. - embeddings = await asyncio.to_thread( - self._model.encode, # type: ignore[union-attr] - texts, - show_progress_bar=False, - ) - return [emb.tolist() for emb in embeddings] + # ONNX inference is synchronous and CPU bound. Offload to a worker + # thread so callers (HTTP/MCP handlers running on the same loop) + # stay responsive during indexing. + embeddings = await asyncio.to_thread(self._encode, texts) + return embeddings.tolist() except Exception as exc: raise EmbeddingError(f"Local embedding failed: {exc}") from exc diff --git a/mimir/infra/llm/__init__.py b/mimir/infra/llm/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/mimir/infra/llm/litellm_client.py b/mimir/infra/llm/litellm_client.py deleted file mode 100644 index 5a99951..0000000 --- a/mimir/infra/llm/litellm_client.py +++ /dev/null @@ -1,82 +0,0 @@ -"""LiteLLM-based LLM client for summarization (llm mode only).""" - -from __future__ import annotations - -import asyncio -import logging -from typing import Optional - -from mimir.domain.errors import MimirError - -logger = logging.getLogger(__name__) - - -class LlmError(MimirError): - """LLM API call failed.""" - - -class LiteLlmClient: - """LLM client wrapping litellm for model-agnostic completions. - - Supports Claude, OpenAI, Ollama, and any OpenAI-compatible API. - """ - - def __init__( - self, - model: str = "claude-haiku-4-5-20251001", - max_concurrent: int = 10, - api_base: Optional[str] = None, - ) -> None: - self._model = model - self._api_base = api_base - self._semaphore = asyncio.Semaphore(max_concurrent) - - async def complete(self, prompt: str) -> str: - async with self._semaphore: - try: - import litellm - litellm.suppress_debug_info = True # STFU litellm - import logging - logging.getLogger("LiteLLM").setLevel(logging.WARNING) - - kwargs = { - "model": self._model, - "messages": [{"role": "user", "content": prompt}], - "max_tokens": 1024, - "temperature": 0.0, - } - if self._api_base: - kwargs["api_base"] = self._api_base - - response = await litellm.acompletion(**kwargs) - return response.choices[0].message.content or "" - except ImportError: - raise LlmError("litellm not installed. Install with: pip install litellm") - except Exception as exc: - raise LlmError(f"LLM completion failed: {exc}") from exc - - async def batch_complete( - self, - prompts: list[str], - *, - concurrency: int = 10, - ) -> list[str]: - """Send multiple prompts with concurrency control.""" - sem = asyncio.Semaphore(concurrency) - - async def _call(prompt: str) -> str: - async with sem: - return await self.complete(prompt) - - tasks = [_call(p) for p in prompts] - results = await asyncio.gather(*tasks, return_exceptions=True) - - output: list[str] = [] - for i, result in enumerate(results): - if isinstance(result, Exception): - logger.error("LLM call %d failed: %s", i, result) - output.append("") # graceful degradation - else: - output.append(result) - - return output diff --git a/mimir/infra/vector_stores/chroma.py b/mimir/infra/vector_stores/chroma.py deleted file mode 100644 index 85bc17a..0000000 --- a/mimir/infra/vector_stores/chroma.py +++ /dev/null @@ -1,124 +0,0 @@ -"""ChromaDB-backed vector store for production use.""" - -from __future__ import annotations - -import logging -from typing import Any, Optional - -from mimir.domain.errors import StorageError -from mimir.ports.vector_store import VectorSearchResult - -logger = logging.getLogger(__name__) - - -class ChromaVectorStore: - """ChromaDB vector store with HNSW indexing and metadata filtering.""" - - def __init__(self, persist_directory: Optional[str] = None, collection_name: str = "mimir") -> None: - try: - import chromadb - except ImportError: - raise StorageError( - "ChromaDB is not installed. Install with: pip install chromadb" - ) - - try: - if persist_directory: - self._client = chromadb.PersistentClient(path=persist_directory) - else: - self._client = chromadb.Client() - - self._collection = self._client.get_or_create_collection( - name=collection_name, - metadata={"hnsw:space": "cosine"}, - ) - logger.info( - "ChromaDB collection '%s' ready (%d vectors)", - collection_name, - self._collection.count(), - ) - except Exception as exc: - raise StorageError(f"Failed to initialise ChromaDB: {exc}") from exc - - def upsert( - self, - ids: list[str], - embeddings: list[list[float]], - metadatas: Optional[list[dict[str, Any]]] = None, - documents: Optional[list[str]] = None, - ) -> None: - try: - kwargs: dict[str, Any] = {"ids": ids, "embeddings": embeddings} - if metadatas: - # ChromaDB requires that all metadata values are str, int, float, or bool - kwargs["metadatas"] = [ - {k: v for k, v in m.items() if isinstance(v, (str, int, float, bool))} - for m in metadatas - ] - if documents: - kwargs["documents"] = documents - self._collection.upsert(**kwargs) - except Exception as exc: - raise StorageError(f"ChromaDB upsert failed: {exc}") from exc - - def search( - self, - query_embedding: list[float], - top_k: int = 10, - where: Optional[dict[str, Any]] = None, - ) -> list[VectorSearchResult]: - try: - kwargs: dict[str, Any] = { - "query_embeddings": [query_embedding], - "n_results": top_k, - } - if where: - kwargs["where"] = where - - results = self._collection.query(**kwargs) - - output: list[VectorSearchResult] = [] - if results["ids"] and results["ids"][0]: - ids = results["ids"][0] - distances = results["distances"][0] if results["distances"] else [0.0] * len(ids) - metadatas = results["metadatas"][0] if results["metadatas"] else [{}] * len(ids) - - for vec_id, dist, meta in zip(ids, distances, metadatas): - # ChromaDB cosine space returns distances in [0, 2]. - # Convert to similarity in [0, 1]: sim = 1 - (dist / 2) - score = max(0.0, 1.0 - dist / 2.0) - output.append(VectorSearchResult(id=vec_id, score=score, metadata=meta or {})) - - return output - except Exception as exc: - raise StorageError(f"ChromaDB search failed: {exc}") from exc - - def delete(self, ids: list[str]) -> None: - try: - self._collection.delete(ids=ids) - except Exception as exc: - raise StorageError(f"ChromaDB delete failed: {exc}") from exc - - def get_existing_ids(self, ids: list[str]) -> set[str]: - if not ids: - return set() - try: - # include=[] skips embeddings/metadata/documents — we only need the ids back. - result = self._collection.get(ids=ids, include=[]) - existing = result.get("ids") if isinstance(result, dict) else None - return set(existing) if existing else set() - except Exception as exc: - raise StorageError(f"ChromaDB get_existing_ids failed: {exc}") from exc - - def count(self) -> int: - return self._collection.count() - - def reset(self) -> None: - try: - self._client.delete_collection(self._collection.name) - self._collection = self._client.get_or_create_collection( - name=self._collection.name, - metadata={"hnsw:space": "cosine"}, - ) - except Exception as exc: - raise StorageError(f"ChromaDB reset failed: {exc}") from exc diff --git a/mimir/infra/vector_stores/numpy_store.py b/mimir/infra/vector_stores/numpy_store.py index 180362d..ef86bbe 100644 --- a/mimir/infra/vector_stores/numpy_store.py +++ b/mimir/infra/vector_stores/numpy_store.py @@ -1,8 +1,8 @@ """NumPy-based in-memory vector store. -Lightweight alternative to ChromaDB for development and small codebases. -Stores all vectors in memory using NumPy arrays. Supports metadata -filtering and cosine similarity search. +Stores all vectors in memory using NumPy arrays and is rebuilt from the +embeddings in graph.db on startup. Supports metadata filtering and exact +(brute-force) cosine similarity search. """ from __future__ import annotations @@ -27,6 +27,13 @@ def __init__(self) -> None: self._metadatas: list[dict[str, Any]] = [] self._documents: list[Optional[str]] = [] self._id_to_idx: dict[str, int] = {} + # Derived caches, invalidated on every mutation + self._unit: Optional[np.ndarray] = None # row-normalized embeddings + self._columns: dict[str, np.ndarray] = {} # metadata key -> values per row + + def _invalidate(self) -> None: + self._unit = None + self._columns.clear() def upsert( self, @@ -39,34 +46,57 @@ def upsert( raise StorageError( f"ids ({len(ids)}) and embeddings ({len(embeddings)}) length mismatch" ) + if not ids: + return metas = metadatas or [{}] * len(ids) docs = documents or [None] * len(ids) - new_vecs = np.array(embeddings, dtype=np.float32) + new_vecs = np.asarray(embeddings, dtype=np.float32) + # Updates are written in place; appends are collected and stacked once + # (row-by-row vstack would make bulk loads quadratic). + update_rows: list[int] = [] + update_idx: list[int] = [] + append_rows: list[int] = [] for i, vec_id in enumerate(ids): - if vec_id in self._id_to_idx: - # Update in-place - idx = self._id_to_idx[vec_id] - if self._embeddings is not None: - self._embeddings[idx] = new_vecs[i] - self._metadatas[idx] = metas[i] - self._documents[idx] = docs[i] - else: - # Append + idx = self._id_to_idx.get(vec_id) + if idx is None: idx = len(self._ids) self._ids.append(vec_id) self._metadatas.append(metas[i]) self._documents.append(docs[i]) self._id_to_idx[vec_id] = idx - - if self._embeddings is None: - self._embeddings = new_vecs[i : i + 1] + append_rows.append(i) + else: + self._metadatas[idx] = metas[i] + self._documents[idx] = docs[i] + if idx < self._stored_rows(): + update_idx.append(idx) + update_rows.append(i) else: - self._embeddings = np.vstack([self._embeddings, new_vecs[i : i + 1]]) + # Duplicate id earlier in this same batch — last write wins + append_rows[idx - self._stored_rows()] = i + + if update_idx: + self._embeddings[update_idx] = new_vecs[update_rows] # type: ignore[index] + if append_rows: + added = new_vecs[append_rows] + self._embeddings = added if self._embeddings is None else np.vstack([self._embeddings, added]) + self._invalidate() logger.debug("Upserted %d vectors (total: %d)", len(ids), len(self._ids)) + def _stored_rows(self) -> int: + return 0 if self._embeddings is None else len(self._embeddings) + + def _column(self, key: str) -> np.ndarray: + col = self._columns.get(key) + if col is None: + col = np.empty(len(self._metadatas), dtype=object) + col[:] = [m.get(key) for m in self._metadatas] + self._columns[key] = col + return col + def search( self, query_embedding: list[float], @@ -76,23 +106,22 @@ def search( if self._embeddings is None or len(self._ids) == 0: return [] - query = np.array(query_embedding, dtype=np.float32) - - # Cosine similarity - norms = np.linalg.norm(self._embeddings, axis=1) + query = np.asarray(query_embedding, dtype=np.float32) query_norm = np.linalg.norm(query) if query_norm == 0: return [] - similarities = self._embeddings @ query / (norms * query_norm + 1e-10) + # Cosine similarity against cached unit vectors + if self._unit is None: + norms = np.linalg.norm(self._embeddings, axis=1, keepdims=True) + self._unit = self._embeddings / (norms + 1e-10) + similarities = self._unit @ (query / query_norm) # Apply metadata filter if where: mask = np.ones(len(self._ids), dtype=bool) for key, value in where.items(): - for i, meta in enumerate(self._metadatas): - if meta.get(key) != value: - mask[i] = False + mask &= self._column(key) == value similarities = np.where(mask, similarities, -np.inf) # Top-k @@ -132,6 +161,7 @@ def delete(self, ids: list[str]) -> None: # Rebuild index self._id_to_idx = {vid: i for i, vid in enumerate(self._ids)} + self._invalidate() def get_existing_ids(self, ids: list[str]) -> set[str]: return {i for i in ids if i in self._id_to_idx} @@ -145,3 +175,4 @@ def reset(self) -> None: self._metadatas.clear() self._documents.clear() self._id_to_idx.clear() + self._invalidate() diff --git a/mimir/ports/__init__.py b/mimir/ports/__init__.py index 1fcf469..f318ee6 100644 --- a/mimir/ports/__init__.py +++ b/mimir/ports/__init__.py @@ -8,7 +8,6 @@ from mimir.ports.embedder import Embedder from mimir.ports.vector_store import VectorStore, VectorSearchResult from mimir.ports.graph_store import GraphStore -from mimir.ports.llm_client import LlmClient from mimir.ports.session_store import SessionStore __all__ = [ @@ -18,6 +17,5 @@ "VectorStore", "VectorSearchResult", "GraphStore", - "LlmClient", "SessionStore", ] diff --git a/mimir/ports/llm_client.py b/mimir/ports/llm_client.py deleted file mode 100644 index 01a4b1a..0000000 --- a/mimir/ports/llm_client.py +++ /dev/null @@ -1,46 +0,0 @@ -"""LlmClient port — interface for LLM completions (used in llm mode only).""" - -from __future__ import annotations - -from typing import Protocol, runtime_checkable - - -@runtime_checkable -class LlmClient(Protocol): - """Interface for LLM text completions. - - Implementation: ``LiteLlmClient``. - Only instantiated when ``summary_mode == "llm"``. - """ - - async def complete(self, prompt: str) -> str: - """Send a single completion request. - - Returns - ------- - str - The model's text response. - """ - ... - - async def batch_complete( - self, - prompts: list[str], - *, - concurrency: int = 10, - ) -> list[str]: - """Send multiple completion requests with concurrency control. - - Parameters - ---------- - prompts - List of prompt strings. - concurrency - Maximum number of concurrent API calls. - - Returns - ------- - list[str] - One response per prompt, in corresponding order. - """ - ... diff --git a/mimir/ports/vector_store.py b/mimir/ports/vector_store.py index 0de7ef9..79a77d2 100644 --- a/mimir/ports/vector_store.py +++ b/mimir/ports/vector_store.py @@ -19,7 +19,7 @@ class VectorSearchResult: class VectorStore(Protocol): """Interface for vector similarity search. - Implementations: ``ChromaVectorStore``, ``NumpyVectorStore``. + Implementation: ``NumpyVectorStore``. """ def upsert( @@ -76,7 +76,7 @@ def get_existing_ids(self, ids: list[str]) -> set[str]: """Return the subset of ``ids`` that already exist in the store. Used by the container's hydration path to skip re-upserting vectors - that persistent backends (e.g. Chroma) already hold on disk. + the store already holds. Implementations should probe only the given ids, not scan the whole store. """ diff --git a/mimir/runtime.py b/mimir/runtime.py index dd4c445..507cc4f 100644 --- a/mimir/runtime.py +++ b/mimir/runtime.py @@ -12,7 +12,7 @@ from pathlib import Path from typing import Optional -from mimir.domain.config import MimirConfig, SummaryMode, VectorBackend +from mimir.domain.config import MimirConfig, SummaryMode from mimir.domain.errors import NoActiveIndexError, StorageError from mimir.domain.graph import CodeGraph from mimir.domain.index_state import IndexJob, IndexJobKind, IndexVersion @@ -81,13 +81,6 @@ def _build_embedder(config: MimirConfig): def _build_vector_store(config: MimirConfig): - if config.vector_db.backend is VectorBackend.CHROMA: - from mimir.infra.vector_stores.chroma import ChromaVectorStore - - return ChromaVectorStore( - persist_directory=config.vector_db.persist_directory - or str(config.session_dir / "chroma"), - ) return NumpyVectorStore() diff --git a/mimir/services/hydration.py b/mimir/services/hydration.py index c62b860..967783a 100644 --- a/mimir/services/hydration.py +++ b/mimir/services/hydration.py @@ -1,9 +1,8 @@ """Vector store hydration — populates the vector store from graph node embeddings. Upserts only the delta: ids present in the graph but missing from the -store. Persistent backends (Chroma) that already hold the HNSW index -on disk skip the work entirely on warm starts. ``upsert`` is -idempotent in every backend, so the delta optimization is purely a +store, so repeated calls (e.g. after a reload) skip vectors already +held. ``upsert`` is idempotent, so the delta optimization is purely a speedup — correctness does not depend on it. """ diff --git a/pyproject.toml b/pyproject.toml index d7c78e0..b0f4438 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,5 +1,5 @@ [build-system] -requires = ["setuptools>=68.0", "wheel>=0.46", "setuptools-scm>=8"] +requires = ["setuptools>=84.0", "wheel>=0.48", "setuptools-scm>=10.3"] build-backend = "setuptools.build_meta" [project] @@ -8,13 +8,12 @@ dynamic = ["version"] description = "Mimir — Context Server: intelligent code context engine for LLMs working with large, multi-repo codebases" readme = "README.md" requires-python = ">=3.11" -license = {text = "MIT"} +license = "MIT" keywords = ["mcp", "context", "code", "llm", "rag", "code-graph", "embeddings", "mimir"] classifiers = [ "Development Status :: 4 - Beta", "Environment :: Console", "Intended Audience :: Developers", - "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", @@ -25,34 +24,26 @@ classifiers = [ ] dependencies = [ - "networkx>=3.5", - "gitpython>=3.1", - "typer>=0.15", - "tomli>=2.2", - "chromadb>=1.5", - "pydantic-settings>=2.0", - "sentence-transformers>=4.1", - "litellm>=1.68", - "mcp>=1.26", - "numpy>=2.2", - "tree-sitter>=0.25", - "tree-sitter-language-pack>=0.9", - "aiohttp>=3.11", - "tiktoken>=0.9", - "rank-bm25>=0.2", - "rich>=14.0", - "watchdog>=6.0", - "pyyaml>=6.0", + "networkx>=3.6.1", + "gitpython>=3.2.0", + "typer>=0.27.2", + "onnxruntime>=1.30.0", + "tokenizers>=0.23.2", + "huggingface-hub>=1.33.0", + "numpy>=2.4.6", + "tree-sitter-language-pack>=1.20.0", + "aiohttp>=3.14.3", + "rank-bm25>=0.2.2", + "rich>=15.0.0", + "watchdog>=6.0.0", + "pyyaml>=6.0.3", ] [project.optional-dependencies] dev = [ - "pytest>=9.0", - "pytest-asyncio>=1.3", - "pytest-cov>=7.0", -] -lsp = [ - "multilspy>=0.2", + "pytest>=9.1.1", + "pytest-asyncio>=1.4.0", + "pytest-cov>=7.1.0", ] [project.urls] diff --git a/tests/adapters/test_cli_adapter.py b/tests/adapters/test_cli_adapter.py index 51efa7d..668ddbe 100644 --- a/tests/adapters/test_cli_adapter.py +++ b/tests/adapters/test_cli_adapter.py @@ -123,8 +123,5 @@ def _write_config(tmp_path): [embeddings] model = "local:test" - - [vector_db] - backend = "numpy" """)) return config_path diff --git a/tests/infra/test_vector_stores.py b/tests/infra/test_vector_stores.py index 06939b2..7a66320 100644 --- a/tests/infra/test_vector_stores.py +++ b/tests/infra/test_vector_stores.py @@ -1,19 +1,12 @@ -"""Parity tests for VectorStore implementations. +"""Contract tests for the VectorStore implementation. -Exercises NumpyVectorStore and ChromaVectorStore against the same fixtures to -ensure they agree on upsert/search/delete/count/reset/get_existing_ids. -Metadata is intentionally scalar-only — ChromaVectorStore silently drops -non-scalar metadata values (see ``chroma.py``), which would masquerade as a -parity failure otherwise. +Exercises NumpyVectorStore's upsert/search/delete/count/reset/get_existing_ids. """ from __future__ import annotations -from pathlib import Path - import pytest -from mimir.infra.vector_stores.chroma import ChromaVectorStore from mimir.infra.vector_stores.numpy_store import NumpyVectorStore from mimir.ports.vector_store import VectorStore @@ -23,22 +16,11 @@ # --------------------------------------------------------------------------- -def _numpy_store() -> VectorStore: +@pytest.fixture +def store() -> VectorStore: return NumpyVectorStore() -def _chroma_store(tmp_path: Path) -> VectorStore: - # Use a unique sub-path so parallel test runs don't collide. - return ChromaVectorStore(persist_directory=str(tmp_path / "chroma")) - - -@pytest.fixture(params=["numpy", "chroma"]) -def store(request, tmp_path: Path) -> VectorStore: - if request.param == "numpy": - return _numpy_store() - return _chroma_store(tmp_path) - - def _sample_vectors() -> tuple[list[str], list[list[float]], list[dict]]: ids = ["a", "b", "c"] # 4-D vectors along distinct axes so ranking is unambiguous. @@ -117,6 +99,45 @@ def test_upsert_updates_existing_id(store: VectorStore) -> None: assert store.count() == 1 +def test_upsert_duplicate_id_in_one_batch_last_write_wins(store: VectorStore) -> None: + store.upsert( + ids=["x", "y", "x"], + embeddings=[[1.0, 0.0], [0.0, 1.0], [0.0, 1.0]], + metadatas=[{"repo": "alpha"}, {"repo": "beta"}, {"repo": "gamma"}], + ) + + assert store.count() == 2 + results = store.search(query_embedding=[1.0, 0.0], top_k=5, where={"repo": "gamma"}) + assert [r.id for r in results] == ["x"] + assert store.search(query_embedding=[1.0, 0.0], top_k=5, where={"repo": "alpha"}) == [] + + +def test_upsert_mixed_update_and_append(store: VectorStore) -> None: + ids, embeddings, metadatas = _sample_vectors() + store.upsert(ids=ids, embeddings=embeddings, metadatas=metadatas) + + store.upsert( + ids=["c", "d"], + embeddings=[[0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 0.0]], + metadatas=[{"repo": "alpha"}, {"repo": "alpha"}], + ) + + assert store.count() == 4 + assert store.search(query_embedding=[0.0, 0.0, 0.0, 1.0], top_k=1)[0].id == "c" + assert store.search(query_embedding=[0.0, 0.0, 1.0, 0.0], top_k=1)[0].id == "d" + + +def test_filtered_search_after_delete(store: VectorStore) -> None: + ids, embeddings, metadatas = _sample_vectors() + store.upsert(ids=ids, embeddings=embeddings, metadatas=metadatas) + store.search(query_embedding=[1.0, 0.0, 0.0, 0.0], top_k=5, where={"repo": "alpha"}) + + store.delete(ids=["a"]) + + results = store.search(query_embedding=[1.0, 0.0, 0.0, 0.0], top_k=5, where={"repo": "alpha"}) + assert [r.id for r in results] == ["c"] + + # --------------------------------------------------------------------------- # delete / count / reset # --------------------------------------------------------------------------- @@ -168,6 +189,5 @@ def test_get_existing_ids_all_present(store: VectorStore) -> None: def test_get_existing_ids_empty_input(store: VectorStore) -> None: # Edge case: callers may pass an empty id list when the graph has no - # embedded nodes. Both backends must handle this without hitting the - # underlying collection. + # embedded nodes. assert store.get_existing_ids([]) == set() diff --git a/tests/services/indexing/test_indexing_integration.py b/tests/services/indexing/test_indexing_integration.py index 75c0846..177ef8f 100644 --- a/tests/services/indexing/test_indexing_integration.py +++ b/tests/services/indexing/test_indexing_integration.py @@ -24,7 +24,6 @@ IndexingConfig, MimirConfig, RepoConfig, - VectorDbConfig, ) from mimir.domain.graph import CodeGraph from mimir.domain.models import EdgeKind, NodeKind, SYMBOL_KINDS @@ -142,7 +141,6 @@ def mimir_config(tmp_path: Path, repo_on_disk: Path) -> MimirConfig: detect_shared_imports=True, ), embeddings=EmbeddingConfig(batch_size=64), - vector_db=VectorDbConfig(backend="numpy"), ) diff --git a/tests/test_runtime_publish_query.py b/tests/test_runtime_publish_query.py index b5705e7..93050d1 100644 --- a/tests/test_runtime_publish_query.py +++ b/tests/test_runtime_publish_query.py @@ -1,6 +1,6 @@ from __future__ import annotations -from types import SimpleNamespace +from unittest.mock import Mock import pytest from aiohttp.test_utils import make_mocked_request @@ -9,7 +9,7 @@ from mimir.adapters.http.state import HttpServerState from mimir.adapters.web.routes import register_routes as register_web_routes from mimir.adapters.web.state import WebServerState -from mimir.domain.config import EmbeddingConfig, MimirConfig, RepoConfig, VectorDbConfig +from mimir.domain.config import EmbeddingConfig, MimirConfig, RepoConfig from mimir.domain.errors import NoActiveIndexError from mimir.domain.graph import CodeGraph from mimir.domain.models import Node, NodeKind @@ -29,7 +29,6 @@ def _config(tmp_path) -> MimirConfig: repos=[RepoConfig(name="repo", path=repo, language_hint="python")], data_dir=tmp_path / ".mimir", embeddings=EmbeddingConfig(model="local:test"), - vector_db=VectorDbConfig(backend="numpy"), ) @@ -191,7 +190,6 @@ def test_query_runtime_rejects_embedding_model_mismatch(tmp_path, monkeypatch: p repos=cfg.repos, data_dir=cfg.data_dir, embeddings=EmbeddingConfig(model="local:other"), - vector_db=VectorDbConfig(backend="numpy"), ) with pytest.raises(Exception, match="embedding model mismatch"): QueryRuntime(mismatched) @@ -242,7 +240,8 @@ async def _request(app, method: str, path: str, *, json_body: dict | None = None import json from aiohttp import streams - payload = streams.StreamReader(protocol=SimpleNamespace(_reading_paused=False), limit=2**16) + # Mock protocol: aiohttp>=3.14 calls flow-control hooks (e.g. resume_reading) on it. + payload = streams.StreamReader(protocol=Mock(_reading_paused=False), limit=2**16) if json_body is not None: payload.feed_data(json.dumps(json_body).encode("utf-8")) payload.feed_eof()