|
1 | 1 | using EssentialCSharp.Chat.Common.Models; |
2 | 2 | using Microsoft.Extensions.AI; |
3 | 3 | using Microsoft.Extensions.VectorData; |
| 4 | +using Npgsql; |
4 | 5 |
|
5 | 6 | namespace EssentialCSharp.Chat.Common.Services; |
6 | 7 |
|
7 | 8 | /// <summary> |
8 | | -/// Service for generating embeddings for markdown chunks using Azure OpenAI |
| 9 | +/// Service for generating embeddings for markdown chunks using Azure OpenAI and uploading |
| 10 | +/// them to a PostgreSQL vector store via a staging-then-swap pattern to avoid downtime. |
9 | 11 | /// </summary> |
10 | | -public class EmbeddingService(VectorStore vectorStore, IEmbeddingGenerator<string, Embedding<float>> embeddingGenerator) |
| 12 | +public class EmbeddingService( |
| 13 | + VectorStore vectorStore, |
| 14 | + IEmbeddingGenerator<string, Embedding<float>> embeddingGenerator, |
| 15 | + NpgsqlDataSource? dataSource = null) |
11 | 16 | { |
12 | 17 | public static string CollectionName { get; } = "markdown_chunks"; |
13 | 18 |
|
14 | 19 | /// <summary> |
15 | 20 | /// Generate an embedding for the given text. |
16 | 21 | /// </summary> |
17 | | - /// <param name="text">The text to generate an embedding for.</param> |
18 | | - /// <param name="cancellationToken">The cancellation token.</param> |
19 | | - /// <returns>A search vector as ReadOnlyMemory<float>.</returns> |
20 | 22 | public async Task<ReadOnlyMemory<float>> GenerateEmbeddingAsync(string text, CancellationToken cancellationToken = default) |
21 | 23 | { |
22 | 24 | var embedding = await embeddingGenerator.GenerateAsync(text, cancellationToken: cancellationToken); |
23 | 25 | return embedding.Vector; |
24 | 26 | } |
25 | 27 |
|
26 | 28 | /// <summary> |
27 | | - /// Generate an embedding for each text paragraph and upload it to the specified collection. |
| 29 | + /// Generate embeddings for all chunks in a single batch call and upload them to the vector |
| 30 | + /// store using a staging-then-atomic-swap pattern so the live collection stays queryable |
| 31 | + /// throughout the rebuild. |
| 32 | + /// |
| 33 | + /// Steps: |
| 34 | + /// 1. Create a staging collection ({collectionName}_staging). |
| 35 | + /// 2. Embed all chunks in one batch API call (Azure OpenAI supports up to 2048 inputs). |
| 36 | + /// 3. Batch-upsert all chunks into staging. |
| 37 | + /// 4. Atomically swap staging → live via three SQL RENAMEs in a single transaction. |
| 38 | + /// PostgreSQL ALTER TABLE acquires AccessExclusiveLock automatically; no explicit |
| 39 | + /// LOCK TABLE is needed. The transaction ensures no reader sees an intermediate state. |
| 40 | + /// 5. Drop the old live backup table. |
| 41 | + /// |
| 42 | + /// If an error occurs before the swap, only the staging table is affected — the live |
| 43 | + /// collection is untouched. |
28 | 44 | /// </summary> |
29 | | - /// <param name="collectionName">The name of the collection to upload the text paragraphs to.</param> |
30 | | - /// <returns>An async task.</returns> |
31 | | - public async Task GenerateBookContentEmbeddingsAndUploadToVectorStore(IEnumerable<BookContentChunk> bookContents, CancellationToken cancellationToken, string? collectionName = null) |
| 45 | + public async Task GenerateBookContentEmbeddingsAndUploadToVectorStore( |
| 46 | + IEnumerable<BookContentChunk> bookContents, |
| 47 | + CancellationToken cancellationToken, |
| 48 | + string? collectionName = null) |
32 | 49 | { |
33 | 50 | collectionName ??= CollectionName; |
| 51 | + string stagingName = $"{collectionName}_staging"; |
| 52 | + string oldName = $"{collectionName}_old"; |
34 | 53 |
|
35 | | - var collection = vectorStore.GetCollection<string, BookContentChunk>(collectionName); |
36 | | - await collection.EnsureCollectionDeletedAsync(cancellationToken); |
37 | | - await collection.EnsureCollectionExistsAsync(cancellationToken); |
| 54 | + if (dataSource is null) |
| 55 | + throw new InvalidOperationException("NpgsqlDataSource is required for the staging swap. Ensure it is registered in DI."); |
38 | 56 |
|
39 | | - int uploadedCount = 0; |
| 57 | + // ── Step 1: Prepare staging collection ──────────────────────────────────────── |
| 58 | + var staging = vectorStore.GetCollection<string, BookContentChunk>(stagingName); |
| 59 | + await staging.EnsureCollectionDeletedAsync(cancellationToken); |
| 60 | + await staging.EnsureCollectionExistsAsync(cancellationToken); |
40 | 61 |
|
41 | | - foreach (var chunk in bookContents) |
| 62 | + // ── Step 2: Batch-embed all chunks in a single API call ─────────────────────── |
| 63 | + // IEmbeddingGenerator.GenerateAsync natively accepts IEnumerable<string>. |
| 64 | + // The single-string overload used previously is a convenience extension method |
| 65 | + // that wraps one item and calls this same method. |
| 66 | + var chunkList = bookContents.ToList(); |
| 67 | + var texts = chunkList.Select(c => c.ChunkText).ToList(); |
| 68 | + |
| 69 | + GeneratedEmbeddings<Embedding<float>> embeddings = |
| 70 | + await embeddingGenerator.GenerateAsync(texts, cancellationToken: cancellationToken); |
| 71 | + |
| 72 | + if (embeddings.Count != chunkList.Count) |
| 73 | + throw new InvalidOperationException( |
| 74 | + $"Embedding count mismatch: expected {chunkList.Count}, got {embeddings.Count}."); |
| 75 | + |
| 76 | + for (int i = 0; i < chunkList.Count; i++) |
| 77 | + { |
| 78 | + chunkList[i].TextEmbedding = embeddings[i].Vector; |
| 79 | + } |
| 80 | + |
| 81 | + // ── Step 3: Batch-upsert all chunks into staging ────────────────────────────── |
| 82 | + await staging.UpsertAsync(chunkList, cancellationToken); |
| 83 | + Console.WriteLine($"Uploaded {chunkList.Count} chunks to staging collection '{stagingName}'."); |
| 84 | + |
| 85 | + // ── Step 4: Atomic swap — staging → live ────────────────────────────────────── |
| 86 | + // Three ALTER TABLE RENAME statements in one transaction. |
| 87 | + // Each RENAME auto-acquires AccessExclusiveLock on its table; the transaction |
| 88 | + // guarantees all three renames are visible atomically to other sessions. |
| 89 | + await using var conn = await dataSource.OpenConnectionAsync(cancellationToken); |
| 90 | + await using var tx = await conn.BeginTransactionAsync(cancellationToken); |
| 91 | + |
| 92 | + await using (var cmd = conn.CreateCommand()) |
42 | 93 | { |
43 | | - cancellationToken.ThrowIfCancellationRequested(); |
44 | | - chunk.TextEmbedding = await GenerateEmbeddingAsync(chunk.ChunkText, cancellationToken); |
45 | | - await collection.UpsertAsync(chunk, cancellationToken); |
46 | | - Console.WriteLine($"Uploaded chunk '{chunk.Id}' to collection '{collectionName}' for file '{chunk.FileName}' with heading '{chunk.Heading}'."); |
47 | | - uploadedCount++; |
| 94 | + cmd.Transaction = tx; |
| 95 | + |
| 96 | + // Drop any leftover backup from a previous run |
| 97 | + cmd.CommandText = $"DROP TABLE IF EXISTS \"{oldName}\""; |
| 98 | + await cmd.ExecuteNonQueryAsync(cancellationToken); |
| 99 | + |
| 100 | + // Rename live → old. IF EXISTS is a no-op on first run when no live table exists. |
| 101 | + // Using ALTER TABLE IF EXISTS avoids PL/pgSQL string interpolation entirely. |
| 102 | + cmd.CommandText = $"ALTER TABLE IF EXISTS \"{collectionName}\" RENAME TO \"{oldName}\""; |
| 103 | + await cmd.ExecuteNonQueryAsync(cancellationToken); |
| 104 | + |
| 105 | + // Rename staging → live |
| 106 | + cmd.CommandText = $"ALTER TABLE \"{stagingName}\" RENAME TO \"{collectionName}\""; |
| 107 | + await cmd.ExecuteNonQueryAsync(cancellationToken); |
| 108 | + } |
| 109 | + |
| 110 | + await tx.CommitAsync(cancellationToken); |
| 111 | + Console.WriteLine($"Swapped '{stagingName}' → '{collectionName}' atomically."); |
| 112 | + |
| 113 | + // ── Step 5: Drop the old backup ─────────────────────────────────────────────── |
| 114 | + await using (var cmd = conn.CreateCommand()) |
| 115 | + { |
| 116 | + cmd.CommandText = $"DROP TABLE IF EXISTS \"{oldName}\""; |
| 117 | + await cmd.ExecuteNonQueryAsync(cancellationToken); |
48 | 118 | } |
49 | | - Console.WriteLine($"Successfully generated embeddings and uploaded {uploadedCount} chunks to collection '{collectionName}'."); |
| 119 | + |
| 120 | + Console.WriteLine($"Successfully generated embeddings and uploaded {chunkList.Count} chunks to collection '{collectionName}'."); |
50 | 121 | } |
51 | 122 | } |
0 commit comments