From 8c2a568fc127b8ac6027f46601f890ca56627f34 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Mon, 26 Oct 2026 03:40:30 +0000 Subject: [PATCH] fix(ai): the rag index keeps each project's chunks apart, deletes a removed file's points before forgetting it, and refills a project its collection lost The rag index previously mixed points across projects because chunk IDs hashed only file path and line numbers without project scope. It also executed deletes without waiting and removed cache entries prematurely, leaving orphan vectors in Qdrant collections. Empty collections went undetected on subsequent runs when local cache entries were present. Isolate vectors across projects and guarantee index consistency: - Generate chunk IDs using uuid.uuid5 over project name, file path, and lines. - Wait for delete operations in Qdrant and propagate errors before cache updates. - Track exact project point counts in index_counts.json to detect missing points. - Refill project points and clear project cache when collection points are lost. - Ensure collections define payload indexes for project_name and file_path. Closes #1388 --- .../.openspec.yaml | 3 + .../design.md | 54 ++ .../proposal.md | 67 ++ .../tasks.md | 47 ++ src/devops_cli/ai/rag/chunker.py | 23 +- src/devops_cli/ai/rag/indexer.py | 368 +++++++--- src/devops_cli/ai/rag/qdrant.py | 93 ++- src/devops_cli/ai/tools/__init__.py | 2 +- src/devops_cli/commands/rag.py | 8 +- src/devops_cli/config/constants.py | 7 + .../fixtures/swallowed_failures_ceilings.json | 2 +- tests/test_rag_indexer_retriever.py | 39 +- tests/test_rag_kb_sync.py | 39 + tests/test_rag_multi_project_indexer.py | 672 ++++++++++++++++-- tests/test_rag_qdrant.py | 31 +- 15 files changed, 1284 insertions(+), 171 deletions(-) create mode 100644 openspec/changes/archive/2026-10-26-1388-rag-project-isolation/.openspec.yaml create mode 100644 openspec/changes/archive/2026-10-26-1388-rag-project-isolation/design.md create mode 100644 openspec/changes/archive/2026-10-26-1388-rag-project-isolation/proposal.md create mode 100644 openspec/changes/archive/2026-10-26-1388-rag-project-isolation/tasks.md diff --git a/openspec/changes/archive/2026-10-26-1388-rag-project-isolation/.openspec.yaml b/openspec/changes/archive/2026-10-26-1388-rag-project-isolation/.openspec.yaml new file mode 100644 index 0000000000..7b65ee7de6 --- /dev/null +++ b/openspec/changes/archive/2026-10-26-1388-rag-project-isolation/.openspec.yaml @@ -0,0 +1,3 @@ +schema: spec-driven +created: 2026-10-26 +skip_specs: true diff --git a/openspec/changes/archive/2026-10-26-1388-rag-project-isolation/design.md b/openspec/changes/archive/2026-10-26-1388-rag-project-isolation/design.md new file mode 100644 index 0000000000..7d2f29775d --- /dev/null +++ b/openspec/changes/archive/2026-10-26-1388-rag-project-isolation/design.md @@ -0,0 +1,54 @@ +# Design + +## Context + +`WorkspaceIndexer` stores chunks from multiple projects in two shared Qdrant collections: code and docs. +Previously, chunk IDs were hashes of only `file_path:start_line:end_line`. +Identical paths across projects collided and overwrote one another. +Deletes were executed without waiting and errors were swallowed, leaving orphan vectors. +Collection emptying was not detected because cache hits prevented re-indexing. +Finally, collections had no payload indexes configured for fast tenant and file path filtering. + +## Decisions + +### 1. Project-Scoped Deterministic UUIDv5 IDs + +- Use standard library `uuid.uuid5(uuid.NAMESPACE_DNS, f"{project_name}:{file_path}:{start_line}:{end_line}")` for all chunk IDs. +- *Rejected alternative:* Use separate Qdrant collections per project. + *Evidence:* Qdrant multitenancy documentation warns that separate collections per tenant waste memory and cluster resources. It recommends one shared collection with an `is_tenant` keyword index. Multi-collection search would also require fanning out queries across twice the number of repositories. + +### 2. Waited Vector Deletes and Strict Error Handling + +- Always send deletes with `wait=True`. +- Delete `_safe_delete_points_by_files` and `delete_points_by_file`. +- Purges call `delete_points_by_files` directly. When deletion fails, raise `QdrantClientError` and keep cache entries intact. +- Add `delete_points_by_project` for scoped project point purges. +- *Rejected alternative:* Keep un-waited deletes with silent fallback to single file deletion. + *Evidence:* Un-waited deletes return immediately before storage updates. If a timeout occurs, the cache entry has already been dropped, leaving undeletable orphan vectors permanently in Qdrant. + +### 3. Scoped Force Re-indexing + +- `--force` deletes only the target project's points from both collections using `delete_points_by_project`. +- Only drop the target project's entries from the cache dictionary. +- *Rejected alternative:* Reset the cache dictionary to empty on `--force`. + *Evidence:* Wiping the entire cache forces every other repository sharing the collection to re-embed all files on its next run, causing thousands of redundant embedding requests. + +### 4. Separate Point Counts File and Intact Check + +- Store exact point counts per scanned project and collection in `index_counts.json` beside `index_cache.json`. +- Before scanning, compare current counts with recorded counts using `count_points`. +- Refill the project as `--force` does if a collection that previously held points now has zero points, or if cached files exist with zero points across both collections. +- Expose `points_intact(project)` on `WorkspaceIndexer`. +- *Rejected alternative:* Use drift's `_count_collection_project_points`. + *Evidence:* Drift's helper returns 0 on errors, which would trigger a complete re-embed on transient connection failures. `count_points` raises `QdrantClientError` on network or server errors, preventing accidental re-indexing. +- *Rejected alternative:* Store counts directly in `index_cache.json`. + *Evidence:* `index_cache.json` is a flat key-value map of `project:relative_path -> content_hash`. Inserting metadata objects breaks purge logic that parses cache keys. + +### 5. Collection Payload Index Provisioning + +- Define `CONST_RAG_PAYLOAD_INDEXES` in `src/devops_cli/config/constants.py`. +- In `ensure_collection`, create keyword indexes for `project_name` (`is_tenant=True`) and `file_path`. +- Check existing `payload_schema` and add any missing index to existing collections. +- Call `ensure_collection` at the start of indexing before inspecting file changes. +- *Rejected alternative:* Create payload indexes only inside `upsert_points`. + *Evidence:* A clean workspace where all files are already cached does not upsert points, so collections would never receive required payload indexes. diff --git a/openspec/changes/archive/2026-10-26-1388-rag-project-isolation/proposal.md b/openspec/changes/archive/2026-10-26-1388-rag-project-isolation/proposal.md new file mode 100644 index 0000000000..af8e37e8cd --- /dev/null +++ b/openspec/changes/archive/2026-10-26-1388-rag-project-isolation/proposal.md @@ -0,0 +1,67 @@ +# Proposal + +## Why + +Issue #1388: `WorkspaceIndexer` writes each project into shared Qdrant collections. +The point id hashes only the relative file path and line range. +Two projects that contain a file with the same path overwrite each other's points. +For example, lines 26-34 of this repository's `README.md` and the bundled knowledge base's `README.md` receive the identical point id. +Also, vector deletion uses `wait=False`, swallows failure, and removes cache entries before deletion finishes. +When a collection loses its points or a forced re-index runs, other projects lose their cache entries and points are not refilled. +Finally, collections lack keyword payload indexes on `project_name` (`is_tenant=True`) and `file_path`. + +## What Changes + +- Change point id generation to `uuid.uuid5` over `project_name`, relative path, and line range. +- Require `wait=True` on vector deletes and raise `QdrantClientError` when a delete operation fails. +- Remove `_safe_delete_points_by_files` and `delete_points_by_file`. +- Drop a cache entry in `_purge_deleted_vectors` only after its points are deleted from both collections. +- Allow `_purge_deleted_vectors` to scan for deleted files under a project when no local files remain. +- Scope `--force` re-indexing to the specified project: delete that project's points with a waited delete, drop its cache entries, and leave other projects intact. +- Write cache files atomically with `write_json_file(..., atomic=True)` and raise errors on write failure. +- Record exact point counts per scanned project and collection after each index run in `index_counts.json`. +- Detect missing or emptied project points before indexing and refill the project as `--force` does. +- Expose `WorkspaceIndexer.points_intact(project)` to verify points without scanning files. +- Create payload indexes on `project_name` (`is_tenant=True`) and `file_path` in `ensure_collection` using `CONST_RAG_PAYLOAD_INDEXES`. +- Call `ensure_collection` at index startup so existing collections receive missing payload indexes even when no files change. +- This change alters no CLI commands, options, messages, manifests, or service behavior. +- The change sets `skip_specs: true` in its `.openspec.yaml`. +- This change fits in one pull request. + +## Capabilities + +### New Capabilities + +None. + +### Modified Capabilities + +None. + +## Impact + +- `src/devops_cli/config/constants.py`: Add `CONST_RAG_PAYLOAD_INDEXES` and `CONST_INDEX_COUNTS_FILENAME`. +- `src/devops_cli/ai/rag/chunker.py`: Use `uuid.uuid5(uuid.NAMESPACE_DNS, ...)` for chunk id generation. +- `src/devops_cli/ai/rag/qdrant.py`: Add `delete_points_by_project`, default `wait=True`, raise `QdrantClientError`, provision payload indexes in `ensure_collection`, and remove `delete_points_by_file`. +- `src/devops_cli/ai/rag/indexer.py`: Remove `_safe_delete_points_by_files`, update purges, implement atomic cache and count recording, and support `points_intact`. +- `src/devops_cli/commands/rag.py`: Clean up `index_counts.json` during cache clearing. +- `tests/test_rag_multi_project_indexer.py`: Add tests with fake Qdrant verifying isolation, purges, count tracking, and payload indexes. + +## Feasibility + +- Confirmed with standard Python library `uuid.uuid5` that distinct project names yield distinct UUIDs for identical file paths and line ranges. +- Confirmed with `qdrant_client` library source that `QdrantClient.count` supports exact counting with payload filters and raises `UnexpectedResponse` or transport errors. +- Confirmed that `qmodels.KeywordIndexParams(type="keyword", is_tenant=True)` is supported in `qdrant_client.models`. +- Confirmed `write_json_file(..., atomic=True)` in `src/devops_cli/output/file_writer.py` performs atomic writes via temporary files. + +## Existing Tool Considered + +We use existing maintained libraries already present in the workspace: +- Standard library `uuid.uuid5` for RFC 4122 compliant deterministic UUID generation. +- `qdrant-client` native methods (`count`, `create_payload_index`, `delete`) rather than custom implementations. +- `write_json_file` from `devops_cli.output.file_writer` for atomic file replacement. + +The change deletes internal code: +- `_safe_delete_points_by_files` in `src/devops_cli/ai/rag/indexer.py`. +- `delete_points_by_file` in `src/devops_cli/ai/rag/qdrant.py`. +- Custom string formatting digest in `SemanticChunker._generate_id`. diff --git a/openspec/changes/archive/2026-10-26-1388-rag-project-isolation/tasks.md b/openspec/changes/archive/2026-10-26-1388-rag-project-isolation/tasks.md new file mode 100644 index 0000000000..e7c6f114d0 --- /dev/null +++ b/openspec/changes/archive/2026-10-26-1388-rag-project-isolation/tasks.md @@ -0,0 +1,47 @@ +# Tasks + +## 1. Deterministic Project-Scoped Chunk IDs + +- [x] Write failing tests verifying that chunk IDs include project name, use `uuid.uuid5`, and do not collide across projects sharing a file path (`uv run pytest tests/test_rag_chunker.py tests/test_rag_multi_project_indexer.py -k test_chunk_ids_scoped_by_project`). +- [x] Implement `_generate_id` with `uuid.uuid5` over `project_name`, `file_path`, `start_line`, and `end_line` in `src/devops_cli/ai/rag/chunker.py` (`uv run pytest tests/test_rag_chunker.py tests/test_rag_multi_project_indexer.py -k test_chunk_ids_scoped_by_project`). +- [x] Replace `"devops-cli-kb"` literals in `src/devops_cli/ai/rag/indexer.py` with `CONST_RAG_KB_PROJECT` (`uv run pytest tests/test_rag_indexer_retriever.py`). +- [x] Regenerate documentation and check consistency (`uv run devops docs generate --sync-readme`). + +## 2. Waited Vector Deletes, Error Propagation, and Project Deletion + +- [x] Write failing tests for waited vector deletes, `QdrantClientError` raising on failed deletes, and project-scoped deletes (`uv run pytest tests/test_rag_qdrant.py tests/test_rag_multi_project_indexer.py -k test_deletes_wait_and_raise`). +- [x] Implement `delete_points_by_project`, update `delete_points_by_files` to default `wait=True` and raise on error, and delete `delete_points_by_file` in `src/devops_cli/ai/rag/qdrant.py` (`uv run pytest tests/test_rag_qdrant.py`). +- [x] Delete `_safe_delete_points_by_files` and update `_purge_deleted_vectors` and `_purge_obsolete_points` in `src/devops_cli/ai/rag/indexer.py` to call `delete_points_by_files(..., wait=True)` directly (`uv run pytest tests/test_rag_multi_project_indexer.py`). +- [x] Update existing tests that mock or call `delete_points_by_file` in `tests/test_rag_qdrant.py`, `tests/test_rag_indexer_retriever.py`, and `tests/test_rag_multi_project_indexer.py` (`uv run pytest tests/test_rag_qdrant.py tests/test_rag_indexer_retriever.py tests/test_rag_multi_project_indexer.py`). +- [x] Regenerate documentation and check consistency (`uv run devops docs generate --sync-readme`). + +## 3. Atomic Cache Writes, Point Counts Tracking, and Missing Points Detection + +- [x] Write failing tests for atomic cache writes, failure retention, point counts recording, and intact checks (`uv run pytest tests/test_rag_multi_project_indexer.py -k test_points_intact_and_atomic_cache`). +- [x] Implement atomic cache writing using `write_json_file(..., atomic=True)` in `src/devops_cli/ai/rag/indexer.py` (`uv run pytest tests/test_rag_multi_project_indexer.py -k test_atomic_cache`). +- [x] Add `CONST_INDEX_COUNTS_FILENAME` to `src/devops_cli/config/constants.py`, record per-project point counts after indexing, and implement `points_intact` on `WorkspaceIndexer` (`uv run pytest tests/test_rag_multi_project_indexer.py -k test_points_intact`). +- [x] Scope `--force` to the target project and refill project points when lost in Qdrant (`uv run pytest tests/test_rag_multi_project_indexer.py -k test_force_scoped_and_refill`). +- [x] Remove `index_counts.json` during `devops ai rag clear` in `src/devops_cli/commands/rag.py` (`uv run pytest tests/test_rag_cli.py`). +- [x] Regenerate documentation and check consistency (`uv run devops docs generate --sync-readme`). + +## 4. Collection Payload Indexes and Pre-Scan Collection Provisioning + +- [x] Write failing tests for payload index provisioning on new and existing collections during index runs (`uv run pytest tests/test_rag_multi_project_indexer.py -k test_payload_indexes_provisioned`). +- [x] Define `CONST_RAG_PAYLOAD_INDEXES` in `src/devops_cli/config/constants.py` (`uv run pytest tests/test_rag_qdrant.py`). +- [x] Update `ensure_collection` in `src/devops_cli/ai/rag/qdrant.py` to create missing payload indexes using `CONST_RAG_PAYLOAD_INDEXES` (`uv run pytest tests/test_rag_qdrant.py`). +- [x] Call `ensure_collection` at the start of `WorkspaceIndexer.index_workspace` before scanning files (`uv run pytest tests/test_rag_multi_project_indexer.py -k test_payload_indexes_provisioned`). +- [x] Regenerate documentation and check consistency (`uv run devops docs generate --sync-readme`). + +## 5. Verification and CI Gate + +- [x] Run full test suite for multi-project indexing and RAG modules (`uv run pytest tests/test_rag_multi_project_indexer.py tests/test_rag_indexer_retriever.py tests/test_rag_qdrant.py tests/test_rag_chunker.py`). +- [x] Run fail-to-pass check to verify tests fail on unpatched code (`uv run devops ci fail-to-pass --base origin/main`). +- [x] Run full CI checks (`uv run devops ci`). + +## Workflow follow-up + +- Ingestion pass command `devops ai rag ingest` (#1389). +- Argo cluster workflow lane for continuous multi-repo RAG indexing (#1389 follow-up). +- Pending a person: run `devops ai rag index --force` once to rewrite points with project-scoped UUIDs. +- Pending a person: verify `devops ai rag query` returns distinct results for repository and knowledge base files. +- Pending a person: review the diff in tuicr (`tuicr -r origin/main..HEAD`). diff --git a/src/devops_cli/ai/rag/chunker.py b/src/devops_cli/ai/rag/chunker.py index 9e1b22b855..ec6201ca23 100644 --- a/src/devops_cli/ai/rag/chunker.py +++ b/src/devops_cli/ai/rag/chunker.py @@ -6,6 +6,7 @@ import hashlib import logging import mimetypes +import uuid import warnings from pathlib import Path @@ -315,7 +316,7 @@ def _make_code_chunk( content, language=language, symbols=sym_list, file_path=file_path ) return CodeChunk( - id=self._generate_id(file_path, start_line, end_line), + id=self._generate_id(file_path, start_line, end_line, project_name=project_name), file_path=file_path, start_line=start_line, end_line=end_line, @@ -590,7 +591,7 @@ def _chunk_tech_docs( if not sec_content: continue - c_id = self._generate_id(file_path, start_idx + 1, end_idx) + c_id = self._generate_id(file_path, start_idx + 1, end_idx, project_name=project_name) chunks.append( CodeChunk( id=c_id, @@ -622,7 +623,7 @@ def _create_window_chunk( project_name: str, ) -> CodeChunk: """Create a CodeChunk from a line-window or sub-window slice.""" - c_id = self._generate_id(file_path, start_line, end_line) + c_id = self._generate_id(file_path, start_line, end_line, project_name=project_name) meta = ( extract_doc_metadata(content, file_path=file_path) if category == "docs" @@ -653,7 +654,7 @@ def _split_large_chunk(self, chunk: CodeChunk) -> list[CodeChunk]: ) return [ CodeChunk( - id=self._generate_id(chunk.file_path, s, e), + id=self._generate_id(chunk.file_path, s, e, project_name=chunk.project_name), file_path=chunk.file_path, start_line=s, end_line=e, @@ -718,11 +719,15 @@ def _chunk_line_window( return chunks @staticmethod - def _generate_id(file_path: str, start_line: int, end_line: int) -> str: - """Generate a deterministic UUID-compatible SHA256 hex ID.""" - raw = f"{file_path}:{start_line}:{end_line}" - digest = hashlib.sha256(raw.encode("utf-8")).hexdigest() - return f"{digest[:8]}-{digest[8:12]}-{digest[12:16]}-{digest[16:20]}-{digest[20:32]}" + def _generate_id( + file_path: str, + start_line: int, + end_line: int, + project_name: str = "default", + ) -> str: + """Generate a deterministic UUID-5 ID based on project, relative path, and line range.""" + raw = f"{project_name}:{file_path}:{start_line}:{end_line}" + return str(uuid.uuid5(uuid.NAMESPACE_DNS, raw)) @staticmethod def _hash_content(content: str) -> str: diff --git a/src/devops_cli/ai/rag/indexer.py b/src/devops_cli/ai/rag/indexer.py index 82dde71bc2..55f2d26a1c 100644 --- a/src/devops_cli/ai/rag/indexer.py +++ b/src/devops_cli/ai/rag/indexer.py @@ -20,11 +20,13 @@ from devops_cli.config.constants import ( CONST_EXIT_FAILURE, CONST_INDEX_CACHE_FILENAME, + CONST_INDEX_COUNTS_FILENAME, CONST_RAG_INCOMPLETE_FILE_MARKER, CONST_RAG_KB_PROJECT, CONST_RAG_SKIPPED_LOCKFILES, ) from devops_cli.config.defaults import ( + DEFAULT_DRY_RUN_EMBEDDING_DIMENSION, DEFAULT_MAX_AST_FILE_SIZE_BYTES, DEFAULT_RAG_CACHE_DIR, DEFAULT_RAG_CHUNK_OVERLAP, @@ -35,6 +37,7 @@ from devops_cli.core.repo import is_ignored_by_git from devops_cli.exceptions import ConfigurationError, DevOpsCLIError from devops_cli.lang.en.errors import ERRORS +from devops_cli.output.file_writer import write_json_file from devops_cli.telemetry import record_metric, trace_span logger = logging.getLogger(__name__) @@ -200,27 +203,36 @@ def _get_single_collection_stat( ) -def _safe_delete_points_by_files( - qdrant: Any, - collection_name: str, - file_paths: Sequence[str], - *, - project_name: str | None = None, -) -> bool: - """Delete points for file paths in batches if supported, falling back to per-file deletion.""" - if not file_paths: - return True - if hasattr(qdrant, "delete_points_by_files"): - return bool( - qdrant.delete_points_by_files( - collection_name, file_paths, project_name=project_name, wait=False - ) - ) - if hasattr(qdrant, "delete_points_by_file"): - for f in file_paths: - qdrant.delete_points_by_file(collection_name, f, project_name=project_name) - return True - return False +def _collect_deleted_keys_by_project( + cache: dict[str, str], + file_hashes: dict[str, str], + scanned_projects: set[str], +) -> dict[str, list[str]]: + """Group deleted cache keys by project name.""" + current_keys = set(file_hashes.keys()) + by_proj: dict[str, list[str]] = defaultdict(list) + for k in cache: + proj, _, rel_path = k.partition(":") + if proj in scanned_projects and k not in current_keys and rel_path: + by_proj[proj].append(rel_path) + return by_proj + + +def _purge_deleted_batch( + qdrant: QdrantClient, + code_collection: str, + docs_collection: str, + proj: str, + chunk: list[str], + cache: dict[str, str], + save_cache_fn: Callable[[dict[str, str]], None], +) -> None: + """Purge a batch of deleted files and update local cache.""" + qdrant.delete_points_by_files(code_collection, chunk, project_name=proj, wait=True) + qdrant.delete_points_by_files(docs_collection, chunk, project_name=proj, wait=True) + for r in chunk: + cache.pop(f"{proj}:{r}", None) + save_cache_fn(cache) def _purge_deleted_vectors( @@ -230,37 +242,38 @@ def _purge_deleted_vectors( code_collection: str, docs_collection: str, save_cache_fn: Callable[[dict[str, str]], None], + *, + project: str | None = None, + projects: set[str] | Sequence[str] | None = None, progress_callback: Callable[[str, int, int], None] | None = None, ) -> int: """Purge obsolete points from Qdrant when files are deleted on disk.""" - scanned_projects = {k.partition(":")[0] for k in file_hashes.keys()} - current_keys = set(file_hashes.keys()) - deleted_keys = [ - k for k in cache if k.partition(":")[0] in scanned_projects and k not in current_keys - ] - if not deleted_keys: + if projects is not None: + scanned_projects = set(projects) + else: + scanned_projects = {k.partition(":")[0] for k in file_hashes} + if project: + scanned_projects.add(project) + + by_proj = _collect_deleted_keys_by_project(cache, file_hashes, scanned_projects) + total_deleted = sum(len(paths) for paths in by_proj.values()) + if total_deleted == 0: return 0 - total_deleted = len(deleted_keys) if progress_callback: progress_callback("Purging deleted files", 0, total_deleted) - by_proj: dict[str, list[str]] = defaultdict(list) - for dkey in deleted_keys: - dproj, _, d_rel_path = dkey.partition(":") - if d_rel_path: - by_proj[dproj].append(d_rel_path) - del cache[dkey] - processed = 0 for proj, rel_paths in by_proj.items(): - _safe_delete_points_by_files(qdrant, code_collection, rel_paths, project_name=proj) - _safe_delete_points_by_files(qdrant, docs_collection, rel_paths, project_name=proj) - processed += len(rel_paths) - if progress_callback: - progress_callback("Purging deleted files", processed, total_deleted) + for i in range(0, len(rel_paths), 100): + chunk = rel_paths[i : i + 100] + _purge_deleted_batch( + qdrant, code_collection, docs_collection, proj, chunk, cache, save_cache_fn + ) + processed += len(chunk) + if progress_callback: + progress_callback("Purging deleted files", processed, total_deleted) - save_cache_fn(cache) return total_deleted @@ -294,8 +307,8 @@ def _purge_obsolete_points( batch_size = 100 for i in range(0, len(rel_paths), batch_size): chunk = rel_paths[i : i + batch_size] - _safe_delete_points_by_files(qdrant, code_collection, chunk, project_name=fproj) - _safe_delete_points_by_files(qdrant, docs_collection, chunk, project_name=fproj) + qdrant.delete_points_by_files(code_collection, chunk, project_name=fproj, wait=True) + qdrant.delete_points_by_files(docs_collection, chunk, project_name=fproj, wait=True) processed += len(chunk) if progress_callback: progress_callback("Purging obsolete vectors", processed, total_files) @@ -342,7 +355,7 @@ def _resolve_indexing_target_metadata( pass if is_kb: - proj_name = "devops-cli-kb" + proj_name = CONST_RAG_KB_PROJECT rel_base = kb_dir else: proj_name = project or detect_project_name(file_path, root_dir) @@ -623,6 +636,7 @@ def __init__( self.docs_collection = docs_collection self.cache_dir = cache_dir self.cache_file = cache_dir / CONST_INDEX_CACHE_FILENAME + self.counts_file = cache_dir / CONST_INDEX_COUNTS_FILENAME self.chunker = SemanticChunker(chunk_size=chunk_size, chunk_overlap=chunk_overlap) def _load_cache(self) -> dict[str, str]: @@ -634,11 +648,48 @@ def _load_cache(self) -> dict[str, str]: return {} def _save_cache(self, cache: dict[str, str]) -> None: - try: - self.cache_dir.mkdir(parents=True, exist_ok=True) - self.cache_file.write_text(json.dumps(cache, indent=2), encoding="utf-8") - except Exception as exc: - logger.debug("Failed to write index cache: %s", exc) + self.cache_dir.mkdir(parents=True, exist_ok=True) + write_json_file(self.cache_file, cache, indent=2, atomic=True) + + def _load_counts(self) -> dict[str, dict[str, int]]: + if self.counts_file.exists(): + try: + data = json.loads(self.counts_file.read_text(encoding="utf-8")) + if isinstance(data, dict): + return data + except Exception as exc: + logger.debug("Failed to read index counts file: %s", exc) + return {} + + def _save_counts(self, counts: dict[str, dict[str, int]]) -> None: + self.cache_dir.mkdir(parents=True, exist_ok=True) + write_json_file(self.counts_file, counts, indent=2, atomic=True) + + def _check_project_points_intact(self, project: str) -> tuple[bool, str | None]: + counts = self._load_counts() + if project in counts: + proj_counts = counts[project] + for coll in (self.code_collection, self.docs_collection): + prev_count = proj_counts.get(coll, 0) + if prev_count > 0: + current = self.qdrant.count_points(coll, {"project_name": project}) + if current == 0: + return False, coll + return True, None + + cache = self._load_cache() + if any(k.partition(":")[0] == project for k in cache): + code_count = self.qdrant.count_points(self.code_collection, {"project_name": project}) + docs_count = self.qdrant.count_points(self.docs_collection, {"project_name": project}) + if code_count == 0 and docs_count == 0: + return False, f"{self.code_collection}, {self.docs_collection}" + + return True, None + + def points_intact(self, project: str) -> bool: + """Check whether the points for a project remain intact in Qdrant collections.""" + intact, _ = self._check_project_points_intact(project) + return intact @staticmethod def collect_files(root_dir: Path) -> list[Path]: @@ -687,12 +738,155 @@ def index_knowledge_base( return self.index_workspace( kb_dir, - project="devops-cli-kb", + project=CONST_RAG_KB_PROJECT, force=force, include_kb=False, progress_callback=progress_callback, ) + def _ensure_collections(self) -> None: + """Ensure collections exist and have payload schema indexes.""" + for coll_name in {self.code_collection, self.docs_collection}: + _verify_collection_compatibility_for_indexing(self.qdrant, self.embedder, coll_name) + + model_dim = ( + _extract_embedder_dimension(self.embedder) or DEFAULT_DRY_RUN_EMBEDDING_DIMENSION + ) + if hasattr(self.qdrant, "ensure_collection"): + self.qdrant.ensure_collection(self.code_collection, vector_size=model_dim) + self.qdrant.ensure_collection(self.docs_collection, vector_size=model_dim) + + def _resolve_scanned_projects( + self, + files: Sequence[Path], + root_dir: Path, + kb_dir: Path, + project: str | None, + include_kb: bool, + ) -> set[str]: + """Determine unique project names across collected files.""" + if project: + scanned = {project} + else: + scanned = { + _resolve_indexing_target_metadata(f, root_dir, kb_dir, None)[0] for f in files + } + if not scanned: + scanned = {detect_project_name(root_dir, root_dir)} + if include_kb: + scanned.add(CONST_RAG_KB_PROJECT) + return scanned + + def _prepare_force_projects(self, scanned_projects: set[str], *, force: bool) -> set[str]: + """Detect and purge projects requiring full re-indexing.""" + force_projects: set[str] = set() + if force: + force_projects.update(scanned_projects) + else: + for proj in sorted(scanned_projects): + intact, lost_coll = self._check_project_points_intact(proj) + if not intact: + logger.info( + "Project '%s' lost points in collection '%s'; refilling index", + proj, + lost_coll, + ) + force_projects.add(proj) + + for proj in sorted(force_projects): + self.qdrant.delete_points_by_project(self.code_collection, proj, wait=True) + self.qdrant.delete_points_by_project(self.docs_collection, proj, wait=True) + + return force_projects + + def _save_project_counts(self, scanned_projects: set[str]) -> None: + """Record point counts per project and collection to counts file.""" + counts = self._load_counts() + for p in sorted(scanned_projects): + counts[p] = { + self.code_collection: self.qdrant.count_points( + self.code_collection, {"project_name": p} + ), + self.docs_collection: self.qdrant.count_points( + self.docs_collection, {"project_name": p} + ), + } + self._save_counts(counts) + + def _scan_workspace_files( + self, + files: Sequence[Path], + root_dir: Path, + kb_dir: Path, + project: str | None, + cache: dict[str, str], + force_projects: set[str], + *, + force: bool, + progress_callback: Callable[[str, int, int], None] | None, + ) -> tuple[dict[str, str], list[CodeChunk], list[tuple[Path, str, str]]]: + """Scan and chunk all indexable workspace files.""" + file_hashes: dict[str, str] = {} + all_chunks: list[CodeChunk] = [] + files_to_reindex: list[tuple[Path, str, str]] = [] + + for idx, file_path in enumerate(files, 1): + if progress_callback: + progress_callback("Scanning files", idx, len(files)) + + proj_name, _, _ = _resolve_indexing_target_metadata( + file_path, root_dir, kb_dir, project + ) + file_forced = force or (proj_name in force_projects) + scanned = _scan_single_file_for_indexing( + file_path, + root_dir, + kb_dir, + project, + self.chunker, + cache, + file_hashes, + file_forced, + ) + if scanned is not None: + file_info, file_chunks = scanned + files_to_reindex.append(file_info) + all_chunks.extend(file_chunks) + + return file_hashes, all_chunks, files_to_reindex + + def _upsert_partitioned_chunks( + self, + all_chunks: list[CodeChunk], + cache: dict[str, str], + file_hashes: dict[str, str], + progress_callback: Callable[[str, int, int], None] | None, + ) -> tuple[list[CodeChunk], list[CodeChunk]]: + """Partition chunks into code and docs, then upsert to Qdrant.""" + code_chunks, doc_chunks = _partition_chunks(all_chunks) + pending = Counter(f"{c.project_name}:{c.file_path}" for c in all_chunks) + if code_chunks: + self._upsert_chunks( + self.code_collection, + code_chunks, + cache, + file_hashes, + pending=pending, + progress_callback=progress_callback, + progress_title="Embedding code", + ) + if doc_chunks: + self._upsert_chunks( + self.docs_collection, + doc_chunks, + cache, + file_hashes, + pending=pending, + progress_callback=progress_callback, + progress_title="Embedding docs", + ) + return code_chunks, doc_chunks + def index_workspace( self, root_dir: Path, @@ -703,8 +897,7 @@ def index_workspace( progress_callback: Callable[[str, int, int], None] | None = None, ) -> dict[str, Any]: """Incrementally index workspace files into Qdrant.""" - for coll_name in {self.code_collection, self.docs_collection}: - _verify_collection_compatibility_for_indexing(self.qdrant, self.embedder, coll_name) + self._ensure_collections() with trace_span( "ai.rag.index_workspace", @@ -716,31 +909,35 @@ def index_workspace( }, ) as root_span: files = _collect_all_indexing_files(self.collect_files, root_dir, include_kb) - cache = {} if force else self._load_cache() - file_hashes: dict[str, str] = {} - - all_chunks: list[CodeChunk] = [] - files_to_reindex: list[tuple[Path, str, str]] = [] - from devops_cli.ai.kb import get_knowledge_base_dir kb_dir = get_knowledge_base_dir().resolve() + scanned_projects = self._resolve_scanned_projects( + files, root_dir, kb_dir, project, include_kb + ) + force_projects = self._prepare_force_projects(scanned_projects, force=force) - for idx, file_path in enumerate(files, 1): - if progress_callback: - progress_callback("Scanning files", idx, len(files)) + cache = self._load_cache() + if force_projects: + cache = { + k: v for k, v in cache.items() if k.partition(":")[0] not in force_projects + } - scanned = _scan_single_file_for_indexing( - file_path, root_dir, kb_dir, project, self.chunker, cache, file_hashes, force - ) - if scanned is not None: - file_info, file_chunks = scanned - files_to_reindex.append(file_info) - all_chunks.extend(file_chunks) + file_hashes, all_chunks, files_to_reindex = self._scan_workspace_files( + files, + root_dir, + kb_dir, + project, + cache, + force_projects, + force=force, + progress_callback=progress_callback, + ) - # Purge files deleted from disk since last index (scoped to scanned projects) + # Purge files deleted from disk since last index (scoped to scanned projects not forced) removed_files_count = 0 - if not force: + projects_to_purge = scanned_projects - force_projects + if projects_to_purge: removed_files_count = _purge_deleted_vectors( self.qdrant, cache, @@ -748,10 +945,12 @@ def index_workspace( self.code_collection, self.docs_collection, self._save_cache, + projects=projects_to_purge, progress_callback=progress_callback, ) if not all_chunks: + self._save_project_counts(scanned_projects) root_span.set_attribute("rag.indexed_files", 0) root_span.set_attribute("rag.total_chunks", 0) return { @@ -777,32 +976,11 @@ def index_workspace( progress_callback=progress_callback, ) - code_chunks, doc_chunks = _partition_chunks(all_chunks) - pending = Counter(f"{c.project_name}:{c.file_path}" for c in all_chunks) - - # Upsert chunks to their respective collections with batch embeddings - if code_chunks: - self._upsert_chunks( - self.code_collection, - code_chunks, - cache, - file_hashes, - pending=pending, - progress_callback=progress_callback, - progress_title="Embedding code", - ) - if doc_chunks: - self._upsert_chunks( - self.docs_collection, - doc_chunks, - cache, - file_hashes, - pending=pending, - progress_callback=progress_callback, - progress_title="Embedding docs", - ) - + code_chunks, doc_chunks = self._upsert_partitioned_chunks( + all_chunks, cache, file_hashes, progress_callback + ) self._save_cache(cache) + self._save_project_counts(scanned_projects) record_metric("rag.indexed_files", len(files) - len(files_to_reindex)) record_metric("rag.total_chunks", len(all_chunks)) diff --git a/src/devops_cli/ai/rag/qdrant.py b/src/devops_cli/ai/rag/qdrant.py index 10a610978c..722cfcb98e 100644 --- a/src/devops_cli/ai/rag/qdrant.py +++ b/src/devops_cli/ai/rag/qdrant.py @@ -337,6 +337,7 @@ def get_collection_info(self, name: str) -> dict[str, Any]: "points_count": points_count, "vectors_count": vectors_count, "vector_size": vector_size, + "payload_schema": getattr(info, "payload_schema", {}) or {}, } except Exception as exc: err_str = str(exc) @@ -377,6 +378,7 @@ def ensure_collection( }, ) elif isinstance(curr_size, int): + self._ensure_payload_indexes(name, info.get("payload_schema", {})) self._verified_collections[name] = vector_size return True @@ -391,12 +393,52 @@ def ensure_collection( "create_collection", name, ) + self._ensure_payload_indexes(name, {}) self._verified_collections[name] = vector_size return True except Exception as exc: logger.error("Error creating collection %s in Qdrant: %s", name, exc) raise QdrantClientError(f"Error creating collection '{name}': {exc}") from exc + def _ensure_payload_indexes(self, name: str, existing_schema: dict[str, Any]) -> None: + """Create missing payload indexes on the collection.""" + from devops_cli.config.constants import CONST_RAG_PAYLOAD_INDEXES + + for spec in CONST_RAG_PAYLOAD_INDEXES: + field_name = spec["field_name"] + if field_name in existing_schema: + continue + is_tenant = spec.get("is_tenant", False) + if is_tenant: + field_schema = qmodels.KeywordIndexParams( + type=qmodels.PayloadSchemaType.KEYWORD, + is_tenant=True, + ) + else: + field_schema = qmodels.PayloadSchemaType.KEYWORD + + def _create_idx( + client: NativeQdrantClient, fn: str = field_name, fs: Any = field_schema + ) -> Any: + return client.create_payload_index( + collection_name=name, + field_name=fn, + field_schema=fs, + wait=True, + ) + + try: + self._execute_with_retry( + _create_idx, + "create_payload_index", + f"{name}:{field_name}", + ) + except Exception as exc: + logger.error("Error creating payload index %s on %s: %s", field_name, name, exc) + raise QdrantClientError( + f"Error creating payload index '{field_name}' on collection '{name}': {exc}" + ) from exc + def delete_collection(self, name: str) -> bool: """Delete a collection from Qdrant.""" self._verified_collections.pop(name, None) @@ -581,12 +623,11 @@ def delete_points_by_files( file_paths: Sequence[str], *, project_name: str | None = None, - wait: bool = False, + wait: bool = True, ) -> bool: """Delete all indexed chunks for multiple file paths in batches, optionally scoped to a project.""" if not file_paths: return True - success = True batch_size = 100 for i in range(0, len(file_paths), batch_size): batch = list(file_paths[i : i + batch_size]) @@ -629,11 +670,47 @@ def _delete_batch( project_name, exc, ) - success = False - return success + raise QdrantClientError(f"Delete failed in '{name}': {exc}") from exc + return True - def delete_points_by_file( - self, name: str, file_path: str, *, project_name: str | None = None + def delete_points_by_project( + self, + name: str, + project_name: str, + *, + wait: bool = True, ) -> bool: - """Delete all indexed chunks for a file path, optionally scoped to a project.""" - return self.delete_points_by_files(name, [file_path], project_name=project_name, wait=False) + """Delete all indexed chunks for a project.""" + if not project_name: + return True + proj_filter = qmodels.Filter( + must=[ + qmodels.FieldCondition( + key="project_name", + match=qmodels.MatchValue(value=project_name), + ) + ] + ) + + def _delete_proj(client: NativeQdrantClient) -> Any: + return client.delete( + collection_name=name, + points_selector=qmodels.FilterSelector(filter=proj_filter), + wait=wait, + ) + + try: + self._execute_with_retry( + _delete_proj, + "delete_points_by_project", + f"{name}, project={project_name}", + ) + return True + except Exception as exc: + logger.debug( + "Failed to delete points by project in %s (project: %s): %s", + name, + project_name, + exc, + ) + raise QdrantClientError(f"Delete by project failed in '{name}': {exc}") from exc diff --git a/src/devops_cli/ai/tools/__init__.py b/src/devops_cli/ai/tools/__init__.py index 359fe87d06..be646c32c9 100644 --- a/src/devops_cli/ai/tools/__init__.py +++ b/src/devops_cli/ai/tools/__init__.py @@ -123,7 +123,7 @@ def execute(self, ctx: Any = None, **kwargs: Any) -> Any: from devops_cli.exceptions.ai import ApprovalRequired raise ApprovalRequired(f"Tool '{self.name}' requires human approval") - fn = cast(Callable[..., Any], self.function) + fn: Any = self.function res = fn(ctx, **kwargs) if self.takes_ctx and ctx is not None else fn(**kwargs) if inspect.isawaitable(res): return _run_coroutine_sync(res) diff --git a/src/devops_cli/commands/rag.py b/src/devops_cli/commands/rag.py index 5147a1508b..70bb828f7c 100644 --- a/src/devops_cli/commands/rag.py +++ b/src/devops_cli/commands/rag.py @@ -617,7 +617,10 @@ def clear_cmd( print_success(f"Cleared collection: {coll}") # Remove local cache - from devops_cli.config.constants import CONST_INDEX_CACHE_FILENAME + from devops_cli.config.constants import ( + CONST_INDEX_CACHE_FILENAME, + CONST_INDEX_COUNTS_FILENAME, + ) from devops_cli.config.settings import load_settings from devops_cli.core.repo import resolve_data_path @@ -626,6 +629,9 @@ def clear_cmd( if cache_file.exists(): cache_file.unlink() print_success(MESSAGES.rag.reset_cache_success) + counts_file = rag_dir / CONST_INDEX_COUNTS_FILENAME + if counts_file.exists(): + counts_file.unlink() # ============================================================================= diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index 543e30f607..c88630ff76 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -677,6 +677,7 @@ CONST_SAMPLES_DIR_NAME = "samples" CONST_RUNS_DIR_NAME = "runs" CONST_INDEX_CACHE_FILENAME = "index_cache.json" +CONST_INDEX_COUNTS_FILENAME: Final[str] = "index_counts.json" # ── Memory & Byte Sizing Constants ──────────────────────────────────────────── CONST_FP32_BYTES_PER_ELEMENT: int = 4 CONST_KILOBYTE_BYTES: int = 1024 @@ -2358,6 +2359,12 @@ class WebhookExposure(StrEnum): # Project identifier used for bundled DevOps CLI Knowledge Base chunks in Qdrant CONST_RAG_KB_PROJECT: Final[str] = "devops-cli-kb" +# Payload fields indexed when ensuring collections in Qdrant (#1388, #1389) +CONST_RAG_PAYLOAD_INDEXES: Final[tuple[dict[str, Any], ...]] = ( + {"field_name": "project_name", "field_schema": "keyword", "is_tenant": True}, + {"field_name": "file_path", "field_schema": "keyword"}, +) + # Helm releases that deploy DaemonSets across all cluster nodes CONST_HELM_DAEMONSET_RELEASES: Final[frozenset[str]] = frozenset( {"k8s-monitoring", "dcgm-exporter"} diff --git a/tests/fixtures/swallowed_failures_ceilings.json b/tests/fixtures/swallowed_failures_ceilings.json index 575b08671a..d71b693239 100644 --- a/tests/fixtures/swallowed_failures_ceilings.json +++ b/tests/fixtures/swallowed_failures_ceilings.json @@ -34,7 +34,7 @@ "src/devops_cli/ai/rag/investigator.py": 2, "src/devops_cli/ai/rag/library_store.py": 2, "src/devops_cli/ai/rag/metadata.py": 2, - "src/devops_cli/ai/rag/qdrant.py": 3, + "src/devops_cli/ai/rag/qdrant.py": 2, "src/devops_cli/ai/rag/retriever.py": 1, "src/devops_cli/ai/repomap.py": 2, "src/devops_cli/ai/response_cache.py": 4, diff --git a/tests/test_rag_indexer_retriever.py b/tests/test_rag_indexer_retriever.py index bcc4208394..5e0c7b1f77 100644 --- a/tests/test_rag_indexer_retriever.py +++ b/tests/test_rag_indexer_retriever.py @@ -66,21 +66,15 @@ def delete_points_by_files( file_paths: Sequence[str], *, project_name: str | None = None, - wait: bool = False, - ) -> bool: - for f in file_paths: - self.delete_points_by_file(name, f, project_name=project_name) - return True - - def delete_points_by_file( - self, name: str, file_path: str, *, project_name: str | None = None + wait: bool = True, ) -> bool: if name in self.collections: + path_set = set(file_paths) self.collections[name] = [ p for p in self.collections[name] if not ( - p.get("payload", {}).get("file_path") == file_path + p.get("payload", {}).get("file_path") in path_set and ( project_name is None or p.get("payload", {}).get("project_name") == project_name @@ -89,6 +83,33 @@ def delete_points_by_file( ] return True + def delete_points_by_project( + self, + name: str, + project_name: str, + *, + wait: bool = True, + ) -> bool: + if name in self.collections: + self.collections[name] = [ + p + for p in self.collections[name] + if p.get("payload", {}).get("project_name") != project_name + ] + return True + + def count_points(self, name: str, filter_payload: dict | None = None) -> int: + if name not in self.collections: + return 0 + if not filter_payload: + return len(self.collections[name]) + count = 0 + for p in self.collections[name]: + payload = p.get("payload", {}) + if all(payload.get(k) == v for k, v in filter_payload.items()): + count += 1 + return count + def search_points( self, name: str, diff --git a/tests/test_rag_kb_sync.py b/tests/test_rag_kb_sync.py index 68040fe1cf..3f1bc53d99 100644 --- a/tests/test_rag_kb_sync.py +++ b/tests/test_rag_kb_sync.py @@ -11,6 +11,7 @@ from __future__ import annotations +from collections.abc import Sequence from pathlib import Path from typing import Any, cast from unittest.mock import patch @@ -93,6 +94,44 @@ def upsert_points( self.collections[name].extend(points) return len(points) + def delete_points_by_files( + self, + name: str, + file_paths: Sequence[str], + *, + project_name: str | None = None, + wait: bool = True, + ) -> bool: + if name in self.collections: + path_set = set(file_paths) + self.collections[name] = [ + p + for p in self.collections[name] + if not ( + p.get("payload", {}).get("file_path") in path_set + and ( + project_name is None + or p.get("payload", {}).get("project_name") == project_name + ) + ) + ] + return True + + def delete_points_by_project( + self, + name: str, + project_name: str, + *, + wait: bool = True, + ) -> bool: + if name in self.collections: + self.collections[name] = [ + p + for p in self.collections[name] + if p.get("payload", {}).get("project_name") != project_name + ] + return True + class DummyEmbedder: """Mock embedder providing deterministic unit vectors.""" diff --git a/tests/test_rag_multi_project_indexer.py b/tests/test_rag_multi_project_indexer.py index 971c746085..28afb55fe7 100644 --- a/tests/test_rag_multi_project_indexer.py +++ b/tests/test_rag_multi_project_indexer.py @@ -1,23 +1,231 @@ -"""Unit tests for multi-project indexing and project auto-detection.""" +"""Unit tests for multi-project indexing, project auto-detection, and multitenancy isolation.""" from __future__ import annotations +import json from collections.abc import Sequence from pathlib import Path +from typing import Any import pytest +from devops_cli.ai.rag.chunker import SemanticChunker from devops_cli.ai.rag.embeddings import EmbeddingsEngine from devops_cli.ai.rag.indexer import WorkspaceIndexer, detect_project_name -from devops_cli.ai.rag.qdrant import QdrantClient +from devops_cli.ai.rag.qdrant import QdrantClient, QdrantClientError +from devops_cli.config import constants +from devops_cli.config.constants import ( + CONST_INDEX_CACHE_FILENAME, + CONST_RAG_KB_PROJECT, +) from devops_cli.config.settings import AIConfig +CONST_INDEX_COUNTS_FILENAME = getattr(constants, "CONST_INDEX_COUNTS_FILENAME", "index_counts.json") +CONST_RAG_PAYLOAD_INDEXES = getattr( + constants, + "CONST_RAG_PAYLOAD_INDEXES", + ( + {"field_name": "project_name", "field_schema": "keyword", "is_tenant": True}, + {"field_name": "file_path", "field_schema": "keyword"}, + ), +) + pytestmark = [ pytest.mark.usefixtures("mock_keyring"), pytest.mark.unreachable("example.com"), ] +class FakeQdrantClient(QdrantClient): + """Hermetic in-memory fake for Qdrant client operations.""" + + def __init__(self, **kwargs: Any) -> None: + super().__init__(base_url="http://example.com:6333", allow_private_network=True) + self.collections: dict[str, dict[str | int, dict[str, Any]]] = {} + self.payload_schemas: dict[str, dict[str, Any]] = {} + self.upsert_calls: list[dict[str, Any]] = [] + self.delete_calls: list[dict[str, Any]] = [] + self.count_calls: list[dict[str, Any]] = [] + self.index_calls: list[dict[str, Any]] = [] + self.raise_on_delete: bool = False + self.raise_on_count: bool = False + + def is_alive(self) -> bool: + return True + + def get_collection_info(self, name: str) -> dict[str, Any]: + if name not in self.collections: + return {} + points = self.collections[name] + return { + "status": "green", + "points_count": len(points), + "vectors_count": len(points), + "vector_size": 384, + "payload_schema": dict(self.payload_schemas.get(name, {})), + } + + def ensure_collection( + self, + name: str, + vector_size: int = 384, + distance: str = "Cosine", + quantize: bool = False, + ) -> bool: + if name not in self.collections: + self.collections[name] = {} + self.payload_schemas[name] = {} + for spec in CONST_RAG_PAYLOAD_INDEXES: + fn = spec["field_name"] + if fn not in self.payload_schemas[name]: + self.create_payload_index( + name, fn, field_schema=spec.get("field_schema", "keyword") + ) + return True + + def create_payload_index( + self, + collection_name: str, + field_name: str, + field_schema: Any = None, + wait: bool = True, + **kwargs: Any, + ) -> Any: + self.index_calls.append( + { + "collection": collection_name, + "field_name": field_name, + "field_schema": field_schema, + "wait": wait, + } + ) + if collection_name in self.payload_schemas: + self.payload_schemas[collection_name][field_name] = field_schema + return True + + def upsert_points( + self, + name: str, + points: list[dict[str, Any]], + *, + batch_size: int = 100, + ) -> int: + self.ensure_collection(name) + for p in points: + pid = p["id"] + self.collections[name][pid] = dict(p) + self.upsert_calls.append({"collection": name, "count": len(points)}) + return len(points) + + def delete_points_by_files( + self, + name: str, + file_paths: Sequence[str], + *, + project_name: str | None = None, + wait: bool = True, + ) -> bool: + self.delete_calls.append( + { + "collection": name, + "file_paths": list(file_paths), + "project_name": project_name, + "wait": wait, + } + ) + if self.raise_on_delete: + raise QdrantClientError("Simulated delete failure") + if name not in self.collections: + return True + to_del: list[str | int] = [] + for pid, p in self.collections[name].items(): + payload = p.get("payload", {}) + if payload.get("file_path") in file_paths: + if project_name is None or payload.get("project_name") == project_name: + to_del.append(pid) + for pid in to_del: + del self.collections[name][pid] + return True + + def delete_points_by_project( + self, + name: str, + project_name: str, + *, + wait: bool = True, + ) -> bool: + self.delete_calls.append( + { + "collection": name, + "project_name": project_name, + "wait": wait, + } + ) + if self.raise_on_delete: + raise QdrantClientError("Simulated delete failure") + if name not in self.collections: + return True + to_del = [ + pid + for pid, p in self.collections[name].items() + if p.get("payload", {}).get("project_name") == project_name + ] + for pid in to_del: + del self.collections[name][pid] + return True + + def count_points(self, name: str, filter_payload: dict[str, Any] | None = None) -> int: + self.count_calls.append({"collection": name, "filter": filter_payload}) + if self.raise_on_count: + raise QdrantClientError("Simulated count failure") + if name not in self.collections: + return 0 + if not filter_payload: + return len(self.collections[name]) + count = 0 + for p in self.collections[name].values(): + payload = p.get("payload", {}) + match = True + for k, v in filter_payload.items(): + if payload.get(k) != v: + match = False + break + if match: + count += 1 + return count + + def scroll_points( + self, + name: str, + limit: int = 1, + with_payload: bool = True, + **kwargs: Any, + ) -> list[dict[str, Any]]: + if name not in self.collections: + return [] + return list(self.collections[name].values())[:limit] + + def delete_collection(self, name: str) -> bool: + self.collections.pop(name, None) + self.payload_schemas.pop(name, None) + return True + + +class FakeEmbedder(EmbeddingsEngine): + """Hermetic deterministic embedder for indexing tests.""" + + def __init__(self, dimension: int = 384) -> None: + super().__init__(AIConfig(provider="custom", ollama_urls=[]), valkey_client=None) + self._dim = dimension + + @property + def dimension(self) -> int: + return self._dim + + def _dispatch_embed(self, prefixed_miss: list[str]) -> list[list[float]]: + return [[0.1] * self._dim for _ in prefixed_miss] + + def test_detect_project_name(tmp_path: Path) -> None: repo_a = tmp_path / "repos" / "frontend-app" repo_a.mkdir(parents=True) @@ -30,58 +238,25 @@ def test_detect_project_name(tmp_path: Path) -> None: def test_multi_project_indexing(tmp_path: Path) -> None: - # Repo 1: Go backend go_repo = tmp_path / "go-service" go_repo.mkdir() (go_repo / "go.mod").write_text("module go-service", encoding="utf-8") (go_repo / "main.go").write_text("package main\nfunc Run() {}", encoding="utf-8") - # Repo 2: Rust service rs_repo = tmp_path / "rs-service" rs_repo.mkdir() (rs_repo / "Cargo.toml").write_text('[package]\nname = "rs-service"', encoding="utf-8") (rs_repo / "lib.rs").write_text("pub fn compute() {}", encoding="utf-8") - # Documentation directory docs_dir = tmp_path / "wiki" docs_dir.mkdir() (docs_dir / "index.md").write_text("# Team Wiki\nWelcome to internal docs.", encoding="utf-8") - upserted: dict[str, list[dict]] = {} - - class DummyQdrant(QdrantClient): - def is_alive(self) -> bool: - return True - - def ensure_collection(self, collection_name: str, vector_size: int = 384) -> bool: - return True - - def upsert_points(self, collection_name: str, points: list[dict]) -> bool: - upserted.setdefault(collection_name, []).extend(points) - return True - - def delete_points_by_files( - self, - collection_name: str, - file_paths: Sequence[str], - *, - project_name: str | None = None, - wait: bool = False, - ) -> bool: - return True - - def delete_points_by_file( - self, collection_name: str, file_path: str, project_name: str | None = None - ) -> bool: - return True - - class DummyEmbedder(EmbeddingsEngine): - def _dispatch_embed(self, prefixed_miss: list[str]) -> list[list[float]]: - return [[0.1] * 384 for _ in prefixed_miss] - + qdrant = FakeQdrantClient() + embedder = FakeEmbedder() indexer = WorkspaceIndexer( - qdrant=DummyQdrant(base_url="http://example.com:6333", allow_private_network=True), - embedder=DummyEmbedder(AIConfig(provider="custom", ollama_urls=[]), valkey_client=None), + qdrant=qdrant, + embedder=embedder, code_collection="test_code", docs_collection="test_docs", cache_dir=tmp_path / ".cache", @@ -92,11 +267,422 @@ def _dispatch_embed(self, prefixed_miss: list[str]) -> list[list[float]]: assert stats["code_chunks"] >= 2 assert stats["doc_chunks"] >= 1 - # Check project tags in payloads - code_points = upserted.get("test_code", []) + code_points = list(qdrant.collections.get("test_code", {}).values()) projects = {p["payload"]["project_name"] for p in code_points} assert "go-service" in projects assert "rs-service" in projects - doc_points = upserted.get("test_docs", []) - assert any(p["payload"]["category"] == "docs" for p in doc_points) + +def test_chunk_ids_scoped_by_project(tmp_path: Path) -> None: + f1 = tmp_path / "README.md" + f1.write_text("line 1\nline 2\nline 3\n", encoding="utf-8") + chunker = SemanticChunker() + c1 = chunker.chunk_file(f1, relative_to=tmp_path, project_name="project-a") + c2 = chunker.chunk_file(f1, relative_to=tmp_path, project_name="project-b") + assert len(c1) > 0 + assert len(c2) > 0 + assert c1[0].id != c2[0].id + + +def test_readme_collision_resolved_between_tree_and_knowledge_base( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + repo_dir = tmp_path / "repo" + repo_dir.mkdir() + (repo_dir / "README.md").write_text( + "# Project\n" + "\n".join(f"line {i}" for i in range(1, 50)), encoding="utf-8" + ) + + kb_dir = tmp_path / "kb" + kb_dir.mkdir() + (kb_dir / "README.md").write_text( + "# KB\n" + "\n".join(f"line {i}" for i in range(1, 50)), encoding="utf-8" + ) + monkeypatch.setattr("devops_cli.ai.kb.get_knowledge_base_dir", lambda: kb_dir) + + qdrant = FakeQdrantClient() + embedder = FakeEmbedder() + indexer = WorkspaceIndexer( + qdrant=qdrant, + embedder=embedder, + code_collection="test_code", + docs_collection="test_docs", + cache_dir=tmp_path / ".cache", + ) + indexer.index_workspace(repo_dir, include_kb=True) + docs = qdrant.collections.get("test_docs", {}) + projs = {p["payload"]["project_name"] for p in docs.values()} + assert "repo" in projs + assert CONST_RAG_KB_PROJECT in projs + + repo_points = [p for p in docs.values() if p["payload"]["project_name"] == "repo"] + kb_points = [p for p in docs.values() if p["payload"]["project_name"] == CONST_RAG_KB_PROJECT] + assert len(repo_points) > 0 + assert len(kb_points) > 0 + + +def test_two_projects_with_same_readme_keep_own_points_and_deleting_one_leaves_other( + tmp_path: Path, +) -> None: + repo_a = tmp_path / "repo-a" + repo_a.mkdir() + (repo_a / "README.md").write_text( + "# Common Title\nContent common to both repos.", encoding="utf-8" + ) + + repo_b = tmp_path / "repo-b" + repo_b.mkdir() + (repo_b / "README.md").write_text( + "# Common Title\nContent common to both repos.", encoding="utf-8" + ) + + qdrant = FakeQdrantClient() + embedder = FakeEmbedder() + cache_dir = tmp_path / ".cache" + indexer = WorkspaceIndexer( + qdrant=qdrant, + embedder=embedder, + code_collection="test_code", + docs_collection="test_docs", + cache_dir=cache_dir, + ) + indexer.index_workspace(repo_a, project="proj-a") + indexer.index_workspace(repo_b, project="proj-b") + + docs = qdrant.collections.get("test_docs", {}) + pts_a = [p for p in docs.values() if p["payload"]["project_name"] == "proj-a"] + pts_b = [p for p in docs.values() if p["payload"]["project_name"] == "proj-b"] + assert len(pts_a) > 0 + assert len(pts_b) > 0 + + (repo_a / "README.md").unlink() + indexer.index_workspace(repo_a, project="proj-a") + + docs_after = qdrant.collections.get("test_docs", {}) + pts_a_after = [p for p in docs_after.values() if p["payload"]["project_name"] == "proj-a"] + pts_b_after = [p for p in docs_after.values() if p["payload"]["project_name"] == "proj-b"] + assert len(pts_a_after) == 0 + assert len(pts_b_after) > 0 + + +def test_delete_that_raises_leaves_cache_entry_and_next_run_deletes_points(tmp_path: Path) -> None: + repo = tmp_path / "repo" + repo.mkdir() + doc_file = repo / "doc.md" + doc_file.write_text("# Doc\nSome text.", encoding="utf-8") + + qdrant = FakeQdrantClient() + embedder = FakeEmbedder() + cache_dir = tmp_path / ".cache" + indexer = WorkspaceIndexer( + qdrant=qdrant, + embedder=embedder, + code_collection="test_code", + docs_collection="test_docs", + cache_dir=cache_dir, + ) + indexer.index_workspace(repo, project="proj-x") + assert "proj-x:doc.md" in indexer._load_cache() + + doc_file.unlink() + qdrant.raise_on_delete = True + with pytest.raises(QdrantClientError): + indexer.index_workspace(repo, project="proj-x") + + assert "proj-x:doc.md" in indexer._load_cache() + + qdrant.raise_on_delete = False + indexer.index_workspace(repo, project="proj-x") + assert "proj-x:doc.md" not in indexer._load_cache() + docs = qdrant.collections.get("test_docs", {}) + assert len([p for p in docs.values() if p["payload"]["project_name"] == "proj-x"]) == 0 + + +def test_deleting_every_file_of_project_purges_all_points(tmp_path: Path) -> None: + repo = tmp_path / "repo" + repo.mkdir() + f1 = repo / "file1.py" + f1.write_text("def a(): pass\n", encoding="utf-8") + f2 = repo / "file2.py" + f2.write_text("def b(): pass\n", encoding="utf-8") + + qdrant = FakeQdrantClient() + embedder = FakeEmbedder() + cache_dir = tmp_path / ".cache" + indexer = WorkspaceIndexer( + qdrant=qdrant, + embedder=embedder, + code_collection="test_code", + docs_collection="test_docs", + cache_dir=cache_dir, + ) + indexer.index_workspace(repo, project="proj-del-all") + assert len(qdrant.collections.get("test_code", {})) > 0 + + f1.unlink() + f2.unlink() + indexer.index_workspace(repo, project="proj-del-all") + + code_points = [ + p + for p in qdrant.collections.get("test_code", {}).values() + if p["payload"]["project_name"] == "proj-del-all" + ] + assert len(code_points) == 0 + cache = indexer._load_cache() + assert not any(k.startswith("proj-del-all:") for k in cache) + + +def test_force_on_project_a_keeps_project_b_cache_entries(tmp_path: Path) -> None: + repo_a = tmp_path / "repo-a" + repo_a.mkdir() + (repo_a / "a.py").write_text("def a(): pass\n", encoding="utf-8") + + repo_b = tmp_path / "repo-b" + repo_b.mkdir() + (repo_b / "b.py").write_text("def b(): pass\n", encoding="utf-8") + + qdrant = FakeQdrantClient() + embedder = FakeEmbedder() + cache_dir = tmp_path / ".cache" + indexer = WorkspaceIndexer( + qdrant=qdrant, + embedder=embedder, + code_collection="test_code", + docs_collection="test_docs", + cache_dir=cache_dir, + ) + indexer.index_workspace(repo_a, project="proj-a") + indexer.index_workspace(repo_b, project="proj-b") + + cache = indexer._load_cache() + assert "proj-a:a.py" in cache + assert "proj-b:b.py" in cache + + indexer.index_workspace(repo_a, project="proj-a", force=True) + + cache_after = indexer._load_cache() + assert "proj-a:a.py" in cache_after + assert "proj-b:b.py" in cache_after + + +def test_file_deleted_between_two_runs_with_force_leaves_no_point(tmp_path: Path) -> None: + repo = tmp_path / "repo" + repo.mkdir() + f1 = repo / "keep.py" + f1.write_text("def keep(): pass\n", encoding="utf-8") + f2 = repo / "del_me.py" + f2.write_text("def del_me(): pass\n", encoding="utf-8") + + qdrant = FakeQdrantClient() + embedder = FakeEmbedder() + cache_dir = tmp_path / ".cache" + indexer = WorkspaceIndexer( + qdrant=qdrant, + embedder=embedder, + code_collection="test_code", + docs_collection="test_docs", + cache_dir=cache_dir, + ) + indexer.index_workspace(repo, project="proj-force-del") + + f2.unlink() + indexer.index_workspace(repo, project="proj-force-del", force=True) + + points = [ + p + for p in qdrant.collections.get("test_code", {}).values() + if p["payload"]["project_name"] == "proj-force-del" + ] + file_paths = {p["payload"]["file_path"] for p in points} + assert "del_me.py" not in file_paths + assert "keep.py" in file_paths + + +def test_counts_recorded_emptying_one_collection_makes_next_run_embed_every_file( + tmp_path: Path, caplog: pytest.LogCaptureFixture +) -> None: + repo = tmp_path / "repo" + repo.mkdir() + (repo / "main.py").write_text("def main(): pass\n", encoding="utf-8") + (repo / "README.md").write_text("# README\nHello docs.\n", encoding="utf-8") + + qdrant = FakeQdrantClient() + embedder = FakeEmbedder() + cache_dir = tmp_path / ".cache" + indexer = WorkspaceIndexer( + qdrant=qdrant, + embedder=embedder, + code_collection="test_code", + docs_collection="test_docs", + cache_dir=cache_dir, + ) + indexer.index_workspace(repo, project="proj-counts") + counts = getattr(indexer, "_load_counts", lambda: {})() + assert "proj-counts" in counts + assert counts["proj-counts"]["test_code"] > 0 + assert counts["proj-counts"]["test_docs"] > 0 + + qdrant.collections["test_code"] = {} + + caplog.clear() + with caplog.at_level("INFO"): + stats = indexer.index_workspace(repo, project="proj-counts") + + assert stats["indexed_files"] >= 1 + assert any( + "proj-counts" in record.message and "test_code" in record.message + for record in caplog.records + ) + assert len(qdrant.collections["test_code"]) > 0 + + +def test_no_record_cache_lists_files_over_two_empty_collections_embeds_every_file( + tmp_path: Path, caplog: pytest.LogCaptureFixture +) -> None: + import hashlib + + repo = tmp_path / "repo" + repo.mkdir() + (repo / "main.py").write_text("def main(): pass\n", encoding="utf-8") + + qdrant = FakeQdrantClient() + embedder = FakeEmbedder() + cache_dir = tmp_path / ".cache" + indexer = WorkspaceIndexer( + qdrant=qdrant, + embedder=embedder, + code_collection="test_code", + docs_collection="test_docs", + cache_dir=cache_dir, + ) + cache_file = cache_dir / CONST_INDEX_CACHE_FILENAME + cache_dir.mkdir(parents=True, exist_ok=True) + content_hash = hashlib.sha256((repo / "main.py").read_bytes()).hexdigest() + cache_file.write_text(json.dumps({"proj-unrecorded:main.py": content_hash}), encoding="utf-8") + counts_file = getattr(indexer, "counts_file", cache_dir / CONST_INDEX_COUNTS_FILENAME) + assert not counts_file.exists() + + caplog.clear() + with caplog.at_level("INFO"): + stats = indexer.index_workspace(repo, project="proj-unrecorded") + + assert stats["indexed_files"] >= 1 + assert any("proj-unrecorded" in record.message for record in caplog.records) + assert len(qdrant.collections["test_code"]) > 0 + + +def test_cache_write_raises_halfway_leaves_previous_file_readable( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + import os + + cache_dir = tmp_path / ".cache" + cache_dir.mkdir(parents=True, exist_ok=True) + cache_file = cache_dir / CONST_INDEX_CACHE_FILENAME + cache_file.write_text(json.dumps({"proj:existing.py": "hash123"}), encoding="utf-8") + + qdrant = FakeQdrantClient() + embedder = FakeEmbedder() + indexer = WorkspaceIndexer( + qdrant=qdrant, + embedder=embedder, + code_collection="test_code", + docs_collection="test_docs", + cache_dir=cache_dir, + ) + + def faulty_replace(src: Any, dst: Any) -> None: + raise OSError("Disk write failed midway") + + monkeypatch.setattr(os, "replace", faulty_replace) + + with pytest.raises(OSError, match="Disk write failed midway"): + indexer._save_cache({"proj:existing.py": "new_hash", "proj:new.py": "hash456"}) + + assert json.loads(cache_file.read_text(encoding="utf-8")) == {"proj:existing.py": "hash123"} + + +def test_new_collection_gets_both_payload_indexes(tmp_path: Path) -> None: + qdrant = FakeQdrantClient() + qdrant.ensure_collection("test_code", vector_size=384) + indexes = qdrant.payload_schemas.get("test_code", {}) + assert "project_name" in indexes + assert "file_path" in indexes + + +def test_existing_collection_missing_payload_indexes_gets_both_on_next_index_run( + tmp_path: Path, +) -> None: + qdrant = FakeQdrantClient() + qdrant.collections["test_code"] = {} + qdrant.collections["test_docs"] = {} + qdrant.payload_schemas["test_code"] = {} + qdrant.payload_schemas["test_docs"] = {} + + repo = tmp_path / "repo" + repo.mkdir() + (repo / "main.py").write_text("def main(): pass\n", encoding="utf-8") + + embedder = FakeEmbedder() + indexer = WorkspaceIndexer( + qdrant=qdrant, + embedder=embedder, + code_collection="test_code", + docs_collection="test_docs", + cache_dir=tmp_path / ".cache", + ) + indexer.index_workspace(repo, project="proj-existing-idx") + assert "project_name" in qdrant.payload_schemas["test_code"] + assert "file_path" in qdrant.payload_schemas["test_code"] + assert "project_name" in qdrant.payload_schemas["test_docs"] + assert "file_path" in qdrant.payload_schemas["test_docs"] + + +def test_no_delete_path_sends_unwaited_delete(tmp_path: Path) -> None: + repo = tmp_path / "repo" + repo.mkdir() + f = repo / "f.py" + f.write_text("def f(): pass\n", encoding="utf-8") + + qdrant = FakeQdrantClient() + embedder = FakeEmbedder() + indexer = WorkspaceIndexer( + qdrant=qdrant, + embedder=embedder, + code_collection="test_code", + docs_collection="test_docs", + cache_dir=tmp_path / ".cache", + ) + indexer.index_workspace(repo, project="proj-waited") + f.unlink() + indexer.index_workspace(repo, project="proj-waited") + indexer.index_workspace(repo, project="proj-waited", force=True) + + assert len(qdrant.delete_calls) > 0 + for call in qdrant.delete_calls: + assert call.get("wait") is True, f"Found un-waited delete: {call}" + + +def test_count_that_raises_fails_run_and_reindexes_nothing(tmp_path: Path) -> None: + repo = tmp_path / "repo" + repo.mkdir() + (repo / "main.py").write_text("def main(): pass\n", encoding="utf-8") + + qdrant = FakeQdrantClient() + embedder = FakeEmbedder() + indexer = WorkspaceIndexer( + qdrant=qdrant, + embedder=embedder, + code_collection="test_code", + docs_collection="test_docs", + cache_dir=tmp_path / ".cache", + ) + indexer.index_workspace(repo, project="proj-count-fail") + + qdrant.raise_on_count = True + upserts_before = len(qdrant.upsert_calls) + with pytest.raises(QdrantClientError): + indexer.index_workspace(repo, project="proj-count-fail") + + assert len(qdrant.upsert_calls) == upserts_before diff --git a/tests/test_rag_qdrant.py b/tests/test_rag_qdrant.py index c953364091..688dbcbc99 100644 --- a/tests/test_rag_qdrant.py +++ b/tests/test_rag_qdrant.py @@ -7,7 +7,7 @@ import pytest from devops_cli.ai.rag.embeddings import EmbeddingsError -from devops_cli.ai.rag.qdrant import QdrantClient +from devops_cli.ai.rag.qdrant import QdrantClient, QdrantClientError pytestmark = pytest.mark.usefixtures("mock_keyring") @@ -17,6 +17,7 @@ def test_qdrant_is_alive() -> None: mock_native = MagicMock() mock_native.get_collections.return_value = MagicMock(collections=[]) client._client = mock_native + client._build_client = lambda: mock_native assert client.is_alive() is True @@ -30,6 +31,7 @@ def test_qdrant_list_collections() -> None: c2.name = "devops_docs" mock_native.get_collections.return_value = MagicMock(collections=[c1, c2]) client._client = mock_native + client._build_client = lambda: mock_native colls = client.list_collections() assert colls == ["devops_code", "devops_docs"] @@ -40,6 +42,7 @@ def test_qdrant_ensure_collection() -> None: mock_native = MagicMock() mock_native.get_collection.side_effect = Exception("Collection not found") client._client = mock_native + client._build_client = lambda: mock_native assert client.ensure_collection("devops_code", vector_size=384) is True mock_native.create_collection.assert_called_once() @@ -67,6 +70,7 @@ def test_qdrant_upsert_and_search() -> None: ) mock_native.query_points.return_value = MagicMock(points=[hit]) client._client = mock_native + client._build_client = lambda: mock_native points = [{"id": "1", "vector": [0.1] * 384, "payload": {"file_path": "src/main.py"}}] upserted = client.upsert_points("devops_code", points) @@ -87,6 +91,7 @@ def test_qdrant_upsert_dimension_mismatch_fails_without_recreating() -> None: info.status = "green" mock_native.get_collection.return_value = info client._client = mock_native + client._build_client = lambda: mock_native # Upsert with 1024 dims points = [{"id": "1", "vector": [0.1] * 1024, "payload": {"file_path": "src/main.py"}}] @@ -107,6 +112,7 @@ def test_qdrant_search_dimension_mismatch_raises_permanent_error() -> None: "Vector dimension error: expected dim: 768, got 1024" ) client._client = mock_native + client._build_client = lambda: mock_native with pytest.raises(EmbeddingsError) as exc_info: client.search_points("devops_code", query_vector=[0.1] * 1024) @@ -123,6 +129,7 @@ def test_qdrant_delete_collection() -> None: mock_native = MagicMock() mock_native.delete_collection.return_value = True client._client = mock_native + client._build_client = lambda: mock_native assert client.delete_collection("devops_code") is True @@ -132,20 +139,36 @@ def test_qdrant_delete_points_by_files() -> None: mock_native = MagicMock() mock_native.delete.return_value = True client._client = mock_native + client._build_client = lambda: mock_native # Empty list returns True with no calls assert client.delete_points_by_files("devops_code", []) is True assert mock_native.delete.call_count == 0 - # Single file via delete_points_by_file - assert client.delete_points_by_file("devops_code", "src/main.py", project_name="devops") is True + # Single file via delete_points_by_files + assert ( + client.delete_points_by_files("devops_code", ["src/main.py"], project_name="devops") is True + ) assert mock_native.delete.call_count == 1 + assert mock_native.delete.call_args.kwargs.get("wait") is True + + # Delete points by project + assert client.delete_points_by_project("devops_code", "devops") is True + assert mock_native.delete.call_count == 2 + assert mock_native.delete.call_args.kwargs.get("wait") is True # 150 files should be split into 2 batches (100 + 50) assert ( client.delete_points_by_files("devops_code", [f"file_{i}.py" for i in range(150)]) is True ) - assert mock_native.delete.call_count == 3 + assert mock_native.delete.call_count == 4 + + # Deletes raise QdrantClientError on failure + mock_native.delete.side_effect = RuntimeError("network timeout") + with pytest.raises(QdrantClientError): + client.delete_points_by_files("devops_code", ["src/main.py"]) + with pytest.raises(QdrantClientError): + client.delete_points_by_project("devops_code", "devops") def test_qdrant_build_client_port_resolution(monkeypatch: pytest.MonkeyPatch) -> None: