Skip to content
Closed
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
33 changes: 30 additions & 3 deletions __tests__/unit/services/rag/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,10 +113,37 @@ describe('RagService', () => {
.rejects.toThrow('already in the knowledge base');
});

it('continues without embeddings if embedding fails', async () => {
// HONESTY: a doc with no embeddings is not searchable, so it must NOT be left in
// the KB looking "added". On any embedding failure, indexDocument rolls back the
// inserted doc + chunks and throws, so the KB add flow surfaces the real error
// (instead of a silent dead entry). backfillEmbeddings has no auto-trigger, so the
// old "continue without embeddings" swallow stranded the doc permanently.
it('rolls back the inserted document and throws when embedding LOAD fails', async () => {
mockEmbedding.load.mockRejectedValueOnce(new Error('model not found'));
const docId = await ragService.indexDocument({ projectId: 'proj1', filePath: '/p', fileName: 'test.txt', fileSize: 100 });
expect(docId).toBe(1); // Still returns docId
await expect(
ragService.indexDocument({ projectId: 'proj1', filePath: '/p', fileName: 'test.txt', fileSize: 100 }),
).rejects.toThrow(/Could not index "test.txt".*embeddings failed/);
expect(mockDb.deleteDocument).toHaveBeenCalledWith(1); // the just-inserted docId
expect(mockDb.insertEmbeddingsBatch).not.toHaveBeenCalled();
});

it('rolls back the inserted document and throws when embedBatch fails (e.g. OOM)', async () => {
mockEmbedding.embedBatch.mockRejectedValueOnce(new Error('Embedding failed (native error). OOM'));
await expect(
ragService.indexDocument({ projectId: 'proj1', filePath: '/p', fileName: 'test.txt', fileSize: 100 }),
).rejects.toThrow(/embeddings failed to generate/);
expect(mockDb.deleteDocument).toHaveBeenCalledWith(1);
expect(mockDb.insertEmbeddingsBatch).not.toHaveBeenCalled();
});

it('rolls back and throws when embedBatch returns fewer embeddings than chunks', async () => {
// insertChunks mock returns [1,2] (2 chunks); return only 1 embedding → mismatch.
mockEmbedding.embedBatch.mockResolvedValueOnce([[0.1, 0.2]]);
await expect(
ragService.indexDocument({ projectId: 'proj1', filePath: '/p', fileName: 'test.txt', fileSize: 100 }),
).rejects.toThrow(/embeddings failed to generate/);
expect(mockDb.deleteDocument).toHaveBeenCalledWith(1);
expect(mockDb.insertEmbeddingsBatch).not.toHaveBeenCalled();
});
});

Expand Down
13 changes: 12 additions & 1 deletion src/services/rag/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,9 @@ class RagService {
await embeddingService.load();
const texts = chunks.map(c => c.content);
const embeddings = await embeddingService.embedBatch(texts);
if (embeddings.length !== rowIds.length) {
throw new Error(`embedding count ${embeddings.length} does not match ${rowIds.length} chunks`);
}
Comment on lines +66 to +68

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remediation recommended

3. Backfill mismatch not handled 🐞 Bug ≡ Correctness

indexDocument now rejects when the embedding count doesn’t match chunk count, but backfillEmbeddings
still blindly uses embeddings[i] for each chunk. If an embedding-count mismatch ever occurs (as the
new guard suggests is possible), backfill can store empty vectors and semantic retrieval can produce
NaN scores.
Agent Prompt
### Issue description
`indexDocument()` now enforces `embeddings.length === rowIds.length`, but `backfillEmbeddings()` does not validate the returned embedding count before indexing `embeddings[i]`. If `embedBatch()` returns fewer embeddings than chunks, `embeddingToBlob(undefined)` will produce an empty embedding blob, and semantic scoring can become `NaN`.

### Issue Context
- `backfillEmbeddings()` builds entries with `embedding: embeddings[i]` without bounds checks.
- `embeddingToBlob()` uses `new Float32Array(embedding)`; when `embedding` is `undefined` it results in a zero-length buffer.
- `cosineSimilarity()` multiplies `a[i] * b[i]` for `i < a.length`; with `b` shorter, this yields `NaN` and unstable sorting.

### Fix Focus Areas
- src/services/rag/index.ts[93-119]
- src/services/rag/database.ts[114-116]
- src/services/rag/vectorMath.ts[9-21]

### Suggested change
Apply the same length check used in `indexDocument()` inside `backfillEmbeddings()`. On mismatch, skip inserting embeddings (and consider logging + continuing), or delete any partially inserted embeddings for that doc if you ever change insertion semantics.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

const entries = rowIds.map((rowId, i) => ({
chunkRowid: rowId,
docId,
Expand All @@ -71,7 +74,15 @@ class RagService {
ragDatabase.insertEmbeddingsBatch(entries);
logger.log(`[RAG] Generated ${embeddings.length} embeddings for ${fileName}`);
} catch (err) {
logger.error('[RAG] Embedding generation failed (non-fatal):', err);
// A document with no embeddings is NOT searchable — semantic search skips it —
// yet the KB would show it as "added". That is the "looks indexed but doesn't
// work" lie. backfillEmbeddings has no auto-trigger, so a swallowed failure
// strands the doc permanently. Roll back the just-inserted doc + chunks and
// surface the failure so the user sees the real error (KnowledgeBaseScreen
// already alerts on an index throw) and can retry — never a silent dead entry.
ragDatabase.deleteDocument(docId);
logger.error('[RAG] Embedding generation failed — rolled back document:', err);
throw new Error(`Could not index "${fileName}": embeddings failed to generate. ${err instanceof Error ? err.message : String(err)}`);
Comment on lines +83 to +85

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Guard the rollback delete so it can't mask the original failure.

If ragDatabase.deleteDocument(docId) throws, the DB error propagates instead of the embedding error, and logger.error / the wrapped throw never run — leaving exactly the stranded, undiagnosable entry this change is meant to prevent. Wrap the rollback so the underlying embedding cause is always surfaced.

🛡️ Proposed fix
-      ragDatabase.deleteDocument(docId);
-      logger.error('[RAG] Embedding generation failed — rolled back document:', err);
+      try {
+        ragDatabase.deleteDocument(docId);
+        logger.error('[RAG] Embedding generation failed — rolled back document:', err);
+      } catch (rollbackErr) {
+        logger.error('[RAG] Embedding generation failed AND rollback failed:', rollbackErr, err);
+      }
       throw new Error(`Could not index "${fileName}": embeddings failed to generate. ${err instanceof Error ? err.message : String(err)}`);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
ragDatabase.deleteDocument(docId);
logger.error('[RAG] Embedding generation failed — rolled back document:', err);
throw new Error(`Could not index "${fileName}": embeddings failed to generate. ${err instanceof Error ? err.message : String(err)}`);
try {
ragDatabase.deleteDocument(docId);
logger.error('[RAG] Embedding generation failed — rolled back document:', err);
} catch (rollbackErr) {
logger.error('[RAG] Embedding generation failed AND rollback failed:', rollbackErr, err);
}
throw new Error(`Could not index "${fileName}": embeddings failed to generate. ${err instanceof Error ? err.message : String(err)}`);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/services/rag/index.ts` around lines 83 - 85, The rollback in the RAG
indexing failure path can mask the original embedding error if
`ragDatabase.deleteDocument(docId)` throws, preventing `logger.error` and the
wrapped `throw` in the `index` flow from running. Update the error handling
around `ragDatabase.deleteDocument` in `src/services/rag/index.ts` so rollback
failures are caught and logged separately, while the original embedding failure
is always the one rethrown from the `index` function with its cause preserved.

Comment on lines +84 to +85

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Informational

4. Error cause not preserved 🐞 Bug ◔ Observability

The new catch block throws a fresh Error string, which drops the original error object/stack as a
cause. This reduces debuggability (especially differentiating load vs native embedding failures)
even though the UI surfaces indexErr.message.
Agent Prompt
### Issue description
`indexDocument()` rethrows embedding failures with a new `Error(...)` message, losing the original error as a structured cause. This makes diagnosing failures harder (stack traces, error typing) even though the message is preserved.

### Issue Context
Callers (e.g. KnowledgeBaseScreen) display `indexErr.message`, but logs/telemetry benefit from retaining the original error via `cause`.

### Fix Focus Areas
- src/services/rag/index.ts[76-86]
- src/screens/KnowledgeBaseScreen.tsx[94-100]

### Suggested change
Use `throw new Error(msg, { cause: err })` (if supported by your TS/JS target) or attach `(e as any).cause = err` before throwing. Keep the user-facing message, but preserve the original error for diagnostics.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

}

onProgress?.({ stage: 'done', message: 'Done' });
Expand Down