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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
schema: spec-driven
created: 2026-10-26
skip_specs: true
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
@@ -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`.
Original file line number Diff line number Diff line change
@@ -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 <checkout> --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`).
23 changes: 14 additions & 9 deletions src/devops_cli/ai/rag/chunker.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import hashlib
import logging
import mimetypes
import uuid
import warnings
from pathlib import Path

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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:
Expand Down
Loading
Loading